Skip to content

Commit 1bab8f2

Browse files
juliannagelefhahn
andauthored
[LoopUnroll] Pick changes introducing parallel reduction phis when unrolling. (#11900)
* [LoopUnroll] Add tests for unrolling loops with reductions. Add tests for unrolling loops with reductions. In some cases, multiple parallel reduction phis could be retained to improve performance. (cherry picked from commit 90f733c) * [LoopUnroll] Add additional reduction unroll tests for llvm#149470. Add additional tests from llvm#149470. (cherry picked from commit d10dc67) * [LoopUnroll] Introduce parallel reduction phis when unrolling. (llvm#149470) When partially or runtime unrolling loops with reductions, currently the reductions are performed in-order in the loop, negating most benefits from unrolling such loops. This patch extends unrolling code-gen to keep a parallel reduction phi per unrolled iteration and combining the final result after the loop. For out-of-order CPUs, this allows executing mutliple reduction chains in parallel. For now, the initial transformation is restricted to cases where we unroll a small number of iterations (hard-coded to 4, but should maybe be capped by TTI depending on the execution units), to avoid introducing an excessive amount of parallel phis. It also requires single block loops for now, where the unrolled iterations are known to not exit the loop (either due to runtime unrolling or partial unrolling). This ensures that the unrolled loop will have a single basic block, with a single exit block where we can place the final reduction value computation. The initial implementation also only supports parallelizing loops with a single reduction and only integer reductions. Those restrictions are just to keep the initial implementation simpler, and can easily be lifted as follow-ups. With corresponding TTI to the AArch64 unrolling preferences which I will also share soon, this triggers in ~300 loops across a wide range of workloads, including LLVM itself, ffmgep, av1aom, sqlite, blender, brotli, zstd and more. PR: llvm#149470 (cherry picked from commit 2d9e452) * [IVDesciptors] Support detecting reductions with vector instructions. (llvm#166353) In combination with llvm#149470 this will introduce parallel accumulators when unrolling reductions with vector instructions. See also llvm#166630, which aims to introduce parallel accumulators for FP reductions. (cherry picked from commit c73de97) * [LoopUnroll] Introduce parallel accumulators when unrolling FP reductions. (llvm#166630) This is building on top of llvm#149470, also introducing parallel accumulator PHIs when the reduction is for floating points, provided we have the reassoc flag. See also llvm#166353, which aims to introduce parallel accumulators for reductions with vector instructions. (cherry picked from commit b641509) * fixup! [LoopUnroll] Introduce parallel accumulators when unrolling FP reductions. (llvm#166630) --------- Co-authored-by: Florian Hahn <flo@fhahn.com>
1 parent 34b6b56 commit 1bab8f2

File tree

6 files changed

+1655
-2
lines changed

6 files changed

+1655
-2
lines changed

llvm/include/llvm/Transforms/Utils/UnrollLoop.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,9 @@ LLVM_ABI bool computeUnrollCount(
163163
TargetTransformInfo::UnrollingPreferences &UP,
164164
TargetTransformInfo::PeelingPreferences &PP, bool &UseUpperBound);
165165

166+
LLVM_ABI std::optional<RecurrenceDescriptor>
167+
canParallelizeReductionWhenUnrolling(PHINode &Phi, Loop *L,
168+
ScalarEvolution *SE);
166169
} // end namespace llvm
167170

168171
#endif // LLVM_TRANSFORMS_UTILS_UNROLLLOOP_H

