1 //===- LoopReroll.cpp - Loop rerolling pass -------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This pass implements a simple loop reroller.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/APInt.h"
14 #include "llvm/ADT/BitVector.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/AliasSetTracker.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/LoopPass.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/InstrTypes.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/IR/Use.h"
44 #include "llvm/IR/User.h"
45 #include "llvm/IR/Value.h"
46 #include "llvm/InitializePasses.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Transforms/Scalar.h"
53 #include "llvm/Transforms/Utils.h"
54 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Transforms/Utils/LoopUtils.h"
57 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
68 #define DEBUG_TYPE "loop-reroll"
70 STATISTIC(NumRerolledLoops, "Number of rerolled loops");
72 static cl::opt<unsigned>
73 NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400),
75 cl::desc("The maximum number of failures to tolerate"
76 " during fuzzy matching. (default: 400)"));
78 // This loop re-rolling transformation aims to transform loops like this:
82 // for (int i = 0; i < 500; i += 3) {
89 // into a loop like this:
92 // for (int i = 0; i < 500; ++i)
96 // It does this by looking for loops that, besides the latch code, are composed
97 // of isomorphic DAGs of instructions, with each DAG rooted at some increment
98 // to the induction variable, and where each DAG is isomorphic to the DAG
99 // rooted at the induction variable (excepting the sub-DAGs which root the
100 // other induction-variable increments). In other words, we're looking for loop
101 // bodies of the form:
103 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
105 // %iv.1 = add %iv, 1 <-- a root increment
107 // %iv.2 = add %iv, 2 <-- a root increment
109 // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
112 // %iv.next = add %iv, scale
113 // %cmp = icmp(%iv, ...)
114 // br %cmp, header, exit
116 // where each f(i) is a set of instructions that, collectively, are a function
117 // only of i (and other loop-invariant values).
119 // As a special case, we can also reroll loops like this:
122 // void bar(int *x) {
123 // for (int i = 0; i < 500; ++i) {
125 // x[3*i+1] = foo(0);
126 // x[3*i+2] = foo(0);
132 // void bar(int *x) {
133 // for (int i = 0; i < 1500; ++i)
137 // in which case, we're looking for inputs like this:
139 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
140 // %scaled.iv = mul %iv, scale
142 // %scaled.iv.1 = add %scaled.iv, 1
144 // %scaled.iv.2 = add %scaled.iv, 2
146 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
147 // f(%scaled.iv.scale_m_1)
149 // %iv.next = add %iv, 1
150 // %cmp = icmp(%iv, ...)
151 // br %cmp, header, exit
155 enum IterationLimits {
156 /// The maximum number of iterations that we'll try and reroll.
157 IL_MaxRerollIterations = 32,
158 /// The bitvector index used by loop induction variables and other
159 /// instructions that belong to all iterations.
164 class LoopReroll : public LoopPass {
166 static char ID; // Pass ID, replacement for typeid
168 LoopReroll() : LoopPass(ID) {
169 initializeLoopRerollPass(*PassRegistry::getPassRegistry());
172 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
174 void getAnalysisUsage(AnalysisUsage &AU) const override {
175 AU.addRequired<TargetLibraryInfoWrapperPass>();
176 getLoopAnalysisUsage(AU);
183 TargetLibraryInfo *TLI;
187 using SmallInstructionVector = SmallVector<Instruction *, 16>;
188 using SmallInstructionSet = SmallPtrSet<Instruction *, 16>;
190 // Map between induction variable and its increment
191 DenseMap<Instruction *, int64_t> IVToIncMap;
193 // For loop with multiple induction variable, remember the one used only to
195 Instruction *LoopControlIV;
197 // A chain of isomorphic instructions, identified by a single-use PHI
198 // representing a reduction. Only the last value may be used outside the
200 struct SimpleLoopReduction {
201 SimpleLoopReduction(Instruction *P, Loop *L) : Instructions(1, P) {
202 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
210 Instruction *getPHI() const {
211 assert(Valid && "Using invalid reduction");
212 return Instructions.front();
215 Instruction *getReducedValue() const {
216 assert(Valid && "Using invalid reduction");
217 return Instructions.back();
220 Instruction *get(size_t i) const {
221 assert(Valid && "Using invalid reduction");
222 return Instructions[i+1];
225 Instruction *operator [] (size_t i) const { return get(i); }
227 // The size, ignoring the initial PHI.
228 size_t size() const {
229 assert(Valid && "Using invalid reduction");
230 return Instructions.size()-1;
233 using iterator = SmallInstructionVector::iterator;
234 using const_iterator = SmallInstructionVector::const_iterator;
237 assert(Valid && "Using invalid reduction");
238 return std::next(Instructions.begin());
241 const_iterator begin() const {
242 assert(Valid && "Using invalid reduction");
243 return std::next(Instructions.begin());
246 iterator end() { return Instructions.end(); }
247 const_iterator end() const { return Instructions.end(); }
251 SmallInstructionVector Instructions;
256 // The set of all reductions, and state tracking of possible reductions
257 // during loop instruction processing.
258 struct ReductionTracker {
259 using SmallReductionVector = SmallVector<SimpleLoopReduction, 16>;
261 // Add a new possible reduction.
262 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
264 // Setup to track possible reductions corresponding to the provided
265 // rerolling scale. Only reductions with a number of non-PHI instructions
266 // that is divisible by the scale are considered. Three instructions sets
268 // - A set of all possible instructions in eligible reductions.
269 // - A set of all PHIs in eligible reductions
270 // - A set of all reduced values (last instructions) in eligible
272 void restrictToScale(uint64_t Scale,
273 SmallInstructionSet &PossibleRedSet,
274 SmallInstructionSet &PossibleRedPHISet,
275 SmallInstructionSet &PossibleRedLastSet) {
276 PossibleRedIdx.clear();
277 PossibleRedIter.clear();
280 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
281 if (PossibleReds[i].size() % Scale == 0) {
282 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
283 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
285 PossibleRedSet.insert(PossibleReds[i].getPHI());
286 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
287 for (Instruction *J : PossibleReds[i]) {
288 PossibleRedSet.insert(J);
289 PossibleRedIdx[J] = i;
294 // The functions below are used while processing the loop instructions.
296 // Are the two instructions both from reductions, and furthermore, from
297 // the same reduction?
298 bool isPairInSame(Instruction *J1, Instruction *J2) {
299 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
300 if (J1I != PossibleRedIdx.end()) {
301 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
302 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
309 // The two provided instructions, the first from the base iteration, and
310 // the second from iteration i, form a matched pair. If these are part of
311 // a reduction, record that fact.
312 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
313 if (PossibleRedIdx.count(J1)) {
314 assert(PossibleRedIdx.count(J2) &&
315 "Recording reduction vs. non-reduction instruction?");
317 PossibleRedIter[J1] = 0;
318 PossibleRedIter[J2] = i;
320 int Idx = PossibleRedIdx[J1];
321 assert(Idx == PossibleRedIdx[J2] &&
322 "Recording pair from different reductions?");
327 // The functions below can be called after we've finished processing all
328 // instructions in the loop, and we know which reductions were selected.
330 bool validateSelected();
331 void replaceSelected();
334 // The vector of all possible reductions (for any scale).
335 SmallReductionVector PossibleReds;
337 DenseMap<Instruction *, int> PossibleRedIdx;
338 DenseMap<Instruction *, int> PossibleRedIter;
342 // A DAGRootSet models an induction variable being used in a rerollable
343 // loop. For example,
349 // Base instruction -> i*3
352 // ST[y1] +1 +2 <-- Roots
356 // There may be multiple DAGRoots, for example:
358 // x[i*2+0] = ... (1)
359 // x[i*2+1] = ... (1)
360 // x[i*2+4] = ... (2)
361 // x[i*2+5] = ... (2)
362 // x[(i+1234)*2+5678] = ... (3)
363 // x[(i+1234)*2+5679] = ... (3)
365 // The loop will be rerolled by adding a new loop induction variable,
366 // one for the Base instruction in each DAGRootSet.
369 Instruction *BaseInst;
370 SmallInstructionVector Roots;
372 // The instructions between IV and BaseInst (but not including BaseInst).
373 SmallInstructionSet SubsumedInsts;
376 // The set of all DAG roots, and state tracking of all roots
377 // for a particular induction variable.
378 struct DAGRootTracker {
379 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
380 ScalarEvolution *SE, AliasAnalysis *AA,
381 TargetLibraryInfo *TLI, DominatorTree *DT, LoopInfo *LI,
383 DenseMap<Instruction *, int64_t> &IncrMap,
384 Instruction *LoopCtrlIV)
385 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), DT(DT), LI(LI),
386 PreserveLCSSA(PreserveLCSSA), IV(IV), IVToIncMap(IncrMap),
387 LoopControlIV(LoopCtrlIV) {}
389 /// Stage 1: Find all the DAG roots for the induction variable.
392 /// Stage 2: Validate if the found roots are valid.
393 bool validate(ReductionTracker &Reductions);
395 /// Stage 3: Assuming validate() returned true, perform the
397 /// @param BackedgeTakenCount The backedge-taken count of L.
398 void replace(const SCEV *BackedgeTakenCount);
401 using UsesTy = MapVector<Instruction *, BitVector>;
403 void findRootsRecursive(Instruction *IVU,
404 SmallInstructionSet SubsumedInsts);
405 bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
406 bool collectPossibleRoots(Instruction *Base,
407 std::map<int64_t,Instruction*> &Roots);
408 bool validateRootSet(DAGRootSet &DRS);
410 bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
411 void collectInLoopUserSet(const SmallInstructionVector &Roots,
412 const SmallInstructionSet &Exclude,
413 const SmallInstructionSet &Final,
414 DenseSet<Instruction *> &Users);
415 void collectInLoopUserSet(Instruction *Root,
416 const SmallInstructionSet &Exclude,
417 const SmallInstructionSet &Final,
418 DenseSet<Instruction *> &Users);
420 UsesTy::iterator nextInstr(int Val, UsesTy &In,
421 const SmallInstructionSet &Exclude,
422 UsesTy::iterator *StartI=nullptr);
423 bool isBaseInst(Instruction *I);
424 bool isRootInst(Instruction *I);
425 bool instrDependsOn(Instruction *I,
426 UsesTy::iterator Start,
427 UsesTy::iterator End);
428 void replaceIV(DAGRootSet &DRS, const SCEV *Start, const SCEV *IncrExpr);
432 // Members of Parent, replicated here for brevity.
436 TargetLibraryInfo *TLI;
441 // The loop induction variable.
447 // Loop reroll count; if Inc == 1, this records the scaling applied
448 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
449 // If Inc is not 1, Scale = Inc.
452 // The roots themselves.
453 SmallVector<DAGRootSet,16> RootSets;
455 // All increment instructions for IV.
456 SmallInstructionVector LoopIncs;
458 // Map of all instructions in the loop (in order) to the iterations
459 // they are used in (or specially, IL_All for instructions
460 // used in the loop increment mechanism).
463 // Map between induction variable and its increment
464 DenseMap<Instruction *, int64_t> &IVToIncMap;
466 Instruction *LoopControlIV;
469 // Check if it is a compare-like instruction whose user is a branch
470 bool isCompareUsedByBranch(Instruction *I) {
471 auto *TI = I->getParent()->getTerminator();
472 if (!isa<BranchInst>(TI) || !isa<CmpInst>(I))
474 return I->hasOneUse() && TI->getOperand(0) == I;
477 bool isLoopControlIV(Loop *L, Instruction *IV);
478 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
479 void collectPossibleReductions(Loop *L,
480 ReductionTracker &Reductions);
481 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header,
482 const SCEV *BackedgeTakenCount, ReductionTracker &Reductions);
485 } // end anonymous namespace
487 char LoopReroll::ID = 0;
489 INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
490 INITIALIZE_PASS_DEPENDENCY(LoopPass)
491 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
492 INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
494 Pass *llvm::createLoopRerollPass() {
495 return new LoopReroll;
498 // Returns true if the provided instruction is used outside the given loop.
499 // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
500 // non-loop blocks to be outside the loop.
501 static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
502 for (User *U : I->users()) {
503 if (!L->contains(cast<Instruction>(U)))
509 // Check if an IV is only used to control the loop. There are two cases:
510 // 1. It only has one use which is loop increment, and the increment is only
511 // used by comparison and the PHI (could has sext with nsw in between), and the
512 // comparison is only used by branch.
513 // 2. It is used by loop increment and the comparison, the loop increment is
514 // only used by the PHI, and the comparison is used only by the branch.
515 bool LoopReroll::isLoopControlIV(Loop *L, Instruction *IV) {
516 unsigned IVUses = IV->getNumUses();
517 if (IVUses != 2 && IVUses != 1)
520 for (auto *User : IV->users()) {
521 int32_t IncOrCmpUses = User->getNumUses();
522 bool IsCompInst = isCompareUsedByBranch(cast<Instruction>(User));
524 // User can only have one or two uses.
525 if (IncOrCmpUses != 2 && IncOrCmpUses != 1)
530 // The only user must be the loop increment.
531 // The loop increment must have two uses.
532 if (IsCompInst || IncOrCmpUses != 2)
537 if (IVUses == 2 && IncOrCmpUses != 1)
540 // The users of the IV must be a binary operation or a comparison
541 if (auto *BO = dyn_cast<BinaryOperator>(User)) {
542 if (BO->getOpcode() == Instruction::Add) {
544 // User of Loop Increment should be either PHI or CMP
545 for (auto *UU : User->users()) {
546 if (PHINode *PN = dyn_cast<PHINode>(UU)) {
550 // Must be a CMP or an ext (of a value with nsw) then CMP
552 Instruction *UUser = dyn_cast<Instruction>(UU);
553 // Skip SExt if we are extending an nsw value
554 // TODO: Allow ZExt too
555 if (BO->hasNoSignedWrap() && UUser && UUser->hasOneUse() &&
556 isa<SExtInst>(UUser))
557 UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
558 if (!isCompareUsedByBranch(UUser))
564 // Compare : can only have one use, and must be branch
565 } else if (!IsCompInst)
571 // Collect the list of loop induction variables with respect to which it might
572 // be possible to reroll the loop.
573 void LoopReroll::collectPossibleIVs(Loop *L,
574 SmallInstructionVector &PossibleIVs) {
575 BasicBlock *Header = L->getHeader();
576 for (BasicBlock::iterator I = Header->begin(),
577 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
578 if (!isa<PHINode>(I))
580 if (!I->getType()->isIntegerTy() && !I->getType()->isPointerTy())
583 if (const SCEVAddRecExpr *PHISCEV =
584 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
585 if (PHISCEV->getLoop() != L)
587 if (!PHISCEV->isAffine())
589 auto IncSCEV = dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE));
591 IVToIncMap[&*I] = IncSCEV->getValue()->getSExtValue();
592 LLVM_DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
595 if (isLoopControlIV(L, &*I)) {
596 assert(!LoopControlIV && "Found two loop control only IV");
597 LoopControlIV = &(*I);
598 LLVM_DEBUG(dbgs() << "LRR: Possible loop control only IV: " << *I
599 << " = " << *PHISCEV << "\n");
601 PossibleIVs.push_back(&*I);
607 // Add the remainder of the reduction-variable chain to the instruction vector
608 // (the initial PHINode has already been added). If successful, the object is
610 void LoopReroll::SimpleLoopReduction::add(Loop *L) {
611 assert(!Valid && "Cannot add to an already-valid chain");
613 // The reduction variable must be a chain of single-use instructions
614 // (including the PHI), except for the last value (which is used by the PHI
615 // and also outside the loop).
616 Instruction *C = Instructions.front();
621 C = cast<Instruction>(*C->user_begin());
622 if (C->hasOneUse()) {
623 if (!C->isBinaryOp())
626 if (!(isa<PHINode>(Instructions.back()) ||
627 C->isSameOperationAs(Instructions.back())))
630 Instructions.push_back(C);
632 } while (C->hasOneUse());
634 if (Instructions.size() < 2 ||
635 !C->isSameOperationAs(Instructions.back()) ||
639 // C is now the (potential) last instruction in the reduction chain.
640 for (User *U : C->users()) {
641 // The only in-loop user can be the initial PHI.
642 if (L->contains(cast<Instruction>(U)))
643 if (cast<Instruction>(U) != Instructions.front())
647 Instructions.push_back(C);
651 // Collect the vector of possible reduction variables.
652 void LoopReroll::collectPossibleReductions(Loop *L,
653 ReductionTracker &Reductions) {
654 BasicBlock *Header = L->getHeader();
655 for (BasicBlock::iterator I = Header->begin(),
656 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
657 if (!isa<PHINode>(I))
659 if (!I->getType()->isSingleValueType())
662 SimpleLoopReduction SLR(&*I, L);
666 LLVM_DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with "
667 << SLR.size() << " chained instructions)\n");
668 Reductions.addSLR(SLR);
672 // Collect the set of all users of the provided root instruction. This set of
673 // users contains not only the direct users of the root instruction, but also
674 // all users of those users, and so on. There are two exceptions:
676 // 1. Instructions in the set of excluded instructions are never added to the
677 // use set (even if they are users). This is used, for example, to exclude
678 // including root increments in the use set of the primary IV.
680 // 2. Instructions in the set of final instructions are added to the use set
681 // if they are users, but their users are not added. This is used, for
682 // example, to prevent a reduction update from forcing all later reduction
683 // updates into the use set.
684 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
685 Instruction *Root, const SmallInstructionSet &Exclude,
686 const SmallInstructionSet &Final,
687 DenseSet<Instruction *> &Users) {
688 SmallInstructionVector Queue(1, Root);
689 while (!Queue.empty()) {
690 Instruction *I = Queue.pop_back_val();
691 if (!Users.insert(I).second)
695 for (Use &U : I->uses()) {
696 Instruction *User = cast<Instruction>(U.getUser());
697 if (PHINode *PN = dyn_cast<PHINode>(User)) {
698 // Ignore "wrap-around" uses to PHIs of this loop's header.
699 if (PN->getIncomingBlock(U) == L->getHeader())
703 if (L->contains(User) && !Exclude.count(User)) {
704 Queue.push_back(User);
708 // We also want to collect single-user "feeder" values.
709 for (User::op_iterator OI = I->op_begin(),
710 OIE = I->op_end(); OI != OIE; ++OI) {
711 if (Instruction *Op = dyn_cast<Instruction>(*OI))
712 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
719 // Collect all of the users of all of the provided root instructions (combined
720 // into a single set).
721 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
722 const SmallInstructionVector &Roots,
723 const SmallInstructionSet &Exclude,
724 const SmallInstructionSet &Final,
725 DenseSet<Instruction *> &Users) {
726 for (Instruction *Root : Roots)
727 collectInLoopUserSet(Root, Exclude, Final, Users);
730 static bool isUnorderedLoadStore(Instruction *I) {
731 if (LoadInst *LI = dyn_cast<LoadInst>(I))
732 return LI->isUnordered();
733 if (StoreInst *SI = dyn_cast<StoreInst>(I))
734 return SI->isUnordered();
735 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
736 return !MI->isVolatile();
740 /// Return true if IVU is a "simple" arithmetic operation.
741 /// This is used for narrowing the search space for DAGRoots; only arithmetic
742 /// and GEPs can be part of a DAGRoot.
743 static bool isSimpleArithmeticOp(User *IVU) {
744 if (Instruction *I = dyn_cast<Instruction>(IVU)) {
745 switch (I->getOpcode()) {
746 default: return false;
747 case Instruction::Add:
748 case Instruction::Sub:
749 case Instruction::Mul:
750 case Instruction::Shl:
751 case Instruction::AShr:
752 case Instruction::LShr:
753 case Instruction::GetElementPtr:
754 case Instruction::Trunc:
755 case Instruction::ZExt:
756 case Instruction::SExt:
763 static bool isLoopIncrement(User *U, Instruction *IV) {
764 BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
766 if ((BO && BO->getOpcode() != Instruction::Add) ||
767 (!BO && !isa<GetElementPtrInst>(U)))
770 for (auto *UU : U->users()) {
771 PHINode *PN = dyn_cast<PHINode>(UU);
778 bool LoopReroll::DAGRootTracker::
779 collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
780 SmallInstructionVector BaseUsers;
782 for (auto *I : Base->users()) {
783 ConstantInt *CI = nullptr;
785 if (isLoopIncrement(I, IV)) {
786 LoopIncs.push_back(cast<Instruction>(I));
790 // The root nodes must be either GEPs, ORs or ADDs.
791 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
792 if (BO->getOpcode() == Instruction::Add ||
793 BO->getOpcode() == Instruction::Or)
794 CI = dyn_cast<ConstantInt>(BO->getOperand(1));
795 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
796 Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
797 CI = dyn_cast<ConstantInt>(LastOperand);
801 if (Instruction *II = dyn_cast<Instruction>(I)) {
802 BaseUsers.push_back(II);
805 LLVM_DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I
811 int64_t V = std::abs(CI->getValue().getSExtValue());
812 if (Roots.find(V) != Roots.end())
813 // No duplicates, please.
816 Roots[V] = cast<Instruction>(I);
819 // Make sure we have at least two roots.
820 if (Roots.empty() || (Roots.size() == 1 && BaseUsers.empty()))
823 // If we found non-loop-inc, non-root users of Base, assume they are
824 // for the zeroth root index. This is because "add %a, 0" gets optimized
826 if (BaseUsers.size()) {
827 if (Roots.find(0) != Roots.end()) {
828 LLVM_DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
834 // Calculate the number of users of the base, or lowest indexed, iteration.
835 unsigned NumBaseUses = BaseUsers.size();
836 if (NumBaseUses == 0)
837 NumBaseUses = Roots.begin()->second->getNumUses();
839 // Check that every node has the same number of users.
840 for (auto &KV : Roots) {
843 if (!KV.second->hasNUses(NumBaseUses)) {
844 LLVM_DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
845 << "#Base=" << NumBaseUses
846 << ", #Root=" << KV.second->getNumUses() << "\n");
854 void LoopReroll::DAGRootTracker::
855 findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
856 // Does the user look like it could be part of a root set?
857 // All its users must be simple arithmetic ops.
858 if (I->hasNUsesOrMore(IL_MaxRerollIterations + 1))
861 if (I != IV && findRootsBase(I, SubsumedInsts))
864 SubsumedInsts.insert(I);
866 for (User *V : I->users()) {
867 Instruction *I = cast<Instruction>(V);
868 if (is_contained(LoopIncs, I))
871 if (!isSimpleArithmeticOp(I))
874 // The recursive call makes a copy of SubsumedInsts.
875 findRootsRecursive(I, SubsumedInsts);
879 bool LoopReroll::DAGRootTracker::validateRootSet(DAGRootSet &DRS) {
880 if (DRS.Roots.empty())
883 // If the value of the base instruction is used outside the loop, we cannot
884 // reroll the loop. Check for other root instructions is unnecessary because
885 // they don't match any base instructions if their values are used outside.
886 if (hasUsesOutsideLoop(DRS.BaseInst, L))
889 // Consider a DAGRootSet with N-1 roots (so N different values including
891 // Define d = Roots[0] - BaseInst, which should be the same as
892 // Roots[I] - Roots[I-1] for all I in [1..N).
893 // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
896 // Now, For the loop iterations to be consecutive:
898 const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
902 // Check that the first root is evenly spaced.
903 unsigned N = DRS.Roots.size() + 1;
904 const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(DRS.Roots[0]), ADR);
905 const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
906 if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV))
909 // Check that the remainling roots are evenly spaced.
910 for (unsigned i = 1; i < N - 1; ++i) {
911 const SCEV *NewStepSCEV = SE->getMinusSCEV(SE->getSCEV(DRS.Roots[i]),
912 SE->getSCEV(DRS.Roots[i-1]));
913 if (NewStepSCEV != StepSCEV)
920 bool LoopReroll::DAGRootTracker::
921 findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
922 // The base of a RootSet must be an AddRec, so it can be erased.
923 const auto *IVU_ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IVU));
924 if (!IVU_ADR || IVU_ADR->getLoop() != L)
927 std::map<int64_t, Instruction*> V;
928 if (!collectPossibleRoots(IVU, V))
931 // If we didn't get a root for index zero, then IVU must be
933 if (V.find(0) == V.end())
934 SubsumedInsts.insert(IVU);
936 // Partition the vector into monotonically increasing indexes.
938 DRS.BaseInst = nullptr;
940 SmallVector<DAGRootSet, 16> PotentialRootSets;
944 DRS.BaseInst = KV.second;
945 DRS.SubsumedInsts = SubsumedInsts;
946 } else if (DRS.Roots.empty()) {
947 DRS.Roots.push_back(KV.second);
948 } else if (V.find(KV.first - 1) != V.end()) {
949 DRS.Roots.push_back(KV.second);
951 // Linear sequence terminated.
952 if (!validateRootSet(DRS))
955 // Construct a new DAGRootSet with the next sequence.
956 PotentialRootSets.push_back(DRS);
957 DRS.BaseInst = KV.second;
962 if (!validateRootSet(DRS))
965 PotentialRootSets.push_back(DRS);
967 RootSets.append(PotentialRootSets.begin(), PotentialRootSets.end());
972 bool LoopReroll::DAGRootTracker::findRoots() {
973 Inc = IVToIncMap[IV];
975 assert(RootSets.empty() && "Unclean state!");
976 if (std::abs(Inc) == 1) {
977 for (auto *IVU : IV->users()) {
978 if (isLoopIncrement(IVU, IV))
979 LoopIncs.push_back(cast<Instruction>(IVU));
981 findRootsRecursive(IV, SmallInstructionSet());
982 LoopIncs.push_back(IV);
984 if (!findRootsBase(IV, SmallInstructionSet()))
988 // Ensure all sets have the same size.
989 if (RootSets.empty()) {
990 LLVM_DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
993 for (auto &V : RootSets) {
994 if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
997 << "LRR: Aborting because not all root sets have the same size\n");
1002 Scale = RootSets[0].Roots.size() + 1;
1004 if (Scale > IL_MaxRerollIterations) {
1005 LLVM_DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
1006 << "#Found=" << Scale
1007 << ", #Max=" << IL_MaxRerollIterations << "\n");
1011 LLVM_DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale
1017 bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
1018 // Populate the MapVector with all instructions in the block, in order first,
1019 // so we can iterate over the contents later in perfect order.
1020 for (auto &I : *L->getHeader()) {
1021 Uses[&I].resize(IL_End);
1024 SmallInstructionSet Exclude;
1025 for (auto &DRS : RootSets) {
1026 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1027 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1028 Exclude.insert(DRS.BaseInst);
1030 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
1032 for (auto &DRS : RootSets) {
1033 DenseSet<Instruction*> VBase;
1034 collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
1035 for (auto *I : VBase) {
1040 for (auto *Root : DRS.Roots) {
1041 DenseSet<Instruction*> V;
1042 collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
1044 // While we're here, check the use sets are the same size.
1045 if (V.size() != VBase.size()) {
1046 LLVM_DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
1056 // Make sure our subsumed instructions are remembered too.
1057 for (auto *I : DRS.SubsumedInsts) {
1058 Uses[I].set(IL_All);
1062 // Make sure the loop increments are also accounted for.
1065 for (auto &DRS : RootSets) {
1066 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1067 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1068 Exclude.insert(DRS.BaseInst);
1071 DenseSet<Instruction*> V;
1072 collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
1074 Uses[I].set(IL_All);
1080 /// Get the next instruction in "In" that is a member of set Val.
1081 /// Start searching from StartI, and do not return anything in Exclude.
1082 /// If StartI is not given, start from In.begin().
1083 LoopReroll::DAGRootTracker::UsesTy::iterator
1084 LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
1085 const SmallInstructionSet &Exclude,
1086 UsesTy::iterator *StartI) {
1087 UsesTy::iterator I = StartI ? *StartI : In.begin();
1088 while (I != In.end() && (I->second.test(Val) == 0 ||
1089 Exclude.count(I->first) != 0))
1094 bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
1095 for (auto &DRS : RootSets) {
1096 if (DRS.BaseInst == I)
1102 bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
1103 for (auto &DRS : RootSets) {
1104 if (is_contained(DRS.Roots, I))
1110 /// Return true if instruction I depends on any instruction between
1112 bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
1113 UsesTy::iterator Start,
1114 UsesTy::iterator End) {
1115 for (auto *U : I->users()) {
1116 for (auto It = Start; It != End; ++It)
1123 static bool isIgnorableInst(const Instruction *I) {
1124 if (isa<DbgInfoIntrinsic>(I))
1126 const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I);
1129 switch (II->getIntrinsicID()) {
1132 case Intrinsic::annotation:
1133 case Intrinsic::ptr_annotation:
1134 case Intrinsic::var_annotation:
1135 // TODO: the following intrinsics may also be allowed:
1136 // lifetime_start, lifetime_end, invariant_start, invariant_end
1142 bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
1143 // We now need to check for equivalence of the use graph of each root with
1144 // that of the primary induction variable (excluding the roots). Our goal
1145 // here is not to solve the full graph isomorphism problem, but rather to
1146 // catch common cases without a lot of work. As a result, we will assume
1147 // that the relative order of the instructions in each unrolled iteration
1148 // is the same (although we will not make an assumption about how the
1149 // different iterations are intermixed). Note that while the order must be
1150 // the same, the instructions may not be in the same basic block.
1152 // An array of just the possible reductions for this scale factor. When we
1153 // collect the set of all users of some root instructions, these reduction
1154 // instructions are treated as 'final' (their uses are not considered).
1155 // This is important because we don't want the root use set to search down
1156 // the reduction chain.
1157 SmallInstructionSet PossibleRedSet;
1158 SmallInstructionSet PossibleRedLastSet;
1159 SmallInstructionSet PossibleRedPHISet;
1160 Reductions.restrictToScale(Scale, PossibleRedSet,
1161 PossibleRedPHISet, PossibleRedLastSet);
1163 // Populate "Uses" with where each instruction is used.
1164 if (!collectUsedInstructions(PossibleRedSet))
1167 // Make sure we mark the reduction PHIs as used in all iterations.
1168 for (auto *I : PossibleRedPHISet) {
1169 Uses[I].set(IL_All);
1172 // Make sure we mark loop-control-only PHIs as used in all iterations. See
1173 // comment above LoopReroll::isLoopControlIV for more information.
1174 BasicBlock *Header = L->getHeader();
1175 if (LoopControlIV && LoopControlIV != IV) {
1176 for (auto *U : LoopControlIV->users()) {
1177 Instruction *IVUser = dyn_cast<Instruction>(U);
1178 // IVUser could be loop increment or compare
1179 Uses[IVUser].set(IL_All);
1180 for (auto *UU : IVUser->users()) {
1181 Instruction *UUser = dyn_cast<Instruction>(UU);
1182 // UUser could be compare, PHI or branch
1183 Uses[UUser].set(IL_All);
1185 if (isa<SExtInst>(UUser)) {
1186 UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
1187 Uses[UUser].set(IL_All);
1189 // Is UUser a compare instruction?
1190 if (UU->hasOneUse()) {
1191 Instruction *BI = dyn_cast<BranchInst>(*UUser->user_begin());
1192 if (BI == cast<BranchInst>(Header->getTerminator()))
1193 Uses[BI].set(IL_All);
1199 // Make sure all instructions in the loop are in one and only one
1201 for (auto &KV : Uses) {
1202 if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) {
1204 dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1205 << *KV.first << " (#uses=" << KV.second.count() << ")\n");
1210 LLVM_DEBUG(for (auto &KV
1212 dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1215 for (unsigned Iter = 1; Iter < Scale; ++Iter) {
1216 // In addition to regular aliasing information, we need to look for
1217 // instructions from later (future) iterations that have side effects
1218 // preventing us from reordering them past other instructions with side
1220 bool FutureSideEffects = false;
1221 AliasSetTracker AST(*AA);
1222 // The map between instructions in f(%iv.(i+1)) and f(%iv).
1223 DenseMap<Value *, Value *> BaseMap;
1225 // Compare iteration Iter to the base.
1226 SmallInstructionSet Visited;
1227 auto BaseIt = nextInstr(0, Uses, Visited);
1228 auto RootIt = nextInstr(Iter, Uses, Visited);
1229 auto LastRootIt = Uses.begin();
1231 while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1232 Instruction *BaseInst = BaseIt->first;
1233 Instruction *RootInst = RootIt->first;
1235 // Skip over the IV or root instructions; only match their users.
1236 bool Continue = false;
1237 if (isBaseInst(BaseInst)) {
1238 Visited.insert(BaseInst);
1239 BaseIt = nextInstr(0, Uses, Visited);
1242 if (isRootInst(RootInst)) {
1243 LastRootIt = RootIt;
1244 Visited.insert(RootInst);
1245 RootIt = nextInstr(Iter, Uses, Visited);
1248 if (Continue) continue;
1250 if (!BaseInst->isSameOperationAs(RootInst)) {
1251 // Last chance saloon. We don't try and solve the full isomorphism
1252 // problem, but try and at least catch the case where two instructions
1253 // *of different types* are round the wrong way. We won't be able to
1254 // efficiently tell, given two ADD instructions, which way around we
1255 // should match them, but given an ADD and a SUB, we can at least infer
1256 // which one is which.
1258 // This should allow us to deal with a greater subset of the isomorphism
1259 // problem. It does however change a linear algorithm into a quadratic
1260 // one, so limit the number of probes we do.
1261 auto TryIt = RootIt;
1262 unsigned N = NumToleratedFailedMatches;
1263 while (TryIt != Uses.end() &&
1264 !BaseInst->isSameOperationAs(TryIt->first) &&
1267 TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1270 if (TryIt == Uses.end() || TryIt == RootIt ||
1271 instrDependsOn(TryIt->first, RootIt, TryIt)) {
1272 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at "
1273 << *BaseInst << " vs. " << *RootInst << "\n");
1278 RootInst = TryIt->first;
1281 // All instructions between the last root and this root
1282 // may belong to some other iteration. If they belong to a
1283 // future iteration, then they're dangerous to alias with.
1285 // Note that because we allow a limited amount of flexibility in the order
1286 // that we visit nodes, LastRootIt might be *before* RootIt, in which
1287 // case we've already checked this set of instructions so we shouldn't
1289 for (; LastRootIt < RootIt; ++LastRootIt) {
1290 Instruction *I = LastRootIt->first;
1291 if (LastRootIt->second.find_first() < (int)Iter)
1293 if (I->mayWriteToMemory())
1295 // Note: This is specifically guarded by a check on isa<PHINode>,
1296 // which while a valid (somewhat arbitrary) micro-optimization, is
1297 // needed because otherwise isSafeToSpeculativelyExecute returns
1298 // false on PHI nodes.
1299 if (!isa<PHINode>(I) && !isUnorderedLoadStore(I) &&
1300 !isSafeToSpeculativelyExecute(I))
1301 // Intervening instructions cause side effects.
1302 FutureSideEffects = true;
1305 // Make sure that this instruction, which is in the use set of this
1306 // root instruction, does not also belong to the base set or the set of
1307 // some other root instruction.
1308 if (RootIt->second.count() > 1) {
1309 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1310 << " vs. " << *RootInst << " (prev. case overlap)\n");
1314 // Make sure that we don't alias with any instruction in the alias set
1315 // tracker. If we do, then we depend on a future iteration, and we
1317 if (RootInst->mayReadFromMemory())
1318 for (auto &K : AST) {
1319 if (K.aliasesUnknownInst(RootInst, *AA)) {
1320 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at "
1321 << *BaseInst << " vs. " << *RootInst
1322 << " (depends on future store)\n");
1327 // If we've past an instruction from a future iteration that may have
1328 // side effects, and this instruction might also, then we can't reorder
1329 // them, and this matching fails. As an exception, we allow the alias
1330 // set tracker to handle regular (unordered) load/store dependencies.
1331 if (FutureSideEffects && ((!isUnorderedLoadStore(BaseInst) &&
1332 !isSafeToSpeculativelyExecute(BaseInst)) ||
1333 (!isUnorderedLoadStore(RootInst) &&
1334 !isSafeToSpeculativelyExecute(RootInst)))) {
1335 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1336 << " vs. " << *RootInst
1337 << " (side effects prevent reordering)\n");
1341 // For instructions that are part of a reduction, if the operation is
1342 // associative, then don't bother matching the operands (because we
1343 // already know that the instructions are isomorphic, and the order
1344 // within the iteration does not matter). For non-associative reductions,
1345 // we do need to match the operands, because we need to reject
1346 // out-of-order instructions within an iteration!
1347 // For example (assume floating-point addition), we need to reject this:
1348 // x += a[i]; x += b[i];
1349 // x += a[i+1]; x += b[i+1];
1350 // x += b[i+2]; x += a[i+2];
1351 bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
1353 if (!(InReduction && BaseInst->isAssociative())) {
1354 bool Swapped = false, SomeOpMatched = false;
1355 for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1356 Value *Op2 = RootInst->getOperand(j);
1358 // If this is part of a reduction (and the operation is not
1359 // associatve), then we match all operands, but not those that are
1360 // part of the reduction.
1362 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
1363 if (Reductions.isPairInSame(RootInst, Op2I))
1366 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
1367 if (BMI != BaseMap.end()) {
1370 for (auto &DRS : RootSets) {
1371 if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1378 if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
1379 // If we've not already decided to swap the matched operands, and
1380 // we've not already matched our first operand (note that we could
1381 // have skipped matching the first operand because it is part of a
1382 // reduction above), and the instruction is commutative, then try
1383 // the swapped match.
1384 if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1385 BaseInst->getOperand(!j) == Op2) {
1389 << "LRR: iteration root match failed at " << *BaseInst
1390 << " vs. " << *RootInst << " (operand " << j << ")\n");
1395 SomeOpMatched = true;
1399 if ((!PossibleRedLastSet.count(BaseInst) &&
1400 hasUsesOutsideLoop(BaseInst, L)) ||
1401 (!PossibleRedLastSet.count(RootInst) &&
1402 hasUsesOutsideLoop(RootInst, L))) {
1403 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1404 << " vs. " << *RootInst << " (uses outside loop)\n");
1408 Reductions.recordPair(BaseInst, RootInst, Iter);
1409 BaseMap.insert(std::make_pair(RootInst, BaseInst));
1411 LastRootIt = RootIt;
1412 Visited.insert(BaseInst);
1413 Visited.insert(RootInst);
1414 BaseIt = nextInstr(0, Uses, Visited);
1415 RootIt = nextInstr(Iter, Uses, Visited);
1417 assert(BaseIt == Uses.end() && RootIt == Uses.end() &&
1418 "Mismatched set sizes!");
1421 LLVM_DEBUG(dbgs() << "LRR: Matched all iteration increments for " << *IV
1427 void LoopReroll::DAGRootTracker::replace(const SCEV *BackedgeTakenCount) {
1428 BasicBlock *Header = L->getHeader();
1430 // Compute the start and increment for each BaseInst before we start erasing
1432 SmallVector<const SCEV *, 8> StartExprs;
1433 SmallVector<const SCEV *, 8> IncrExprs;
1434 for (auto &DRS : RootSets) {
1435 const SCEVAddRecExpr *IVSCEV =
1436 cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
1437 StartExprs.push_back(IVSCEV->getStart());
1438 IncrExprs.push_back(SE->getMinusSCEV(SE->getSCEV(DRS.Roots[0]), IVSCEV));
1441 // Remove instructions associated with non-base iterations.
1442 for (BasicBlock::reverse_iterator J = Header->rbegin(), JE = Header->rend();
1444 unsigned I = Uses[&*J].find_first();
1445 if (I > 0 && I < IL_All) {
1446 LLVM_DEBUG(dbgs() << "LRR: removing: " << *J << "\n");
1447 J++->eraseFromParent();
1454 // Rewrite each BaseInst using SCEV.
1455 for (size_t i = 0, e = RootSets.size(); i != e; ++i)
1456 // Insert the new induction variable.
1457 replaceIV(RootSets[i], StartExprs[i], IncrExprs[i]);
1459 { // Limit the lifetime of SCEVExpander.
1460 BranchInst *BI = cast<BranchInst>(Header->getTerminator());
1461 const DataLayout &DL = Header->getModule()->getDataLayout();
1462 SCEVExpander Expander(*SE, DL, "reroll");
1463 auto Zero = SE->getZero(BackedgeTakenCount->getType());
1464 auto One = SE->getOne(BackedgeTakenCount->getType());
1465 auto NewIVSCEV = SE->getAddRecExpr(Zero, One, L, SCEV::FlagAnyWrap);
1467 Expander.expandCodeFor(NewIVSCEV, BackedgeTakenCount->getType(),
1468 Header->getFirstNonPHIOrDbg());
1469 // FIXME: This arithmetic can overflow.
1470 auto TripCount = SE->getAddExpr(BackedgeTakenCount, One);
1471 auto ScaledTripCount = SE->getMulExpr(
1472 TripCount, SE->getConstant(BackedgeTakenCount->getType(), Scale));
1473 auto ScaledBECount = SE->getMinusSCEV(ScaledTripCount, One);
1475 Expander.expandCodeFor(ScaledBECount, BackedgeTakenCount->getType(),
1476 Header->getFirstNonPHIOrDbg());
1478 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, TakenCount, "exitcond");
1479 BI->setCondition(Cond);
1481 if (BI->getSuccessor(1) != Header)
1482 BI->swapSuccessors();
1485 SimplifyInstructionsInBlock(Header, TLI);
1486 DeleteDeadPHIs(Header, TLI);
1489 void LoopReroll::DAGRootTracker::replaceIV(DAGRootSet &DRS,
1491 const SCEV *IncrExpr) {
1492 BasicBlock *Header = L->getHeader();
1493 Instruction *Inst = DRS.BaseInst;
1495 const SCEV *NewIVSCEV =
1496 SE->getAddRecExpr(Start, IncrExpr, L, SCEV::FlagAnyWrap);
1498 { // Limit the lifetime of SCEVExpander.
1499 const DataLayout &DL = Header->getModule()->getDataLayout();
1500 SCEVExpander Expander(*SE, DL, "reroll");
1501 Value *NewIV = Expander.expandCodeFor(NewIVSCEV, Inst->getType(),
1502 Header->getFirstNonPHIOrDbg());
1504 for (auto &KV : Uses)
1505 if (KV.second.find_first() == 0)
1506 KV.first->replaceUsesOfWith(Inst, NewIV);
1510 // Validate the selected reductions. All iterations must have an isomorphic
1511 // part of the reduction chain and, for non-associative reductions, the chain
1512 // entries must appear in order.
1513 bool LoopReroll::ReductionTracker::validateSelected() {
1514 // For a non-associative reduction, the chain entries must appear in order.
1515 for (int i : Reds) {
1516 int PrevIter = 0, BaseCount = 0, Count = 0;
1517 for (Instruction *J : PossibleReds[i]) {
1518 // Note that all instructions in the chain must have been found because
1519 // all instructions in the function must have been assigned to some
1521 int Iter = PossibleRedIter[J];
1522 if (Iter != PrevIter && Iter != PrevIter + 1 &&
1523 !PossibleReds[i].getReducedValue()->isAssociative()) {
1524 LLVM_DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: "
1529 if (Iter != PrevIter) {
1530 if (Count != BaseCount) {
1532 << "LRR: Iteration " << PrevIter << " reduction use count "
1533 << Count << " is not equal to the base use count "
1534 << BaseCount << "\n");
1552 // For all selected reductions, remove all parts except those in the first
1553 // iteration (and the PHI). Replace outside uses of the reduced value with uses
1554 // of the first-iteration reduced value (in other words, reroll the selected
1556 void LoopReroll::ReductionTracker::replaceSelected() {
1557 // Fixup reductions to refer to the last instruction associated with the
1558 // first iteration (not the last).
1559 for (int i : Reds) {
1561 for (int e = PossibleReds[i].size(); j != e; ++j)
1562 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1567 // Replace users with the new end-of-chain value.
1568 SmallInstructionVector Users;
1569 for (User *U : PossibleReds[i].getReducedValue()->users()) {
1570 Users.push_back(cast<Instruction>(U));
1573 for (Instruction *User : Users)
1574 User->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1575 PossibleReds[i][j]);
1579 // Reroll the provided loop with respect to the provided induction variable.
1580 // Generally, we're looking for a loop like this:
1582 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
1584 // %iv.1 = add %iv, 1 <-- a root increment
1586 // %iv.2 = add %iv, 2 <-- a root increment
1588 // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1591 // %iv.next = add %iv, scale
1592 // %cmp = icmp(%iv, ...)
1593 // br %cmp, header, exit
1595 // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1596 // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1597 // be intermixed with eachother. The restriction imposed by this algorithm is
1598 // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1599 // etc. be the same.
1601 // First, we collect the use set of %iv, excluding the other increment roots.
1602 // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1603 // times, having collected the use set of f(%iv.(i+1)), during which we:
1604 // - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1605 // the next unmatched instruction in f(%iv.(i+1)).
1606 // - Ensure that both matched instructions don't have any external users
1607 // (with the exception of last-in-chain reduction instructions).
1608 // - Track the (aliasing) write set, and other side effects, of all
1609 // instructions that belong to future iterations that come before the matched
1610 // instructions. If the matched instructions read from that write set, then
1611 // f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1612 // f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1613 // if any of these future instructions had side effects (could not be
1614 // speculatively executed), and so do the matched instructions, when we
1615 // cannot reorder those side-effect-producing instructions, and rerolling
1618 // Finally, we make sure that all loop instructions are either loop increment
1619 // roots, belong to simple latch code, parts of validated reductions, part of
1620 // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1621 // have been validated), then we reroll the loop.
1622 bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1623 const SCEV *BackedgeTakenCount,
1624 ReductionTracker &Reductions) {
1625 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DT, LI, PreserveLCSSA,
1626 IVToIncMap, LoopControlIV);
1628 if (!DAGRoots.findRoots())
1630 LLVM_DEBUG(dbgs() << "LRR: Found all root induction increments for: " << *IV
1633 if (!DAGRoots.validate(Reductions))
1635 if (!Reductions.validateSelected())
1637 // At this point, we've validated the rerolling, and we're committed to
1640 Reductions.replaceSelected();
1641 DAGRoots.replace(BackedgeTakenCount);
1647 bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
1651 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1652 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1653 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1654 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
1655 *L->getHeader()->getParent());
1656 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1657 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1659 BasicBlock *Header = L->getHeader();
1660 LLVM_DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() << "] Loop %"
1661 << Header->getName() << " (" << L->getNumBlocks()
1664 // For now, we'll handle only single BB loops.
1665 if (L->getNumBlocks() > 1)
1668 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1671 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1672 LLVM_DEBUG(dbgs() << "\n Before Reroll:\n" << *(L->getHeader()) << "\n");
1673 LLVM_DEBUG(dbgs() << "LRR: backedge-taken count = " << *BackedgeTakenCount
1676 // First, we need to find the induction variable with respect to which we can
1677 // reroll (there may be several possible options).
1678 SmallInstructionVector PossibleIVs;
1680 LoopControlIV = nullptr;
1681 collectPossibleIVs(L, PossibleIVs);
1683 if (PossibleIVs.empty()) {
1684 LLVM_DEBUG(dbgs() << "LRR: No possible IVs found\n");
1688 ReductionTracker Reductions;
1689 collectPossibleReductions(L, Reductions);
1690 bool Changed = false;
1692 // For each possible IV, collect the associated possible set of 'root' nodes
1693 // (i+1, i+2, etc.).
1694 for (Instruction *PossibleIV : PossibleIVs)
1695 if (reroll(PossibleIV, L, Header, BackedgeTakenCount, Reductions)) {
1699 LLVM_DEBUG(dbgs() << "\n After Reroll:\n" << *(L->getHeader()) << "\n");
1701 // Trip count of L has changed so SE must be re-evaluated.