[llvm] [InstCombine] Fold trunc(umin/umax(zext(x), y & mask)) to narrower umin/umax (PR #173221)

via llvm-commits llvm-commits at lists.llvm.org
Sat Dec 27 03:25:11 PST 2025


================
@@ -122,6 +125,19 @@ static Value *EvaluateInDifferentTypeImpl(Value *V, Type *Ty, bool isSigned,
         Res = CallInst::Create(Fn->getFunctionType(), Fn);
         break;
       }
+      case Intrinsic::umin:
+      case Intrinsic::umax: {
+        Value *LHS = IC.InsertNewInstWith(
+            CastInst::CreateIntegerCast(I->getOperand(0), Ty, isSigned),
+            I->getIterator());
----------------
Xinlong-Wu wrote:

Yeah, I've done the same thing as you suggested (using `EvaluateInDifferentTypeImpl`), but I found it doesn't work for the case mentioned in issue:
```
define i16 @umin(i32 %arg1, i32 %arg2, ptr %arg0) {
  %v0 = udiv i32 %arg2, %arg1
  %v1 = load i16, ptr %arg0, align 2
  %v2 = and i32 %v0, 65535
  %v3 = zext i16 %v1 to i32
  %v4 = call i32 @llvm.umin.i32(i32 %v2, i32 %v3)
  %v5 = trunc nuw i32 %v4 to i16
  ret i16 %v5
}
```
The issue is that the standard recursive approach (canEvaluateTruncatedImpl + EvaluateInDifferentTypeImpl) requires the entire operand chain to be narrowable. In this case:

- `%v2 = and i32 %v0, 65535`: recursively checks `udiv`
- `%v0 = udiv i32 %arg2, %arg1`: cannot be narrowed since arguments have unknown high bits

So using `&&` with `canEvaluateTruncatedImpl` would return false, and the optimization would never trigger.
(That explains my changes at https://github.com/llvm/llvm-project/pull/173221/files#diff-f58c914c06010d2cd2c1359514ce9b8a4170e8c214eb52dd49ef5b17d391950eR641)

Further more, it will crash if we narrow this operand chain by calling `EvaluateInDifferentTypeImpl` recursively with same reason.

However, this transformation is valid because:
Both operands of umin have their high bits known to be zero (and with 65535, zext from i16)
We can safely insert trunc for each operand, even if they can't be recursively narrowed

See Alive2 proof: https://alive2.llvm.org/ce/z/taBhYJ

My approach:

In `canEvaluateTruncatedPred`: return true if high bits of all operands are zero (via MaskedValueIsZero), and at least one operand can be recursively narrowed (to ensure we make progress)
In `EvaluateInDifferentTypeImpl`: insert trunc directly for operands that can't be recursively narrowed, and let subsequent InstCombine iterations clean up redundant operations

Hope this explanation would make sence to you. 

https://github.com/llvm/llvm-project/pull/173221


More information about the llvm-commits mailing list