| Issue |
235263
|
| Summary |
[clang][DAGCombiner] foldSelectToABD negates an INT_MIN constant lane: `|a + INT_MIN|` becomes `a + 2^31`
|
| Labels |
backend:X86,
miscompilation,
llvm:SelectionDAG,
generated by fuzzer
|
| Assignees |
|
| Reporter |
YuanchengJiang
|
The following code:
```cpp
/* foldSelectToABD INT_MIN negation bug.
Godbolt: x86-64 clang (trunk) -O2 (also -O1/-O3; -march=haswell; aarch64/riscv64 -O2)
Expected: lanes 1,3 = 0x80000000 - (x & 0x3fffffff), i.e. |a + INT_MIN|.
Wrong: lanes 1,3 = a + 0x80000000 (abds(a, -INT_MIN) with -INT_MIN == INT_MIN). */
#include <stdio.h>
typedef int v4i __attribute__((ext_vector_type(4)));
__attribute__((noinline)) v4i f(v4i x) {
v4i a = x & 0x3fffffff;
v4i s = a + (v4i){5, (int)0x80000000, 7, (int)0x80000000};
return s > 0 ? s : -s; /* |s| (no overflow: s in [-2^31+1, 2^30+7]) */
}
int main(void) {
volatile int in = 1;
v4i x = {in, in, in, in};
v4i r = f(x);
unsigned exp[4] = {6, 0x7fffffffu, 8, 0x7fffffffu};
int bad = 0;
for (int i = 0; i < 4; i++) {
printf("lane %d: got 0x%08x expected 0x%08x%s\n", i, (unsigned)r[i], exp[i],
(unsigned)r[i] == exp[i] ? "" : " MISMATCH");
bad |= (unsigned)r[i] != exp[i];
}
return bad;
}
```
Resulted in this output:
```
$ clang -O2 repro.c && ./a.out
lane 0: got 0x00000006 expected 0x00000006
lane 1: got 0x80000001 expected 0x7fffffff MISMATCH
lane 2: got 0x00000008 expected 0x00000008
lane 3: got 0x80000001 expected 0x7fffffff MISMATCH
(exit 1; -O0 prints the expected values)
f: # x86-64 -O2
pand .LCPI0_0(%rip), %xmm0
psubd .LCPI0_1(%rip), %xmm0
retq
```
| lane (a = 1) | expected abs(a + C) | actual |
|--------------|--------------------|--------|
| 1, 3 (C = INT_MIN) | 0x7fffffff | 0x80000001 |
Trunk: https://godbolt.org/z/ds513o957 (x86-64 clang trunk, -O2, compiles and executes; prints MISMATCH as of 2026-10-23; also AArch64 `sabd` and RISC-V V)
Root cause: `DAGCombiner::foldSelectToABD` (llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp) rewrites `setcc (add nsw A, C), 0` to `setcc A, -C` via `DAG.getNegative(B, ...)`. The equivalence `A + C < 0 <=> A < -C` only holds when `-C` is representable. For a lane with C = INT_MIN, `-C` wraps back to INT_MIN, so the compare becomes the always-false `A < INT_MIN`, while `A + INT_MIN < 0` is true for every A allowed by `nsw`. The select then becomes `abds(A, INT_MIN)` = `A + 2^31` instead of `2^31 - A`. The sibling `foldABSToABD` already rejects INT_MIN (`IsNotMinSignedInt`). In C this is `s = a + C; s > 0 ? s : -s` with a non-splat constant vector, at -O1 and above.
Suggested fix: Skip the `(add nsw A, C)` rewrite when any lane of the constant C is the signed minimum value. Validated locally (a local tree carries this fix, and the reproducer then prints the expected values).
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs