1 //===-- LoopUnroll.cpp - Loop unroller 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 unroller. It works best when loops have
11 // been canonicalized by the -indvars pass, allowing it to determine the trip
12 // counts of loops easily.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/CodeMetrics.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DiagnosticInfo.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/InstVisitor.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Utils/UnrollLoop.h"
38 #define DEBUG_TYPE "loop-unroll"
40 static cl::opt<unsigned>
41 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
42 cl::desc("The baseline cost threshold for loop unrolling"));
44 static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold(
45 "unroll-percent-dynamic-cost-saved-threshold", cl::init(20), cl::Hidden,
46 cl::desc("The percentage of estimated dynamic cost which must be saved by "
47 "unrolling to allow unrolling up to the max threshold."));
49 static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount(
50 "unroll-dynamic-cost-savings-discount", cl::init(2000), cl::Hidden,
51 cl::desc("This is the amount discounted from the total unroll cost when "
52 "the unrolled form has a high dynamic cost savings (triggered by "
53 "the '-unroll-perecent-dynamic-cost-saved-threshold' flag)."));
55 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
56 "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
57 cl::desc("Don't allow loop unrolling to simulate more than this number of"
58 "iterations when checking full unroll profitability"));
60 static cl::opt<unsigned>
61 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
62 cl::desc("Use this unroll count for all loops including those with "
63 "unroll_count pragma values, for testing purposes"));
66 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
67 cl::desc("Allows loops to be partially unrolled until "
68 "-unroll-threshold loop size is reached."));
71 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
72 cl::desc("Unroll loops with run-time trip counts"));
74 static cl::opt<unsigned>
75 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
76 cl::desc("Unrolled size limit for loops with an unroll(full) or "
77 "unroll_count pragma."));
80 class LoopUnroll : public LoopPass {
82 static char ID; // Pass ID, replacement for typeid
83 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
84 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
85 CurrentPercentDynamicCostSavedThreshold =
86 UnrollPercentDynamicCostSavedThreshold;
87 CurrentDynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount;
88 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
89 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
90 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
92 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
93 UserPercentDynamicCostSavedThreshold =
94 (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0);
95 UserDynamicCostSavingsDiscount =
96 (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0);
97 UserAllowPartial = (P != -1) ||
98 (UnrollAllowPartial.getNumOccurrences() > 0);
99 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
100 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
102 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
105 /// A magic value for use with the Threshold parameter to indicate
106 /// that the loop unroll should be performed regardless of how much
107 /// code expansion would result.
108 static const unsigned NoThreshold = UINT_MAX;
110 // Threshold to use when optsize is specified (and there is no
111 // explicit -unroll-threshold).
112 static const unsigned OptSizeUnrollThreshold = 50;
114 // Default unroll count for loops with run-time trip count if
115 // -unroll-count is not set
116 static const unsigned UnrollRuntimeCount = 8;
118 unsigned CurrentCount;
119 unsigned CurrentThreshold;
120 unsigned CurrentPercentDynamicCostSavedThreshold;
121 unsigned CurrentDynamicCostSavingsDiscount;
122 bool CurrentAllowPartial;
125 // Flags for whether the 'current' settings are user-specified.
128 bool UserPercentDynamicCostSavedThreshold;
129 bool UserDynamicCostSavingsDiscount;
130 bool UserAllowPartial;
133 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
135 /// This transformation requires natural loop information & requires that
136 /// loop preheaders be inserted into the CFG...
138 void getAnalysisUsage(AnalysisUsage &AU) const override {
139 AU.addRequired<AssumptionCacheTracker>();
140 AU.addRequired<LoopInfoWrapperPass>();
141 AU.addPreserved<LoopInfoWrapperPass>();
142 AU.addRequiredID(LoopSimplifyID);
143 AU.addPreservedID(LoopSimplifyID);
144 AU.addRequiredID(LCSSAID);
145 AU.addPreservedID(LCSSAID);
146 AU.addRequired<ScalarEvolution>();
147 AU.addPreserved<ScalarEvolution>();
148 AU.addRequired<TargetTransformInfoWrapperPass>();
149 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
150 // If loop unroll does not preserve dom info then LCSSA pass on next
151 // loop will receive invalid dom info.
152 // For now, recreate dom info, if loop is unrolled.
153 AU.addPreserved<DominatorTreeWrapperPass>();
156 // Fill in the UnrollingPreferences parameter with values from the
157 // TargetTransformationInfo.
158 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
159 TargetTransformInfo::UnrollingPreferences &UP) {
160 UP.Threshold = CurrentThreshold;
161 UP.PercentDynamicCostSavedThreshold =
162 CurrentPercentDynamicCostSavedThreshold;
163 UP.DynamicCostSavingsDiscount = CurrentDynamicCostSavingsDiscount;
164 UP.OptSizeThreshold = OptSizeUnrollThreshold;
165 UP.PartialThreshold = CurrentThreshold;
166 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
167 UP.Count = CurrentCount;
168 UP.MaxCount = UINT_MAX;
169 UP.Partial = CurrentAllowPartial;
170 UP.Runtime = CurrentRuntime;
171 UP.AllowExpensiveTripCount = false;
172 TTI.getUnrollingPreferences(L, UP);
175 // Select and return an unroll count based on parameters from
176 // user, unroll preferences, unroll pragmas, or a heuristic.
177 // SetExplicitly is set to true if the unroll count is is set by
178 // the user or a pragma rather than selected heuristically.
180 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
181 unsigned PragmaCount,
182 const TargetTransformInfo::UnrollingPreferences &UP,
183 bool &SetExplicitly);
185 // Select threshold values used to limit unrolling based on a
186 // total unrolled size. Parameters Threshold and PartialThreshold
187 // are set to the maximum unrolled size for fully and partially
188 // unrolled loops respectively.
189 void selectThresholds(const Loop *L, bool HasPragma,
190 const TargetTransformInfo::UnrollingPreferences &UP,
191 unsigned &Threshold, unsigned &PartialThreshold,
192 unsigned &PercentDynamicCostSavedThreshold,
193 unsigned &DynamicCostSavingsDiscount) {
194 // Determine the current unrolling threshold. While this is
195 // normally set from UnrollThreshold, it is overridden to a
196 // smaller value if the current function is marked as
197 // optimize-for-size, and the unroll threshold was not user
199 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
200 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
201 PercentDynamicCostSavedThreshold =
202 UserPercentDynamicCostSavedThreshold
203 ? CurrentPercentDynamicCostSavedThreshold
204 : UP.PercentDynamicCostSavedThreshold;
205 DynamicCostSavingsDiscount = UserDynamicCostSavingsDiscount
206 ? CurrentDynamicCostSavingsDiscount
207 : UP.DynamicCostSavingsDiscount;
209 if (!UserThreshold &&
210 L->getHeader()->getParent()->hasFnAttribute(
211 Attribute::OptimizeForSize)) {
212 Threshold = UP.OptSizeThreshold;
213 PartialThreshold = UP.PartialOptSizeThreshold;
216 // If the loop has an unrolling pragma, we want to be more
217 // aggressive with unrolling limits. Set thresholds to at
218 // least the PragmaTheshold value which is larger than the
220 if (Threshold != NoThreshold)
221 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
222 if (PartialThreshold != NoThreshold)
224 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
227 bool canUnrollCompletely(Loop *L, unsigned Threshold,
228 unsigned PercentDynamicCostSavedThreshold,
229 unsigned DynamicCostSavingsDiscount,
230 uint64_t UnrolledCost, uint64_t RolledDynamicCost);
234 char LoopUnroll::ID = 0;
235 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
236 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
237 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
238 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
239 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
240 INITIALIZE_PASS_DEPENDENCY(LCSSA)
241 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
242 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
244 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
246 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
249 Pass *llvm::createSimpleLoopUnrollPass() {
250 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
254 // This class is used to get an estimate of the optimization effects that we
255 // could get from complete loop unrolling. It comes from the fact that some
256 // loads might be replaced with concrete constant values and that could trigger
257 // a chain of instruction simplifications.
259 // E.g. we might have:
260 // int a[] = {0, 1, 0};
262 // for (i = 0; i < 3; i ++)
264 // If we completely unroll the loop, we would get:
265 // v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
266 // Which then will be simplified to:
267 // v = b[0]* 0 + b[1]* 1 + b[2]* 0
270 class UnrolledInstAnalyzer : private InstVisitor<UnrolledInstAnalyzer, bool> {
271 typedef InstVisitor<UnrolledInstAnalyzer, bool> Base;
272 friend class InstVisitor<UnrolledInstAnalyzer, bool>;
273 struct SimplifiedAddress {
274 Value *Base = nullptr;
275 ConstantInt *Offset = nullptr;
279 UnrolledInstAnalyzer(unsigned Iteration,
280 DenseMap<Value *, Constant *> &SimplifiedValues,
281 const Loop *L, ScalarEvolution &SE)
282 : Iteration(Iteration), SimplifiedValues(SimplifiedValues), L(L), SE(SE) {
283 IterationNumber = SE.getConstant(APInt(64, Iteration));
286 // Allow access to the initial visit method.
290 /// \brief A cache of pointer bases and constant-folded offsets corresponding
291 /// to GEP (or derived from GEP) instructions.
293 /// In order to find the base pointer one needs to perform non-trivial
294 /// traversal of the corresponding SCEV expression, so it's good to have the
296 DenseMap<Value *, SimplifiedAddress> SimplifiedAddresses;
298 /// \brief Number of currently simulated iteration.
300 /// If an expression is ConstAddress+Constant, then the Constant is
301 /// Start + Iteration*Step, where Start and Step could be obtained from
305 /// \brief SCEV expression corresponding to number of currently simulated
307 const SCEV *IterationNumber;
309 /// \brief A Value->Constant map for keeping values that we managed to
310 /// constant-fold on the given iteration.
312 /// While we walk the loop instructions, we build up and maintain a mapping
313 /// of simplified values specific to this iteration. The idea is to propagate
314 /// any special information we have about loads that can be replaced with
315 /// constants after complete unrolling, and account for likely simplifications
317 DenseMap<Value *, Constant *> &SimplifiedValues;
322 /// \brief Try to simplify instruction \param I using its SCEV expression.
324 /// The idea is that some AddRec expressions become constants, which then
325 /// could trigger folding of other instructions. However, that only happens
326 /// for expressions whose start value is also constant, which isn't always the
327 /// case. In another common and important case the start value is just some
328 /// address (i.e. SCEVUnknown) - in this case we compute the offset and save
329 /// it along with the base address instead.
330 bool simplifyInstWithSCEV(Instruction *I) {
331 if (!SE.isSCEVable(I->getType()))
334 const SCEV *S = SE.getSCEV(I);
335 if (auto *SC = dyn_cast<SCEVConstant>(S)) {
336 SimplifiedValues[I] = SC->getValue();
340 auto *AR = dyn_cast<SCEVAddRecExpr>(S);
344 const SCEV *ValueAtIteration = AR->evaluateAtIteration(IterationNumber, SE);
345 // Check if the AddRec expression becomes a constant.
346 if (auto *SC = dyn_cast<SCEVConstant>(ValueAtIteration)) {
347 SimplifiedValues[I] = SC->getValue();
351 // Check if the offset from the base address becomes a constant.
352 auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(S));
356 dyn_cast<SCEVConstant>(SE.getMinusSCEV(ValueAtIteration, Base));
359 SimplifiedAddress Address;
360 Address.Base = Base->getValue();
361 Address.Offset = Offset->getValue();
362 SimplifiedAddresses[I] = Address;
366 /// Base case for the instruction visitor.
367 bool visitInstruction(Instruction &I) {
368 return simplifyInstWithSCEV(&I);
371 /// Try to simplify binary operator I.
373 /// TODO: Probaly it's worth to hoist the code for estimating the
374 /// simplifications effects to a separate class, since we have a very similar
375 /// code in InlineCost already.
376 bool visitBinaryOperator(BinaryOperator &I) {
377 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
378 if (!isa<Constant>(LHS))
379 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
381 if (!isa<Constant>(RHS))
382 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
385 Value *SimpleV = nullptr;
386 const DataLayout &DL = I.getModule()->getDataLayout();
387 if (auto FI = dyn_cast<FPMathOperator>(&I))
389 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
391 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
393 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
394 SimplifiedValues[&I] = C;
398 return Base::visitBinaryOperator(I);
401 /// Try to fold load I.
402 bool visitLoad(LoadInst &I) {
403 Value *AddrOp = I.getPointerOperand();
405 auto AddressIt = SimplifiedAddresses.find(AddrOp);
406 if (AddressIt == SimplifiedAddresses.end())
408 ConstantInt *SimplifiedAddrOp = AddressIt->second.Offset;
410 auto *GV = dyn_cast<GlobalVariable>(AddressIt->second.Base);
411 // We're only interested in loads that can be completely folded to a
413 if (!GV || !GV->hasInitializer())
416 ConstantDataSequential *CDS =
417 dyn_cast<ConstantDataSequential>(GV->getInitializer());
421 int ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
422 assert(SimplifiedAddrOp->getValue().getActiveBits() < 64 &&
423 "Unexpectedly large index value.");
424 int64_t Index = SimplifiedAddrOp->getSExtValue() / ElemSize;
425 if (Index >= CDS->getNumElements()) {
426 // FIXME: For now we conservatively ignore out of bound accesses, but
427 // we're allowed to perform the optimization in this case.
431 Constant *CV = CDS->getElementAsConstant(Index);
432 assert(CV && "Constant expected.");
433 SimplifiedValues[&I] = CV;
438 bool visitCastInst(CastInst &I) {
439 // Propagate constants through casts.
440 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
442 COp = SimplifiedValues.lookup(I.getOperand(0));
445 ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
446 SimplifiedValues[&I] = C;
450 return Base::visitCastInst(I);
453 bool visitCmpInst(CmpInst &I) {
454 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
456 // First try to handle simplified comparisons.
457 if (!isa<Constant>(LHS))
458 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
460 if (!isa<Constant>(RHS))
461 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
464 if (!isa<Constant>(LHS) && !isa<Constant>(RHS)) {
465 auto SimplifiedLHS = SimplifiedAddresses.find(LHS);
466 if (SimplifiedLHS != SimplifiedAddresses.end()) {
467 auto SimplifiedRHS = SimplifiedAddresses.find(RHS);
468 if (SimplifiedRHS != SimplifiedAddresses.end()) {
469 SimplifiedAddress &LHSAddr = SimplifiedLHS->second;
470 SimplifiedAddress &RHSAddr = SimplifiedRHS->second;
471 if (LHSAddr.Base == RHSAddr.Base) {
472 LHS = LHSAddr.Offset;
473 RHS = RHSAddr.Offset;
479 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
480 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
481 if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
482 SimplifiedValues[&I] = C;
488 return Base::visitCmpInst(I);
495 struct EstimatedUnrollCost {
496 /// \brief The estimated cost after unrolling.
497 unsigned UnrolledCost;
499 /// \brief The estimated dynamic cost of executing the instructions in the
501 unsigned RolledDynamicCost;
505 /// \brief Figure out if the loop is worth full unrolling.
507 /// Complete loop unrolling can make some loads constant, and we need to know
508 /// if that would expose any further optimization opportunities. This routine
509 /// estimates this optimization. It computes cost of unrolled loop
510 /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
511 /// dynamic cost we mean that we won't count costs of blocks that are known not
512 /// to be executed (i.e. if we have a branch in the loop and we know that at the
513 /// given iteration its condition would be resolved to true, we won't add up the
514 /// cost of the 'false'-block).
515 /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
516 /// the analysis failed (no benefits expected from the unrolling, or the loop is
517 /// too big to analyze), the returned value is None.
518 Optional<EstimatedUnrollCost>
519 analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, ScalarEvolution &SE,
520 const TargetTransformInfo &TTI,
521 unsigned MaxUnrolledLoopSize) {
522 // We want to be able to scale offsets by the trip count and add more offsets
523 // to them without checking for overflows, and we already don't want to
524 // analyze *massive* trip counts, so we force the max to be reasonably small.
525 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
526 "The unroll iterations max is too large!");
528 // Don't simulate loops with a big or unknown tripcount
529 if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
530 TripCount > UnrollMaxIterationsCountToAnalyze)
533 SmallSetVector<BasicBlock *, 16> BBWorklist;
534 DenseMap<Value *, Constant *> SimplifiedValues;
536 // The estimated cost of the unrolled form of the loop. We try to estimate
537 // this by simplifying as much as we can while computing the estimate.
538 unsigned UnrolledCost = 0;
539 // We also track the estimated dynamic (that is, actually executed) cost in
540 // the rolled form. This helps identify cases when the savings from unrolling
541 // aren't just exposing dead control flows, but actual reduced dynamic
542 // instructions due to the simplifications which we expect to occur after
544 unsigned RolledDynamicCost = 0;
546 // Simulate execution of each iteration of the loop counting instructions,
547 // which would be simplified.
548 // Since the same load will take different values on different iterations,
549 // we literally have to go through all loop's iterations.
550 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
551 SimplifiedValues.clear();
552 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, L, SE);
555 BBWorklist.insert(L->getHeader());
556 // Note that we *must not* cache the size, this loop grows the worklist.
557 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
558 BasicBlock *BB = BBWorklist[Idx];
560 // Visit all instructions in the given basic block and try to simplify
561 // it. We don't change the actual IR, just count optimization
563 for (Instruction &I : *BB) {
564 unsigned InstCost = TTI.getUserCost(&I);
566 // Visit the instruction to analyze its loop cost after unrolling,
567 // and if the visitor returns false, include this instruction in the
569 if (!Analyzer.visit(I))
570 UnrolledCost += InstCost;
572 // Also track this instructions expected cost when executing the rolled
574 RolledDynamicCost += InstCost;
576 // If unrolled body turns out to be too big, bail out.
577 if (UnrolledCost > MaxUnrolledLoopSize)
581 TerminatorInst *TI = BB->getTerminator();
583 // Add in the live successors by first checking whether we have terminator
584 // that may be simplified based on the values simplified by this call.
585 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
586 if (BI->isConditional()) {
587 if (Constant *SimpleCond =
588 SimplifiedValues.lookup(BI->getCondition())) {
589 BBWorklist.insert(BI->getSuccessor(
590 cast<ConstantInt>(SimpleCond)->isZero() ? 1 : 0));
594 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
595 if (Constant *SimpleCond =
596 SimplifiedValues.lookup(SI->getCondition())) {
598 SI->getSuccessor(cast<ConstantInt>(SimpleCond)->getSExtValue()));
603 // Add BB's successors to the worklist.
604 for (BasicBlock *Succ : successors(BB))
605 if (L->contains(Succ))
606 BBWorklist.insert(Succ);
609 // If we found no optimization opportunities on the first iteration, we
610 // won't find them on later ones too.
611 if (UnrolledCost == RolledDynamicCost)
614 return {{UnrolledCost, RolledDynamicCost}};
617 /// ApproximateLoopSize - Approximate the size of the loop.
618 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
619 bool &NotDuplicatable,
620 const TargetTransformInfo &TTI,
621 AssumptionCache *AC) {
622 SmallPtrSet<const Value *, 32> EphValues;
623 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
626 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
628 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
629 NumCalls = Metrics.NumInlineCandidates;
630 NotDuplicatable = Metrics.notDuplicatable;
632 unsigned LoopSize = Metrics.NumInsts;
634 // Don't allow an estimate of size zero. This would allows unrolling of loops
635 // with huge iteration counts, which is a compile time problem even if it's
636 // not a problem for code quality. Also, the code using this size may assume
637 // that each loop has at least three instructions (likely a conditional
638 // branch, a comparison feeding that branch, and some kind of loop increment
639 // feeding that comparison instruction).
640 LoopSize = std::max(LoopSize, 3u);
645 // Returns the loop hint metadata node with the given name (for example,
646 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
648 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
649 if (MDNode *LoopID = L->getLoopID())
650 return GetUnrollMetadata(LoopID, Name);
654 // Returns true if the loop has an unroll(full) pragma.
655 static bool HasUnrollFullPragma(const Loop *L) {
656 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
659 // Returns true if the loop has an unroll(disable) pragma.
660 static bool HasUnrollDisablePragma(const Loop *L) {
661 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
664 // Returns true if the loop has an runtime unroll(disable) pragma.
665 static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
666 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
669 // If loop has an unroll_count pragma return the (necessarily
670 // positive) value from the pragma. Otherwise return 0.
671 static unsigned UnrollCountPragmaValue(const Loop *L) {
672 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
674 assert(MD->getNumOperands() == 2 &&
675 "Unroll count hint metadata should have two operands.");
677 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
678 assert(Count >= 1 && "Unroll count must be positive.");
684 // Remove existing unroll metadata and add unroll disable metadata to
685 // indicate the loop has already been unrolled. This prevents a loop
686 // from being unrolled more than is directed by a pragma if the loop
687 // unrolling pass is run more than once (which it generally is).
688 static void SetLoopAlreadyUnrolled(Loop *L) {
689 MDNode *LoopID = L->getLoopID();
692 // First remove any existing loop unrolling metadata.
693 SmallVector<Metadata *, 4> MDs;
694 // Reserve first location for self reference to the LoopID metadata node.
695 MDs.push_back(nullptr);
696 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
697 bool IsUnrollMetadata = false;
698 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
700 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
701 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
703 if (!IsUnrollMetadata)
704 MDs.push_back(LoopID->getOperand(i));
707 // Add unroll(disable) metadata to disable future unrolling.
708 LLVMContext &Context = L->getHeader()->getContext();
709 SmallVector<Metadata *, 1> DisableOperands;
710 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
711 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
712 MDs.push_back(DisableNode);
714 MDNode *NewLoopID = MDNode::get(Context, MDs);
715 // Set operand 0 to refer to the loop id itself.
716 NewLoopID->replaceOperandWith(0, NewLoopID);
717 L->setLoopID(NewLoopID);
720 bool LoopUnroll::canUnrollCompletely(Loop *L, unsigned Threshold,
721 unsigned PercentDynamicCostSavedThreshold,
722 unsigned DynamicCostSavingsDiscount,
723 uint64_t UnrolledCost,
724 uint64_t RolledDynamicCost) {
726 if (Threshold == NoThreshold) {
727 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n");
731 if (UnrolledCost <= Threshold) {
732 DEBUG(dbgs() << " Can fully unroll, because unrolled cost: "
733 << UnrolledCost << "<" << Threshold << "\n");
737 assert(UnrolledCost && "UnrolledCost can't be 0 at this point.");
738 assert(RolledDynamicCost >= UnrolledCost &&
739 "Cannot have a higher unrolled cost than a rolled cost!");
741 // Compute the percentage of the dynamic cost in the rolled form that is
742 // saved when unrolled. If unrolling dramatically reduces the estimated
743 // dynamic cost of the loop, we use a higher threshold to allow more
745 unsigned PercentDynamicCostSaved =
746 (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost;
748 if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold &&
749 (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <=
750 (int64_t)Threshold) {
751 DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the "
752 "expected dynamic cost by " << PercentDynamicCostSaved
753 << "% (threshold: " << PercentDynamicCostSavedThreshold
755 << " and the unrolled cost (" << UnrolledCost
756 << ") is less than the max threshold ("
757 << DynamicCostSavingsDiscount << ").\n");
761 DEBUG(dbgs() << " Too large to fully unroll:\n");
762 DEBUG(dbgs() << " Threshold: " << Threshold << "\n");
763 DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n");
764 DEBUG(dbgs() << " Percent cost saved threshold: "
765 << PercentDynamicCostSavedThreshold << "%\n");
766 DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n");
767 DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n");
768 DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved
773 unsigned LoopUnroll::selectUnrollCount(
774 const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
775 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
776 bool &SetExplicitly) {
777 SetExplicitly = true;
779 // User-specified count (either as a command-line option or
780 // constructor parameter) has highest precedence.
781 unsigned Count = UserCount ? CurrentCount : 0;
783 // If there is no user-specified count, unroll pragmas have the next
784 // highest precendence.
788 } else if (PragmaFullUnroll) {
797 SetExplicitly = false;
799 // Runtime trip count.
800 Count = UnrollRuntimeCount;
802 // Conservative heuristic: if we know the trip count, see if we can
803 // completely unroll (subject to the threshold, checked below); otherwise
804 // try to find greatest modulo of the trip count which is still under
808 if (TripCount && Count > TripCount)
813 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
814 if (skipOptnoneFunction(L))
817 Function &F = *L->getHeader()->getParent();
819 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
820 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
821 const TargetTransformInfo &TTI =
822 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
823 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
825 BasicBlock *Header = L->getHeader();
826 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
827 << "] Loop %" << Header->getName() << "\n");
829 if (HasUnrollDisablePragma(L)) {
832 bool PragmaFullUnroll = HasUnrollFullPragma(L);
833 unsigned PragmaCount = UnrollCountPragmaValue(L);
834 bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
836 TargetTransformInfo::UnrollingPreferences UP;
837 getUnrollingPreferences(L, TTI, UP);
839 // Find trip count and trip multiple if count is not available
840 unsigned TripCount = 0;
841 unsigned TripMultiple = 1;
842 // If there are multiple exiting blocks but one of them is the latch, use the
843 // latch for the trip count estimation. Otherwise insist on a single exiting
844 // block for the trip count estimation.
845 BasicBlock *ExitingBlock = L->getLoopLatch();
846 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
847 ExitingBlock = L->getExitingBlock();
849 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
850 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
853 // Select an initial unroll count. This may be reduced later based
854 // on size thresholds.
855 bool CountSetExplicitly;
856 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
857 PragmaCount, UP, CountSetExplicitly);
859 unsigned NumInlineCandidates;
860 bool notDuplicatable;
862 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
863 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
865 // When computing the unrolled size, note that the conditional branch on the
866 // backedge and the comparison feeding it are not replicated like the rest of
867 // the loop body (which is why 2 is subtracted).
868 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
869 if (notDuplicatable) {
870 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
871 << " instructions.\n");
874 if (NumInlineCandidates != 0) {
875 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
879 unsigned Threshold, PartialThreshold;
880 unsigned PercentDynamicCostSavedThreshold;
881 unsigned DynamicCostSavingsDiscount;
882 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold,
883 PercentDynamicCostSavedThreshold,
884 DynamicCostSavingsDiscount);
886 // Given Count, TripCount and thresholds determine the type of
887 // unrolling which is to be performed.
888 enum { Full = 0, Partial = 1, Runtime = 2 };
890 if (TripCount && Count == TripCount) {
892 // If the loop is really small, we don't need to run an expensive analysis.
893 if (canUnrollCompletely(L, Threshold, 100, DynamicCostSavingsDiscount,
894 UnrolledSize, UnrolledSize)) {
897 // The loop isn't that small, but we still can fully unroll it if that
898 // helps to remove a significant number of instructions.
899 // To check that, run additional analysis on the loop.
900 if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
901 L, TripCount, *SE, TTI, Threshold + DynamicCostSavingsDiscount))
902 if (canUnrollCompletely(L, Threshold, PercentDynamicCostSavedThreshold,
903 DynamicCostSavingsDiscount, Cost->UnrolledCost,
904 Cost->RolledDynamicCost)) {
908 } else if (TripCount && Count < TripCount) {
914 // Reduce count based on the type of unrolling and the threshold values.
915 unsigned OriginalCount = Count;
917 (PragmaCount > 0) || (UserRuntime ? CurrentRuntime : UP.Runtime);
918 // Don't unroll a runtime trip count loop with unroll full pragma.
919 if (HasRuntimeUnrollDisablePragma(L) || PragmaFullUnroll) {
920 AllowRuntime = false;
922 if (Unrolling == Partial) {
923 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
924 if (!AllowPartial && !CountSetExplicitly) {
925 DEBUG(dbgs() << " will not try to unroll partially because "
926 << "-unroll-allow-partial not given\n");
929 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
930 // Reduce unroll count to be modulo of TripCount for partial unrolling.
931 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
932 while (Count != 0 && TripCount % Count != 0)
935 } else if (Unrolling == Runtime) {
936 if (!AllowRuntime && !CountSetExplicitly) {
937 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
938 << "-unroll-runtime not given\n");
941 // Reduce unroll count to be the largest power-of-two factor of
942 // the original count which satisfies the threshold limit.
943 while (Count != 0 && UnrolledSize > PartialThreshold) {
945 UnrolledSize = (LoopSize-2) * Count + 2;
947 if (Count > UP.MaxCount)
949 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
953 if (PragmaCount != 0)
954 // If loop has an unroll count pragma mark loop as unrolled to prevent
955 // unrolling beyond that requested by the pragma.
956 SetLoopAlreadyUnrolled(L);
958 // Emit optimization remarks if we are unable to unroll the loop
959 // as directed by a pragma.
960 DebugLoc LoopLoc = L->getStartLoc();
961 Function *F = Header->getParent();
962 LLVMContext &Ctx = F->getContext();
963 if (PragmaFullUnroll && PragmaCount == 0) {
964 if (TripCount && Count != TripCount) {
965 emitOptimizationRemarkMissed(
966 Ctx, DEBUG_TYPE, *F, LoopLoc,
967 "Unable to fully unroll loop as directed by unroll(full) pragma "
968 "because unrolled size is too large.");
969 } else if (!TripCount) {
970 emitOptimizationRemarkMissed(
971 Ctx, DEBUG_TYPE, *F, LoopLoc,
972 "Unable to fully unroll loop as directed by unroll(full) pragma "
973 "because loop has a runtime trip count.");
975 } else if (PragmaCount > 0 && Count != OriginalCount) {
976 emitOptimizationRemarkMissed(
977 Ctx, DEBUG_TYPE, *F, LoopLoc,
978 "Unable to unroll loop the number of times directed by "
979 "unroll_count pragma because unrolled size is too large.");
983 if (Unrolling != Full && Count < 2) {
984 // Partial unrolling by 1 is a nop. For full unrolling, a factor
985 // of 1 makes sense because loop control can be eliminated.
990 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
991 TripMultiple, LI, this, &LPM, &AC))