[llvm] [VPlan] Expand negated add operands as a subtract in VPSCEVExpander. (PR #215253)

Ramkumar Ramachandra via llvm-commits llvm-commits at lists.llvm.org
Tue Aug 11 13:02:18 PDT 2026


================
@@ -894,24 +894,44 @@ VPValue *VPSCEVExpander::tryToExpand(const SCEV *S) {
 
     bool IsAdd = isa<SCEVAddExpr>(S);
     unsigned Opcode = IsAdd ? Instruction::Add : Instruction::Mul;
-    // Iterate in reverse so that constants are emitted last. For adds, sort
-    // non-constant-negative operands last, matching SCEVExpander's LoopCompare,
-    // so that they are accumulated into the result rather than starting it.
+    // Non-constant-negative add operands are expanded negated and subtracted
+    // from the running result below, instead of being negated and added.
+    auto UseSubtract = [IsAdd](const SCEV *Op) {
+      return IsAdd && Op->isNonConstantNegative();
+    };
+    // Iterate in reverse so that constants are emitted last, and move the
+    // subtracted operands last, matching SCEVExpander's LoopCompare, so that
+    // they don't start the running result.
     SmallVector<const SCEV *, 2> SCEVOps(reverse(NAry->operands()));
-    if (IsAdd)
-      stable_sort(SCEVOps, [](const SCEV *L, const SCEV *R) {
-        return !L->isNonConstantNegative() && R->isNonConstantNegative();
+    if (IsAdd) {
+      stable_sort(SCEVOps, [&](const SCEV *L, const SCEV *R) {
+        return !UseSubtract(L) && UseSubtract(R);
       });
+    }
----------------
artagnon wrote:

Maybe the best thing to do would be to separate the Add and Mul cases? It's very minor duplication, but we'll get a lot more clarity in return?

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


More information about the llvm-commits mailing list