[llvm] [LV][AArch64] Provide option to use partial reductions by default (PR #216001)

Graham Hunter via llvm-commits llvm-commits at lists.llvm.org
Wed Aug 26 03:18:32 PDT 2026


https://github.com/huntergr-arm updated https://github.com/llvm/llvm-project/pull/216001

>From 10f2bdec5dd05bc45d14714496bb8f9a68a97c20 Mon Sep 17 00:00:00 2001
From: Graham Hunter <graham.hunter at arm.com>
Date: Wed, 12 Aug 2026 13:12:12 +0000
Subject: [PATCH 1/4] [LV][AArch64] Provide option to use partial reductions by
 default

Partial reduction intrinsics are explicitly unordered, which may
allow us to perform extra optimizations that may result in a different
ordering of lanes within a vector. This would only be done if
the target indicated the intrinsic was at least as cheap as the
normal accumulation operation.

Off by default to start with.
---
 .../AArch64/AArch64TargetTransformInfo.cpp    | 18 ++++-
 llvm/lib/Transforms/Vectorize/VPlan.h         |  4 +-
 .../Transforms/Vectorize/VPlanTransforms.cpp  | 66 +++++++++++++++++--
 .../Transforms/Vectorize/VPlanTransforms.h    |  7 +-
 4 files changed, 83 insertions(+), 12 deletions(-)

diff --git a/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp b/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp
index 46d2ecfde484e..10ee10822f826 100644
--- a/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp
@@ -6684,10 +6684,24 @@ InstructionCost AArch64TTIImpl::getPartialReductionCost(
     return Invalid;
 
   if ((Opcode != Instruction::Add && Opcode != Instruction::Sub &&
-       Opcode != Instruction::FAdd && Opcode != Instruction::FSub) ||
-      OpAExtend == TTI::PR_None)
+       Opcode != Instruction::FAdd && Opcode != Instruction::FSub))
     return Invalid;
 