llvm/lib/Analysis/IVDescriptors.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -268,10 +268,12 @@ bool RecurrenceDescriptor::AddReductionVar(
268268
// resulting from the type promotion performed by InstCombine. Vector
269269
// operations are not limited to the legal integer widths, so we may be able
270270
// to evaluate the reduction in the narrower width.
271-
if (RecurrenceType->isFloatingPointTy()) {
271+
// Check the scalar type to handle both scalar and vector types.
272+
Type *ScalarTy = RecurrenceType->getScalarType();
273+
if (ScalarTy->isFloatingPointTy()) {
272274
if (!isFloatingPointRecurrenceKind(Kind))
273275
return false;
274-
} else if (RecurrenceType->isIntegerTy()) {
276+
} else if (ScalarTy->isIntegerTy()) {
275277
if (!isIntegerRecurrenceKind(Kind))
276278
return false;
277279
if (!isMinMaxRecurrenceKind(Kind))

llvm/lib/Transforms/Utils/LoopUnroll.cpp

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
#include "llvm/IR/DiagnosticInfo.h"
4242
#include "llvm/IR/Dominators.h"
4343
#include "llvm/IR/Function.h"
44+
#include "llvm/IR/IRBuilder.h"
4445
#include "llvm/IR/Instruction.h"
4546
#include "llvm/IR/Instructions.h"
4647
#include "llvm/IR/IntrinsicInst.h"
@@ -108,6 +109,9 @@ UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden,
108109
#endif
109110
);
110111

112+
static cl::opt<bool> UnrollAddParallelReductions(
113+
"unroll-add-parallel-reductions", cl::init(false), cl::Hidden,
114+
cl::desc("Allow unrolling to add parallel reduction phis."));
111115

112116
/// Check if unrolling created a situation where we need to insert phi nodes to
113117
/// preserve LCSSA form.
@@ -660,6 +664,39 @@ llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
660664
OrigPHINode.push_back(cast<PHINode>(I));
661665
}
662666

667+
// Collect phi nodes for reductions for which we can introduce multiple
668+
// parallel reduction phis and compute the final reduction result after the
669+
// loop. This requires a single exit block after unrolling. This is ensured by
670+
// restricting to single-block loops where the unrolled iterations are known
671+
// to not exit.
672+
DenseMap<PHINode *, RecurrenceDescriptor> Reductions;
673+
bool CanAddAdditionalAccumulators =
674+
UnrollAddParallelReductions && !CompletelyUnroll &&
675+
L->getNumBlocks() == 1 &&
676+
(ULO.Runtime ||
677+
(ExitInfos.contains(Header) && ((ExitInfos[Header].TripCount != 0 &&
678+
ExitInfos[Header].BreakoutTrip == 0))));
679+
680+
// Limit parallelizing reductions to unroll counts of 4 or less for now.
681+
// TODO: The number of parallel reductions should depend on the number of
682+
// execution units. We also don't have to add a parallel reduction phi per
683+
// unrolled iteration, but could for example add a parallel phi for every 2
684+
// unrolled iterations.
685+
if (CanAddAdditionalAccumulators && ULO.Count <= 4) {
686+
for (PHINode &Phi : Header->phis()) {
687+
auto RdxDesc = canParallelizeReductionWhenUnrolling(Phi, L, SE);
688+
if (!RdxDesc)
689+
continue;
690+
691+
// Only handle duplicate phis for a single reduction for now.
692+
// TODO: Handle any number of reductions
693+
if (!Reductions.empty())
694+
continue;
695+
696+
Reductions[&Phi] = *RdxDesc;
697+
}
698+
}
699+
663700
std::vector<BasicBlock *> Headers;
664701
std::vector<BasicBlock *> Latches;
665702
Headers.push_back(Header);
@@ -710,6 +747,7 @@ llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
710747
// latch. This is a reasonable default placement if we don't have block
711748
// frequencies, and if we do, well the layout will be adjusted later.
712749
auto BlockInsertPt = std::next(LatchBlock->getIterator());
750+
SmallVector<Instruction *> PartialReductions;
713751
for (unsigned It = 1; It != ULO.Count; ++It) {
714752
SmallVector<BasicBlock *, 8> NewBlocks;
715753
SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
@@ -733,6 +771,31 @@ llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
733771
for (PHINode *OrigPHI : OrigPHINode) {
734772
PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
735773
Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
774+
775+
// Use cloned phis as parallel phis for partial reductions, which will
776+
// get combined to the final reduction result after the loop.
777+
if (Reductions.contains(OrigPHI)) {
778+
// Collect partial reduction results.
779+
if (PartialReductions.empty())
780+
PartialReductions.push_back(cast<Instruction>(InVal));
781+
PartialReductions.push_back(cast<Instruction>(VMap[InVal]));
782+
783+
// Update the start value for the cloned phis to use the identity
784+
// value for the reduction.
785+
const RecurrenceDescriptor &RdxDesc = Reductions[OrigPHI];
786+
NewPHI->setIncomingValueForBlock(
787+
L->getLoopPreheader(),
788+
getRecurrenceIdentity(RdxDesc.getRecurrenceKind(),
789+
OrigPHI->getType(),
790+
RdxDesc.getFastMathFlags()));
791+
792+
// Update NewPHI to use the cloned value for the iteration and move
793+
// to header.
794+
NewPHI->replaceUsesOfWith(InVal, VMap[InVal]);
795+
NewPHI->moveBefore(OrigPHI->getIterator());
796+
continue;
797+
}
798+
736799
if (Instruction *InValI = dyn_cast<Instruction>(InVal))
737800
if (It > 1 && L->contains(InValI))
738801
InVal = LastValueMap[InValI];
@@ -832,6 +895,9 @@ llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
832895
PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
833896
PN->eraseFromParent();
834897
} else if (ULO.Count > 1) {
898+
if (Reductions.contains(PN))
899+
continue;
900+
835901
Value *InVal = PN->removeIncomingValue(LatchBlock, false);
836902
// If this value was defined in the loop, take the value defined by the
837903
// last iteration of the loop.
@@ -1010,6 +1076,39 @@ llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
10101076
}
10111077
}
10121078

1079+
// If there are partial reductions, create code in the exit block to compute
1080+
// the final result and update users of the final result.
1081+
if (!PartialReductions.empty()) {
1082+
BasicBlock *ExitBlock = L->getExitBlock();
1083+
assert(ExitBlock &&
1084+
"Can only introduce parallel reduction phis with single exit block");
1085+
assert(Reductions.size() == 1 &&
1086+
"currently only a single reduction is supported");
1087+
Value *FinalRdxValue = PartialReductions.back();
1088+
Value *RdxResult = nullptr;
1089+
for (PHINode &Phi : ExitBlock->phis()) {
1090+
if (Phi.getIncomingValueForBlock(L->getLoopLatch()) != FinalRdxValue)
1091+
continue;
1092+
if (!RdxResult) {
1093+
RdxResult = PartialReductions.front();
1094+
IRBuilder Builder(ExitBlock, ExitBlock->getFirstNonPHIIt());
1095+
Builder.setFastMathFlags(Reductions.begin()->second.getFastMathFlags());
1096+
RecurKind RK = Reductions.begin()->second.getRecurrenceKind();
1097+
for (Instruction *RdxPart : drop_begin(PartialReductions)) {
1098+
RdxResult = Builder.CreateBinOp(
1099+
(Instruction::BinaryOps)RecurrenceDescriptor::getOpcode(RK),
1100+
RdxPart, RdxResult, "bin.rdx");
1101+
}
1102+
NeedToFixLCSSA = true;
1103+
for (Instruction *RdxPart : PartialReductions)
1104+
RdxPart->dropPoisonGeneratingFlags();
1105+
}
1106+
1107+
Phi.replaceAllUsesWith(RdxResult);
1108+
continue;
1109+
}
1110+
}
1111+
10131112
if (DTUToUse) {
10141113
// Apply updates to the DomTree.
10151114
DT = &DTU.getDomTree();
@@ -1111,3 +1210,42 @@ MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
11111210
}
11121211
return nullptr;
11131212
}
1213+
1214+
std::optional<RecurrenceDescriptor>
1215+
llvm::canParallelizeReductionWhenUnrolling(PHINode &Phi, Loop *L,
1216+
ScalarEvolution *SE) {
1217+
RecurrenceDescriptor RdxDesc;
1218+
if (!RecurrenceDescriptor::isReductionPHI(&Phi, L, RdxDesc,
1219+
/*DemandedBits=*/nullptr,
1220+
/*AC=*/nullptr, /*DT=*/nullptr, SE))
1221+
return std::nullopt;
1222+
RecurKind RK = RdxDesc.getRecurrenceKind();
1223+
// Skip unsupported reductions.
1224+
// TODO: Handle additional reductions, including min-max reductions.
1225+
if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RK) ||
1226+
RecurrenceDescriptor::isFindIVRecurrenceKind(RK) ||
1227+
RecurrenceDescriptor::isMinMaxRecurrenceKind(RK))
1228+
return std::nullopt;
1229+
1230+
if (RdxDesc.hasExactFPMath())
1231+
return std::nullopt;
1232+
1233+
if (RdxDesc.IntermediateStore)
1234+
return std::nullopt;
1235+
1236+
// Don't unroll reductions with constant ops; those can be folded to a
1237+
// single induction update.
1238+
if (any_of(cast<Instruction>(Phi.getIncomingValueForBlock(L->getLoopLatch()))
1239+
->operands(),
1240+
IsaPred<Constant>))
1241+
return std::nullopt;
1242+
1243+
BasicBlock *Latch = L->getLoopLatch();
1244+
if (!Latch ||
1245+
!is_contained(
1246+
cast<Instruction>(Phi.getIncomingValueForBlock(Latch))->operands(),
1247+
&Phi))
1248+
return std::nullopt;
1249+
1250+
return RdxDesc;
1251+
}

0 commit comments

Comments
 (0)