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

[InstCombine] Missed folds for equality comparisons of `x & -x`

Open ChrisLee02 opened this issue 4 months ago • 0 comments

InstCombine already recognizes x & -x in foldICmpAndConstant() for sign-bit comparisons. x & -x isolates the lowest set bit of x, but the following equality folds are currently missed:

define i1 @src_eq_zero(i8 %x) {
  %neg = sub i8 0, %x
  %lowbit = and i8 %x, %neg
  %r = icmp eq i8 %lowbit, 0
  ret i1 %r
}

define i1 @tgt_eq_zero(i8 %x) {
  %r = icmp eq i8 %x, 0
  ret i1 %r
}
define i1 @src_ne_zero(i8 %x) {
  %neg = sub i8 0, %x
  %lowbit = and i8 %x, %neg
  %r = icmp ne i8 %lowbit, 0
  ret i1 %r
}

define i1 @tgt_ne_zero(i8 %x) {
  %r = icmp ne i8 %x, 0
  ret i1 %r
}
define i1 @src_eq_one(i8 %x) {
  %neg = sub i8 0, %x
  %lowbit = and i8 %x, %neg
  %r = icmp eq i8 %lowbit, 1
  ret i1 %r
}

define i1 @tgt_eq_one(i8 %x) {
  %r = trunc i8 %x to i1
  ret i1 %r
}
define i1 @src_ne_one(i8 %x) {
  %neg = sub i8 0, %x
  %lowbit = and i8 %x, %neg
  %r = icmp ne i8 %lowbit, 1
  ret i1 %r
}

define i1 @tgt_ne_one(i8 %x) {
  %lsb = trunc i8 %x to i1
  %r = xor i1 %lsb, true
  ret i1 %r
}

The same folds are missed for scalar iN types where N > 1; this was reproduced with i8, i32, and i64 on current LLVM trunk.

Alive2: https://alive2.llvm.org/ce/z/Zwy2hW

ChrisLee02 avatar Aug 03 '26 16:08 ChrisLee02