xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp (revision 3ca4a6bcf11d6b4ac34fed640f3ab23995ec1877)
1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/GlobalsModRef.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/LoopPassManager.h"
22 #include "llvm/Analysis/LoopUnrollAnalyzer.h"
23 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
24 #include "llvm/Analysis/ScalarEvolution.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/InstVisitor.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/Transforms/Utils/LoopUtils.h"
36 #include "llvm/Transforms/Utils/UnrollLoop.h"
37 #include <climits>
38 #include <utility>
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "loop-unroll"
43 
44 static cl::opt<unsigned>
45     UnrollThreshold("unroll-threshold", cl::Hidden,
46                     cl::desc("The baseline cost threshold for loop unrolling"));
47 
48 static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold(
49     "unroll-percent-dynamic-cost-saved-threshold", cl::init(50), cl::Hidden,
50     cl::desc("The percentage of estimated dynamic cost which must be saved by "
51              "unrolling to allow unrolling up to the max threshold."));
52 
53 static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount(
54     "unroll-dynamic-cost-savings-discount", cl::init(100), cl::Hidden,
55     cl::desc("This is the amount discounted from the total unroll cost when "
56              "the unrolled form has a high dynamic cost savings (triggered by "
57              "the '-unroll-perecent-dynamic-cost-saved-threshold' flag)."));
58 
59 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
60     "unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden,
61     cl::desc("Don't allow loop unrolling to simulate more than this number of"
62              "iterations when checking full unroll profitability"));
63 
64 static cl::opt<unsigned> UnrollCount(
65     "unroll-count", cl::Hidden,
66     cl::desc("Use this unroll count for all loops including those with "
67              "unroll_count pragma values, for testing purposes"));
68 
69 static cl::opt<unsigned> UnrollMaxCount(
70     "unroll-max-count", cl::Hidden,
71     cl::desc("Set the max unroll count for partial and runtime unrolling, for"
72              "testing purposes"));
73 
74 static cl::opt<unsigned> UnrollFullMaxCount(
75     "unroll-full-max-count", cl::Hidden,
76     cl::desc(
77         "Set the max unroll count for full unrolling, for testing purposes"));
78 
79 static cl::opt<bool>
80     UnrollAllowPartial("unroll-allow-partial", cl::Hidden,
81                        cl::desc("Allows loops to be partially unrolled until "
82                                 "-unroll-threshold loop size is reached."));
83 
84 static cl::opt<bool> UnrollAllowRemainder(
85     "unroll-allow-remainder", cl::Hidden,
86     cl::desc("Allow generation of a loop remainder (extra iterations) "
87              "when unrolling a loop."));
88 
89 static cl::opt<bool>
90     UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden,
91                   cl::desc("Unroll loops with run-time trip counts"));
92 
93 static cl::opt<unsigned> UnrollMaxUpperBound(
94     "unroll-max-upperbound", cl::init(8), cl::Hidden,
95     cl::desc(
96         "The max of trip count upper bound that is considered in unrolling"));
97 
98 static cl::opt<unsigned> PragmaUnrollThreshold(
99     "pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
100     cl::desc("Unrolled size limit for loops with an unroll(full) or "
101              "unroll_count pragma."));
102 
103 static cl::opt<unsigned> FlatLoopTripCountThreshold(
104     "flat-loop-tripcount-threshold", cl::init(5), cl::Hidden,
105     cl::desc("If the runtime tripcount for the loop is lower than the "
106              "threshold, the loop is considered as flat and will be less "
107              "aggressively unrolled."));
108 
109 static cl::opt<bool>
110     UnrollAllowPeeling("unroll-allow-peeling", cl::Hidden,
111                        cl::desc("Allows loops to be peeled when the dynamic "
112                                 "trip count is known to be low."));
113 
114 /// A magic value for use with the Threshold parameter to indicate
115 /// that the loop unroll should be performed regardless of how much
116 /// code expansion would result.
117 static const unsigned NoThreshold = UINT_MAX;
118 
119 /// Gather the various unrolling parameters based on the defaults, compiler
120 /// flags, TTI overrides and user specified parameters.
121 static TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences(
122     Loop *L, const TargetTransformInfo &TTI, Optional<unsigned> UserThreshold,
123     Optional<unsigned> UserCount, Optional<bool> UserAllowPartial,
124     Optional<bool> UserRuntime, Optional<bool> UserUpperBound) {
125   TargetTransformInfo::UnrollingPreferences UP;
126 
127   // Set up the defaults
128   UP.Threshold = 150;
129   UP.PercentDynamicCostSavedThreshold = 50;
130   UP.DynamicCostSavingsDiscount = 100;
131   UP.OptSizeThreshold = 0;
132   UP.PartialThreshold = UP.Threshold;
133   UP.PartialOptSizeThreshold = 0;
134   UP.Count = 0;
135   UP.PeelCount = 0;
136   UP.DefaultUnrollRuntimeCount = 8;
137   UP.MaxCount = UINT_MAX;
138   UP.FullUnrollMaxCount = UINT_MAX;
139   UP.BEInsns = 2;
140   UP.Partial = false;
141   UP.Runtime = false;
142   UP.AllowRemainder = true;
143   UP.AllowExpensiveTripCount = false;
144   UP.Force = false;
145   UP.UpperBound = false;
146   UP.AllowPeeling = false;
147 
148   // Override with any target specific settings
149   TTI.getUnrollingPreferences(L, UP);
150 
151   // Apply size attributes
152   if (L->getHeader()->getParent()->optForSize()) {
153     UP.Threshold = UP.OptSizeThreshold;
154     UP.PartialThreshold = UP.PartialOptSizeThreshold;
155   }
156 
157   // Apply any user values specified by cl::opt
158   if (UnrollThreshold.getNumOccurrences() > 0) {
159     UP.Threshold = UnrollThreshold;
160     UP.PartialThreshold = UnrollThreshold;
161   }
162   if (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0)
163     UP.PercentDynamicCostSavedThreshold =
164         UnrollPercentDynamicCostSavedThreshold;
165   if (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0)
166     UP.DynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount;
167   if (UnrollMaxCount.getNumOccurrences() > 0)
168     UP.MaxCount = UnrollMaxCount;
169   if (UnrollFullMaxCount.getNumOccurrences() > 0)
170     UP.FullUnrollMaxCount = UnrollFullMaxCount;
171   if (UnrollAllowPartial.getNumOccurrences() > 0)
172     UP.Partial = UnrollAllowPartial;
173   if (UnrollAllowRemainder.getNumOccurrences() > 0)
174     UP.AllowRemainder = UnrollAllowRemainder;
175   if (UnrollRuntime.getNumOccurrences() > 0)
176     UP.Runtime = UnrollRuntime;
177   if (UnrollMaxUpperBound == 0)
178     UP.UpperBound = false;
179   if (UnrollAllowPeeling.getNumOccurrences() > 0)
180     UP.AllowPeeling = UnrollAllowPeeling;
181 
182   // Apply user values provided by argument
183   if (UserThreshold.hasValue()) {
184     UP.Threshold = *UserThreshold;
185     UP.PartialThreshold = *UserThreshold;
186   }
187   if (UserCount.hasValue())
188     UP.Count = *UserCount;
189   if (UserAllowPartial.hasValue())
190     UP.Partial = *UserAllowPartial;
191   if (UserRuntime.hasValue())
192     UP.Runtime = *UserRuntime;
193   if (UserUpperBound.hasValue())
194     UP.UpperBound = *UserUpperBound;
195 
196   return UP;
197 }
198 
199 namespace {
200 /// A struct to densely store the state of an instruction after unrolling at
201 /// each iteration.
202 ///
203 /// This is designed to work like a tuple of <Instruction *, int> for the
204 /// purposes of hashing and lookup, but to be able to associate two boolean
205 /// states with each key.
206 struct UnrolledInstState {
207   Instruction *I;
208   int Iteration : 30;
209   unsigned IsFree : 1;
210   unsigned IsCounted : 1;
211 };
212 
213 /// Hashing and equality testing for a set of the instruction states.
214 struct UnrolledInstStateKeyInfo {
215   typedef DenseMapInfo<Instruction *> PtrInfo;
216   typedef DenseMapInfo<std::pair<Instruction *, int>> PairInfo;
217   static inline UnrolledInstState getEmptyKey() {
218     return {PtrInfo::getEmptyKey(), 0, 0, 0};
219   }
220   static inline UnrolledInstState getTombstoneKey() {
221     return {PtrInfo::getTombstoneKey(), 0, 0, 0};
222   }
223   static inline unsigned getHashValue(const UnrolledInstState &S) {
224     return PairInfo::getHashValue({S.I, S.Iteration});
225   }
226   static inline bool isEqual(const UnrolledInstState &LHS,
227                              const UnrolledInstState &RHS) {
228     return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration});
229   }
230 };
231 }
232 
233 namespace {
234 struct EstimatedUnrollCost {
235   /// \brief The estimated cost after unrolling.
236   unsigned UnrolledCost;
237 
238   /// \brief The estimated dynamic cost of executing the instructions in the
239   /// rolled form.
240   unsigned RolledDynamicCost;
241 };
242 }
243 
244 /// \brief Figure out if the loop is worth full unrolling.
245 ///
246 /// Complete loop unrolling can make some loads constant, and we need to know
247 /// if that would expose any further optimization opportunities.  This routine
248 /// estimates this optimization.  It computes cost of unrolled loop
249 /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
250 /// dynamic cost we mean that we won't count costs of blocks that are known not
251 /// to be executed (i.e. if we have a branch in the loop and we know that at the
252 /// given iteration its condition would be resolved to true, we won't add up the
253 /// cost of the 'false'-block).
254 /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
255 /// the analysis failed (no benefits expected from the unrolling, or the loop is
256 /// too big to analyze), the returned value is None.
257 static Optional<EstimatedUnrollCost>
258 analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT,
259                       ScalarEvolution &SE, const TargetTransformInfo &TTI,
260                       unsigned MaxUnrolledLoopSize) {
261   // We want to be able to scale offsets by the trip count and add more offsets
262   // to them without checking for overflows, and we already don't want to
263   // analyze *massive* trip counts, so we force the max to be reasonably small.
264   assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
265          "The unroll iterations max is too large!");
266 
267   // Only analyze inner loops. We can't properly estimate cost of nested loops
268   // and we won't visit inner loops again anyway.
269   if (!L->empty())
270     return None;
271 
272   // Don't simulate loops with a big or unknown tripcount
273   if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
274       TripCount > UnrollMaxIterationsCountToAnalyze)
275     return None;
276 
277   SmallSetVector<BasicBlock *, 16> BBWorklist;
278   SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist;
279   DenseMap<Value *, Constant *> SimplifiedValues;
280   SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
281 
282   // The estimated cost of the unrolled form of the loop. We try to estimate
283   // this by simplifying as much as we can while computing the estimate.
284   unsigned UnrolledCost = 0;
285 
286   // We also track the estimated dynamic (that is, actually executed) cost in
287   // the rolled form. This helps identify cases when the savings from unrolling
288   // aren't just exposing dead control flows, but actual reduced dynamic
289   // instructions due to the simplifications which we expect to occur after
290   // unrolling.
291   unsigned RolledDynamicCost = 0;
292 
293   // We track the simplification of each instruction in each iteration. We use
294   // this to recursively merge costs into the unrolled cost on-demand so that
295   // we don't count the cost of any dead code. This is essentially a map from
296   // <instruction, int> to <bool, bool>, but stored as a densely packed struct.
297   DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap;
298 
299   // A small worklist used to accumulate cost of instructions from each
300   // observable and reached root in the loop.
301   SmallVector<Instruction *, 16> CostWorklist;
302 
303   // PHI-used worklist used between iterations while accumulating cost.
304   SmallVector<Instruction *, 4> PHIUsedList;
305 
306   // Helper function to accumulate cost for instructions in the loop.
307   auto AddCostRecursively = [&](Instruction &RootI, int Iteration) {
308     assert(Iteration >= 0 && "Cannot have a negative iteration!");
309     assert(CostWorklist.empty() && "Must start with an empty cost list");
310     assert(PHIUsedList.empty() && "Must start with an empty phi used list");
311     CostWorklist.push_back(&RootI);
312     for (;; --Iteration) {
313       do {
314         Instruction *I = CostWorklist.pop_back_val();
315 
316         // InstCostMap only uses I and Iteration as a key, the other two values
317         // don't matter here.
318         auto CostIter = InstCostMap.find({I, Iteration, 0, 0});
319         if (CostIter == InstCostMap.end())
320           // If an input to a PHI node comes from a dead path through the loop
321           // we may have no cost data for it here. What that actually means is
322           // that it is free.
323           continue;
324         auto &Cost = *CostIter;
325         if (Cost.IsCounted)
326           // Already counted this instruction.
327           continue;
328 
329         // Mark that we are counting the cost of this instruction now.
330         Cost.IsCounted = true;
331 
332         // If this is a PHI node in the loop header, just add it to the PHI set.
333         if (auto *PhiI = dyn_cast<PHINode>(I))
334           if (PhiI->getParent() == L->getHeader()) {
335             assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they "
336                                   "inherently simplify during unrolling.");
337             if (Iteration == 0)
338               continue;
339 
340             // Push the incoming value from the backedge into the PHI used list
341             // if it is an in-loop instruction. We'll use this to populate the
342             // cost worklist for the next iteration (as we count backwards).
343             if (auto *OpI = dyn_cast<Instruction>(
344                     PhiI->getIncomingValueForBlock(L->getLoopLatch())))
345               if (L->contains(OpI))
346                 PHIUsedList.push_back(OpI);
347             continue;
348           }
349 
350         // First accumulate the cost of this instruction.
351         if (!Cost.IsFree) {
352           UnrolledCost += TTI.getUserCost(I);
353           DEBUG(dbgs() << "Adding cost of instruction (iteration " << Iteration
354                        << "): ");
355           DEBUG(I->dump());
356         }
357 
358         // We must count the cost of every operand which is not free,
359         // recursively. If we reach a loop PHI node, simply add it to the set
360         // to be considered on the next iteration (backwards!).
361         for (Value *Op : I->operands()) {
362           // Check whether this operand is free due to being a constant or
363           // outside the loop.
364           auto *OpI = dyn_cast<Instruction>(Op);
365           if (!OpI || !L->contains(OpI))
366             continue;
367 
368           // Otherwise accumulate its cost.
369           CostWorklist.push_back(OpI);
370         }
371       } while (!CostWorklist.empty());
372 
373       if (PHIUsedList.empty())
374         // We've exhausted the search.
375         break;
376 
377       assert(Iteration > 0 &&
378              "Cannot track PHI-used values past the first iteration!");
379       CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end());
380       PHIUsedList.clear();
381     }
382   };
383 
384   // Ensure that we don't violate the loop structure invariants relied on by
385   // this analysis.
386   assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
387   assert(L->isLCSSAForm(DT) &&
388          "Must have loops in LCSSA form to track live-out values.");
389 
390   DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
391 
392   // Simulate execution of each iteration of the loop counting instructions,
393   // which would be simplified.
394   // Since the same load will take different values on different iterations,
395   // we literally have to go through all loop's iterations.
396   for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
397     DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
398 
399     // Prepare for the iteration by collecting any simplified entry or backedge
400     // inputs.
401     for (Instruction &I : *L->getHeader()) {
402       auto *PHI = dyn_cast<PHINode>(&I);
403       if (!PHI)
404         break;
405 
406       // The loop header PHI nodes must have exactly two input: one from the
407       // loop preheader and one from the loop latch.
408       assert(
409           PHI->getNumIncomingValues() == 2 &&
410           "Must have an incoming value only for the preheader and the latch.");
411 
412       Value *V = PHI->getIncomingValueForBlock(
413           Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
414       Constant *C = dyn_cast<Constant>(V);
415       if (Iteration != 0 && !C)
416         C = SimplifiedValues.lookup(V);
417       if (C)
418         SimplifiedInputValues.push_back({PHI, C});
419     }
420 
421     // Now clear and re-populate the map for the next iteration.
422     SimplifiedValues.clear();
423     while (!SimplifiedInputValues.empty())
424       SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
425 
426     UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L);
427 
428     BBWorklist.clear();
429     BBWorklist.insert(L->getHeader());
430     // Note that we *must not* cache the size, this loop grows the worklist.
431     for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
432       BasicBlock *BB = BBWorklist[Idx];
433 
434       // Visit all instructions in the given basic block and try to simplify
435       // it.  We don't change the actual IR, just count optimization
436       // opportunities.
437       for (Instruction &I : *BB) {
438         if (isa<DbgInfoIntrinsic>(I))
439           continue;
440 
441         // Track this instruction's expected baseline cost when executing the
442         // rolled loop form.
443         RolledDynamicCost += TTI.getUserCost(&I);
444 
445         // Visit the instruction to analyze its loop cost after unrolling,
446         // and if the visitor returns true, mark the instruction as free after
447         // unrolling and continue.
448         bool IsFree = Analyzer.visit(I);
449         bool Inserted = InstCostMap.insert({&I, (int)Iteration,
450                                            (unsigned)IsFree,
451                                            /*IsCounted*/ false}).second;
452         (void)Inserted;
453         assert(Inserted && "Cannot have a state for an unvisited instruction!");
454 
455         if (IsFree)
456           continue;
457 
458         // Can't properly model a cost of a call.
459         // FIXME: With a proper cost model we should be able to do it.
460         if(isa<CallInst>(&I))
461           return None;
462 
463         // If the instruction might have a side-effect recursively account for
464         // the cost of it and all the instructions leading up to it.
465         if (I.mayHaveSideEffects())
466           AddCostRecursively(I, Iteration);
467 
468         // If unrolled body turns out to be too big, bail out.
469         if (UnrolledCost > MaxUnrolledLoopSize) {
470           DEBUG(dbgs() << "  Exceeded threshold.. exiting.\n"
471                        << "  UnrolledCost: " << UnrolledCost
472                        << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
473                        << "\n");
474           return None;
475         }
476       }
477 
478       TerminatorInst *TI = BB->getTerminator();
479 
480       // Add in the live successors by first checking whether we have terminator
481       // that may be simplified based on the values simplified by this call.
482       BasicBlock *KnownSucc = nullptr;
483       if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
484         if (BI->isConditional()) {
485           if (Constant *SimpleCond =
486                   SimplifiedValues.lookup(BI->getCondition())) {
487             // Just take the first successor if condition is undef
488             if (isa<UndefValue>(SimpleCond))
489               KnownSucc = BI->getSuccessor(0);
490             else if (ConstantInt *SimpleCondVal =
491                          dyn_cast<ConstantInt>(SimpleCond))
492               KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0);
493           }
494         }
495       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
496         if (Constant *SimpleCond =
497                 SimplifiedValues.lookup(SI->getCondition())) {
498           // Just take the first successor if condition is undef
499           if (isa<UndefValue>(SimpleCond))
500             KnownSucc = SI->getSuccessor(0);
501           else if (ConstantInt *SimpleCondVal =
502                        dyn_cast<ConstantInt>(SimpleCond))
503             KnownSucc = SI->findCaseValue(SimpleCondVal).getCaseSuccessor();
504         }
505       }
506       if (KnownSucc) {
507         if (L->contains(KnownSucc))
508           BBWorklist.insert(KnownSucc);
509         else
510           ExitWorklist.insert({BB, KnownSucc});
511         continue;
512       }
513 
514       // Add BB's successors to the worklist.
515       for (BasicBlock *Succ : successors(BB))
516         if (L->contains(Succ))
517           BBWorklist.insert(Succ);
518         else
519           ExitWorklist.insert({BB, Succ});
520       AddCostRecursively(*TI, Iteration);
521     }
522 
523     // If we found no optimization opportunities on the first iteration, we
524     // won't find them on later ones too.
525     if (UnrolledCost == RolledDynamicCost) {
526       DEBUG(dbgs() << "  No opportunities found.. exiting.\n"
527                    << "  UnrolledCost: " << UnrolledCost << "\n");
528       return None;
529     }
530   }
531 
532   while (!ExitWorklist.empty()) {
533     BasicBlock *ExitingBB, *ExitBB;
534     std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val();
535 
536     for (Instruction &I : *ExitBB) {
537       auto *PN = dyn_cast<PHINode>(&I);
538       if (!PN)
539         break;
540 
541       Value *Op = PN->getIncomingValueForBlock(ExitingBB);
542       if (auto *OpI = dyn_cast<Instruction>(Op))
543         if (L->contains(OpI))
544           AddCostRecursively(*OpI, TripCount - 1);
545     }
546   }
547 
548   DEBUG(dbgs() << "Analysis finished:\n"
549                << "UnrolledCost: " << UnrolledCost << ", "
550                << "RolledDynamicCost: " << RolledDynamicCost << "\n");
551   return {{UnrolledCost, RolledDynamicCost}};
552 }
553 
554 /// ApproximateLoopSize - Approximate the size of the loop.
555 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
556                                     bool &NotDuplicatable, bool &Convergent,
557                                     const TargetTransformInfo &TTI,
558                                     unsigned BEInsns) {
559   SmallPtrSet<const Value *, 32> EphValues;
560   CodeMetrics::collectEphemeralValues(L, EphValues);
561 
562   CodeMetrics Metrics;
563   for (BasicBlock *BB : L->blocks())
564     Metrics.analyzeBasicBlock(BB, TTI, EphValues);
565   NumCalls = Metrics.NumInlineCandidates;
566   NotDuplicatable = Metrics.notDuplicatable;
567   Convergent = Metrics.convergent;
568 
569   unsigned LoopSize = Metrics.NumInsts;
570 
571   // Don't allow an estimate of size zero.  This would allows unrolling of loops
572   // with huge iteration counts, which is a compile time problem even if it's
573   // not a problem for code quality. Also, the code using this size may assume
574   // that each loop has at least three instructions (likely a conditional
575   // branch, a comparison feeding that branch, and some kind of loop increment
576   // feeding that comparison instruction).
577   LoopSize = std::max(LoopSize, BEInsns + 1);
578 
579   return LoopSize;
580 }
581 
582 // Returns the loop hint metadata node with the given name (for example,
583 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
584 // returned.
585 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
586   if (MDNode *LoopID = L->getLoopID())
587     return GetUnrollMetadata(LoopID, Name);
588   return nullptr;
589 }
590 
591 // Returns true if the loop has an unroll(full) pragma.
592 static bool HasUnrollFullPragma(const Loop *L) {
593   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
594 }
595 
596 // Returns true if the loop has an unroll(enable) pragma. This metadata is used
597 // for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
598 static bool HasUnrollEnablePragma(const Loop *L) {
599   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
600 }
601 
602 // Returns true if the loop has an unroll(disable) pragma.
603 static bool HasUnrollDisablePragma(const Loop *L) {
604   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
605 }
606 
607 // Returns true if the loop has an runtime unroll(disable) pragma.
608 static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
609   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
610 }
611 
612 // If loop has an unroll_count pragma return the (necessarily
613 // positive) value from the pragma.  Otherwise return 0.
614 static unsigned UnrollCountPragmaValue(const Loop *L) {
615   MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
616   if (MD) {
617     assert(MD->getNumOperands() == 2 &&
618            "Unroll count hint metadata should have two operands.");
619     unsigned Count =
620         mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
621     assert(Count >= 1 && "Unroll count must be positive.");
622     return Count;
623   }
624   return 0;
625 }
626 
627 // Remove existing unroll metadata and add unroll disable metadata to
628 // indicate the loop has already been unrolled.  This prevents a loop
629 // from being unrolled more than is directed by a pragma if the loop
630 // unrolling pass is run more than once (which it generally is).
631 static void SetLoopAlreadyUnrolled(Loop *L) {
632   MDNode *LoopID = L->getLoopID();
633   // First remove any existing loop unrolling metadata.
634   SmallVector<Metadata *, 4> MDs;
635   // Reserve first location for self reference to the LoopID metadata node.
636   MDs.push_back(nullptr);
637 
638   if (LoopID) {
639     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
640       bool IsUnrollMetadata = false;
641       MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
642       if (MD) {
643         const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
644         IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
645       }
646       if (!IsUnrollMetadata)
647         MDs.push_back(LoopID->getOperand(i));
648     }
649   }
650 
651   // Add unroll(disable) metadata to disable future unrolling.
652   LLVMContext &Context = L->getHeader()->getContext();
653   SmallVector<Metadata *, 1> DisableOperands;
654   DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
655   MDNode *DisableNode = MDNode::get(Context, DisableOperands);
656   MDs.push_back(DisableNode);
657 
658   MDNode *NewLoopID = MDNode::get(Context, MDs);
659   // Set operand 0 to refer to the loop id itself.
660   NewLoopID->replaceOperandWith(0, NewLoopID);
661   L->setLoopID(NewLoopID);
662 }
663 
664 static bool canUnrollCompletely(Loop *L, unsigned Threshold,
665                                 unsigned PercentDynamicCostSavedThreshold,
666                                 unsigned DynamicCostSavingsDiscount,
667                                 uint64_t UnrolledCost,
668                                 uint64_t RolledDynamicCost) {
669   if (Threshold == NoThreshold) {
670     DEBUG(dbgs() << "  Can fully unroll, because no threshold is set.\n");
671     return true;
672   }
673 
674   if (UnrolledCost <= Threshold) {
675     DEBUG(dbgs() << "  Can fully unroll, because unrolled cost: "
676                  << UnrolledCost << "<=" << Threshold << "\n");
677     return true;
678   }
679 
680   assert(UnrolledCost && "UnrolledCost can't be 0 at this point.");
681   assert(RolledDynamicCost >= UnrolledCost &&
682          "Cannot have a higher unrolled cost than a rolled cost!");
683 
684   // Compute the percentage of the dynamic cost in the rolled form that is
685   // saved when unrolled. If unrolling dramatically reduces the estimated
686   // dynamic cost of the loop, we use a higher threshold to allow more
687   // unrolling.
688   unsigned PercentDynamicCostSaved =
689       (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost;
690 
691   if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold &&
692       (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <=
693           (int64_t)Threshold) {
694     DEBUG(dbgs() << "  Can fully unroll, because unrolling will reduce the "
695                     "expected dynamic cost by "
696                  << PercentDynamicCostSaved << "% (threshold: "
697                  << PercentDynamicCostSavedThreshold << "%)\n"
698                  << "  and the unrolled cost (" << UnrolledCost
699                  << ") is less than the max threshold ("
700                  << DynamicCostSavingsDiscount << ").\n");
701     return true;
702   }
703 
704   DEBUG(dbgs() << "  Too large to fully unroll:\n");
705   DEBUG(dbgs() << "    Threshold: " << Threshold << "\n");
706   DEBUG(dbgs() << "    Max threshold: " << DynamicCostSavingsDiscount << "\n");
707   DEBUG(dbgs() << "    Percent cost saved threshold: "
708                << PercentDynamicCostSavedThreshold << "%\n");
709   DEBUG(dbgs() << "    Unrolled cost: " << UnrolledCost << "\n");
710   DEBUG(dbgs() << "    Rolled dynamic cost: " << RolledDynamicCost << "\n");
711   DEBUG(dbgs() << "    Percent cost saved: " << PercentDynamicCostSaved
712                << "\n");
713   return false;
714 }
715 
716 // Returns loop size estimation for unrolled loop.
717 static uint64_t getUnrolledLoopSize(
718     unsigned LoopSize,
719     TargetTransformInfo::UnrollingPreferences &UP) {
720   assert(LoopSize >= UP.BEInsns && "LoopSize should not be less than BEInsns!");
721   return (uint64_t)(LoopSize - UP.BEInsns) * UP.Count + UP.BEInsns;
722 }
723 
724 // Returns true if unroll count was set explicitly.
725 // Calculates unroll count and writes it to UP.Count.
726 static bool computeUnrollCount(
727     Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI,
728     ScalarEvolution *SE, OptimizationRemarkEmitter *ORE, unsigned &TripCount,
729     unsigned MaxTripCount, unsigned &TripMultiple, unsigned LoopSize,
730     TargetTransformInfo::UnrollingPreferences &UP, bool &UseUpperBound) {
731   // Check for explicit Count.
732   // 1st priority is unroll count set by "unroll-count" option.
733   bool UserUnrollCount = UnrollCount.getNumOccurrences() > 0;
734   if (UserUnrollCount) {
735     UP.Count = UnrollCount;
736     UP.AllowExpensiveTripCount = true;
737     UP.Force = true;
738     if (UP.AllowRemainder && getUnrolledLoopSize(LoopSize, UP) < UP.Threshold)
739       return true;
740   }
741 
742   // 2nd priority is unroll count set by pragma.
743   unsigned PragmaCount = UnrollCountPragmaValue(L);
744   if (PragmaCount > 0) {
745     UP.Count = PragmaCount;
746     UP.Runtime = true;
747     UP.AllowExpensiveTripCount = true;
748     UP.Force = true;
749     if (UP.AllowRemainder &&
750         getUnrolledLoopSize(LoopSize, UP) < PragmaUnrollThreshold)
751       return true;
752   }
753   bool PragmaFullUnroll = HasUnrollFullPragma(L);
754   if (PragmaFullUnroll && TripCount != 0) {
755     UP.Count = TripCount;
756     if (getUnrolledLoopSize(LoopSize, UP) < PragmaUnrollThreshold)
757       return false;
758   }
759 
760   bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
761   bool ExplicitUnroll = PragmaCount > 0 || PragmaFullUnroll ||
762                         PragmaEnableUnroll || UserUnrollCount;
763 
764   if (ExplicitUnroll && TripCount != 0) {
765     // If the loop has an unrolling pragma, we want to be more aggressive with
766     // unrolling limits. Set thresholds to at least the PragmaThreshold value
767     // which is larger than the default limits.
768     UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold);
769     UP.PartialThreshold =
770         std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold);
771   }
772 
773   // 3rd priority is full unroll count.
774   // Full unroll makes sense only when TripCount or its upper bound could be
775   // statically calculated.
776   // Also we need to check if we exceed FullUnrollMaxCount.
777   // If using the upper bound to unroll, TripMultiple should be set to 1 because
778   // we do not know when loop may exit.
779   // MaxTripCount and ExactTripCount cannot both be non zero since we only
780   // compute the former when the latter is zero.
781   unsigned ExactTripCount = TripCount;
782   assert((ExactTripCount == 0 || MaxTripCount == 0) &&
783          "ExtractTripCound and MaxTripCount cannot both be non zero.");
784   unsigned FullUnrollTripCount = ExactTripCount ? ExactTripCount : MaxTripCount;
785   UP.Count = FullUnrollTripCount;
786   if (FullUnrollTripCount && FullUnrollTripCount <= UP.FullUnrollMaxCount) {
787     // When computing the unrolled size, note that BEInsns are not replicated
788     // like the rest of the loop body.
789     if (canUnrollCompletely(L, UP.Threshold, 100, UP.DynamicCostSavingsDiscount,
790                             getUnrolledLoopSize(LoopSize, UP),
791                             getUnrolledLoopSize(LoopSize, UP))) {
792       UseUpperBound = (MaxTripCount == FullUnrollTripCount);
793       TripCount = FullUnrollTripCount;
794       TripMultiple = UP.UpperBound ? 1 : TripMultiple;
795       return ExplicitUnroll;
796     } else {
797       // The loop isn't that small, but we still can fully unroll it if that
798       // helps to remove a significant number of instructions.
799       // To check that, run additional analysis on the loop.
800       if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
801               L, FullUnrollTripCount, DT, *SE, TTI,
802               UP.Threshold + UP.DynamicCostSavingsDiscount))
803         if (canUnrollCompletely(L, UP.Threshold,
804                                 UP.PercentDynamicCostSavedThreshold,
805                                 UP.DynamicCostSavingsDiscount,
806                                 Cost->UnrolledCost, Cost->RolledDynamicCost)) {
807           UseUpperBound = (MaxTripCount == FullUnrollTripCount);
808           TripCount = FullUnrollTripCount;
809           TripMultiple = UP.UpperBound ? 1 : TripMultiple;
810           return ExplicitUnroll;
811         }
812     }
813   }
814 
815   // 4rd priority is partial unrolling.
816   // Try partial unroll only when TripCount could be staticaly calculated.
817   if (TripCount) {
818     UP.Partial |= ExplicitUnroll;
819     if (!UP.Partial) {
820       DEBUG(dbgs() << "  will not try to unroll partially because "
821                    << "-unroll-allow-partial not given\n");
822       UP.Count = 0;
823       return false;
824     }
825     if (UP.Count == 0)
826       UP.Count = TripCount;
827     if (UP.PartialThreshold != NoThreshold) {
828       // Reduce unroll count to be modulo of TripCount for partial unrolling.
829       if (getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
830         UP.Count =
831             (std::max(UP.PartialThreshold, UP.BEInsns + 1) - UP.BEInsns) /
832             (LoopSize - UP.BEInsns);
833       if (UP.Count > UP.MaxCount)
834         UP.Count = UP.MaxCount;
835       while (UP.Count != 0 && TripCount % UP.Count != 0)
836         UP.Count--;
837       if (UP.AllowRemainder && UP.Count <= 1) {
838         // If there is no Count that is modulo of TripCount, set Count to
839         // largest power-of-two factor that satisfies the threshold limit.
840         // As we'll create fixup loop, do the type of unrolling only if
841         // remainder loop is allowed.
842         UP.Count = UP.DefaultUnrollRuntimeCount;
843         while (UP.Count != 0 &&
844                getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
845           UP.Count >>= 1;
846       }
847       if (UP.Count < 2) {
848         if (PragmaEnableUnroll)
849           ORE->emit(
850               OptimizationRemarkMissed(DEBUG_TYPE, "UnrollAsDirectedTooLarge",
851                                        L->getStartLoc(), L->getHeader())
852               << "Unable to unroll loop as directed by unroll(enable) pragma "
853                  "because unrolled size is too large.");
854         UP.Count = 0;
855       }
856     } else {
857       UP.Count = TripCount;
858     }
859     if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
860         UP.Count != TripCount)
861       ORE->emit(
862           OptimizationRemarkMissed(DEBUG_TYPE, "FullUnrollAsDirectedTooLarge",
863                                    L->getStartLoc(), L->getHeader())
864           << "Unable to fully unroll loop as directed by unroll pragma because "
865              "unrolled size is too large.");
866     return ExplicitUnroll;
867   }
868   assert(TripCount == 0 &&
869          "All cases when TripCount is constant should be covered here.");
870   if (PragmaFullUnroll)
871     ORE->emit(
872         OptimizationRemarkMissed(DEBUG_TYPE,
873                                  "CantFullUnrollAsDirectedRuntimeTripCount",
874                                  L->getStartLoc(), L->getHeader())
875         << "Unable to fully unroll loop as directed by unroll(full) pragma "
876            "because loop has a runtime trip count.");
877 
878   // 5th priority is loop peeling
879   computePeelCount(L, LoopSize, UP);
880   if (UP.PeelCount) {
881     UP.Runtime = false;
882     UP.Count = 1;
883     return ExplicitUnroll;
884   }
885 
886   // 6th priority is runtime unrolling.
887   // Don't unroll a runtime trip count loop when it is disabled.
888   if (HasRuntimeUnrollDisablePragma(L)) {
889     UP.Count = 0;
890     return false;
891   }
892 
893   // Check if the runtime trip count is too small when profile is available.
894   if (L->getHeader()->getParent()->getEntryCount()) {
895     if (auto ProfileTripCount = getLoopEstimatedTripCount(L)) {
896       if (*ProfileTripCount < FlatLoopTripCountThreshold)
897         return false;
898       else
899         UP.AllowExpensiveTripCount = true;
900     }
901   }
902 
903   // Reduce count based on the type of unrolling and the threshold values.
904   UP.Runtime |= PragmaEnableUnroll || PragmaCount > 0 || UserUnrollCount;
905   if (!UP.Runtime) {
906     DEBUG(dbgs() << "  will not try to unroll loop with runtime trip count "
907                  << "-unroll-runtime not given\n");
908     UP.Count = 0;
909     return false;
910   }
911   if (UP.Count == 0)
912     UP.Count = UP.DefaultUnrollRuntimeCount;
913 
914   // Reduce unroll count to be the largest power-of-two factor of
915   // the original count which satisfies the threshold limit.
916   while (UP.Count != 0 &&
917          getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
918     UP.Count >>= 1;
919 
920 #ifndef NDEBUG
921   unsigned OrigCount = UP.Count;
922 #endif
923 
924   if (!UP.AllowRemainder && UP.Count != 0 && (TripMultiple % UP.Count) != 0) {
925     while (UP.Count != 0 && TripMultiple % UP.Count != 0)
926       UP.Count >>= 1;
927     DEBUG(dbgs() << "Remainder loop is restricted (that could architecture "
928                     "specific or because the loop contains a convergent "
929                     "instruction), so unroll count must divide the trip "
930                     "multiple, "
931                  << TripMultiple << ".  Reducing unroll count from "
932                  << OrigCount << " to " << UP.Count << ".\n");
933     using namespace ore;
934     if (PragmaCount > 0 && !UP.AllowRemainder)
935       ORE->emit(
936           OptimizationRemarkMissed(DEBUG_TYPE,
937                                    "DifferentUnrollCountFromDirected",
938                                    L->getStartLoc(), L->getHeader())
939           << "Unable to unroll loop the number of times directed by "
940              "unroll_count pragma because remainder loop is restricted "
941              "(that could architecture specific or because the loop "
942              "contains a convergent instruction) and so must have an unroll "
943              "count that divides the loop trip multiple of "
944           << NV("TripMultiple", TripMultiple) << ".  Unrolling instead "
945           << NV("UnrollCount", UP.Count) << " time(s).");
946   }
947 
948   if (UP.Count > UP.MaxCount)
949     UP.Count = UP.MaxCount;
950   DEBUG(dbgs() << "  partially unrolling with count: " << UP.Count << "\n");
951   if (UP.Count < 2)
952     UP.Count = 0;
953   return ExplicitUnroll;
954 }
955 
956 static bool tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
957                             ScalarEvolution *SE, const TargetTransformInfo &TTI,
958                             OptimizationRemarkEmitter &ORE,
959                             bool PreserveLCSSA,
960                             Optional<unsigned> ProvidedCount,
961                             Optional<unsigned> ProvidedThreshold,
962                             Optional<bool> ProvidedAllowPartial,
963                             Optional<bool> ProvidedRuntime,
964                             Optional<bool> ProvidedUpperBound) {
965   DEBUG(dbgs() << "Loop Unroll: F[" << L->getHeader()->getParent()->getName()
966                << "] Loop %" << L->getHeader()->getName() << "\n");
967   if (HasUnrollDisablePragma(L))
968     return false;
969   if (!L->isLoopSimplifyForm()) {
970     DEBUG(
971         dbgs() << "  Not unrolling loop which is not in loop-simplify form.\n");
972     return false;
973   }
974 
975   unsigned NumInlineCandidates;
976   bool NotDuplicatable;
977   bool Convergent;
978   TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
979       L, TTI, ProvidedThreshold, ProvidedCount, ProvidedAllowPartial,
980       ProvidedRuntime, ProvidedUpperBound);
981   // Exit early if unrolling is disabled.
982   if (UP.Threshold == 0 && (!UP.Partial || UP.PartialThreshold == 0))
983     return false;
984   unsigned LoopSize = ApproximateLoopSize(
985       L, NumInlineCandidates, NotDuplicatable, Convergent, TTI, UP.BEInsns);
986   DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
987   if (NotDuplicatable) {
988     DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
989                  << " instructions.\n");
990     return false;
991   }
992   if (NumInlineCandidates != 0) {
993     DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
994     return false;
995   }
996 
997   // Find trip count and trip multiple if count is not available
998   unsigned TripCount = 0;
999   unsigned MaxTripCount = 0;
1000   unsigned TripMultiple = 1;
1001   // If there are multiple exiting blocks but one of them is the latch, use the
1002   // latch for the trip count estimation. Otherwise insist on a single exiting
1003   // block for the trip count estimation.
1004   BasicBlock *ExitingBlock = L->getLoopLatch();
1005   if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
1006     ExitingBlock = L->getExitingBlock();
1007   if (ExitingBlock) {
1008     TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
1009     TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
1010   }
1011 
1012   // If the loop contains a convergent operation, the prelude we'd add
1013   // to do the first few instructions before we hit the unrolled loop
1014   // is unsafe -- it adds a control-flow dependency to the convergent
1015   // operation.  Therefore restrict remainder loop (try unrollig without).
1016   //
1017   // TODO: This is quite conservative.  In practice, convergent_op()
1018   // is likely to be called unconditionally in the loop.  In this
1019   // case, the program would be ill-formed (on most architectures)
1020   // unless n were the same on all threads in a thread group.
1021   // Assuming n is the same on all threads, any kind of unrolling is
1022   // safe.  But currently llvm's notion of convergence isn't powerful
1023   // enough to express this.
1024   if (Convergent)
1025     UP.AllowRemainder = false;
1026 
1027   // Try to find the trip count upper bound if we cannot find the exact trip
1028   // count.
1029   bool MaxOrZero = false;
1030   if (!TripCount) {
1031     MaxTripCount = SE->getSmallConstantMaxTripCount(L);
1032     MaxOrZero = SE->isBackedgeTakenCountMaxOrZero(L);
1033     // We can unroll by the upper bound amount if it's generally allowed or if
1034     // we know that the loop is executed either the upper bound or zero times.
1035     // (MaxOrZero unrolling keeps only the first loop test, so the number of
1036     // loop tests remains the same compared to the non-unrolled version, whereas
1037     // the generic upper bound unrolling keeps all but the last loop test so the
1038     // number of loop tests goes up which may end up being worse on targets with
1039     // constriained branch predictor resources so is controlled by an option.)
1040     // In addition we only unroll small upper bounds.
1041     if (!(UP.UpperBound || MaxOrZero) || MaxTripCount > UnrollMaxUpperBound) {
1042       MaxTripCount = 0;
1043     }
1044   }
1045 
1046   // computeUnrollCount() decides whether it is beneficial to use upper bound to
1047   // fully unroll the loop.
1048   bool UseUpperBound = false;
1049   bool IsCountSetExplicitly =
1050       computeUnrollCount(L, TTI, DT, LI, SE, &ORE, TripCount, MaxTripCount,
1051                          TripMultiple, LoopSize, UP, UseUpperBound);
1052   if (!UP.Count)
1053     return false;
1054   // Unroll factor (Count) must be less or equal to TripCount.
1055   if (TripCount && UP.Count > TripCount)
1056     UP.Count = TripCount;
1057 
1058   // Unroll the loop.
1059   if (!UnrollLoop(L, UP.Count, TripCount, UP.Force, UP.Runtime,
1060                   UP.AllowExpensiveTripCount, UseUpperBound, MaxOrZero,
1061                   TripMultiple, UP.PeelCount, LI, SE, &DT, &ORE,
1062                   PreserveLCSSA))
1063     return false;
1064 
1065   // If loop has an unroll count pragma or unrolled by explicitly set count
1066   // mark loop as unrolled to prevent unrolling beyond that requested.
1067   // If the loop was peeled, we already "used up" the profile information
1068   // we had, so we don't want to unroll or peel again.
1069   if (IsCountSetExplicitly || UP.PeelCount)
1070     SetLoopAlreadyUnrolled(L);
1071 
1072   return true;
1073 }
1074 
1075 namespace {
1076 class LoopUnroll : public LoopPass {
1077 public:
1078   static char ID; // Pass ID, replacement for typeid
1079   LoopUnroll(Optional<unsigned> Threshold = None,
1080              Optional<unsigned> Count = None,
1081              Optional<bool> AllowPartial = None, Optional<bool> Runtime = None,
1082              Optional<bool> UpperBound = None)
1083       : LoopPass(ID), ProvidedCount(std::move(Count)),
1084         ProvidedThreshold(Threshold), ProvidedAllowPartial(AllowPartial),
1085         ProvidedRuntime(Runtime), ProvidedUpperBound(UpperBound) {
1086     initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
1087   }
1088 
1089   Optional<unsigned> ProvidedCount;
1090   Optional<unsigned> ProvidedThreshold;
1091   Optional<bool> ProvidedAllowPartial;
1092   Optional<bool> ProvidedRuntime;
1093   Optional<bool> ProvidedUpperBound;
1094 
1095   bool runOnLoop(Loop *L, LPPassManager &) override {
1096     if (skipLoop(L))
1097       return false;
1098 
1099     Function &F = *L->getHeader()->getParent();
1100 
1101     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1102     LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1103     ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1104     const TargetTransformInfo &TTI =
1105         getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1106     // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
1107     // pass.  Function analyses need to be preserved across loop transformations
1108     // but ORE cannot be preserved (see comment before the pass definition).
1109     OptimizationRemarkEmitter ORE(&F);
1110     bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1111 
1112     return tryToUnrollLoop(L, DT, LI, SE, TTI, ORE, PreserveLCSSA,
1113                            ProvidedCount, ProvidedThreshold,
1114                            ProvidedAllowPartial, ProvidedRuntime,
1115                            ProvidedUpperBound);
1116   }
1117 
1118   /// This transformation requires natural loop information & requires that
1119   /// loop preheaders be inserted into the CFG...
1120   ///
1121   void getAnalysisUsage(AnalysisUsage &AU) const override {
1122     AU.addRequired<TargetTransformInfoWrapperPass>();
1123     // FIXME: Loop passes are required to preserve domtree, and for now we just
1124     // recreate dom info if anything gets unrolled.
1125     getLoopAnalysisUsage(AU);
1126   }
1127 };
1128 }
1129 
1130 char LoopUnroll::ID = 0;
1131 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1132 INITIALIZE_PASS_DEPENDENCY(LoopPass)
1133 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1134 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1135 
1136 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
1137                                  int Runtime, int UpperBound) {
1138   // TODO: It would make more sense for this function to take the optionals
1139   // directly, but that's dangerous since it would silently break out of tree
1140   // callers.
1141   return new LoopUnroll(Threshold == -1 ? None : Optional<unsigned>(Threshold),
1142                         Count == -1 ? None : Optional<unsigned>(Count),
1143                         AllowPartial == -1 ? None
1144                                            : Optional<bool>(AllowPartial),
1145                         Runtime == -1 ? None : Optional<bool>(Runtime),
1146                         UpperBound == -1 ? None : Optional<bool>(UpperBound));
1147 }
1148 
1149 Pass *llvm::createSimpleLoopUnrollPass() {
1150   return llvm::createLoopUnrollPass(-1, -1, 0, 0, 0);
1151 }
1152 
1153 PreservedAnalyses LoopUnrollPass::run(Loop &L, LoopAnalysisManager &AM) {
1154   const auto &FAM =
1155       AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
1156   Function *F = L.getHeader()->getParent();
1157 
1158 
1159   DominatorTree *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
1160   LoopInfo *LI = FAM.getCachedResult<LoopAnalysis>(*F);
1161   ScalarEvolution *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
1162   auto *TTI = FAM.getCachedResult<TargetIRAnalysis>(*F);
1163   auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
1164   if (!DT)
1165     report_fatal_error(
1166         "LoopUnrollPass: DominatorTreeAnalysis not cached at a higher level");
1167   if (!LI)
1168     report_fatal_error(
1169         "LoopUnrollPass: LoopAnalysis not cached at a higher level");
1170   if (!SE)
1171     report_fatal_error(
1172         "LoopUnrollPass: ScalarEvolutionAnalysis not cached at a higher level");
1173   if (!TTI)
1174     report_fatal_error(
1175         "LoopUnrollPass: TargetIRAnalysis not cached at a higher level");
1176   if (!ORE)
1177     report_fatal_error("LoopUnrollPass: OptimizationRemarkEmitterAnalysis not "
1178                        "cached at a higher level");
1179 
1180   bool Changed =
1181       tryToUnrollLoop(&L, *DT, LI, SE, *TTI, *ORE, /*PreserveLCSSA*/ true,
1182                       ProvidedCount, ProvidedThreshold, ProvidedAllowPartial,
1183                       ProvidedRuntime, ProvidedUpperBound);
1184 
1185   if (!Changed)
1186     return PreservedAnalyses::all();
1187   return getLoopPassPreservedAnalyses();
1188 }
1189