[llvm] [X86] Fold generic ADD/SUB with constants to X86ISD::SUB/ADD (PR #164316)

Simon Pilgrim via llvm-commits llvm-commits at lists.llvm.org
Thu Oct 23 03:10:59 PDT 2025


================
@@ -57631,8 +57631,25 @@ static SDValue combineX86AddSub(SDNode *N, SelectionDAG &DAG,
       DCI.CombineTo(GenericAddSub, Op);
     }
   };
-  MatchGeneric(LHS, RHS, false);
-  MatchGeneric(RHS, LHS, X86ISD::SUB == N->getOpcode());
+  MatchGeneric(GenericOpc, LHS, RHS, false);
+  MatchGeneric(GenericOpc, RHS, LHS, X86ISD::SUB == N->getOpcode());
+
+  if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(RHS)) {
+    SDValue NegC = DAG.getConstant(-Const->getAPIntValue(), DL, VT);
+    if (X86ISD::SUB == N->getOpcode()) {
+      // Fold generic add(LHS, -C) to X86ISD::SUB(LHS, C).
+      MatchGeneric(ISD::ADD, LHS, NegC, false);
+    } else {
+      // Negate X86ISD::ADD(LHS, C) and replace generic sub(-C, LHS).
+      MatchGeneric(ISD::SUB, NegC, LHS, true);
+    }
+  } else if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(LHS)) {
+    SDValue NegC = DAG.getConstant(-Const->getAPIntValue(), DL, VT);
----------------
RKSimon wrote:

Move this inside the `if (X86ISD::SUB == N->getOpcode())` case - just to avoid unnecessary DAG node creation

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


More information about the llvm-commits mailing list