llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[InstCombine] Missed low-bit mask comparison fold through subtraction-to-zero

Open maple-syntax opened this issue 1 month ago • 1 comments

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

maple-syntax avatar Nov 03 '26 14:11 maple-syntax

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

hiandgodblessyou avatar Nov 04 '26 03:11 hiandgodblessyou