[Clang] Clang does not detect undefined behavior for bitshift
When Clang compile this code, it incorrectly optimizes it to nothing at -O3. The latest Clang that did compile the code correct was Clang 11.0.1. Adding a (uint64_t) at line 17 made Clang compile right.
At this similar code, Both C code are the same in behavior, yet the first C source uses less instructions than the second.
I've tried compiling this with the bound set to 1, 2, ... 64.
// compiled with -DBOUND_VAL=1, -DBOUND_VAL=2, ..., -DBOUND_VAL=64
#include <inttypes.h>
#include <stddef.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
uint64_t expozig_Tokenize_v2_ret_bitstring(uint8_t * restrict ptr, const uint8_t is_type){
uint64_t ret_val = 0;
bool tmp_bools[BOUND_VAL] = {};
size_t n = 0;
gtloop1:
if(n == BOUND_VAL)
goto end_gtloop1;
switch(is_type){
case 0:
tmp_bools[n] = ptr[n] == '\n';
// Adding cast removes bug
ret_val += (uint64_t)(tmp_bools[n] << n);
break;
default:
__builtin_unreachable();
break;
}
++n;
goto gtloop1;
end_gtloop1:
return ret_val;
}
Then when BOUND_VAL > 32, the whole function body was optimized out, while less BOUND_VAL values triggered correct behavior.
I think Clang is conforming here. When BOUND_VAL > 32, the n in subexpression tmp_bools[n] << n can be greater than or equal to 32. As the promoted type of bool (i.e. int) is of 32-bit, such bit shift would definitely raise undefined behavior, and thus the whole function body would be effectively marked __builtin_unreachable(). Cast to uint64_t before bit shift is a correct fix to me.
Perhaps there's no bug of Clang that needs to be fixed. IMO you've already found the fix of a bug in your code. But perhaps some diagnostic message is desired here.
@llvm/issue-subscribers-clang-frontend
Author: None (BreadTom)
Perhaps there's no bug of Clang that needs to be fixed. IMO you've already found the fix of a bug in your code. But perhaps some diagnostic message is desired here.
https://www.open-std.org/JTC1/SC22/WG14/www/docs/n3220.pdf 6.5.8 Bitwise shift operators If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
I recompile with -Wall -Wextra -Weverything and the only relevant warning was: 17:39 warning: unsafe buffer access [-Wunsafe-buffer-usage] No warning for GCC 14.2 with -Wall -Wextra -fanalyzer