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

[InstCombine] Missed fold `uadd.sat(x, C) - C` to `umin(x, umax - C)`

Open wimmings opened this issue 3 months ago • 1 comments

Summary

InstCombine does not currently fold unsigned saturating addition followed by subtracting the same nonzero constant:

declare i64 @llvm.uadd.sat.i64(i64, i64)

define i64 @src(i64 %x) {
entry:
  %sat = call i64 @llvm.uadd.sat.i64(i64 %x, i64 1)
  %sub = add i64 %sat, -1
  ret i64 %sub
}

This can be folded to:

declare i64 @llvm.umin.i64(i64, i64)

define i64 @tgt(i64 %x) {
entry:
  %res = call i64 @llvm.umin.i64(i64 %x, i64 -2)
  ret i64 %res
}

In general, for a nonzero unsigned constant C:

uadd.sat(X, C) - C  ->  umin(X, umax - C)

The C == 0 case already simplifies trivially.

Reasoning

A saturating add returns X + C when the addition fits, and umax when it overflows. Subtracting C then gives either X or umax - C, which is exactly umin(X, umax - C).

No additional no-wrap or range conditions are needed. The same reasoning applies element-wise to vectors when C is a constant splat.

Verification

  • Current LLVM trunk: https://godbolt.org/z/GhYGz4e5v
  • AliveProof: https://alive2.llvm.org/ce/z/Eq7PyE
  • Compiler-explorer sample & perf: https://compiler-explorer.com/z/Ea34MnMM7

wimmings avatar Aug 09 '26 14:08 wimmings

I'd like to work on this.

Bagodiya avatar Aug 09 '26 18:08 Bagodiya