| Issue |
235262
|
| Summary |
[clang] [DAGCombiner] visitVSELECT folds `x > C-1 ? x + -C : 0` to `usubsat x, C` also for lanes with C = 0, where the compare is the never-true `x > UINT_MAX`: those lanes return x instead of 0
|
| Labels |
backend:X86,
llvm:codegen,
miscompilation,
generated by fuzzer
|
| Assignees |
|
| Reporter |
YuanchengJiang
|
The following code:
```cpp
/* DAGCombiner visitVSELECT USUBSAT fold "x > C-1 ? x + -C : 0 --> usubsat x, C" accepts a lane with C == 0
(compare constant -1: `x > 0xFFFF` is never true, the lane must be 0), giving usubsat(x, 0) = x.
Godbolt: x86-64 clang (trunk), flags: -O2 (also -O1/-O3, any -march; aarch64 / riscv64 -march=rv64gcv)
EXPECTED (clang -O0, gcc): lane0 = 0, lane1 = 95, lane3 = 0 -> exit 0
BUGGY (clang -O2): lane0 = 100, lane3 = 100 -> exit 1 */
#include <stdio.h>
typedef unsigned short v8u16 __attribute__((ext_vector_type(8)));
__attribute__((noinline)) v8u16 f(v8u16 x) {
v8u16 c = {0xffff, 4, 9, 0xffff, 0xffff, 4, 9, 0xffff};
v8u16 k = {0, 5, 10, 0, 0, 5, 10, 0};
return x > c ? x - k : 0; /* lanes 0,3,4,7: x > 0xffff is false -> 0 */
}
int main(void) {
volatile unsigned short in = 100;
v8u16 x = in;
v8u16 r = f(x);
unsigned short exp[8] = {0, 95, 90, 0, 0, 95, 90, 0};
int bad = 0;
for (int i = 0; i < 8; i++) {
printf("lane %d: got %u expected %u%s\n", i, r[i], exp[i], r[i] == exp[i] ? "" : " MISMATCH");
bad |= r[i] != exp[i];
}
return bad;
}
```
Resulted in this output:
```
$ clang -O2 repro.c && ./a.out
lane 0: got 100 expected 0 MISMATCH
lane 1: got 95 expected 95
lane 2: got 90 expected 90
lane 3: got 100 expected 0 MISMATCH
lane 4: got 100 expected 0 MISMATCH
lane 5: got 95 expected 95
lane 6: got 90 expected 90
lane 7: got 100 expected 0 MISMATCH
(exit 1; -O0 prints the expected values)
f: # x86-64 -O2
psubusw .LCPI0_0(%rip), %xmm0
retq
```
| lane (x = 100) | c, k | expected | actual |
|----------------|------|----------|--------|
| 0, 3, 4, 7 | 0xffff, 0 | 0 | 100 |
| 1, 5 | 4, 5 | 95 | 95 |
| 2, 6 | 9, 10 | 90 | 90 |
Trunk: https://godbolt.org/z/8vf1aexzc (x86-64 clang trunk, -O2, compiles and executes; prints MISMATCH as of 2026-10-23; also AArch64 `uqsub` and RISC-V V)
Root cause: In `DAGCombiner::visitVSELECT` (llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp), the USUBSAT fold `x >u C-1 ? x + -C : 0 -> usubsat(x, C)` checks each constant lane with `MatchUSUBSAT`, which requires `Cond == -Op - 1`. For a lane with `Op = 0` (C = 0) that accepts `Cond = -1 = UINT_MAX`. But `x >u UINT_MAX` is never true, so the original lane is always 0, whereas `usubsat(x, 0) = x`. In C this is `x > c ? x - k : 0` on an unsigned vector with some lanes `c = UINT_MAX, k = 0`, at -O1 and above.
Suggested fix: In `MatchUSUBSAT`, also require `!Op->isZero()`. Validated locally (a local tree carries this fix, and the reproducer then prints 0 for those lanes).
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs