Issue 241265
Summary [DAGCombiner] visitVECTOR_COMPRESS tests mask lanes with isConstTrueVal; -1 counts as false (miscompile at -O3)
Labels new issue
Assignees
Reporter jeffchen006
    A wide `ctlz` (i1024, znver4/AVX512CD) is expanded into a `VECTOR_COMPRESS` with a constant mask. After type legalization a true mask lane is `i8 -1`. `visitVECTOR_COMPRESS` tests it with the scalar boolean rule (ZeroOrOne on X86), so every lane is false and the result folds to the UNDEF passthru.

**Reproducer** (`repro.c`)
```c
/* a = 2^512 and z | 1 = 1, so q = 2^512 and q >> 512 = 1: the program must
   print 1. Clang -O3 -march=znver4 prints 0. */
int printf(const char *, ...);
volatile unsigned z = 0;
int main(void) {
 unsigned _BitInt(513) a = (unsigned _BitInt(513))1 << 512;
  unsigned _BitInt(513) q = a / (z | 1);
  printf("%d\n", (int)(q >> 512));
 return 0;
}
```

**Commands and output** (clang version 24.0.0git (https://github.com/llvm/llvm-project.git 8207e9143575), Target: x86_64-unknown-linux-gnu):
```console
$ clang -O0 -march=znver4 repro.c -o o0
$ ./o0
1
$ clang -O3 -march=znver4 repro.c -o o3
$ ./o3
0
```
Expected (as `-O0`): `1`. `-O3` prints `0`.

**Why the expected output is right**
The divisor `z|1` is nonzero; `1<<512` fits `unsigned _BitInt(513)`; the shift count 512 < 513. UBSan/ASan/MSan at -O0 are clean. (gcc 11 has no `_BitInt`.)

**Potential Root cause**
`llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp`, `DAGCombiner::visitVECTOR_COMPRESS`, constant-mask path: each lane is tested with `TLI.isConstTrueVal(MaskI)` on the scalar operand. `FoldConstantArithmetic` folds a vector SETCC per lane and sign-extends a true lane to `i8 -1`; `isConstTrueVal` uses `getBooleanContents(i8)` = ZeroOrOne on X86, so `-1` is "not true". The compress comes from X86 `ReplaceNodeResults` CTLZ (i512 half of `ExpandIntRes_CTLZ`).

**Possible Proposed fix**
Mask elements are i1: test only bit 0.
```diff
-      if (TLI.isConstTrueVal(MaskI)) {
+      if (MaskI->getAsAPIntVal()[0]) {
```

**Reduced IR**
```llvm
target triple = "x86_64-unknown-linux-gnu"
define i32 @b(i16 %x) #0 {
  %o = or i16 %x, 1
  %z = zext i16 %o to i1024
  %s = shl i1024 %z, 511
  %c = call i1024 @llvm.ctlz.i1024(i1024 %s, i1 true)
  %t = trunc i1024 %c to i32
  ret i32 %t
}
declare i1024 @llvm.ctlz.i1024(i1024, i1)
attributes #0 = { noinline "target-cpu"="znver4" }
```
`llc -O2` on this IR: `@b(0)` returns 0; the right value is 512. It is right with `-mattr=-avx512cd`.

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to