Description
Originally discovered by running compiler tests with -Cllvm-args=santize-undefined
.
Running the following piece of code:
#[no_mangle]
fn ub()->u32{
black_box(1_u128).leading_zeros()
}
will trip UB checks. This is caused by an improper implementation of the 128 bit ctlz intrinsic. Currently, this intrinsic first checks if the argument is not 0, and then counts the leading zeroes in the high and low 8 bytes of the value - separately.
This is incorrect: if either the low xor the high bytes are zero, then counting the leading zeroes in those 8 byte numbers is UB.
Here is the relevant part of GIMPLE, which shows the underlying issue:
if (param0 == 0) goto then; else goto else;
then:
zeros = 128;
goto after;
else:
_2 = param0 >> 64;
_3 = (size_t) _2;
_4 = __builtin_clzll (_3);
_5 = (uint128_t) _4;
count_loading_zeroes_results[0] = _5;
_6 = (size_t) param0;
_7 = __builtin_clzll (_6);
In the case of param0 = 1_u128
, the top if
will jump to else
. There, the value _2
will be zero(the high 8 bytes of 1_u128 are zero). This means that the value of _3
will also be zero, and on this line:
_4 = __builtin_clzll (_3);
__builtin_clzll
will be called with an argument of 0
, which is UB.
Activity