+  // If none of the operands are extended and there's no extra BinOp, just
+  // cost this as the equivalent arithmetic instruction.
+  // TODO: Depending on VF and element type, we may be able to improve on this.
+  if (OpAExtend == TTI::PR_None) {
+    if (OpBExtend != TTI::PR_None || BinOp)
+      return Invalid;
+
+    assert(InputTypeA == InputTypeB && InputTypeA == AccumType &&
+           "Type mismatch with no extensions.");
+
+    VectorType *VTy = VectorType::get(AccumType, VF);
+
+    return getArithmeticInstrCost(Opcode, VTy, CostKind);
+  }
+
   // Floating-point partial reductions are invalid if `reassoc` and `contract`
   // are not allowed.
   if (AccumType->isFloatingPointTy()) {
diff --git a/llvm/lib/Transforms/Vectorize/VPlan.h b/llvm/lib/Transforms/Vectorize/VPlan.h
index fe1342e4309ab..9d13d51526e4c 100644
--- a/llvm/lib/Transforms/Vectorize/VPlan.h
+++ b/llvm/lib/Transforms/Vectorize/VPlan.h
@@ -3323,7 +3323,9 @@ class LLVM_ABI_FOR_TEST VPReductionRecipe : public VPRecipeWithIRFlags {
   /// Return true if the in-loop reduction is conditional.
   bool isConditional() const { return IsConditional; };
   /// Returns true if the reduction outputs a vector with a scaled down VF.
-  bool isPartialReduction() const { return getVFScaleFactor() > 1; }
+  bool isPartialReduction() const {
+    return std::holds_alternative<RdxUnordered>(Style);
+  }
   /// Returns true if the reduction is in-loop.
   bool isInLoop() const {
     return std::holds_alternative<RdxInLoop>(Style) ||
diff --git a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
index 9027846fa54f9..e7cb7e36432ff 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
@@ -36,6 +36,7 @@
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/Metadata.h"
 #include "llvm/Support/Casting.h"
+#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/TypeSize.h"
 #include "llvm/Transforms/Utils/LoopUtils.h"
 
@@ -43,6 +44,13 @@ using namespace llvm;
 using namespace VPlanPatternMatch;
 using namespace SCEVPatternMatch;
 
+
+static cl::opt<bool>
+    UsePartialReduceByDefault("use-partial-reduce-by-default", cl::init(false),
+                              cl::Hidden,
+                              cl::desc("Use partial reduction intrinsics for "
+                                       "all supported unordered reductions."));
+
 /// If the pointer operand \p Addr of a memory access is an affine AddRec
 /// w.r.t. \p L with a constant stride, return the stride in units of
 /// \p AccessTy. Otherwise return std::nullopt.
@@ -3460,8 +3468,9 @@ tryToMatchAndCreateExtendedReduction(VPReductionRecipe *Red, VPCostContext &Ctx,
   Type *RedTy = Red->getScalarType();
   VPValue *VecOp = Red->getVecOp();
 
-  assert(!Red->isPartialReduction() &&
-         "This path does not support partial reductions");
+  // We don't handle partial reductions here.
+  if (Red->isPartialReduction())
+    return nullptr;
 
   // Clamp the range if using extended-reduction is profitable.
   auto IsExtendedRedValidAndClampRange =
@@ -3514,8 +3523,10 @@ tryToMatchAndCreateMulAccumulateReduction(VPReductionRecipe *Red,
       Opcode != Instruction::FAdd)
     return nullptr;
 
-  assert(!Red->isPartialReduction() &&
-         "This path does not support partial reductions");
+  // We don't handle partial reductions here.
+  if (Red->isPartialReduction())
+    return nullptr;
+
   Type *RedTy = Red->getScalarType();
 
   // Clamp the range if using multiply-accumulate-reduction is profitable.
@@ -3679,8 +3690,8 @@ static void tryToCreateAbstractReductionRecipe(VPReductionRecipe *Red,
                                                VFRange &Range) {
   // Creation of VPExpressions for partial reductions is entirely handled in
   // transformToPartialReduction.
-  assert(!Red->isPartialReduction() &&
-         "This path does not support partial reductions");
+  if (Red->isPartialReduction())
+    return;
 
   VPExpressionRecipe *AbstractR = nullptr;
   auto IP = std::next(Red->getIterator());
@@ -5230,6 +5241,7 @@ void VPlanTransforms::createPartialReductions(VPlan &Plan,
   MapVector<VPReductionPHIRecipe *, SmallVector<VPPartialReductionChain>>
       ChainsByPhi;
   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
+  SmallVector<VPReductionPHIRecipe *, 4> UnorderedReductions;
   for (VPRecipeBase &R : HeaderVPBB->phis()) {
     auto *RedPhiR = dyn_cast<VPReductionPHIRecipe>(&R);
     if (!RedPhiR)
@@ -5237,6 +5249,48 @@ void VPlanTransforms::createPartialReductions(VPlan &Plan,
 
     if (auto Chains = getScaledReductions(RedPhiR))
       ChainsByPhi.try_emplace(RedPhiR, std::move(*Chains));
+    else if (UsePartialReduceByDefault &&
+             (RedPhiR->getRecurrenceKind() == RecurKind::Add ||
+              (RedPhiR->getRecurrenceKind() == RecurKind::FAdd &&
+               !RedPhiR->isOrdered() && !RedPhiR->isInLoop())))
+      UnorderedReductions.push_back(RedPhiR);
+  }
+
+  // For general unordered reductions which aren't part of a candidate
+  // chain for a scaled partial reduction, we can potentially still use
+  // the intrinsic to allow for more optimization later on.
+  for (auto *Rdx : UnorderedReductions) {
+    auto *Backedge = dyn_cast<VPWidenRecipe>(Rdx->getBackedgeValue());
+    VPValue *OtherOp;
+    if (!Backedge ||
+        !match(Backedge,
+               m_CombineOr(m_c_FAdd(m_Specific(Rdx), m_VPValue(OtherOp)),
+                           m_c_Add(m_Specific(Rdx), m_VPValue(OtherOp)))))
+      continue;
+
+    // If the target indicates that the intrinsic is as cheap as (or cheaper
+    // than) the add, then prefer the intrinsic.
+    if (!LoopVectorizationPlanner::getDecisionAndClampRange(
+            [&CostCtx, Rdx, Backedge](ElementCount VF) {
+              InstructionCost CurrentCost = Backedge->computeCost(VF, CostCtx);
+              Type *ScalarTy = Backedge->getScalarType();
+              InstructionCost PRCost = CostCtx.TTI.getPartialReductionCost(
+                  Backedge->getOpcode(), ScalarTy, ScalarTy, ScalarTy, VF,
+                  TTI::PR_None, TTI::PR_None, std::nullopt, CostCtx.CostKind,
+                  Rdx->getFastMathFlagsOrNone());
+              return PRCost <= CurrentCost;
+            },
+            Range))
+      continue;
+
+    auto *Partial = new VPReductionRecipe(
+        Rdx->getRecurrenceKind(), Rdx->getFastMathFlagsOrNone(),
+        Backedge->getUnderlyingInstr(), Rdx, OtherOp, nullptr,
+        getReductionStyle(/*InLoop=*/false, /*Ordered=*/false,
+                          /*ScaleFactor=*/1));
+    Partial->insertBefore(Backedge);
+    Backedge->replaceAllUsesWith(Partial);
+    Backedge->eraseFromParent();
   }
 
   if (ChainsByPhi.empty())
diff --git a/llvm/lib/Transforms/Vectorize/VPlanTransforms.h b/llvm/lib/Transforms/Vectorize/VPlanTransforms.h
index c3dd00acfe839..b99c5263c1241 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanTransforms.h
+++ b/llvm/lib/Transforms/Vectorize/VPlanTransforms.h
@@ -600,9 +600,10 @@ struct VPlanTransforms {
   static void optimizeFindIVReductions(VPlan &Plan,
                                        PredicatedScalarEvolution &PSE, Loop &L);
 
-  /// Detect and create partial reduction recipes for scaled reductions in
-  /// \p Plan. Must be called after recipe construction. If partial reductions
-  /// are only valid for a subset of VFs in Range, Range.End is updated.
+  /// Detect and create partial reduction recipes for scaled or unordered
+  /// reductions in \p Plan. Must be called after recipe construction. If
+  /// partial reductions are only valid for a subset of VFs in Range, Range.End
+  /// is updated.
   static void createPartialReductions(VPlan &Plan, VPCostContext &CostCtx,
                                       VFRange &Range);
 

>From d961be46ebe3c37e9aab2b45d3554701f56d8707 Mon Sep 17 00:00:00 2001
From: Graham Hunter <graham.hunter at arm.com>
Date: Thu, 13 Aug 2026 15:36:03 +0000
Subject: [PATCH 2/4] Add a working example to contrast

---
 .../AArch64/aarch64-predication.ll            | 44 +++++++++++++++++++
 1 file changed, 44 insertions(+)

diff --git a/llvm/test/Transforms/LoopVectorize/AArch64/aarch64-predication.ll b/llvm/test/Transforms/LoopVectorize/AArch64/aarch64-predication.ll
index d5b96fbd4ce4c..8465dffd45a84 100644
--- a/llvm/test/Transforms/LoopVectorize/AArch64/aarch64-predication.ll
+++ b/llvm/test/Transforms/LoopVectorize/AArch64/aarch64-predication.ll
@@ -2,6 +2,7 @@
 ; REQUIRES: asserts
 ; RUN: opt < %s -passes=loop-vectorize -force-vector-interleave=1 -disable-output -debug-only=loop-vectorize 2>&1 | FileCheck %s --check-prefix=COST
 ; RUN: opt < %s -passes=loop-vectorize -force-vector-interleave=1 -force-vector-width=2 -S | FileCheck %s
+; RUN: opt < %s -passes=loop-vectorize -force-vector-interleave=1 -force-vector-width=2 -use-partial-reduce-by-default -S | FileCheck %s --check-prefix=PARTIALRDX
 
 target datalayout = "e-m:e-i64:64-i128:128-n32:64-S128"
 target triple = "aarch64--linux-gnu"
@@ -58,6 +59,49 @@ define i64 @predicated_udiv_scalarized_operand(ptr %a, i64 %x) {
 ; CHECK:       [[FOR_END]]:
 ; CHECK-NEXT:    ret i64 [[TMP18]]
 ;
+; PARTIALRDX-LABEL: define i64 @predicated_udiv_scalarized_operand(
+; PARTIALRDX-SAME: ptr [[A:%.*]], i64 [[X:%.*]]) {
+; PARTIALRDX-NEXT:  [[ENTRY:.*:]]
+; PARTIALRDX-NEXT:    br label %[[VECTOR_PH:.*]]
+; PARTIALRDX:       [[VECTOR_PH]]:
+; PARTIALRDX-NEXT:    br label %[[VECTOR_BODY:.*]]
+; PARTIALRDX:       [[VECTOR_BODY]]:
+; PARTIALRDX-NEXT:    [[INDEX:%.*]] = phi i64 [ 0, %[[VECTOR_PH]] ], [ [[INDEX_NEXT:%.*]], %[[PRED_UDIV_CONTINUE2:.*]] ]
+; PARTIALRDX-NEXT:    [[VEC_PHI:%.*]] = phi <2 x i64> [ zeroinitializer, %[[VECTOR_PH]] ], [ [[PARTIAL_REDUCE:%.*]], %[[PRED_UDIV_CONTINUE2]] ]
+; PARTIALRDX-NEXT:    [[TMP0:%.*]] = getelementptr inbounds i64, ptr [[A]], i64 [[INDEX]]
+; PARTIALRDX-NEXT:    [[WIDE_LOAD:%.*]] = load <2 x i64>, ptr [[TMP0]], align 4
+; PARTIALRDX-NEXT:    [[TMP1:%.*]] = icmp sgt <2 x i64> [[WIDE_LOAD]], zeroinitializer
+; PARTIALRDX-NEXT:    [[TMP2:%.*]] = extractelement <2 x i1> [[TMP1]], i64 0
+; PARTIALRDX-NEXT:    br i1 [[TMP2]], label %[[PRED_UDIV_IF:.*]], label %[[PRED_UDIV_CONTINUE:.*]]
+; PARTIALRDX:       [[PRED_UDIV_IF]]:
+; PARTIALRDX-NEXT:    [[TMP3:%.*]] = extractelement <2 x i64> [[WIDE_LOAD]], i64 0
+; PARTIALRDX-NEXT:    [[TMP4:%.*]] = add nsw i64 [[TMP3]], [[X]]
+; PARTIALRDX-NEXT:    [[TMP5:%.*]] = udiv i64 [[TMP3]], [[TMP4]]
+; PARTIALRDX-NEXT:    [[TMP6:%.*]] = insertelement <2 x i64> poison, i64 [[TMP5]], i64 0
+; PARTIALRDX-NEXT:    br label %[[PRED_UDIV_CONTINUE]]
+; PARTIALRDX:       [[PRED_UDIV_CONTINUE]]:
+; PARTIALRDX-NEXT:    [[TMP7:%.*]] = phi <2 x i64> [ poison, %[[VECTOR_BODY]] ], [ [[TMP6]], %[[PRED_UDIV_IF]] ]
+; PARTIALRDX-NEXT:    [[TMP8:%.*]] = extractelement <2 x i1> [[TMP1]], i64 1
+; PARTIALRDX-NEXT:    br i1 [[TMP8]], label %[[PRED_UDIV_IF1:.*]], label %[[PRED_UDIV_CONTINUE2]]
+; PARTIALRDX:       [[PRED_UDIV_IF1]]:
+; PARTIALRDX-NEXT:    [[TMP9:%.*]] = extractelement <2 x i64> [[WIDE_LOAD]], i64 1
+; PARTIALRDX-NEXT:    [[TMP10:%.*]] = add nsw i64 [[TMP9]], [[X]]
+; PARTIALRDX-NEXT:    [[TMP11:%.*]] = udiv i64 [[TMP9]], [[TMP10]]
+; PARTIALRDX-NEXT:    [[TMP12:%.*]] = insertelement <2 x i64> [[TMP7]], i64 [[TMP11]], i64 1
+; PARTIALRDX-NEXT:    br label %[[PRED_UDIV_CONTINUE2]]
+; PARTIALRDX:       [[PRED_UDIV_CONTINUE2]]:
+; PARTIALRDX-NEXT:    [[TMP13:%.*]] = phi <2 x i64> [ [[TMP7]], %[[PRED_UDIV_CONTINUE]] ], [ [[TMP12]], %[[PRED_UDIV_IF1]] ]
+; PARTIALRDX-NEXT:    [[PREDPHI:%.*]] = select <2 x i1> [[TMP1]], <2 x i64> [[TMP13]], <2 x i64> [[WIDE_LOAD]]
+; PARTIALRDX-NEXT:    [[PARTIAL_REDUCE]] = call <2 x i64> @llvm.vector.partial.reduce.add.v2i64.v2i64(<2 x i64> [[VEC_PHI]], <2 x i64> [[PREDPHI]])
+; PARTIALRDX-NEXT:    [[INDEX_NEXT]] = add nuw i64 [[INDEX]], 2
+; PARTIALRDX-NEXT:    [[TMP14:%.*]] = icmp eq i64 [[INDEX_NEXT]], 100
+; PARTIALRDX-NEXT:    br i1 [[TMP14]], label %[[MIDDLE_BLOCK:.*]], label %[[VECTOR_BODY]], !llvm.loop [[LOOP0:![0-9]+]]
+; PARTIALRDX:       [[MIDDLE_BLOCK]]:
+; PARTIALRDX-NEXT:    [[TMP15:%.*]] = call i64 @llvm.vector.reduce.add.v2i64(<2 x i64> [[PARTIAL_REDUCE]])
+; PARTIALRDX-NEXT:    br label %[[FOR_END:.*]]
+; PARTIALRDX:       [[FOR_END]]:
+; PARTIALRDX-NEXT:    ret i64 [[TMP15]]
+;
 entry:
   br label %for.body
 

>From f37b81d5bb036de63ac3131d1ae28bc8e13f695e Mon Sep 17 00:00:00 2001
From: Graham Hunter <graham.hunter at arm.com>
Date: Tue, 25 Aug 2026 10:11:09 +0000
Subject: [PATCH 3/4] Fix spec crash

---
 llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp b/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp
index 10ee10822f826..e431aa8dfae18 100644
--- a/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp
@@ -6687,6 +6687,12 @@ InstructionCost AArch64TTIImpl::getPartialReductionCost(
        Opcode != Instruction::FAdd && Opcode != Instruction::FSub))
     return Invalid;
 
+  // We don't support 128b or higher element types.
+  if (InputTypeA->getScalarSizeInBits() > 64 ||
+      (InputTypeB && InputTypeB->getScalarSizeInBits() > 64) ||
+      AccumType->getScalarSizeInBits() > 64)
+    return Invalid;
+
   // If none of the operands are extended and there's no extra BinOp, just
   // cost this as the equivalent arithmetic instruction.
   // TODO: Depending on VF and element type, we may be able to improve on this.

>From a7b43ea339404356907f20eaa91feecbf1186491 Mon Sep 17 00:00:00 2001
From: Graham Hunter <graham.hunter at arm.com>
Date: Wed, 26 Aug 2026 10:08:33 +0000
Subject: [PATCH 4/4] Remove extra blank line

---
 llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
index e7cb7e36432ff..1548d574609c0 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
@@ -44,7 +44,6 @@ using namespace llvm;
 using namespace VPlanPatternMatch;
 using namespace SCEVPatternMatch;
 
-
 static cl::opt<bool>
     UsePartialReduceByDefault("use-partial-reduce-by-default", cl::init(false),
                               cl::Hidden,



More information about the llvm-commits mailing list