[llvm] [InstCombine] Fold `(x < 2^32) & (trunc(x to i32) == 0)` into `x == 0` (PR #171195)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Tue Dec 9 09:09:23 PST 2025


dtcxzyw wrote:

> maybe can add support for trunc to a mask there?

Oh yes, we can simply handle this in `decomposeBitTestICmp`. The following patch works, but I think it should be moved into `decomposeBitTestICmp`.
```
diff --git a/llvm/lib/Analysis/CmpInstAnalysis.cpp b/llvm/lib/Analysis/CmpInstAnalysis.cpp
index a1a79e5685f8..362e7d0508a5 100644
--- a/llvm/lib/Analysis/CmpInstAnalysis.cpp
+++ b/llvm/lib/Analysis/CmpInstAnalysis.cpp
@@ -193,9 +193,25 @@ std::optional<DecomposedBitTest> llvm::decomposeBitTest(Value *Cond,
     // Don't allow pointers. Splat vectors are fine.
     if (!ICmp->getOperand(0)->getType()->isIntOrIntVectorTy())
       return std::nullopt;
-    return decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
+    if (auto Res = decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
                                 ICmp->getPredicate(), LookThruTrunc,
-                                AllowNonZeroC, DecomposeAnd);
+                                AllowNonZeroC, DecomposeAnd)) {
+      return Res;
+    }
+
+    CmpPredicate Pred;
+    Value *X;
+    const APInt *RHSC;
+    if (LookThruTrunc && match(Cond, m_ICmp(Pred, m_Trunc(m_Value(X)), 
+                               m_APInt(RHSC))) && (AllowNonZeroC || RHSC->isZero()) && ICmpInst::isEquality(Pred)) {
+      DecomposedBitTest Result;
+      Result.X = X;
+      unsigned BitWidth = X->getType()->getScalarSizeInBits();
+      Result.Mask = APInt::getLowBitsSet(BitWidth, RHSC->getBitWidth());
+      Result.C = RHSC->zext(BitWidth);
+      Result.Pred = Pred;
+      return Result;
+    }
   }
   Value *X;
   if (Cond->getType()->isIntOrIntVectorTy(1) &&

```


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


More information about the llvm-commits mailing list