Issue 238372
Summary [InstCombine] Missed low-bit mask comparison fold with De Morgan _expression_
Labels new issue
Assignees
Reporter maple-syntax
    InstCombine fails to simplify an equality comparison involving a contiguous low-bit mask.

For valid shift amounts, `(0xff >> y) & 7` is a contiguous low-bit mask, so `x == (x & mask)` is equivalent to `x <=u mask`.

The upstream test [`[src_is_mask_or](https://github.com/llvm/llvm-project/blob/8b5ece820daa3736362ce4144d79b3b586978592/llvm/test/Transforms/InstCombine/icmp-and-lowbit-mask.ll)`](https://github.com/llvm/llvm-project/blob/8b5ece820daa3736362ce4144d79b3b586978592/llvm/test/Transforms/InstCombine/icmp-and-lowbit-mask.ll) already simplifies this pattern to `icmp ule`. However, the equivalent input below retains additional bitwise operations and an equality comparison under both InstCombine and O2.

### Input Program

**repro.ll**

```llvm
define i1 @src_is_mask_or(i8 %x_in, i8 %y) {
  %x = xor i8 %x_in, 123
  %my = lshr i8 -1, %y
  %mask = and i8 %my, 7
  %mut.not = xor i8 %mask, -1
  %mut.not1 = xor i8 %x, -1
  %mut.or = or i8 %mut.not, %mut.not1
  %mut.not2 = xor i8 %mut.or, -1
  %r = icmp eq i8 %x, %mut.not2
  ret i1 %r
}
```

### Actual Result

After `default<O2>`, LLVM retains:

```llvm
%my = lshr i8 -1, %y
%1 = and i8 %x_in, 7
%2 = xor i8 %1, 3
%mut.not2 = and i8 %2, %my
%3 = xor i8 %mut.not2, %x_in
%r = icmp eq i8 %3, 123
ret i1 %r
```

### Expected Result

Since `~(~mask | ~x) == mask & x`, the input can use the same unsigned comparison as the upstream test:

```llvm
%my = lshr i8 -1, %y
%mask = and i8 %my, 7
%1 = xor i8 %x_in, 123
%r = icmp ule i8 %1, %mask
ret i1 %r
```

This reduces six computational IR instructions to four while preserving the original semantics, including poison propagation.

### Command

```bash
opt -passes=verify -disable-output repro.ll
opt -S -passes=instcombine repro.ll -o -
opt -S -passes='default<O2>' repro.ll -o -
```

### LLVM Version

- LLVM `24.0.0git`
- Commit: [`[8b5ece820daa3736362ce4144d79b3b586978592](https://github.com/llvm/llvm-project/commit/8b5ece820daa3736362ce4144d79b3b586978592)`](https://github.com/llvm/llvm-project/commit/8b5ece820daa3736362ce4144d79b3b586978592)
- Release build with assertions enabled
- Default target: `x86_64-unknown-linux-gnu`
- No explicit target triple in the input
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to