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

[InstCombine] Missed fold `ashr((zext (xor X, C)) - 1, 31)` to `sext(X == C)`

Open wimmings opened this issue 2 months ago • 1 comments

Summary

InstCombine does not currently fold the following all-ones equality-mask idiom for a nonzero i8 constant:

define i32 @src(i8 %x) {
entry:
  %xor = xor i8 %x, 3
  %zext = zext i8 %xor to i32
  %sub = add nsw i32 %zext, -1
  %mask = ashr i32 %sub, 31
  ret i32 %mask
}

This can be folded to:

define i32 @tgt(i8 %x) {
entry:
  %eq = icmp eq i8 %x, 3
  %mask = sext i1 %eq to i32
  ret i32 %mask
}

In general, for a nonzero i8 integer constant C:

ashr (add nsw (zext (xor i8 X, C) to i32), -1), 31
  -> sext (icmp eq i8 X, C) to i32

For the initial fold, this report focuses on the scalar i8-to-i32 form with a nonzero integer literal C. Other integer widths, vectors, and non-literal values are out of scope.

Reasoning

X xor C is zero exactly when X == C. Zero-extension places the intermediate value in [0, 255], so subtracting one produces a value in [-1, 254] without signed overflow. The result is negative only when X == C, and arithmetic shift right by 31 therefore produces -1 for the equality case and 0 otherwise. This is exactly the result of sign-extending the i1 equality comparison to i32.

If X is poison, both forms propagate poison to the result, so the replacement does not introduce new defined behavior or remove existing poison behavior.

The proposed form removes two intermediate IR operations and exposes the equality predicate directly.

Verification

  • Current LLVM trunk reproducer: https://godbolt.org/z/4zM1d89n4
  • Alive2 correctness proof: https://alive2.llvm.org/ce/z/Ff8C2q
  • AArch64 code generation and llvm-mca results: https://compiler-explorer.com/z/5sechMWMh

cc @ParkHanbum

wimmings avatar Sep 30 '26 15:09 wimmings

@ParkHanbum I’d like to work on this issue

wimmings avatar Sep 30 '26 15:09 wimmings