[llvm] [InstCombine] Fold `A == MIN_INT ? MAX_INT : 0 - A` to `ssub_sat 0, A` (PR #194519)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Sat May 2 03:07:20 PDT 2026


================
@@ -1104,6 +1104,49 @@ static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
   return Result;
 }
 
+static Value *
+canonicalizeSaturatedSubtractSigned(const ICmpInst *ICI, const Value *TrueVal,
+                                    const Value *FalseVal,
+                                    InstCombiner::BuilderTy &Builder) {
+  ICmpInst::Predicate Pred = ICI->getPredicate();
+  Value *CmpLHS = ICI->getOperand(0);
+  Value *CmpRHS = ICI->getOperand(1);
+
+  // `A != B ? X : Y` --> `A == B ? Y : X`
+  // This canonicalization allows us to handle more patterns with fewer checks.
+  if (Pred == ICmpInst::ICMP_NE) {
+    Pred = ICmpInst::getInversePredicate(Pred);
+    std::swap(TrueVal, FalseVal);
+  }
+
+  if (Pred == ICmpInst::ICMP_EQ) {
+    // `A == MIN_INT ? MAX_INT : 0 - A` --> `ssub_sat 0, A`
+    if (match(CmpRHS, m_SignMask()) && match(TrueVal, m_MaxSignedValue()) &&
----------------
dtcxzyw wrote:

```suggestion
  // `A == MIN_INT ? MAX_INT : 0 - A` --> `ssub_sat 0, A`
  if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_SignMask()) && match(TrueVal, m_MaxSignedValue()) &&
```

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


More information about the llvm-commits mailing list