Warning: comparison of integers of different signs

Hi,

int64_t signed64 = X
uint64_t unsigned64 = Y
if (signed64 > unsigned64) {
…do stuff…
}

For this, one would get a warning of:
“warning: comparison of integers of different signs”

Is there a CLANG/LLVM built-in or compiler flag that can do comparison of signed and unsigned safely?
Say the bits of the 64-bit integers are labeled 0 to 63.
If bit 63 == 0 of both signed64 and unsigned64, then the comparison is perfectly valid.
If bit 63 == 1, the comparison then only has to reason on bit 63, and ignore the rest of the bits.
signed-bit-63 unsigned-bit-63 comparison (signed > unsigned) true/false
0 1 false
1 0 false
1 1 false
0 0 compare the numbers

One can do the comparison safely, if one takes bit-63 into account.
The true/false matrix is different depending on the comparison operation (>, <, == etc)
So, I would like a compiler to just do the comparison safely, rather than raise a warning.
This approach would be considerably safer from a security hardening point of view.
I guess I am asking for CLANG to automatically create the right bit-63 code at the LLVM IR level to make it safe.

Now after that, all the programmer would need to consider would be performance, and its quite easy to remember that a different signs comparison is slower than a same signs comparison and the programmer could modify their program to take that into account.

What do people think?

The name is bike-shedding. You will probably need something like:

int64_t signed64 = X
uint64_t unsigned64 = Y
if (checked_larger_than(signed64, unsigned64)) {
…do stuff…
}

It will trap at runtime, if the comparison is not safe. At least Rust and Swift will trap, if you do unsafe stuff at runtime.

There’s not a compiler flag, but there are utilities to help.

For C++: std::cmp_equal, cmp_not_equal, cmp_less, cmp_greater, cmp_less_equal, cmp_greater_equal - cppreference.com
For C: GitHub - rcseacord/cmp_int: C implementation of C++ Utility functions https://en.cppreference.com/w/cpp/utility/intcmp is a C implementation of the C++ interfaces.

The problem is: those conversions are well-defined and changing the behavior would be a non-conforming language extension.

1 Like