<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/143397>143397</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Incorrect optimization of multiple __builtin_unreachable() conditions leads to logic errors in control flow
</td>
</tr>
<tr>
<th>Labels</th>
<td>
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
hutuhutong
</td>
</tr>
</table>
<pre>
this problems exist in X86_64 clang 18/20。
clang exhibits incorrect optimization behavior when handling multiple (>2) __builtin_unreachable() statements.
When only a single __builtin_unreachable() is used, or when compiling with -O0, the code executes correctly. However, when two or more __builtin_unreachable() statements are present, the program behaves correctly under -O0, but under -O1/O2/O3/Os, clang incorrectly folds the entire test_builtin_unreachable() function, leading to an infinite loop at runtime.
This suggests that the optimizer does not correctly account for the interactions of multiple unreachable paths during optimization.
========the code========
#include <stdio.h>
#include <stdlib.h>
void test_output() {
printf("the code is executing\n");
}
void test_builtin_unreachable() {
int bb = 2;
if ((bb & ~3) != 0)
__builtin_unreachable();
if ((bb & 1) == 0)
__builtin_unreachable();
if (bb == 2)
printf("the value of bb is: %d\n", bb);
}
int main() {
test_output();
test_builtin_unreachable();
return 0;
}
========the output========
$ clang -O0 test.c -o test
$ ./test
the code is executing
the value of bb is: 2
$ clang -O1 test.c -o test
$ ./test
the code is executing
the code is executing
Segmentation fault (core dumped)
========the assembly code=========
when use the -O1, we can see the function test_builtin_unreachable is none, so the test_output always be executing:
test_output:
lea rdi, [rip + .Lstr]
jmp puts@PLT
test_builtin_unreachable:
main:
push rax
lea rdi, [rip + .Lstr]
call puts@PLT
.Lstr:
.asciz "the code is executing"
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJykVlFvozgQ_jXOy6gRmJDAAw9p2uhOWmlPupXu3ioDA3hlbGSPk2Yf7refDKTJtmlOuq0qaD3j-b6Z-TxGOCdbjViw9JGlTwvhqTO26Dz5zpPR7a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