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

[InstCombine] Missed low-bit mask comparison fold with De Morgan expression

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

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) 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

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:

%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:

%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

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)))
  =>
  ((x_in ^ 123) <=_u ((-1 >>u y) & 7))

can be generalized to:

(((C2 & (C2 + 1)) == 0) && (((C2 & C3) & ((C2 & C3) + 1)) == 0)) |=
  (x == ~(~((C2 >>u y) & C3) | ~x))
  =>
  (x <=_u ((C2 >>u y) & C3))

https://alive2.llvm.org/ce/z/BpPnFY

hiandgodblessyou avatar Nov 04 '26 01:11 hiandgodblessyou