[InstCombine] Missed low-bit mask comparison fold through subtraction-to-zero
InstCombine misses an unsigned comparison simplification when x == (x & mask) is expressed as a wrapping subtraction followed by comparison against zero.
For a contiguous low-bit mask, the following expressions are equivalent:
(x - (x & mask)) == 0
x == (x & mask)
x <=u mask
The existing upstream test [src_is_mask_or](https://github.com/llvm/llvm-project/blob/8b5ece820daa3736362ce4144d79b3b586978592/llvm/test/Transforms/InstCombine/icmp-and-lowbit-mask.ll) simplifies to icmp ule, but the input below does not recover this form under InstCombine or O2.
Input Program
repro.ll
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
%and = and i8 %mask, %x
%mut.difference = sub i8 %x, %and
%mut.eqzero = icmp eq i8 %mut.difference, 0
ret i1 %mut.eqzero
}
Actual Result
After default<O2>, LLVM retains:
%x = xor i8 %x_in, 122
%my = lshr i8 -1, %y
%1 = and i8 %my, 6
%mask.not = xor i8 %1, -2
%mut.difference = and i8 %mask.not, %x
%mut.eqzero = icmp eq i8 %mut.difference, 0
ret i1 %mut.eqzero
Expected Result
The input can be simplified to the same form as the upstream test:
%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.
The subtraction has no overflow flags, so its equality-to-zero test preserves the original equality semantics. The shift's poison behavior is also preserved.
Command
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) - Release build with assertions enabled
- Default target:
x86_64-unknown-linux-gnu - No explicit target triple in the input
Hi, I think the optimization:
(((x_in ^ 123) - (((-1 >>u y) & 7) & (x_in ^ 123))) == 0)
=>
((x_in ^ 123) <=_u ((-1 >>u y) & 7))
can be generalized to:
((C2 & (C2 + 1)) == 0) |=
(((x_in ^ C1) - (((-1 >>u y) & C2) & (x_in ^ C1))) == 0)
=>
((x_in ^ C1) <=_u ((-1 >>u y) & C2))
https://alive2.llvm.org/ce/z/ud5WSK