Issue 233232
Summary [InstCombine] `ctlz(X) ^ (BW-1)` -> `cttz(X)` for power-of-two `X` is wrong when the bit width is not a power of two
Labels miscompilation, llvm:instcombine, generated by fuzzer
Assignees
Reporter ChoKyuWon
    ### reproducer
godbolt: https://godbolt.org/z/7zn61PrW4
alive: https://alive2.llvm.org/ce/z/6M47X9

```llvm
define i24 @g(i24 %x) {
 %neg = sub i24 0, %x
  %p = and i24 %x, %neg
  %c = call i24 @llvm.ctlz.i24(i24 %p, i1 true)
  %r = xor i24 %c, 23
  ret i24 %r
}
```

```console
$ opt -passes=instcombine -S repro.ll
define i24 @g(i24 %x) {
  %r = call range(i24 0, 25) i24 @llvm.cttz.i24(i24 %x, i1 true)
  ret i24 %r
}

$ alive-tv --disable-undef-input --disable-poison-input --passes=instcombine repro.ll
ERROR: Value mismatch
Example:
i24 %x = #x244000 (2375680)
Source:
i24 %p = #x004000 (16384)
i24 %c = #x000009 (9)
i24 %r = #x00001e (30)
Source value: #x00001e (30)
Target value: #x00000e (14)
```

### suggested fix
The ctlz/cttz swap in `InstCombinerImpl::visitXor` (InstCombineAndOrXor.cpp) for `*RHSC == BW - 1` relies on `k ^ (BW-1) == BW-1-k`, which holds only when `BW-1` is all ones.
Add `isPowerOf2_32(Ty->getScalarSizeInBits())` to that guard; it covers both the ctlz->cttz and cttz->ctlz arms (the select form of this idiom got the same guard in #200583).

> Disclaimer: This test case was generated by a fuzzer, and the report was written with LLM assistance.

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

Reply via email to