[llvm] [InstCombine] Optimize sub(sext(add(x, y)), sext(add(x, z))). (PR #144174)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Fri Jun 13 22:20:19 PDT 2025


================
@@ -2807,6 +2807,56 @@ Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
   if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
     return Res;
 
+  // (sub[ nsw][ nuw] (sext (add nsw (X, Y)), sext (X))) --> (sext (Y))
+  {
+    Value *Add0;
+    if (match(Op1, m_SExt(m_Value(X))) && match(Op0, m_SExt(m_Value(Add0))) &&
+        match(Add0, m_c_NSWAdd(m_Specific(X), m_Value(Y)))) {
+      // Non-constant Y requires new SExt.
+      unsigned NumOfNewInstrs = !isa<Constant>(Y) ? 1 : 0;
+      // Check if we can trade some of the old instructions for the new ones.
+      unsigned NumOfDeadInstrs = 0;
+      NumOfDeadInstrs += Op0->hasOneUse() ? 1 : 0;
+      NumOfDeadInstrs += Op1->hasOneUse() ? 1 : 0;
+      NumOfDeadInstrs += Add0->hasOneUse() ? 1 : 0;
+      if (NumOfDeadInstrs >= NumOfNewInstrs) {
+        Value *SExtY = Builder.CreateSExt(Y, I.getType());
+        return replaceInstUsesWith(I, SExtY);
----------------
dtcxzyw wrote:

It is always profitable since the sub instruction will be eliminated.


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


More information about the llvm-commits mailing list