[llvm] [ConstantFolding] Fold vector.partial.reduce.add constants (PR #212112)

Simon Pilgrim via llvm-commits llvm-commits at lists.llvm.org
Thu Sep 10 06:15:56 PDT 2026


================
@@ -2413,6 +2396,53 @@ Constant *constantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) {
   return ConstantInt::get(Op->getContext(), Acc);
 }
 
+/// Fold a vector partial reduction add using the deterministic grouping
+/// chosen by TargetLowering::expandPartialReduceMLA. Although the
+/// LangRef leaves the grouping unspecified, input element I is accumulated
+/// into result lane I % NumAccElts, with each accumulator element seeding
+/// its corresponding result lane. Returns nullptr if any element cannot be
+/// folded.
+static Constant *constantFoldVectorPartialReduceAdd(Constant *Acc,
+                                                    Constant *Input,
+                                                    const DataLayout &DL) {
+  auto *AccTy = cast<FixedVectorType>(Acc->getType());
+  // A fixed result type does not guarantee a fixed input type.
+  auto *InputTy = dyn_cast<FixedVectorType>(Input->getType());
+  if (!InputTy)
+    return nullptr;
+
+  unsigned NumAccElts = AccTy->getNumElements();
+  unsigned NumInputElts = InputTy->getNumElements();
+
+  SmallVector<Constant *> ResultElts;
+  ResultElts.reserve(NumAccElts);
----------------
RKSimon wrote:

reserve isn't necessary as we know the target size:
```
SmallVector<Constant *> ResultElts(NumAccElts);
for (unsigned I = 0; I < NumAccElts; ++I) {
  ResultElts[I] = Acc->getAggregateElement(I);
  if (!ResultElts[I])
    return nullptr;
}
```

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


More information about the llvm-commits mailing list