[llvm] [InstCombine] Add optimization to combine adds through zext nneg, and add testcase (PR #157723)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Fri Sep 19 08:38:03 PDT 2025


================
@@ -1910,6 +1910,33 @@ Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
   if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
     return Res;
 
+  {
+    Value *X;
+    const APInt *C1, *C2;
+    if (match(&I, m_c_Add(m_NNegZExt(m_Add(m_Value(X), m_APInt(C1))),
+                          m_APInt(C2)))) {
+      // Check if inner constant C1 is negative C1 < 0 and outer constant C2 >=
+      // 0
+      if (!C1->isNegative() || C2->isNegative())
+        return nullptr;
+
+      APInt Sum = C1->sext(C2->getBitWidth()) + *C2;
+      APInt newSum = Sum.trunc(C1->getBitWidth());
+
+      if (newSum.sext(C2->getBitWidth()) != Sum)
+        return nullptr;
+
+      // X if sum is zero, else X + newSum
+      Value *Inner =
+          Sum.isZero()
+              ? X
+              : Builder.CreateAdd(X, ConstantInt::get(X->getType(), newSum));
+
+      Value *NewZExt = Builder.CreateZExt(Inner, I.getType());
+      return replaceInstUsesWith(I, NewZExt);
----------------
dtcxzyw wrote:

```suggestion
      return new ZExtInst(Inner, I.getType());
```

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


More information about the llvm-commits mailing list