1 //===-- LoopReroll.cpp - Loop rerolling pass ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass implements a simple loop reroller.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/AliasSetTracker.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/ScalarEvolutionExpander.h"
23 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Analysis/TargetLibraryInfo.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include "llvm/Transforms/Utils/LoopUtils.h"
38 #define DEBUG_TYPE "loop-reroll"
40 STATISTIC(NumRerolledLoops, "Number of rerolled loops");
42 static cl::opt<unsigned>
43 MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
44 cl::desc("The maximum increment for loop rerolling"));
46 // This loop re-rolling transformation aims to transform loops like this:
50 // for (int i = 0; i < 500; i += 3) {
57 // into a loop like this:
60 // for (int i = 0; i < 500; ++i)
64 // It does this by looking for loops that, besides the latch code, are composed
65 // of isomorphic DAGs of instructions, with each DAG rooted at some increment
66 // to the induction variable, and where each DAG is isomorphic to the DAG
67 // rooted at the induction variable (excepting the sub-DAGs which root the
68 // other induction-variable increments). In other words, we're looking for loop
69 // bodies of the form:
71 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
73 // %iv.1 = add %iv, 1 <-- a root increment
75 // %iv.2 = add %iv, 2 <-- a root increment
77 // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
80 // %iv.next = add %iv, scale
81 // %cmp = icmp(%iv, ...)
82 // br %cmp, header, exit
84 // where each f(i) is a set of instructions that, collectively, are a function
85 // only of i (and other loop-invariant values).
87 // As a special case, we can also reroll loops like this:
91 // for (int i = 0; i < 500; ++i) {
100 // void bar(int *x) {
101 // for (int i = 0; i < 1500; ++i)
105 // in which case, we're looking for inputs like this:
107 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
108 // %scaled.iv = mul %iv, scale
110 // %scaled.iv.1 = add %scaled.iv, 1
112 // %scaled.iv.2 = add %scaled.iv, 2
114 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
115 // f(%scaled.iv.scale_m_1)
117 // %iv.next = add %iv, 1
118 // %cmp = icmp(%iv, ...)
119 // br %cmp, header, exit
122 class LoopReroll : public LoopPass {
124 static char ID; // Pass ID, replacement for typeid
125 LoopReroll() : LoopPass(ID) {
126 initializeLoopRerollPass(*PassRegistry::getPassRegistry());
129 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
131 void getAnalysisUsage(AnalysisUsage &AU) const override {
132 AU.addRequired<AliasAnalysis>();
133 AU.addRequired<LoopInfoWrapperPass>();
134 AU.addPreserved<LoopInfoWrapperPass>();
135 AU.addRequired<DominatorTreeWrapperPass>();
136 AU.addPreserved<DominatorTreeWrapperPass>();
137 AU.addRequired<ScalarEvolution>();
138 AU.addRequired<TargetLibraryInfoWrapperPass>();
145 const DataLayout *DL;
146 TargetLibraryInfo *TLI;
149 typedef SmallVector<Instruction *, 16> SmallInstructionVector;
150 typedef SmallSet<Instruction *, 16> SmallInstructionSet;
152 // A chain of isomorphic instructions, indentified by a single-use PHI,
153 // representing a reduction. Only the last value may be used outside the
155 struct SimpleLoopReduction {
156 SimpleLoopReduction(Instruction *P, Loop *L)
157 : Valid(false), Instructions(1, P) {
158 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
166 Instruction *getPHI() const {
167 assert(Valid && "Using invalid reduction");
168 return Instructions.front();
171 Instruction *getReducedValue() const {
172 assert(Valid && "Using invalid reduction");
173 return Instructions.back();
176 Instruction *get(size_t i) const {
177 assert(Valid && "Using invalid reduction");
178 return Instructions[i+1];
181 Instruction *operator [] (size_t i) const { return get(i); }
183 // The size, ignoring the initial PHI.
184 size_t size() const {
185 assert(Valid && "Using invalid reduction");
186 return Instructions.size()-1;
189 typedef SmallInstructionVector::iterator iterator;
190 typedef SmallInstructionVector::const_iterator const_iterator;
193 assert(Valid && "Using invalid reduction");
194 return std::next(Instructions.begin());
197 const_iterator begin() const {
198 assert(Valid && "Using invalid reduction");
199 return std::next(Instructions.begin());
202 iterator end() { return Instructions.end(); }
203 const_iterator end() const { return Instructions.end(); }
207 SmallInstructionVector Instructions;
212 // The set of all reductions, and state tracking of possible reductions
213 // during loop instruction processing.
214 struct ReductionTracker {
215 typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
217 // Add a new possible reduction.
218 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
220 // Setup to track possible reductions corresponding to the provided
221 // rerolling scale. Only reductions with a number of non-PHI instructions
222 // that is divisible by the scale are considered. Three instructions sets
224 // - A set of all possible instructions in eligible reductions.
225 // - A set of all PHIs in eligible reductions
226 // - A set of all reduced values (last instructions) in eligible
228 void restrictToScale(uint64_t Scale,
229 SmallInstructionSet &PossibleRedSet,
230 SmallInstructionSet &PossibleRedPHISet,
231 SmallInstructionSet &PossibleRedLastSet) {
232 PossibleRedIdx.clear();
233 PossibleRedIter.clear();
236 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
237 if (PossibleReds[i].size() % Scale == 0) {
238 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
239 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
241 PossibleRedSet.insert(PossibleReds[i].getPHI());
242 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
243 for (Instruction *J : PossibleReds[i]) {
244 PossibleRedSet.insert(J);
245 PossibleRedIdx[J] = i;
250 // The functions below are used while processing the loop instructions.
252 // Are the two instructions both from reductions, and furthermore, from
253 // the same reduction?
254 bool isPairInSame(Instruction *J1, Instruction *J2) {
255 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
256 if (J1I != PossibleRedIdx.end()) {
257 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
258 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
265 // The two provided instructions, the first from the base iteration, and
266 // the second from iteration i, form a matched pair. If these are part of
267 // a reduction, record that fact.
268 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
269 if (PossibleRedIdx.count(J1)) {
270 assert(PossibleRedIdx.count(J2) &&
271 "Recording reduction vs. non-reduction instruction?");
273 PossibleRedIter[J1] = 0;
274 PossibleRedIter[J2] = i;
276 int Idx = PossibleRedIdx[J1];
277 assert(Idx == PossibleRedIdx[J2] &&
278 "Recording pair from different reductions?");
283 // The functions below can be called after we've finished processing all
284 // instructions in the loop, and we know which reductions were selected.
286 // Is the provided instruction the PHI of a reduction selected for
288 bool isSelectedPHI(Instruction *J) {
289 if (!isa<PHINode>(J))
292 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
295 if (cast<Instruction>(J) == PossibleReds[i].getPHI())
302 bool validateSelected();
303 void replaceSelected();
306 // The vector of all possible reductions (for any scale).
307 SmallReductionVector PossibleReds;
309 DenseMap<Instruction *, int> PossibleRedIdx;
310 DenseMap<Instruction *, int> PossibleRedIter;
314 // The set of all DAG roots, and state tracking of all roots
315 // for a particular induction variable.
316 struct DAGRootTracker {
317 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
318 ScalarEvolution *SE, AliasAnalysis *AA,
319 TargetLibraryInfo *TLI, const DataLayout *DL)
320 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI),
324 /// Stage 1: Find all the DAG roots for the induction variable.
326 /// Stage 2: Validate if the found roots are valid.
327 bool validate(ReductionTracker &Reductions);
328 /// Stage 3: Assuming validate() returned true, perform the
330 /// @param IterCount The maximum iteration count of L.
331 void replace(const SCEV *IterCount);
334 bool findScaleFromMul();
335 bool collectAllRoots();
337 void collectInLoopUserSet(const SmallInstructionVector &Roots,
338 const SmallInstructionSet &Exclude,
339 const SmallInstructionSet &Final,
340 DenseSet<Instruction *> &Users);
341 void collectInLoopUserSet(Instruction *Root,
342 const SmallInstructionSet &Exclude,
343 const SmallInstructionSet &Final,
344 DenseSet<Instruction *> &Users);
348 // Members of Parent, replicated here for brevity.
352 TargetLibraryInfo *TLI;
353 const DataLayout *DL;
355 // The loop induction variable.
359 // Loop reroll count; if Inc == 1, this records the scaling applied
360 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
361 // If Inc is not 1, Scale = Inc.
363 // If Scale != Inc, then RealIV is IV after its multiplication.
365 // The roots themselves.
366 SmallInstructionVector Roots;
367 // All increment instructions for IV.
368 SmallInstructionVector LoopIncs;
369 // All instructions transitively used by any root.
370 DenseSet<Instruction *> AllRootUses;
371 // All instructions transitively used by the base.
372 DenseSet<Instruction *> BaseUseSet;
373 // All instructions transitively used by the increments.
374 DenseSet<Instruction *> LoopIncUseSet;
377 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
378 void collectPossibleReductions(Loop *L,
379 ReductionTracker &Reductions);
380 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
381 ReductionTracker &Reductions);
385 char LoopReroll::ID = 0;
386 INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
387 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
388 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
389 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
390 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
391 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
392 INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
394 Pass *llvm::createLoopRerollPass() {
395 return new LoopReroll;
398 // Returns true if the provided instruction is used outside the given loop.
399 // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
400 // non-loop blocks to be outside the loop.
401 static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
402 for (User *U : I->users())
403 if (!L->contains(cast<Instruction>(U)))
409 // Collect the list of loop induction variables with respect to which it might
410 // be possible to reroll the loop.
411 void LoopReroll::collectPossibleIVs(Loop *L,
412 SmallInstructionVector &PossibleIVs) {
413 BasicBlock *Header = L->getHeader();
414 for (BasicBlock::iterator I = Header->begin(),
415 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
416 if (!isa<PHINode>(I))
418 if (!I->getType()->isIntegerTy())
421 if (const SCEVAddRecExpr *PHISCEV =
422 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
423 if (PHISCEV->getLoop() != L)
425 if (!PHISCEV->isAffine())
427 if (const SCEVConstant *IncSCEV =
428 dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) {
429 if (!IncSCEV->getValue()->getValue().isStrictlyPositive())
431 if (IncSCEV->getValue()->uge(MaxInc))
434 DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " <<
436 PossibleIVs.push_back(I);
442 // Add the remainder of the reduction-variable chain to the instruction vector
443 // (the initial PHINode has already been added). If successful, the object is
445 void LoopReroll::SimpleLoopReduction::add(Loop *L) {
446 assert(!Valid && "Cannot add to an already-valid chain");
448 // The reduction variable must be a chain of single-use instructions
449 // (including the PHI), except for the last value (which is used by the PHI
450 // and also outside the loop).
451 Instruction *C = Instructions.front();
454 C = cast<Instruction>(*C->user_begin());
455 if (C->hasOneUse()) {
456 if (!C->isBinaryOp())
459 if (!(isa<PHINode>(Instructions.back()) ||
460 C->isSameOperationAs(Instructions.back())))
463 Instructions.push_back(C);
465 } while (C->hasOneUse());
467 if (Instructions.size() < 2 ||
468 !C->isSameOperationAs(Instructions.back()) ||
472 // C is now the (potential) last instruction in the reduction chain.
473 for (User *U : C->users())
474 // The only in-loop user can be the initial PHI.
475 if (L->contains(cast<Instruction>(U)))
476 if (cast<Instruction>(U) != Instructions.front())
479 Instructions.push_back(C);
483 // Collect the vector of possible reduction variables.
484 void LoopReroll::collectPossibleReductions(Loop *L,
485 ReductionTracker &Reductions) {
486 BasicBlock *Header = L->getHeader();
487 for (BasicBlock::iterator I = Header->begin(),
488 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
489 if (!isa<PHINode>(I))
491 if (!I->getType()->isSingleValueType())
494 SimpleLoopReduction SLR(I, L);
498 DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
499 SLR.size() << " chained instructions)\n");
500 Reductions.addSLR(SLR);
504 // Collect the set of all users of the provided root instruction. This set of
505 // users contains not only the direct users of the root instruction, but also
506 // all users of those users, and so on. There are two exceptions:
508 // 1. Instructions in the set of excluded instructions are never added to the
509 // use set (even if they are users). This is used, for example, to exclude
510 // including root increments in the use set of the primary IV.
512 // 2. Instructions in the set of final instructions are added to the use set
513 // if they are users, but their users are not added. This is used, for
514 // example, to prevent a reduction update from forcing all later reduction
515 // updates into the use set.
516 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
517 Instruction *Root, const SmallInstructionSet &Exclude,
518 const SmallInstructionSet &Final,
519 DenseSet<Instruction *> &Users) {
520 SmallInstructionVector Queue(1, Root);
521 while (!Queue.empty()) {
522 Instruction *I = Queue.pop_back_val();
523 if (!Users.insert(I).second)
527 for (Use &U : I->uses()) {
528 Instruction *User = cast<Instruction>(U.getUser());
529 if (PHINode *PN = dyn_cast<PHINode>(User)) {
530 // Ignore "wrap-around" uses to PHIs of this loop's header.
531 if (PN->getIncomingBlock(U) == L->getHeader())
535 if (L->contains(User) && !Exclude.count(User)) {
536 Queue.push_back(User);
540 // We also want to collect single-user "feeder" values.
541 for (User::op_iterator OI = I->op_begin(),
542 OIE = I->op_end(); OI != OIE; ++OI) {
543 if (Instruction *Op = dyn_cast<Instruction>(*OI))
544 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
551 // Collect all of the users of all of the provided root instructions (combined
552 // into a single set).
553 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
554 const SmallInstructionVector &Roots,
555 const SmallInstructionSet &Exclude,
556 const SmallInstructionSet &Final,
557 DenseSet<Instruction *> &Users) {
558 for (SmallInstructionVector::const_iterator I = Roots.begin(),
559 IE = Roots.end(); I != IE; ++I)
560 collectInLoopUserSet(*I, Exclude, Final, Users);
563 static bool isSimpleLoadStore(Instruction *I) {
564 if (LoadInst *LI = dyn_cast<LoadInst>(I))
565 return LI->isSimple();
566 if (StoreInst *SI = dyn_cast<StoreInst>(I))
567 return SI->isSimple();
568 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
569 return !MI->isVolatile();
573 bool LoopReroll::DAGRootTracker::findRoots() {
575 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(IV));
576 Inc = cast<SCEVConstant>(RealIVSCEV->getOperand(1))->
577 getValue()->getZExtValue();
579 // The effective induction variable, IV, is normally also the real induction
580 // variable. When we're dealing with a loop like:
581 // for (int i = 0; i < 500; ++i)
585 // then the real IV is still i, but the effective IV is (3*i).
588 if (Inc == 1 && !findScaleFromMul())
591 // The set of increment instructions for each increment value.
592 if (!collectAllRoots())
598 // Recognize loops that are setup like this:
600 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
601 // %scaled.iv = mul %iv, scale
603 // %scaled.iv.1 = add %scaled.iv, 1
605 // %scaled.iv.2 = add %scaled.iv, 2
607 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
608 // f(%scaled.iv.scale_m_1)
610 // %iv.next = add %iv, 1
611 // %cmp = icmp(%iv, ...)
612 // br %cmp, header, exit
614 // and, if found, set IV = %scaled.iv, and add %iv.next to LoopIncs.
615 bool LoopReroll::DAGRootTracker::findScaleFromMul() {
617 // This is a special case: here we're looking for all uses (except for
618 // the increment) to be multiplied by a common factor. The increment must
619 // be by one. This is to capture loops like:
620 // for (int i = 0; i < 500; ++i) {
621 // foo(3*i); foo(3*i+1); foo(3*i+2);
623 if (RealIV->getNumUses() != 2)
625 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(RealIV));
626 Instruction *User1 = cast<Instruction>(*RealIV->user_begin()),
627 *User2 = cast<Instruction>(*std::next(RealIV->user_begin()));
628 if (!SE->isSCEVable(User1->getType()) || !SE->isSCEVable(User2->getType()))
630 const SCEVAddRecExpr *User1SCEV =
631 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(User1)),
633 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(User2));
634 if (!User1SCEV || !User1SCEV->isAffine() ||
635 !User2SCEV || !User2SCEV->isAffine())
638 // We assume below that User1 is the scale multiply and User2 is the
639 // increment. If this can't be true, then swap them.
640 if (User1SCEV == RealIVSCEV->getPostIncExpr(*SE)) {
641 std::swap(User1, User2);
642 std::swap(User1SCEV, User2SCEV);
645 if (User2SCEV != RealIVSCEV->getPostIncExpr(*SE))
647 assert(User2SCEV->getStepRecurrence(*SE)->isOne() &&
648 "Invalid non-unit step for multiplicative scaling");
649 LoopIncs.push_back(User2);
651 if (const SCEVConstant *MulScale =
652 dyn_cast<SCEVConstant>(User1SCEV->getStepRecurrence(*SE))) {
653 // Make sure that both the start and step have the same multiplier.
654 if (RealIVSCEV->getStart()->getType() != MulScale->getType())
656 if (SE->getMulExpr(RealIVSCEV->getStart(), MulScale) !=
657 User1SCEV->getStart())
660 ConstantInt *MulScaleCI = MulScale->getValue();
661 if (!MulScaleCI->uge(2) || MulScaleCI->uge(MaxInc))
663 Scale = MulScaleCI->getZExtValue();
668 DEBUG(dbgs() << "LRR: Found possible scaling " << *User1 << "\n");
670 assert(Scale <= MaxInc && "Scale is too large");
671 assert(Scale > 1 && "Scale must be at least 2");
676 // Collect all root increments with respect to the provided induction variable
677 // (normally the PHI, but sometimes a multiply). A root increment is an
678 // instruction, normally an add, with a positive constant less than Scale. In a
679 // rerollable loop, each of these increments is the root of an instruction
680 // graph isomorphic to the others. Also, we collect the final induction
681 // increment (the increment equal to the Scale), and its users in LoopIncs.
682 bool LoopReroll::DAGRootTracker::collectAllRoots() {
683 Roots.resize(Scale-1);
685 for (User *U : IV->users()) {
686 Instruction *UI = cast<Instruction>(U);
687 if (!SE->isSCEVable(UI->getType()))
689 if (UI->getType() != IV->getType())
691 if (!L->contains(UI))
693 if (hasUsesOutsideLoop(UI, L))
696 if (const SCEVConstant *Diff = dyn_cast<SCEVConstant>(SE->getMinusSCEV(
697 SE->getSCEV(UI), SE->getSCEV(IV)))) {
698 uint64_t Idx = Diff->getValue()->getValue().getZExtValue();
699 if (Idx > 0 && Idx < Scale) {
701 // No duplicates allowed.
704 } else if (Idx == Scale && Inc > 1) {
705 LoopIncs.push_back(UI);
710 for (unsigned i = 0; i < Scale-1; ++i) {
718 bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
719 BasicBlock *Header = L->getHeader();
721 // We now need to check for equivalence of the use graph of each root with
722 // that of the primary induction variable (excluding the roots). Our goal
723 // here is not to solve the full graph isomorphism problem, but rather to
724 // catch common cases without a lot of work. As a result, we will assume
725 // that the relative order of the instructions in each unrolled iteration
726 // is the same (although we will not make an assumption about how the
727 // different iterations are intermixed). Note that while the order must be
728 // the same, the instructions may not be in the same basic block.
729 SmallInstructionSet Exclude;
730 Exclude.insert(Roots.begin(), Roots.end());
731 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
733 // An array of just the possible reductions for this scale factor. When we
734 // collect the set of all users of some root instructions, these reduction
735 // instructions are treated as 'final' (their uses are not considered).
736 // This is important because we don't want the root use set to search down
737 // the reduction chain.
738 SmallInstructionSet PossibleRedSet;
739 SmallInstructionSet PossibleRedLastSet;
740 SmallInstructionSet PossibleRedPHISet;
741 Reductions.restrictToScale(Scale, PossibleRedSet,
742 PossibleRedPHISet, PossibleRedLastSet);
745 collectInLoopUserSet(IV, Exclude, PossibleRedSet, BaseUseSet);
747 std::vector<DenseSet<Instruction *> > RootUseSets(Scale-1);
749 bool MatchFailed = false;
750 for (unsigned i = 0; i < Scale-1 && !MatchFailed; ++i) {
751 DenseSet<Instruction *> &RootUseSet = RootUseSets[i];
752 collectInLoopUserSet(Roots[i], SmallInstructionSet(),
753 PossibleRedSet, RootUseSet);
755 DEBUG(dbgs() << "LRR: base use set size: " << BaseUseSet.size() <<
756 " vs. iteration increment " << (i+1) <<
757 " use set size: " << RootUseSet.size() << "\n");
759 if (BaseUseSet.size() != RootUseSet.size()) {
764 // In addition to regular aliasing information, we need to look for
765 // instructions from later (future) iterations that have side effects
766 // preventing us from reordering them past other instructions with side
768 bool FutureSideEffects = false;
769 AliasSetTracker AST(*AA);
771 // The map between instructions in f(%iv.(i+1)) and f(%iv).
772 DenseMap<Value *, Value *> BaseMap;
774 assert(L->getNumBlocks() == 1 && "Cannot handle multi-block loops");
775 for (BasicBlock::iterator J1 = Header->begin(), J2 = Header->begin(),
776 JE = Header->end(); J1 != JE && !MatchFailed; ++J1) {
777 if (cast<Instruction>(J1) == RealIV)
779 if (cast<Instruction>(J1) == IV)
781 if (!BaseUseSet.count(J1))
783 if (PossibleRedPHISet.count(J1)) // Skip reduction PHIs.
786 while (J2 != JE && (!RootUseSet.count(J2) || Roots[i] == J2)) {
787 // As we iterate through the instructions, instructions that don't
788 // belong to previous iterations (or the base case), must belong to
789 // future iterations. We want to track the alias set of writes from
790 // previous iterations.
791 if (!isa<PHINode>(J2) && !BaseUseSet.count(J2) &&
792 !AllRootUses.count(J2)) {
793 if (J2->mayWriteToMemory())
796 // Note: This is specifically guarded by a check on isa<PHINode>,
797 // which while a valid (somewhat arbitrary) micro-optimization, is
798 // needed because otherwise isSafeToSpeculativelyExecute returns
799 // false on PHI nodes.
800 if (!isSimpleLoadStore(J2) && !isSafeToSpeculativelyExecute(J2, DL))
801 FutureSideEffects = true;
807 if (!J1->isSameOperationAs(J2)) {
808 DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
809 " vs. " << *J2 << "\n");
814 // Make sure that this instruction, which is in the use set of this
815 // root instruction, does not also belong to the base set or the set of
816 // some previous root instruction.
817 if (BaseUseSet.count(J2) || AllRootUses.count(J2)) {
818 DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
819 " vs. " << *J2 << " (prev. case overlap)\n");
824 // Make sure that we don't alias with any instruction in the alias set
825 // tracker. If we do, then we depend on a future iteration, and we
827 if (J2->mayReadFromMemory()) {
828 for (AliasSetTracker::iterator K = AST.begin(), KE = AST.end();
829 K != KE && !MatchFailed; ++K) {
830 if (K->aliasesUnknownInst(J2, *AA)) {
831 DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
832 " vs. " << *J2 << " (depends on future store)\n");
839 // If we've past an instruction from a future iteration that may have
840 // side effects, and this instruction might also, then we can't reorder
841 // them, and this matching fails. As an exception, we allow the alias
842 // set tracker to handle regular (simple) load/store dependencies.
843 if (FutureSideEffects &&
844 ((!isSimpleLoadStore(J1) &&
845 !isSafeToSpeculativelyExecute(J1, DL)) ||
846 (!isSimpleLoadStore(J2) &&
847 !isSafeToSpeculativelyExecute(J2, DL)))) {
848 DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
850 " (side effects prevent reordering)\n");
855 // For instructions that are part of a reduction, if the operation is
856 // associative, then don't bother matching the operands (because we
857 // already know that the instructions are isomorphic, and the order
858 // within the iteration does not matter). For non-associative reductions,
859 // we do need to match the operands, because we need to reject
860 // out-of-order instructions within an iteration!
861 // For example (assume floating-point addition), we need to reject this:
862 // x += a[i]; x += b[i];
863 // x += a[i+1]; x += b[i+1];
864 // x += b[i+2]; x += a[i+2];
865 bool InReduction = Reductions.isPairInSame(J1, J2);
867 if (!(InReduction && J1->isAssociative())) {
868 bool Swapped = false, SomeOpMatched = false;
869 for (unsigned j = 0; j < J1->getNumOperands() && !MatchFailed; ++j) {
870 Value *Op2 = J2->getOperand(j);
872 // If this is part of a reduction (and the operation is not
873 // associatve), then we match all operands, but not those that are
874 // part of the reduction.
876 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
877 if (Reductions.isPairInSame(J2, Op2I))
880 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
881 if (BMI != BaseMap.end())
883 else if (Roots[i] == (Instruction*) Op2)
886 if (J1->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
887 // If we've not already decided to swap the matched operands, and
888 // we've not already matched our first operand (note that we could
889 // have skipped matching the first operand because it is part of a
890 // reduction above), and the instruction is commutative, then try
891 // the swapped match.
892 if (!Swapped && J1->isCommutative() && !SomeOpMatched &&
893 J1->getOperand(!j) == Op2) {
896 DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
897 " vs. " << *J2 << " (operand " << j << ")\n");
903 SomeOpMatched = true;
907 if ((!PossibleRedLastSet.count(J1) && hasUsesOutsideLoop(J1, L)) ||
908 (!PossibleRedLastSet.count(J2) && hasUsesOutsideLoop(J2, L))) {
909 DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
910 " vs. " << *J2 << " (uses outside loop)\n");
916 BaseMap.insert(std::pair<Value *, Value *>(J2, J1));
918 AllRootUses.insert(J2);
919 Reductions.recordPair(J1, J2, i+1);
928 DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
931 collectInLoopUserSet(LoopIncs, SmallInstructionSet(),
932 SmallInstructionSet(), LoopIncUseSet);
933 DEBUG(dbgs() << "LRR: Loop increment set size: " <<
934 LoopIncUseSet.size() << "\n");
936 // Make sure that all instructions in the loop have been included in some
938 for (BasicBlock::iterator J = Header->begin(), JE = Header->end();
940 if (isa<DbgInfoIntrinsic>(J))
942 if (cast<Instruction>(J) == RealIV)
944 if (cast<Instruction>(J) == IV)
946 if (BaseUseSet.count(J) || AllRootUses.count(J) ||
947 (LoopIncUseSet.count(J) && (J->isTerminator() ||
948 isSafeToSpeculativelyExecute(J, DL))))
951 if (std::find(Roots.begin(), Roots.end(), J) != Roots.end())
954 if (Reductions.isSelectedPHI(J))
957 DEBUG(dbgs() << "LRR: aborting reroll based on " << *RealIV <<
958 " unprocessed instruction found: " << *J << "\n");
966 DEBUG(dbgs() << "LRR: all instructions processed from " <<
971 void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
972 BasicBlock *Header = L->getHeader();
973 // Remove instructions associated with non-base iterations.
974 for (BasicBlock::reverse_iterator J = Header->rbegin();
975 J != Header->rend();) {
976 if (AllRootUses.count(&*J)) {
977 Instruction *D = &*J;
978 DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
979 D->eraseFromParent();
986 // Insert the new induction variable.
987 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(RealIV));
988 const SCEV *Start = RealIVSCEV->getStart();
990 Start = SE->getMulExpr(Start,
991 SE->getConstant(Start->getType(), Scale));
992 const SCEVAddRecExpr *H =
993 cast<SCEVAddRecExpr>(SE->getAddRecExpr(Start,
994 SE->getConstant(RealIVSCEV->getType(), 1),
995 L, SCEV::FlagAnyWrap));
996 { // Limit the lifetime of SCEVExpander.
997 SCEVExpander Expander(*SE, "reroll");
998 Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
1000 for (DenseSet<Instruction *>::iterator J = BaseUseSet.begin(),
1001 JE = BaseUseSet.end(); J != JE; ++J)
1002 (*J)->replaceUsesOfWith(IV, NewIV);
1004 if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1005 if (LoopIncUseSet.count(BI)) {
1006 const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1009 SE->getMulExpr(ICSCEV, SE->getConstant(ICSCEV->getType(), Scale));
1010 // Iteration count SCEV minus 1
1011 const SCEV *ICMinus1SCEV =
1012 SE->getMinusSCEV(ICSCEV, SE->getConstant(ICSCEV->getType(), 1));
1014 Value *ICMinus1; // Iteration count minus 1
1015 if (isa<SCEVConstant>(ICMinus1SCEV)) {
1016 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
1018 BasicBlock *Preheader = L->getLoopPreheader();
1020 Preheader = InsertPreheaderForLoop(L, Parent);
1022 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(),
1023 Preheader->getTerminator());
1027 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1, "exitcond");
1028 BI->setCondition(Cond);
1030 if (BI->getSuccessor(1) != Header)
1031 BI->swapSuccessors();
1036 SimplifyInstructionsInBlock(Header, DL, TLI);
1037 DeleteDeadPHIs(Header, TLI);
1040 // Validate the selected reductions. All iterations must have an isomorphic
1041 // part of the reduction chain and, for non-associative reductions, the chain
1042 // entries must appear in order.
1043 bool LoopReroll::ReductionTracker::validateSelected() {
1044 // For a non-associative reduction, the chain entries must appear in order.
1045 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1048 int PrevIter = 0, BaseCount = 0, Count = 0;
1049 for (Instruction *J : PossibleReds[i]) {
1050 // Note that all instructions in the chain must have been found because
1051 // all instructions in the function must have been assigned to some
1053 int Iter = PossibleRedIter[J];
1054 if (Iter != PrevIter && Iter != PrevIter + 1 &&
1055 !PossibleReds[i].getReducedValue()->isAssociative()) {
1056 DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
1061 if (Iter != PrevIter) {
1062 if (Count != BaseCount) {
1063 DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1064 " reduction use count " << Count <<
1065 " is not equal to the base use count " <<
1084 // For all selected reductions, remove all parts except those in the first
1085 // iteration (and the PHI). Replace outside uses of the reduced value with uses
1086 // of the first-iteration reduced value (in other words, reroll the selected
1088 void LoopReroll::ReductionTracker::replaceSelected() {
1089 // Fixup reductions to refer to the last instruction associated with the
1090 // first iteration (not the last).
1091 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1095 for (int e = PossibleReds[i].size(); j != e; ++j)
1096 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1101 // Replace users with the new end-of-chain value.
1102 SmallInstructionVector Users;
1103 for (User *U : PossibleReds[i].getReducedValue()->users())
1104 Users.push_back(cast<Instruction>(U));
1106 for (SmallInstructionVector::iterator J = Users.begin(),
1107 JE = Users.end(); J != JE; ++J)
1108 (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1109 PossibleReds[i][j]);
1113 // Reroll the provided loop with respect to the provided induction variable.
1114 // Generally, we're looking for a loop like this:
1116 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
1118 // %iv.1 = add %iv, 1 <-- a root increment
1120 // %iv.2 = add %iv, 2 <-- a root increment
1122 // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1125 // %iv.next = add %iv, scale
1126 // %cmp = icmp(%iv, ...)
1127 // br %cmp, header, exit
1129 // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1130 // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1131 // be intermixed with eachother. The restriction imposed by this algorithm is
1132 // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1133 // etc. be the same.
1135 // First, we collect the use set of %iv, excluding the other increment roots.
1136 // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1137 // times, having collected the use set of f(%iv.(i+1)), during which we:
1138 // - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1139 // the next unmatched instruction in f(%iv.(i+1)).
1140 // - Ensure that both matched instructions don't have any external users
1141 // (with the exception of last-in-chain reduction instructions).
1142 // - Track the (aliasing) write set, and other side effects, of all
1143 // instructions that belong to future iterations that come before the matched
1144 // instructions. If the matched instructions read from that write set, then
1145 // f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1146 // f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1147 // if any of these future instructions had side effects (could not be
1148 // speculatively executed), and so do the matched instructions, when we
1149 // cannot reorder those side-effect-producing instructions, and rerolling
1152 // Finally, we make sure that all loop instructions are either loop increment
1153 // roots, belong to simple latch code, parts of validated reductions, part of
1154 // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1155 // have been validated), then we reroll the loop.
1156 bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1157 const SCEV *IterCount,
1158 ReductionTracker &Reductions) {
1159 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DL);
1161 if (!DAGRoots.findRoots())
1163 DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
1166 if (!DAGRoots.validate(Reductions))
1168 if (!Reductions.validateSelected())
1170 // At this point, we've validated the rerolling, and we're committed to
1173 Reductions.replaceSelected();
1174 DAGRoots.replace(IterCount);
1180 bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
1181 if (skipOptnoneFunction(L))
1184 AA = &getAnalysis<AliasAnalysis>();
1185 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1186 SE = &getAnalysis<ScalarEvolution>();
1187 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1188 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1189 DL = DLP ? &DLP->getDataLayout() : nullptr;
1190 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1192 BasicBlock *Header = L->getHeader();
1193 DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1194 "] Loop %" << Header->getName() << " (" <<
1195 L->getNumBlocks() << " block(s))\n");
1197 bool Changed = false;
1199 // For now, we'll handle only single BB loops.
1200 if (L->getNumBlocks() > 1)
1203 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1206 const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
1207 const SCEV *IterCount =
1208 SE->getAddExpr(LIBETC, SE->getConstant(LIBETC->getType(), 1));
1209 DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1211 // First, we need to find the induction variable with respect to which we can
1212 // reroll (there may be several possible options).
1213 SmallInstructionVector PossibleIVs;
1214 collectPossibleIVs(L, PossibleIVs);
1216 if (PossibleIVs.empty()) {
1217 DEBUG(dbgs() << "LRR: No possible IVs found\n");
1221 ReductionTracker Reductions;
1222 collectPossibleReductions(L, Reductions);
1224 // For each possible IV, collect the associated possible set of 'root' nodes
1225 // (i+1, i+2, etc.).
1226 for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1227 IE = PossibleIVs.end(); I != IE; ++I)
1228 if (reroll(*I, L, Header, IterCount, Reductions)) {