Issue 234429
Summary [InstCombine] Miscompilation where the ceiling-log2 idiom fold ignores non-power-of-two widths
Labels new issue
Assignees
Reporter sairam2661
    **Fuzzer Generated Test**
**Reproducer**
https://alive2.llvm.org/ce/z/Scrck8

**Test Commit**
[e633c7da8ff144a11b3d875956fbaea06b969070](https://github.com/llvm/llvm-project/commit/e633c7da8ff144a11b3d875956fbaea06b969070)

**Description**
Since `ctlz(x) ^ (BW - 1)` is `BW - 1 - ctlz(x)` for power-of-two widths, InstCombine (`visitAdd`, the `log2_ceil` from #76661) rewrites `(ctlz(x, true) ^ (BW - 1)) + zext(ctpop(x) >u 1)` to `BW - ctlz(x - 1)`, but it only checks that the xor constant is `BW - 1`, so on `i33` it returns 1 for `%x = 2` where the source returns 63.

**Steps to reproduce**
- Minimized test case (src), `input.ll`

```llvm
define i33 @f(i33 %x) {
  %ctlz = call i33 @llvm.ctlz.i33(i33 %x, i1 true)
  %xor = xor i33 %ctlz, 32
  %ctpop = call i33 @llvm.ctpop.i33(i33 %x)
  %cmp = icmp ugt i33 %ctpop, 1
  %zext = zext i1 %cmp to i33
  %r = add i33 %xor, %zext
  ret i33 %r
}
```

- InstCombine output (tgt), `output.ll`

```llvm
define i33 @f(i33 %x) {
 %1 = add i33 %x, -1
  %2 = call range(i33 0, 34) i33 @llvm.ctlz.i33(i33 %1, i1 false)
  %r = sub nuw nsw i33 33, %2
  ret i33 %r
}

declare i33 @llvm.ctlz.i33(i33, i1 immarg)

declare i33 @llvm.ctpop.i33(i33)
```

**Output**

```
define i33 @f(i33 %x) {
#0:
  %ctlz = ctlz i33 %x, 1
  %xor = xor i33 %ctlz, 32
  %ctpop = ctpop i33 %x
  %cmp = icmp ugt i33 %ctpop, 1
  %zext = zext i1 %cmp to i33
  %r = add i33 %xor, %zext
  ret i33 %r
}
=>
define i33 @f(i33 %x) {
#0:
  %#1 = add i33 %x, 8589934591
  %#2 = ctlz i33 %#1, 0
 %#range_0_%#2 = !range i33 %#2, i33 0, i33 34
  %r = sub nsw nuw i33 33, %#range_0_%#2
  ret i33 %r
}
Transformation doesn't verify!

ERROR: Value mismatch

Example:
i33 %x = #x000000002 (2)

Source:
i33 %ctlz = #x00000001f (31)
i33 %xor = #x00000003f (63)
i33 %ctpop = #x000000001 (1)
i1 %cmp = #x0 (0)
i33 %zext = #x000000000 (0)
i33 %r = #x00000003f (63)

Target:
i33 %#1 = #x000000001 (1)
i33 %#2 = #x000000020 (32)
i33 %#range_0_%#2 = #x000000020 (32)
i33 %r = #x000000001 (1)
Source value: #x00000003f (63)
Target value: #x000000001 (1)

Summary:
  0 correct transformations
  1 incorrect transformations
  0 failed-to-prove transformations
  0 Alive2 errors
```

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

Reply via email to