xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp (revision 4d559837e887c278d7c27274f4f6b1b78b97c00d)
1 //===- LoopUnroll.cpp - Loop unroller pass --------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements a simple loop unroller.  It works best when loops have
10 // been canonicalized by the -indvars pass, allowing it to determine the trip
11 // counts of loops easily.
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseMapInfo.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Analysis/AssumptionCache.h"
26 #include "llvm/Analysis/BlockFrequencyInfo.h"
27 #include "llvm/Analysis/CodeMetrics.h"
28 #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
29 #include "llvm/Analysis/LoopAnalysisManager.h"
30 #include "llvm/Analysis/LoopInfo.h"
31 #include "llvm/Analysis/LoopPass.h"
32 #include "llvm/Analysis/LoopUnrollAnalyzer.h"
33 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
34 #include "llvm/Analysis/ProfileSummaryInfo.h"
35 #include "llvm/Analysis/ScalarEvolution.h"
36 #include "llvm/Analysis/TargetTransformInfo.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DiagnosticInfo.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/Instruction.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/IR/Metadata.h"
48 #include "llvm/IR/PassManager.h"
49 #include "llvm/InitializePasses.h"
50 #include "llvm/Pass.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Scalar.h"
57 #include "llvm/Transforms/Scalar/LoopPassManager.h"
58 #include "llvm/Transforms/Utils.h"
59 #include "llvm/Transforms/Utils/LoopPeel.h"
60 #include "llvm/Transforms/Utils/LoopSimplify.h"
61 #include "llvm/Transforms/Utils/LoopUtils.h"
62 #include "llvm/Transforms/Utils/SizeOpts.h"
63 #include "llvm/Transforms/Utils/UnrollLoop.h"
64 #include <algorithm>
65 #include <cassert>
66 #include <cstdint>
67 #include <limits>
68 #include <optional>
69 #include <string>
70 #include <tuple>
71 #include <utility>
72 
73 using namespace llvm;
74 
75 #define DEBUG_TYPE "loop-unroll"
76 
77 cl::opt<bool> llvm::ForgetSCEVInLoopUnroll(
78     "forget-scev-loop-unroll", cl::init(false), cl::Hidden,
79     cl::desc("Forget everything in SCEV when doing LoopUnroll, instead of just"
80              " the current top-most loop. This is sometimes preferred to reduce"
81              " compile time."));
82 
83 static cl::opt<unsigned>
84     UnrollThreshold("unroll-threshold", cl::Hidden,
85                     cl::desc("The cost threshold for loop unrolling"));
86 
87 static cl::opt<unsigned>
88     UnrollOptSizeThreshold(
89       "unroll-optsize-threshold", cl::init(0), cl::Hidden,
90       cl::desc("The cost threshold for loop unrolling when optimizing for "
91                "size"));
92 
93 static cl::opt<unsigned> UnrollPartialThreshold(
94     "unroll-partial-threshold", cl::Hidden,
95     cl::desc("The cost threshold for partial loop unrolling"));
96 
97 static cl::opt<unsigned> UnrollMaxPercentThresholdBoost(
98     "unroll-max-percent-threshold-boost", cl::init(400), cl::Hidden,
99     cl::desc("The maximum 'boost' (represented as a percentage >= 100) applied "
100              "to the threshold when aggressively unrolling a loop due to the "
101              "dynamic cost savings. If completely unrolling a loop will reduce "
102              "the total runtime from X to Y, we boost the loop unroll "
103              "threshold to DefaultThreshold*std::min(MaxPercentThresholdBoost, "
104              "X/Y). This limit avoids excessive code bloat."));
105 
106 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
107     "unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden,
108     cl::desc("Don't allow loop unrolling to simulate more than this number of"
109              "iterations when checking full unroll profitability"));
110 
111 static cl::opt<unsigned> UnrollCount(
112     "unroll-count", cl::Hidden,
113     cl::desc("Use this unroll count for all loops including those with "
114              "unroll_count pragma values, for testing purposes"));
115 
116 static cl::opt<unsigned> UnrollMaxCount(
117     "unroll-max-count", cl::Hidden,
118     cl::desc("Set the max unroll count for partial and runtime unrolling, for"
119              "testing purposes"));
120 
121 static cl::opt<unsigned> UnrollFullMaxCount(
122     "unroll-full-max-count", cl::Hidden,
123     cl::desc(
124         "Set the max unroll count for full unrolling, for testing purposes"));
125 
126 static cl::opt<bool>
127     UnrollAllowPartial("unroll-allow-partial", cl::Hidden,
128                        cl::desc("Allows loops to be partially unrolled until "
129                                 "-unroll-threshold loop size is reached."));
130 
131 static cl::opt<bool> UnrollAllowRemainder(
132     "unroll-allow-remainder", cl::Hidden,
133     cl::desc("Allow generation of a loop remainder (extra iterations) "
134              "when unrolling a loop."));
135 
136 static cl::opt<bool>
137     UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden,
138                   cl::desc("Unroll loops with run-time trip counts"));
139 
140 static cl::opt<unsigned> UnrollMaxUpperBound(
141     "unroll-max-upperbound", cl::init(8), cl::Hidden,
142     cl::desc(
143         "The max of trip count upper bound that is considered in unrolling"));
144 
145 static cl::opt<unsigned> PragmaUnrollThreshold(
146     "pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
147     cl::desc("Unrolled size limit for loops with an unroll(full) or "
148              "unroll_count pragma."));
149 
150 static cl::opt<unsigned> FlatLoopTripCountThreshold(
151     "flat-loop-tripcount-threshold", cl::init(5), cl::Hidden,
152     cl::desc("If the runtime tripcount for the loop is lower than the "
153              "threshold, the loop is considered as flat and will be less "
154              "aggressively unrolled."));
155 
156 static cl::opt<bool> UnrollUnrollRemainder(
157   "unroll-remainder", cl::Hidden,
158   cl::desc("Allow the loop remainder to be unrolled."));
159 
160 // This option isn't ever intended to be enabled, it serves to allow
161 // experiments to check the assumptions about when this kind of revisit is
162 // necessary.
163 static cl::opt<bool> UnrollRevisitChildLoops(
164     "unroll-revisit-child-loops", cl::Hidden,
165     cl::desc("Enqueue and re-visit child loops in the loop PM after unrolling. "
166              "This shouldn't typically be needed as child loops (or their "
167              "clones) were already visited."));
168 
169 static cl::opt<unsigned> UnrollThresholdAggressive(
170     "unroll-threshold-aggressive", cl::init(300), cl::Hidden,
171     cl::desc("Threshold (max size of unrolled loop) to use in aggressive (O3) "
172              "optimizations"));
173 static cl::opt<unsigned>
174     UnrollThresholdDefault("unroll-threshold-default", cl::init(150),
175                            cl::Hidden,
176                            cl::desc("Default threshold (max size of unrolled "
177                                     "loop), used in all but O3 optimizations"));
178 
179 /// A magic value for use with the Threshold parameter to indicate
180 /// that the loop unroll should be performed regardless of how much
181 /// code expansion would result.
182 static const unsigned NoThreshold = std::numeric_limits<unsigned>::max();
183 
184 /// Gather the various unrolling parameters based on the defaults, compiler
185 /// flags, TTI overrides and user specified parameters.
186 TargetTransformInfo::UnrollingPreferences llvm::gatherUnrollingPreferences(
187     Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI,
188     BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
189     OptimizationRemarkEmitter &ORE, int OptLevel,
190     Optional<unsigned> UserThreshold, Optional<unsigned> UserCount,
191     Optional<bool> UserAllowPartial, Optional<bool> UserRuntime,
192     Optional<bool> UserUpperBound, Optional<unsigned> UserFullUnrollMaxCount) {
193   TargetTransformInfo::UnrollingPreferences UP;
194 
195   // Set up the defaults
196   UP.Threshold =
197       OptLevel > 2 ? UnrollThresholdAggressive : UnrollThresholdDefault;
198   UP.MaxPercentThresholdBoost = 400;
199   UP.OptSizeThreshold = UnrollOptSizeThreshold;
200   UP.PartialThreshold = 150;
201   UP.PartialOptSizeThreshold = UnrollOptSizeThreshold;
202   UP.Count = 0;
203   UP.DefaultUnrollRuntimeCount = 8;
204   UP.MaxCount = std::numeric_limits<unsigned>::max();
205   UP.FullUnrollMaxCount = std::numeric_limits<unsigned>::max();
206   UP.BEInsns = 2;
207   UP.Partial = false;
208   UP.Runtime = false;
209   UP.AllowRemainder = true;
210   UP.UnrollRemainder = false;
211   UP.AllowExpensiveTripCount = false;
212   UP.Force = false;
213   UP.UpperBound = false;
214   UP.UnrollAndJam = false;
215   UP.UnrollAndJamInnerLoopThreshold = 60;
216   UP.MaxIterationsCountToAnalyze = UnrollMaxIterationsCountToAnalyze;
217 
218   // Override with any target specific settings
219   TTI.getUnrollingPreferences(L, SE, UP, &ORE);
220 
221   // Apply size attributes
222   bool OptForSize = L->getHeader()->getParent()->hasOptSize() ||
223                     // Let unroll hints / pragmas take precedence over PGSO.
224                     (hasUnrollTransformation(L) != TM_ForcedByUser &&
225                      llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
226                                                  PGSOQueryType::IRPass));
227   if (OptForSize) {
228     UP.Threshold = UP.OptSizeThreshold;
229     UP.PartialThreshold = UP.PartialOptSizeThreshold;
230     UP.MaxPercentThresholdBoost = 100;
231   }
232 
233   // Apply any user values specified by cl::opt
234   if (UnrollThreshold.getNumOccurrences() > 0)
235     UP.Threshold = UnrollThreshold;
236   if (UnrollPartialThreshold.getNumOccurrences() > 0)
237     UP.PartialThreshold = UnrollPartialThreshold;
238   if (UnrollMaxPercentThresholdBoost.getNumOccurrences() > 0)
239     UP.MaxPercentThresholdBoost = UnrollMaxPercentThresholdBoost;
240   if (UnrollMaxCount.getNumOccurrences() > 0)
241     UP.MaxCount = UnrollMaxCount;
242   if (UnrollFullMaxCount.getNumOccurrences() > 0)
243     UP.FullUnrollMaxCount = UnrollFullMaxCount;
244   if (UnrollAllowPartial.getNumOccurrences() > 0)
245     UP.Partial = UnrollAllowPartial;
246   if (UnrollAllowRemainder.getNumOccurrences() > 0)
247     UP.AllowRemainder = UnrollAllowRemainder;
248   if (UnrollRuntime.getNumOccurrences() > 0)
249     UP.Runtime = UnrollRuntime;
250   if (UnrollMaxUpperBound == 0)
251     UP.UpperBound = false;
252   if (UnrollUnrollRemainder.getNumOccurrences() > 0)
253     UP.UnrollRemainder = UnrollUnrollRemainder;
254   if (UnrollMaxIterationsCountToAnalyze.getNumOccurrences() > 0)
255     UP.MaxIterationsCountToAnalyze = UnrollMaxIterationsCountToAnalyze;
256 
257   // Apply user values provided by argument
258   if (UserThreshold.hasValue()) {
259     UP.Threshold = *UserThreshold;
260     UP.PartialThreshold = *UserThreshold;
261   }
262   if (UserCount.hasValue())
263     UP.Count = *UserCount;
264   if (UserAllowPartial.hasValue())
265     UP.Partial = *UserAllowPartial;
266   if (UserRuntime.hasValue())
267     UP.Runtime = *UserRuntime;
268   if (UserUpperBound.hasValue())
269     UP.UpperBound = *UserUpperBound;
270   if (UserFullUnrollMaxCount.hasValue())
271     UP.FullUnrollMaxCount = *UserFullUnrollMaxCount;
272 
273   return UP;
274 }
275 
276 namespace {
277 
278 /// A struct to densely store the state of an instruction after unrolling at
279 /// each iteration.
280 ///
281 /// This is designed to work like a tuple of <Instruction *, int> for the
282 /// purposes of hashing and lookup, but to be able to associate two boolean
283 /// states with each key.
284 struct UnrolledInstState {
285   Instruction *I;
286   int Iteration : 30;
287   unsigned IsFree : 1;
288   unsigned IsCounted : 1;
289 };
290 
291 /// Hashing and equality testing for a set of the instruction states.
292 struct UnrolledInstStateKeyInfo {
293   using PtrInfo = DenseMapInfo<Instruction *>;
294   using PairInfo = DenseMapInfo<std::pair<Instruction *, int>>;
295 
296   static inline UnrolledInstState getEmptyKey() {
297     return {PtrInfo::getEmptyKey(), 0, 0, 0};
298   }
299 
300   static inline UnrolledInstState getTombstoneKey() {
301     return {PtrInfo::getTombstoneKey(), 0, 0, 0};
302   }
303 
304   static inline unsigned getHashValue(const UnrolledInstState &S) {
305     return PairInfo::getHashValue({S.I, S.Iteration});
306   }
307 
308   static inline bool isEqual(const UnrolledInstState &LHS,
309                              const UnrolledInstState &RHS) {
310     return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration});
311   }
312 };
313 
314 struct EstimatedUnrollCost {
315   /// The estimated cost after unrolling.
316   unsigned UnrolledCost;
317 
318   /// The estimated dynamic cost of executing the instructions in the
319   /// rolled form.
320   unsigned RolledDynamicCost;
321 };
322 
323 struct PragmaInfo {
324   PragmaInfo(bool UUC, bool PFU, unsigned PC, bool PEU)
325       : UserUnrollCount(UUC), PragmaFullUnroll(PFU), PragmaCount(PC),
326         PragmaEnableUnroll(PEU) {}
327   const bool UserUnrollCount;
328   const bool PragmaFullUnroll;
329   const unsigned PragmaCount;
330   const bool PragmaEnableUnroll;
331 };
332 
333 } // end anonymous namespace
334 
335 /// Figure out if the loop is worth full unrolling.
336 ///
337 /// Complete loop unrolling can make some loads constant, and we need to know
338 /// if that would expose any further optimization opportunities.  This routine
339 /// estimates this optimization.  It computes cost of unrolled loop
340 /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
341 /// dynamic cost we mean that we won't count costs of blocks that are known not
342 /// to be executed (i.e. if we have a branch in the loop and we know that at the
343 /// given iteration its condition would be resolved to true, we won't add up the
344 /// cost of the 'false'-block).
345 /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
346 /// the analysis failed (no benefits expected from the unrolling, or the loop is
347 /// too big to analyze), the returned value is None.
348 static Optional<EstimatedUnrollCost> analyzeLoopUnrollCost(
349     const Loop *L, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE,
350     const SmallPtrSetImpl<const Value *> &EphValues,
351     const TargetTransformInfo &TTI, unsigned MaxUnrolledLoopSize,
352     unsigned MaxIterationsCountToAnalyze) {
353   // We want to be able to scale offsets by the trip count and add more offsets
354   // to them without checking for overflows, and we already don't want to
355   // analyze *massive* trip counts, so we force the max to be reasonably small.
356   assert(MaxIterationsCountToAnalyze <
357              (unsigned)(std::numeric_limits<int>::max() / 2) &&
358          "The unroll iterations max is too large!");
359 
360   // Only analyze inner loops. We can't properly estimate cost of nested loops
361   // and we won't visit inner loops again anyway.
362   if (!L->isInnermost())
363     return None;
364 
365   // Don't simulate loops with a big or unknown tripcount
366   if (!TripCount || TripCount > MaxIterationsCountToAnalyze)
367     return None;
368 
369   SmallSetVector<BasicBlock *, 16> BBWorklist;
370   SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist;
371   DenseMap<Value *, Value *> SimplifiedValues;
372   SmallVector<std::pair<Value *, Value *>, 4> SimplifiedInputValues;
373 
374   // The estimated cost of the unrolled form of the loop. We try to estimate
375   // this by simplifying as much as we can while computing the estimate.
376   InstructionCost UnrolledCost = 0;
377 
378   // We also track the estimated dynamic (that is, actually executed) cost in
379   // the rolled form. This helps identify cases when the savings from unrolling
380   // aren't just exposing dead control flows, but actual reduced dynamic
381   // instructions due to the simplifications which we expect to occur after
382   // unrolling.
383   InstructionCost RolledDynamicCost = 0;
384 
385   // We track the simplification of each instruction in each iteration. We use
386   // this to recursively merge costs into the unrolled cost on-demand so that
387   // we don't count the cost of any dead code. This is essentially a map from
388   // <instruction, int> to <bool, bool>, but stored as a densely packed struct.
389   DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap;
390 
391   // A small worklist used to accumulate cost of instructions from each
392   // observable and reached root in the loop.
393   SmallVector<Instruction *, 16> CostWorklist;
394 
395   // PHI-used worklist used between iterations while accumulating cost.
396   SmallVector<Instruction *, 4> PHIUsedList;
397 
398   // Helper function to accumulate cost for instructions in the loop.
399   auto AddCostRecursively = [&](Instruction &RootI, int Iteration) {
400     assert(Iteration >= 0 && "Cannot have a negative iteration!");
401     assert(CostWorklist.empty() && "Must start with an empty cost list");
402     assert(PHIUsedList.empty() && "Must start with an empty phi used list");
403     CostWorklist.push_back(&RootI);
404     TargetTransformInfo::TargetCostKind CostKind =
405       RootI.getFunction()->hasMinSize() ?
406       TargetTransformInfo::TCK_CodeSize :
407       TargetTransformInfo::TCK_SizeAndLatency;
408     for (;; --Iteration) {
409       do {
410         Instruction *I = CostWorklist.pop_back_val();
411 
412         // InstCostMap only uses I and Iteration as a key, the other two values
413         // don't matter here.
414         auto CostIter = InstCostMap.find({I, Iteration, 0, 0});
415         if (CostIter == InstCostMap.end())
416           // If an input to a PHI node comes from a dead path through the loop
417           // we may have no cost data for it here. What that actually means is
418           // that it is free.
419           continue;
420         auto &Cost = *CostIter;
421         if (Cost.IsCounted)
422           // Already counted this instruction.
423           continue;
424 
425         // Mark that we are counting the cost of this instruction now.
426         Cost.IsCounted = true;
427 
428         // If this is a PHI node in the loop header, just add it to the PHI set.
429         if (auto *PhiI = dyn_cast<PHINode>(I))
430           if (PhiI->getParent() == L->getHeader()) {
431             assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they "
432                                   "inherently simplify during unrolling.");
433             if (Iteration == 0)
434               continue;
435 
436             // Push the incoming value from the backedge into the PHI used list
437             // if it is an in-loop instruction. We'll use this to populate the
438             // cost worklist for the next iteration (as we count backwards).
439             if (auto *OpI = dyn_cast<Instruction>(
440                     PhiI->getIncomingValueForBlock(L->getLoopLatch())))
441               if (L->contains(OpI))
442                 PHIUsedList.push_back(OpI);
443             continue;
444           }
445 
446         // First accumulate the cost of this instruction.
447         if (!Cost.IsFree) {
448           UnrolledCost += TTI.getUserCost(I, CostKind);
449           LLVM_DEBUG(dbgs() << "Adding cost of instruction (iteration "
450                             << Iteration << "): ");
451           LLVM_DEBUG(I->dump());
452         }
453 
454         // We must count the cost of every operand which is not free,
455         // recursively. If we reach a loop PHI node, simply add it to the set
456         // to be considered on the next iteration (backwards!).
457         for (Value *Op : I->operands()) {
458           // Check whether this operand is free due to being a constant or
459           // outside the loop.
460           auto *OpI = dyn_cast<Instruction>(Op);
461           if (!OpI || !L->contains(OpI))
462             continue;
463 
464           // Otherwise accumulate its cost.
465           CostWorklist.push_back(OpI);
466         }
467       } while (!CostWorklist.empty());
468 
469       if (PHIUsedList.empty())
470         // We've exhausted the search.
471         break;
472 
473       assert(Iteration > 0 &&
474              "Cannot track PHI-used values past the first iteration!");
475       CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end());
476       PHIUsedList.clear();
477     }
478   };
479 
480   // Ensure that we don't violate the loop structure invariants relied on by
481   // this analysis.
482   assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
483   assert(L->isLCSSAForm(DT) &&
484          "Must have loops in LCSSA form to track live-out values.");
485 
486   LLVM_DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
487 
488   TargetTransformInfo::TargetCostKind CostKind =
489     L->getHeader()->getParent()->hasMinSize() ?
490     TargetTransformInfo::TCK_CodeSize : TargetTransformInfo::TCK_SizeAndLatency;
491   // Simulate execution of each iteration of the loop counting instructions,
492   // which would be simplified.
493   // Since the same load will take different values on different iterations,
494   // we literally have to go through all loop's iterations.
495   for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
496     LLVM_DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
497 
498     // Prepare for the iteration by collecting any simplified entry or backedge
499     // inputs.
500     for (Instruction &I : *L->getHeader()) {
501       auto *PHI = dyn_cast<PHINode>(&I);
502       if (!PHI)
503         break;
504 
505       // The loop header PHI nodes must have exactly two input: one from the
506       // loop preheader and one from the loop latch.
507       assert(
508           PHI->getNumIncomingValues() == 2 &&
509           "Must have an incoming value only for the preheader and the latch.");
510 
511       Value *V = PHI->getIncomingValueForBlock(
512           Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
513       if (Iteration != 0 && SimplifiedValues.count(V))
514         V = SimplifiedValues.lookup(V);
515       SimplifiedInputValues.push_back({PHI, V});
516     }
517 
518     // Now clear and re-populate the map for the next iteration.
519     SimplifiedValues.clear();
520     while (!SimplifiedInputValues.empty())
521       SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
522 
523     UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L);
524 
525     BBWorklist.clear();
526     BBWorklist.insert(L->getHeader());
527     // Note that we *must not* cache the size, this loop grows the worklist.
528     for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
529       BasicBlock *BB = BBWorklist[Idx];
530 
531       // Visit all instructions in the given basic block and try to simplify
532       // it.  We don't change the actual IR, just count optimization
533       // opportunities.
534       for (Instruction &I : *BB) {
535         // These won't get into the final code - don't even try calculating the
536         // cost for them.
537         if (isa<DbgInfoIntrinsic>(I) || EphValues.count(&I))
538           continue;
539 
540         // Track this instruction's expected baseline cost when executing the
541         // rolled loop form.
542         RolledDynamicCost += TTI.getUserCost(&I, CostKind);
543 
544         // Visit the instruction to analyze its loop cost after unrolling,
545         // and if the visitor returns true, mark the instruction as free after
546         // unrolling and continue.
547         bool IsFree = Analyzer.visit(I);
548         bool Inserted = InstCostMap.insert({&I, (int)Iteration,
549                                            (unsigned)IsFree,
550                                            /*IsCounted*/ false}).second;
551         (void)Inserted;
552         assert(Inserted && "Cannot have a state for an unvisited instruction!");
553 
554         if (IsFree)
555           continue;
556 
557         // Can't properly model a cost of a call.
558         // FIXME: With a proper cost model we should be able to do it.
559         if (auto *CI = dyn_cast<CallInst>(&I)) {
560           const Function *Callee = CI->getCalledFunction();
561           if (!Callee || TTI.isLoweredToCall(Callee)) {
562             LLVM_DEBUG(dbgs() << "Can't analyze cost of loop with call\n");
563             return None;
564           }
565         }
566 
567         // If the instruction might have a side-effect recursively account for
568         // the cost of it and all the instructions leading up to it.
569         if (I.mayHaveSideEffects())
570           AddCostRecursively(I, Iteration);
571 
572         // If unrolled body turns out to be too big, bail out.
573         if (UnrolledCost > MaxUnrolledLoopSize) {
574           LLVM_DEBUG(dbgs() << "  Exceeded threshold.. exiting.\n"
575                             << "  UnrolledCost: " << UnrolledCost
576                             << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
577                             << "\n");
578           return None;
579         }
580       }
581 
582       Instruction *TI = BB->getTerminator();
583 
584       auto getSimplifiedConstant = [&](Value *V) -> Constant * {
585         if (SimplifiedValues.count(V))
586           V = SimplifiedValues.lookup(V);
587         return dyn_cast<Constant>(V);
588       };
589 
590       // Add in the live successors by first checking whether we have terminator
591       // that may be simplified based on the values simplified by this call.
592       BasicBlock *KnownSucc = nullptr;
593       if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
594         if (BI->isConditional()) {
595           if (auto *SimpleCond = getSimplifiedConstant(BI->getCondition())) {
596             // Just take the first successor if condition is undef
597             if (isa<UndefValue>(SimpleCond))
598               KnownSucc = BI->getSuccessor(0);
599             else if (ConstantInt *SimpleCondVal =
600                          dyn_cast<ConstantInt>(SimpleCond))
601               KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0);
602           }
603         }
604       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
605         if (auto *SimpleCond = getSimplifiedConstant(SI->getCondition())) {
606           // Just take the first successor if condition is undef
607           if (isa<UndefValue>(SimpleCond))
608             KnownSucc = SI->getSuccessor(0);
609           else if (ConstantInt *SimpleCondVal =
610                        dyn_cast<ConstantInt>(SimpleCond))
611             KnownSucc = SI->findCaseValue(SimpleCondVal)->getCaseSuccessor();
612         }
613       }
614       if (KnownSucc) {
615         if (L->contains(KnownSucc))
616           BBWorklist.insert(KnownSucc);
617         else
618           ExitWorklist.insert({BB, KnownSucc});
619         continue;
620       }
621 
622       // Add BB's successors to the worklist.
623       for (BasicBlock *Succ : successors(BB))
624         if (L->contains(Succ))
625           BBWorklist.insert(Succ);
626         else
627           ExitWorklist.insert({BB, Succ});
628       AddCostRecursively(*TI, Iteration);
629     }
630 
631     // If we found no optimization opportunities on the first iteration, we
632     // won't find them on later ones too.
633     if (UnrolledCost == RolledDynamicCost) {
634       LLVM_DEBUG(dbgs() << "  No opportunities found.. exiting.\n"
635                         << "  UnrolledCost: " << UnrolledCost << "\n");
636       return None;
637     }
638   }
639 
640   while (!ExitWorklist.empty()) {
641     BasicBlock *ExitingBB, *ExitBB;
642     std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val();
643 
644     for (Instruction &I : *ExitBB) {
645       auto *PN = dyn_cast<PHINode>(&I);
646       if (!PN)
647         break;
648 
649       Value *Op = PN->getIncomingValueForBlock(ExitingBB);
650       if (auto *OpI = dyn_cast<Instruction>(Op))
651         if (L->contains(OpI))
652           AddCostRecursively(*OpI, TripCount - 1);
653     }
654   }
655 
656   assert(UnrolledCost.isValid() && RolledDynamicCost.isValid() &&
657          "All instructions must have a valid cost, whether the "
658          "loop is rolled or unrolled.");
659 
660   LLVM_DEBUG(dbgs() << "Analysis finished:\n"
661                     << "UnrolledCost: " << UnrolledCost << ", "
662                     << "RolledDynamicCost: " << RolledDynamicCost << "\n");
663   return {{unsigned(*UnrolledCost.getValue()),
664            unsigned(*RolledDynamicCost.getValue())}};
665 }
666 
667 /// ApproximateLoopSize - Approximate the size of the loop.
668 unsigned llvm::ApproximateLoopSize(
669     const Loop *L, unsigned &NumCalls, bool &NotDuplicatable, bool &Convergent,
670     const TargetTransformInfo &TTI,
671     const SmallPtrSetImpl<const Value *> &EphValues, unsigned BEInsns) {
672   CodeMetrics Metrics;
673   for (BasicBlock *BB : L->blocks())
674     Metrics.analyzeBasicBlock(BB, TTI, EphValues);
675   NumCalls = Metrics.NumInlineCandidates;
676   NotDuplicatable = Metrics.notDuplicatable;
677   Convergent = Metrics.convergent;
678 
679   unsigned LoopSize = Metrics.NumInsts;
680 
681   // Don't allow an estimate of size zero.  This would allows unrolling of loops
682   // with huge iteration counts, which is a compile time problem even if it's
683   // not a problem for code quality. Also, the code using this size may assume
684   // that each loop has at least three instructions (likely a conditional
685   // branch, a comparison feeding that branch, and some kind of loop increment
686   // feeding that comparison instruction).
687   LoopSize = std::max(LoopSize, BEInsns + 1);
688 
689   return LoopSize;
690 }
691 
692 // Returns the loop hint metadata node with the given name (for example,
693 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
694 // returned.
695 static MDNode *getUnrollMetadataForLoop(const Loop *L, StringRef Name) {
696   if (MDNode *LoopID = L->getLoopID())
697     return GetUnrollMetadata(LoopID, Name);
698   return nullptr;
699 }
700 
701 // Returns true if the loop has an unroll(full) pragma.
702 static bool hasUnrollFullPragma(const Loop *L) {
703   return getUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
704 }
705 
706 // Returns true if the loop has an unroll(enable) pragma. This metadata is used
707 // for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
708 static bool hasUnrollEnablePragma(const Loop *L) {
709   return getUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
710 }
711 
712 // Returns true if the loop has an runtime unroll(disable) pragma.
713 static bool hasRuntimeUnrollDisablePragma(const Loop *L) {
714   return getUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
715 }
716 
717 // If loop has an unroll_count pragma return the (necessarily
718 // positive) value from the pragma.  Otherwise return 0.
719 static unsigned unrollCountPragmaValue(const Loop *L) {
720   MDNode *MD = getUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
721   if (MD) {
722     assert(MD->getNumOperands() == 2 &&
723            "Unroll count hint metadata should have two operands.");
724     unsigned Count =
725         mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
726     assert(Count >= 1 && "Unroll count must be positive.");
727     return Count;
728   }
729   return 0;
730 }
731 
732 // Computes the boosting factor for complete unrolling.
733 // If fully unrolling the loop would save a lot of RolledDynamicCost, it would
734 // be beneficial to fully unroll the loop even if unrolledcost is large. We
735 // use (RolledDynamicCost / UnrolledCost) to model the unroll benefits to adjust
736 // the unroll threshold.
737 static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost,
738                                             unsigned MaxPercentThresholdBoost) {
739   if (Cost.RolledDynamicCost >= std::numeric_limits<unsigned>::max() / 100)
740     return 100;
741   else if (Cost.UnrolledCost != 0)
742     // The boosting factor is RolledDynamicCost / UnrolledCost
743     return std::min(100 * Cost.RolledDynamicCost / Cost.UnrolledCost,
744                     MaxPercentThresholdBoost);
745   else
746     return MaxPercentThresholdBoost;
747 }
748 
749 // Produce an estimate of the unrolled cost of the specified loop.  This
750 // is used to a) produce a cost estimate for partial unrolling and b) to
751 // cheaply estimate cost for full unrolling when we don't want to symbolically
752 // evaluate all iterations.
753 class UnrollCostEstimator {
754   const unsigned LoopSize;
755 
756 public:
757   UnrollCostEstimator(Loop &L, unsigned LoopSize) : LoopSize(LoopSize) {}
758 
759   // Returns loop size estimation for unrolled loop, given the unrolling
760   // configuration specified by UP.
761   uint64_t
762   getUnrolledLoopSize(const TargetTransformInfo::UnrollingPreferences &UP,
763                       const unsigned CountOverwrite = 0) const {
764     assert(LoopSize >= UP.BEInsns &&
765            "LoopSize should not be less than BEInsns!");
766     if (CountOverwrite)
767       return static_cast<uint64_t>(LoopSize - UP.BEInsns) * CountOverwrite +
768              UP.BEInsns;
769     else
770       return static_cast<uint64_t>(LoopSize - UP.BEInsns) * UP.Count +
771              UP.BEInsns;
772   }
773 };
774 
775 static Optional<unsigned>
776 shouldPragmaUnroll(Loop *L, const PragmaInfo &PInfo,
777                    const unsigned TripMultiple, const unsigned TripCount,
778                    const UnrollCostEstimator UCE,
779                    const TargetTransformInfo::UnrollingPreferences &UP) {
780 
781   // Using unroll pragma
782   // 1st priority is unroll count set by "unroll-count" option.
783 
784   if (PInfo.UserUnrollCount) {
785     if (UP.AllowRemainder &&
786         UCE.getUnrolledLoopSize(UP, (unsigned)UnrollCount) < UP.Threshold)
787       return (unsigned)UnrollCount;
788   }
789 
790   // 2nd priority is unroll count set by pragma.
791   if (PInfo.PragmaCount > 0) {
792     if ((UP.AllowRemainder || (TripMultiple % PInfo.PragmaCount == 0)) &&
793         UCE.getUnrolledLoopSize(UP, PInfo.PragmaCount) < PragmaUnrollThreshold)
794       return PInfo.PragmaCount;
795   }
796 
797   if (PInfo.PragmaFullUnroll && TripCount != 0) {
798     if (UCE.getUnrolledLoopSize(UP, TripCount) < PragmaUnrollThreshold)
799       return TripCount;
800   }
801   // if didn't return until here, should continue to other priorties
802   return None;
803 }
804 
805 static Optional<unsigned> shouldFullUnroll(
806     Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT,
807     ScalarEvolution &SE, const SmallPtrSetImpl<const Value *> &EphValues,
808     const unsigned FullUnrollTripCount, const UnrollCostEstimator UCE,
809     const TargetTransformInfo::UnrollingPreferences &UP) {
810 
811   if (FullUnrollTripCount && FullUnrollTripCount <= UP.FullUnrollMaxCount) {
812     // When computing the unrolled size, note that BEInsns are not replicated
813     // like the rest of the loop body.
814     if (UCE.getUnrolledLoopSize(UP) < UP.Threshold) {
815       return FullUnrollTripCount;
816 
817     } else {
818       // The loop isn't that small, but we still can fully unroll it if that
819       // helps to remove a significant number of instructions.
820       // To check that, run additional analysis on the loop.
821       if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
822               L, FullUnrollTripCount, DT, SE, EphValues, TTI,
823               UP.Threshold * UP.MaxPercentThresholdBoost / 100,
824               UP.MaxIterationsCountToAnalyze)) {
825         unsigned Boost =
826             getFullUnrollBoostingFactor(*Cost, UP.MaxPercentThresholdBoost);
827         if (Cost->UnrolledCost < UP.Threshold * Boost / 100) {
828           return FullUnrollTripCount;
829         }
830       }
831     }
832   }
833   return None;
834 }
835 
836 static Optional<unsigned>
837 shouldPartialUnroll(const unsigned LoopSize, const unsigned TripCount,
838                     const UnrollCostEstimator UCE,
839                     const TargetTransformInfo::UnrollingPreferences &UP) {
840 
841   unsigned count = UP.Count;
842   if (TripCount) {
843     if (!UP.Partial) {
844       LLVM_DEBUG(dbgs() << "  will not try to unroll partially because "
845                         << "-unroll-allow-partial not given\n");
846       count = 0;
847       return count;
848     }
849     if (count == 0)
850       count = TripCount;
851     if (UP.PartialThreshold != NoThreshold) {
852       // Reduce unroll count to be modulo of TripCount for partial unrolling.
853       if (UCE.getUnrolledLoopSize(UP, count) > UP.PartialThreshold)
854         count = (std::max(UP.PartialThreshold, UP.BEInsns + 1) - UP.BEInsns) /
855                 (LoopSize - UP.BEInsns);
856       if (count > UP.MaxCount)
857         count = UP.MaxCount;
858       while (count != 0 && TripCount % count != 0)
859         count--;
860       if (UP.AllowRemainder && count <= 1) {
861         // If there is no Count that is modulo of TripCount, set Count to
862         // largest power-of-two factor that satisfies the threshold limit.
863         // As we'll create fixup loop, do the type of unrolling only if
864         // remainder loop is allowed.
865         count = UP.DefaultUnrollRuntimeCount;
866         while (count != 0 &&
867                UCE.getUnrolledLoopSize(UP, count) > UP.PartialThreshold)
868           count >>= 1;
869       }
870       if (count < 2) {
871         count = 0;
872       }
873     } else {
874       count = TripCount;
875     }
876     if (count > UP.MaxCount)
877       count = UP.MaxCount;
878 
879     LLVM_DEBUG(dbgs() << "  partially unrolling with count: " << count << "\n");
880 
881     return count;
882   }
883 
884   // if didn't return until here, should continue to other priorties
885   return None;
886 }
887 // Returns true if unroll count was set explicitly.
888 // Calculates unroll count and writes it to UP.Count.
889 // Unless IgnoreUser is true, will also use metadata and command-line options
890 // that are specific to to the LoopUnroll pass (which, for instance, are
891 // irrelevant for the LoopUnrollAndJam pass).
892 // FIXME: This function is used by LoopUnroll and LoopUnrollAndJam, but consumes
893 // many LoopUnroll-specific options. The shared functionality should be
894 // refactored into it own function.
895 bool llvm::computeUnrollCount(
896     Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI,
897     ScalarEvolution &SE, const SmallPtrSetImpl<const Value *> &EphValues,
898     OptimizationRemarkEmitter *ORE, unsigned TripCount, unsigned MaxTripCount,
899     bool MaxOrZero, unsigned TripMultiple, unsigned LoopSize,
900     TargetTransformInfo::UnrollingPreferences &UP,
901     TargetTransformInfo::PeelingPreferences &PP, bool &UseUpperBound) {
902 
903   UnrollCostEstimator UCE(*L, LoopSize);
904   Optional<unsigned> UnrollFactor;
905 
906   const bool UserUnrollCount = UnrollCount.getNumOccurrences() > 0;
907   const bool PragmaFullUnroll = hasUnrollFullPragma(L);
908   const unsigned PragmaCount = unrollCountPragmaValue(L);
909   const bool PragmaEnableUnroll = hasUnrollEnablePragma(L);
910 
911   const bool ExplicitUnroll = PragmaCount > 0 || PragmaFullUnroll ||
912                               PragmaEnableUnroll || UserUnrollCount;
913 
914   PragmaInfo PInfo(UserUnrollCount, PragmaFullUnroll, PragmaCount,
915                    PragmaEnableUnroll);
916   // Use an explicit peel count that has been specified for testing. In this
917   // case it's not permitted to also specify an explicit unroll count.
918   if (PP.PeelCount) {
919     if (UnrollCount.getNumOccurrences() > 0) {
920       report_fatal_error("Cannot specify both explicit peel count and "
921                          "explicit unroll count");
922     }
923     UP.Count = 1;
924     UP.Runtime = false;
925     return true;
926   }
927   // Check for explicit Count.
928   // 1st priority is unroll count set by "unroll-count" option.
929   // 2nd priority is unroll count set by pragma.
930   UnrollFactor = shouldPragmaUnroll(L, PInfo, TripMultiple, TripCount, UCE, UP);
931 
932   if (UnrollFactor) {
933     UP.Count = *UnrollFactor;
934 
935     if (UserUnrollCount || (PragmaCount > 0)) {
936       UP.AllowExpensiveTripCount = true;
937       UP.Force = true;
938     }
939     UP.Runtime |= (PragmaCount > 0);
940     return ExplicitUnroll;
941   } else {
942     if (ExplicitUnroll && TripCount != 0) {
943       // If the loop has an unrolling pragma, we want to be more aggressive with
944       // unrolling limits. Set thresholds to at least the PragmaUnrollThreshold
945       // value which is larger than the default limits.
946       UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold);
947       UP.PartialThreshold =
948           std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold);
949     }
950   }
951 
952   // 3rd priority is full unroll count.
953   // Full unroll makes sense only when TripCount or its upper bound could be
954   // statically calculated.
955   // Also we need to check if we exceed FullUnrollMaxCount.
956 
957   // We can unroll by the upper bound amount if it's generally allowed or if
958   // we know that the loop is executed either the upper bound or zero times.
959   // (MaxOrZero unrolling keeps only the first loop test, so the number of
960   // loop tests remains the same compared to the non-unrolled version, whereas
961   // the generic upper bound unrolling keeps all but the last loop test so the
962   // number of loop tests goes up which may end up being worse on targets with
963   // constrained branch predictor resources so is controlled by an option.)
964   // In addition we only unroll small upper bounds.
965   unsigned FullUnrollMaxTripCount = MaxTripCount;
966   if (!(UP.UpperBound || MaxOrZero) ||
967       FullUnrollMaxTripCount > UnrollMaxUpperBound)
968     FullUnrollMaxTripCount = 0;
969 
970   // UnrollByMaxCount and ExactTripCount cannot both be non zero since we only
971   // compute the former when the latter is zero.
972   unsigned ExactTripCount = TripCount;
973   assert((ExactTripCount == 0 || FullUnrollMaxTripCount == 0) &&
974          "ExtractTripCount and UnrollByMaxCount cannot both be non zero.");
975 
976   unsigned FullUnrollTripCount =
977       ExactTripCount ? ExactTripCount : FullUnrollMaxTripCount;
978   UP.Count = FullUnrollTripCount;
979 
980   UnrollFactor =
981       shouldFullUnroll(L, TTI, DT, SE, EphValues, FullUnrollTripCount, UCE, UP);
982 
983   // if shouldFullUnroll can do the unrolling, some side parameteres should be
984   // set
985   if (UnrollFactor) {
986     UP.Count = *UnrollFactor;
987     UseUpperBound = (FullUnrollMaxTripCount == FullUnrollTripCount);
988     TripCount = FullUnrollTripCount;
989     TripMultiple = UP.UpperBound ? 1 : TripMultiple;
990     return ExplicitUnroll;
991   } else {
992     UP.Count = FullUnrollTripCount;
993   }
994 
995   // 4th priority is loop peeling.
996   computePeelCount(L, LoopSize, PP, TripCount, SE, UP.Threshold);
997   if (PP.PeelCount) {
998     UP.Runtime = false;
999     UP.Count = 1;
1000     return ExplicitUnroll;
1001   }
1002 
1003   // Before starting partial unrolling, set up.partial to true,
1004   // if user explicitly asked  for unrolling
1005   if (TripCount)
1006     UP.Partial |= ExplicitUnroll;
1007 
1008   // 5th priority is partial unrolling.
1009   // Try partial unroll only when TripCount could be statically calculated.
1010   UnrollFactor = shouldPartialUnroll(LoopSize, TripCount, UCE, UP);
1011 
1012   if (UnrollFactor) {
1013     UP.Count = *UnrollFactor;
1014 
1015     if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
1016         UP.Count != TripCount)
1017       ORE->emit([&]() {
1018         return OptimizationRemarkMissed(DEBUG_TYPE,
1019                                         "FullUnrollAsDirectedTooLarge",
1020                                         L->getStartLoc(), L->getHeader())
1021                << "Unable to fully unroll loop as directed by unroll pragma "
1022                   "because "
1023                   "unrolled size is too large.";
1024       });
1025 
1026     if (UP.PartialThreshold != NoThreshold) {
1027       if (UP.Count == 0) {
1028         if (PragmaEnableUnroll)
1029           ORE->emit([&]() {
1030             return OptimizationRemarkMissed(DEBUG_TYPE,
1031                                             "UnrollAsDirectedTooLarge",
1032                                             L->getStartLoc(), L->getHeader())
1033                    << "Unable to unroll loop as directed by unroll(enable) "
1034                       "pragma "
1035                       "because unrolled size is too large.";
1036           });
1037       }
1038     }
1039     return ExplicitUnroll;
1040   }
1041   assert(TripCount == 0 &&
1042          "All cases when TripCount is constant should be covered here.");
1043   if (PragmaFullUnroll)
1044     ORE->emit([&]() {
1045       return OptimizationRemarkMissed(
1046                  DEBUG_TYPE, "CantFullUnrollAsDirectedRuntimeTripCount",
1047                  L->getStartLoc(), L->getHeader())
1048              << "Unable to fully unroll loop as directed by unroll(full) "
1049                 "pragma "
1050                 "because loop has a runtime trip count.";
1051     });
1052 
1053   // 6th priority is runtime unrolling.
1054   // Don't unroll a runtime trip count loop when it is disabled.
1055   if (hasRuntimeUnrollDisablePragma(L)) {
1056     UP.Count = 0;
1057     return false;
1058   }
1059 
1060   // Don't unroll a small upper bound loop unless user or TTI asked to do so.
1061   if (MaxTripCount && !UP.Force && MaxTripCount < UnrollMaxUpperBound) {
1062     UP.Count = 0;
1063     return false;
1064   }
1065 
1066   // Check if the runtime trip count is too small when profile is available.
1067   if (L->getHeader()->getParent()->hasProfileData()) {
1068     if (auto ProfileTripCount = getLoopEstimatedTripCount(L)) {
1069       if (*ProfileTripCount < FlatLoopTripCountThreshold)
1070         return false;
1071       else
1072         UP.AllowExpensiveTripCount = true;
1073     }
1074   }
1075   UP.Runtime |= PragmaEnableUnroll || PragmaCount > 0 || UserUnrollCount;
1076   if (!UP.Runtime) {
1077     LLVM_DEBUG(
1078         dbgs() << "  will not try to unroll loop with runtime trip count "
1079                << "-unroll-runtime not given\n");
1080     UP.Count = 0;
1081     return false;
1082   }
1083   if (UP.Count == 0)
1084     UP.Count = UP.DefaultUnrollRuntimeCount;
1085 
1086   // Reduce unroll count to be the largest power-of-two factor of
1087   // the original count which satisfies the threshold limit.
1088   while (UP.Count != 0 &&
1089          UCE.getUnrolledLoopSize(UP) > UP.PartialThreshold)
1090     UP.Count >>= 1;
1091 
1092 #ifndef NDEBUG
1093   unsigned OrigCount = UP.Count;
1094 #endif
1095 
1096   if (!UP.AllowRemainder && UP.Count != 0 && (TripMultiple % UP.Count) != 0) {
1097     while (UP.Count != 0 && TripMultiple % UP.Count != 0)
1098       UP.Count >>= 1;
1099     LLVM_DEBUG(
1100         dbgs() << "Remainder loop is restricted (that could architecture "
1101                   "specific or because the loop contains a convergent "
1102                   "instruction), so unroll count must divide the trip "
1103                   "multiple, "
1104                << TripMultiple << ".  Reducing unroll count from " << OrigCount
1105                << " to " << UP.Count << ".\n");
1106 
1107     using namespace ore;
1108 
1109     if (unrollCountPragmaValue(L) > 0 && !UP.AllowRemainder)
1110       ORE->emit([&]() {
1111         return OptimizationRemarkMissed(DEBUG_TYPE,
1112                                         "DifferentUnrollCountFromDirected",
1113                                         L->getStartLoc(), L->getHeader())
1114                << "Unable to unroll loop the number of times directed by "
1115                   "unroll_count pragma because remainder loop is restricted "
1116                   "(that could architecture specific or because the loop "
1117                   "contains a convergent instruction) and so must have an "
1118                   "unroll "
1119                   "count that divides the loop trip multiple of "
1120                << NV("TripMultiple", TripMultiple) << ".  Unrolling instead "
1121                << NV("UnrollCount", UP.Count) << " time(s).";
1122       });
1123   }
1124 
1125   if (UP.Count > UP.MaxCount)
1126     UP.Count = UP.MaxCount;
1127 
1128   if (MaxTripCount && UP.Count > MaxTripCount)
1129     UP.Count = MaxTripCount;
1130 
1131   LLVM_DEBUG(dbgs() << "  runtime unrolling with count: " << UP.Count
1132                     << "\n");
1133   if (UP.Count < 2)
1134     UP.Count = 0;
1135   return ExplicitUnroll;
1136 }
1137 
1138 static LoopUnrollResult tryToUnrollLoop(
1139     Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE,
1140     const TargetTransformInfo &TTI, AssumptionCache &AC,
1141     OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,
1142     ProfileSummaryInfo *PSI, bool PreserveLCSSA, int OptLevel,
1143     bool OnlyWhenForced, bool ForgetAllSCEV, Optional<unsigned> ProvidedCount,
1144     Optional<unsigned> ProvidedThreshold, Optional<bool> ProvidedAllowPartial,
1145     Optional<bool> ProvidedRuntime, Optional<bool> ProvidedUpperBound,
1146     Optional<bool> ProvidedAllowPeeling,
1147     Optional<bool> ProvidedAllowProfileBasedPeeling,
1148     Optional<unsigned> ProvidedFullUnrollMaxCount) {
1149   LLVM_DEBUG(dbgs() << "Loop Unroll: F["
1150                     << L->getHeader()->getParent()->getName() << "] Loop %"
1151                     << L->getHeader()->getName() << "\n");
1152   TransformationMode TM = hasUnrollTransformation(L);
1153   if (TM & TM_Disable)
1154     return LoopUnrollResult::Unmodified;
1155   if (!L->isLoopSimplifyForm()) {
1156     LLVM_DEBUG(
1157         dbgs() << "  Not unrolling loop which is not in loop-simplify form.\n");
1158     return LoopUnrollResult::Unmodified;
1159   }
1160 
1161   // When automatic unrolling is disabled, do not unroll unless overridden for
1162   // this loop.
1163   if (OnlyWhenForced && !(TM & TM_Enable))
1164     return LoopUnrollResult::Unmodified;
1165 
1166   bool OptForSize = L->getHeader()->getParent()->hasOptSize();
1167   unsigned NumInlineCandidates;
1168   bool NotDuplicatable;
1169   bool Convergent;
1170   TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
1171       L, SE, TTI, BFI, PSI, ORE, OptLevel, ProvidedThreshold, ProvidedCount,
1172       ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound,
1173       ProvidedFullUnrollMaxCount);
1174   TargetTransformInfo::PeelingPreferences PP = gatherPeelingPreferences(
1175       L, SE, TTI, ProvidedAllowPeeling, ProvidedAllowProfileBasedPeeling, true);
1176 
1177   // Exit early if unrolling is disabled. For OptForSize, we pick the loop size
1178   // as threshold later on.
1179   if (UP.Threshold == 0 && (!UP.Partial || UP.PartialThreshold == 0) &&
1180       !OptForSize)
1181     return LoopUnrollResult::Unmodified;
1182 
1183   SmallPtrSet<const Value *, 32> EphValues;
1184   CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
1185 
1186   unsigned LoopSize =
1187       ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
1188                           TTI, EphValues, UP.BEInsns);
1189   LLVM_DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
1190   if (NotDuplicatable) {
1191     LLVM_DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
1192                       << " instructions.\n");
1193     return LoopUnrollResult::Unmodified;
1194   }
1195 
1196   // When optimizing for size, use LoopSize + 1 as threshold (we use < Threshold
1197   // later), to (fully) unroll loops, if it does not increase code size.
1198   if (OptForSize)
1199     UP.Threshold = std::max(UP.Threshold, LoopSize + 1);
1200 
1201   if (NumInlineCandidates != 0) {
1202     LLVM_DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
1203     return LoopUnrollResult::Unmodified;
1204   }
1205 
1206   // Find the smallest exact trip count for any exit. This is an upper bound
1207   // on the loop trip count, but an exit at an earlier iteration is still
1208   // possible. An unroll by the smallest exact trip count guarantees that all
1209   // brnaches relating to at least one exit can be eliminated. This is unlike
1210   // the max trip count, which only guarantees that the backedge can be broken.
1211   unsigned TripCount = 0;
1212   unsigned TripMultiple = 1;
1213   SmallVector<BasicBlock *, 8> ExitingBlocks;
1214   L->getExitingBlocks(ExitingBlocks);
1215   for (BasicBlock *ExitingBlock : ExitingBlocks)
1216     if (unsigned TC = SE.getSmallConstantTripCount(L, ExitingBlock))
1217       if (!TripCount || TC < TripCount)
1218         TripCount = TripMultiple = TC;
1219 
1220   if (!TripCount) {
1221     // If no exact trip count is known, determine the trip multiple of either
1222     // the loop latch or the single exiting block.
1223     // TODO: Relax for multiple exits.
1224     BasicBlock *ExitingBlock = L->getLoopLatch();
1225     if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
1226       ExitingBlock = L->getExitingBlock();
1227     if (ExitingBlock)
1228       TripMultiple = SE.getSmallConstantTripMultiple(L, ExitingBlock);
1229   }
1230 
1231   // If the loop contains a convergent operation, the prelude we'd add
1232   // to do the first few instructions before we hit the unrolled loop
1233   // is unsafe -- it adds a control-flow dependency to the convergent
1234   // operation.  Therefore restrict remainder loop (try unrolling without).
1235   //
1236   // TODO: This is quite conservative.  In practice, convergent_op()
1237   // is likely to be called unconditionally in the loop.  In this
1238   // case, the program would be ill-formed (on most architectures)
1239   // unless n were the same on all threads in a thread group.
1240   // Assuming n is the same on all threads, any kind of unrolling is
1241   // safe.  But currently llvm's notion of convergence isn't powerful
1242   // enough to express this.
1243   if (Convergent)
1244     UP.AllowRemainder = false;
1245 
1246   // Try to find the trip count upper bound if we cannot find the exact trip
1247   // count.
1248   unsigned MaxTripCount = 0;
1249   bool MaxOrZero = false;
1250   if (!TripCount) {
1251     MaxTripCount = SE.getSmallConstantMaxTripCount(L);
1252     MaxOrZero = SE.isBackedgeTakenCountMaxOrZero(L);
1253   }
1254 
1255   // computeUnrollCount() decides whether it is beneficial to use upper bound to
1256   // fully unroll the loop.
1257   bool UseUpperBound = false;
1258   bool IsCountSetExplicitly = computeUnrollCount(
1259       L, TTI, DT, LI, SE, EphValues, &ORE, TripCount, MaxTripCount, MaxOrZero,
1260       TripMultiple, LoopSize, UP, PP, UseUpperBound);
1261   if (!UP.Count)
1262     return LoopUnrollResult::Unmodified;
1263 
1264   if (PP.PeelCount) {
1265     assert(UP.Count == 1 && "Cannot perform peel and unroll in the same step");
1266     LLVM_DEBUG(dbgs() << "PEELING loop %" << L->getHeader()->getName()
1267                       << " with iteration count " << PP.PeelCount << "!\n");
1268     ORE.emit([&]() {
1269       return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(),
1270                                 L->getHeader())
1271              << " peeled loop by " << ore::NV("PeelCount", PP.PeelCount)
1272              << " iterations";
1273     });
1274 
1275     if (peelLoop(L, PP.PeelCount, LI, &SE, &DT, &AC, PreserveLCSSA)) {
1276       simplifyLoopAfterUnroll(L, true, LI, &SE, &DT, &AC, &TTI);
1277       // If the loop was peeled, we already "used up" the profile information
1278       // we had, so we don't want to unroll or peel again.
1279       if (PP.PeelProfiledIterations)
1280         L->setLoopAlreadyUnrolled();
1281       return LoopUnrollResult::PartiallyUnrolled;
1282     }
1283     return LoopUnrollResult::Unmodified;
1284   }
1285 
1286   // At this point, UP.Runtime indicates that run-time unrolling is allowed.
1287   // However, we only want to actually perform it if we don't know the trip
1288   // count and the unroll count doesn't divide the known trip multiple.
1289   // TODO: This decision should probably be pushed up into
1290   // computeUnrollCount().
1291   UP.Runtime &= TripCount == 0 && TripMultiple % UP.Count != 0;
1292 
1293   // Save loop properties before it is transformed.
1294   MDNode *OrigLoopID = L->getLoopID();
1295 
1296   // Unroll the loop.
1297   Loop *RemainderLoop = nullptr;
1298   LoopUnrollResult UnrollResult = UnrollLoop(
1299       L,
1300       {UP.Count, UP.Force, UP.Runtime, UP.AllowExpensiveTripCount,
1301        UP.UnrollRemainder, ForgetAllSCEV},
1302       LI, &SE, &DT, &AC, &TTI, &ORE, PreserveLCSSA, &RemainderLoop);
1303   if (UnrollResult == LoopUnrollResult::Unmodified)
1304     return LoopUnrollResult::Unmodified;
1305 
1306   if (RemainderLoop) {
1307     Optional<MDNode *> RemainderLoopID =
1308         makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll,
1309                                         LLVMLoopUnrollFollowupRemainder});
1310     if (RemainderLoopID.hasValue())
1311       RemainderLoop->setLoopID(RemainderLoopID.getValue());
1312   }
1313 
1314   if (UnrollResult != LoopUnrollResult::FullyUnrolled) {
1315     Optional<MDNode *> NewLoopID =
1316         makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll,
1317                                         LLVMLoopUnrollFollowupUnrolled});
1318     if (NewLoopID.hasValue()) {
1319       L->setLoopID(NewLoopID.getValue());
1320 
1321       // Do not setLoopAlreadyUnrolled if loop attributes have been specified
1322       // explicitly.
1323       return UnrollResult;
1324     }
1325   }
1326 
1327   // If loop has an unroll count pragma or unrolled by explicitly set count
1328   // mark loop as unrolled to prevent unrolling beyond that requested.
1329   if (UnrollResult != LoopUnrollResult::FullyUnrolled && IsCountSetExplicitly)
1330     L->setLoopAlreadyUnrolled();
1331 
1332   return UnrollResult;
1333 }
1334 
1335 namespace {
1336 
1337 class LoopUnroll : public LoopPass {
1338 public:
1339   static char ID; // Pass ID, replacement for typeid
1340 
1341   int OptLevel;
1342 
1343   /// If false, use a cost model to determine whether unrolling of a loop is
1344   /// profitable. If true, only loops that explicitly request unrolling via
1345   /// metadata are considered. All other loops are skipped.
1346   bool OnlyWhenForced;
1347 
1348   /// If false, when SCEV is invalidated, only forget everything in the
1349   /// top-most loop (call forgetTopMostLoop), of the loop being processed.
1350   /// Otherwise, forgetAllLoops and rebuild when needed next.
1351   bool ForgetAllSCEV;
1352 
1353   Optional<unsigned> ProvidedCount;
1354   Optional<unsigned> ProvidedThreshold;
1355   Optional<bool> ProvidedAllowPartial;
1356   Optional<bool> ProvidedRuntime;
1357   Optional<bool> ProvidedUpperBound;
1358   Optional<bool> ProvidedAllowPeeling;
1359   Optional<bool> ProvidedAllowProfileBasedPeeling;
1360   Optional<unsigned> ProvidedFullUnrollMaxCount;
1361 
1362   LoopUnroll(int OptLevel = 2, bool OnlyWhenForced = false,
1363              bool ForgetAllSCEV = false, Optional<unsigned> Threshold = None,
1364              Optional<unsigned> Count = None,
1365              Optional<bool> AllowPartial = None, Optional<bool> Runtime = None,
1366              Optional<bool> UpperBound = None,
1367              Optional<bool> AllowPeeling = None,
1368              Optional<bool> AllowProfileBasedPeeling = None,
1369              Optional<unsigned> ProvidedFullUnrollMaxCount = None)
1370       : LoopPass(ID), OptLevel(OptLevel), OnlyWhenForced(OnlyWhenForced),
1371         ForgetAllSCEV(ForgetAllSCEV), ProvidedCount(std::move(Count)),
1372         ProvidedThreshold(Threshold), ProvidedAllowPartial(AllowPartial),
1373         ProvidedRuntime(Runtime), ProvidedUpperBound(UpperBound),
1374         ProvidedAllowPeeling(AllowPeeling),
1375         ProvidedAllowProfileBasedPeeling(AllowProfileBasedPeeling),
1376         ProvidedFullUnrollMaxCount(ProvidedFullUnrollMaxCount) {
1377     initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
1378   }
1379 
1380   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
1381     if (skipLoop(L))
1382       return false;
1383 
1384     Function &F = *L->getHeader()->getParent();
1385 
1386     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1387     LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1388     ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1389     const TargetTransformInfo &TTI =
1390         getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1391     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1392     // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
1393     // pass.  Function analyses need to be preserved across loop transformations
1394     // but ORE cannot be preserved (see comment before the pass definition).
1395     OptimizationRemarkEmitter ORE(&F);
1396     bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1397 
1398     LoopUnrollResult Result = tryToUnrollLoop(
1399         L, DT, LI, SE, TTI, AC, ORE, nullptr, nullptr, PreserveLCSSA, OptLevel,
1400         OnlyWhenForced, ForgetAllSCEV, ProvidedCount, ProvidedThreshold,
1401         ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound,
1402         ProvidedAllowPeeling, ProvidedAllowProfileBasedPeeling,
1403         ProvidedFullUnrollMaxCount);
1404 
1405     if (Result == LoopUnrollResult::FullyUnrolled)
1406       LPM.markLoopAsDeleted(*L);
1407 
1408     return Result != LoopUnrollResult::Unmodified;
1409   }
1410 
1411   /// This transformation requires natural loop information & requires that
1412   /// loop preheaders be inserted into the CFG...
1413   void getAnalysisUsage(AnalysisUsage &AU) const override {
1414     AU.addRequired<AssumptionCacheTracker>();
1415     AU.addRequired<TargetTransformInfoWrapperPass>();
1416     // FIXME: Loop passes are required to preserve domtree, and for now we just
1417     // recreate dom info if anything gets unrolled.
1418     getLoopAnalysisUsage(AU);
1419   }
1420 };
1421 
1422 } // end anonymous namespace
1423 
1424 char LoopUnroll::ID = 0;
1425 
1426 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1427 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1428 INITIALIZE_PASS_DEPENDENCY(LoopPass)
1429 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1430 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1431 
1432 Pass *llvm::createLoopUnrollPass(int OptLevel, bool OnlyWhenForced,
1433                                  bool ForgetAllSCEV, int Threshold, int Count,
1434                                  int AllowPartial, int Runtime, int UpperBound,
1435                                  int AllowPeeling) {
1436   // TODO: It would make more sense for this function to take the optionals
1437   // directly, but that's dangerous since it would silently break out of tree
1438   // callers.
1439   return new LoopUnroll(
1440       OptLevel, OnlyWhenForced, ForgetAllSCEV,
1441       Threshold == -1 ? None : Optional<unsigned>(Threshold),
1442       Count == -1 ? None : Optional<unsigned>(Count),
1443       AllowPartial == -1 ? None : Optional<bool>(AllowPartial),
1444       Runtime == -1 ? None : Optional<bool>(Runtime),
1445       UpperBound == -1 ? None : Optional<bool>(UpperBound),
1446       AllowPeeling == -1 ? None : Optional<bool>(AllowPeeling));
1447 }
1448 
1449 Pass *llvm::createSimpleLoopUnrollPass(int OptLevel, bool OnlyWhenForced,
1450                                        bool ForgetAllSCEV) {
1451   return createLoopUnrollPass(OptLevel, OnlyWhenForced, ForgetAllSCEV, -1, -1,
1452                               0, 0, 0, 1);
1453 }
1454 
1455 PreservedAnalyses LoopFullUnrollPass::run(Loop &L, LoopAnalysisManager &AM,
1456                                           LoopStandardAnalysisResults &AR,
1457                                           LPMUpdater &Updater) {
1458   // For the new PM, we can't use OptimizationRemarkEmitter as an analysis
1459   // pass. Function analyses need to be preserved across loop transformations
1460   // but ORE cannot be preserved (see comment before the pass definition).
1461   OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
1462 
1463   // Keep track of the previous loop structure so we can identify new loops
1464   // created by unrolling.
1465   Loop *ParentL = L.getParentLoop();
1466   SmallPtrSet<Loop *, 4> OldLoops;
1467   if (ParentL)
1468     OldLoops.insert(ParentL->begin(), ParentL->end());
1469   else
1470     OldLoops.insert(AR.LI.begin(), AR.LI.end());
1471 
1472   std::string LoopName = std::string(L.getName());
1473 
1474   bool Changed = tryToUnrollLoop(&L, AR.DT, &AR.LI, AR.SE, AR.TTI, AR.AC, ORE,
1475                                  /*BFI*/ nullptr, /*PSI*/ nullptr,
1476                                  /*PreserveLCSSA*/ true, OptLevel,
1477                                  OnlyWhenForced, ForgetSCEV, /*Count*/ None,
1478                                  /*Threshold*/ None, /*AllowPartial*/ false,
1479                                  /*Runtime*/ false, /*UpperBound*/ false,
1480                                  /*AllowPeeling*/ true,
1481                                  /*AllowProfileBasedPeeling*/ false,
1482                                  /*FullUnrollMaxCount*/ None) !=
1483                  LoopUnrollResult::Unmodified;
1484   if (!Changed)
1485     return PreservedAnalyses::all();
1486 
1487   // The parent must not be damaged by unrolling!
1488 #ifndef NDEBUG
1489   if (ParentL)
1490     ParentL->verifyLoop();
1491 #endif
1492 
1493   // Unrolling can do several things to introduce new loops into a loop nest:
1494   // - Full unrolling clones child loops within the current loop but then
1495   //   removes the current loop making all of the children appear to be new
1496   //   sibling loops.
1497   //
1498   // When a new loop appears as a sibling loop after fully unrolling,
1499   // its nesting structure has fundamentally changed and we want to revisit
1500   // it to reflect that.
1501   //
1502   // When unrolling has removed the current loop, we need to tell the
1503   // infrastructure that it is gone.
1504   //
1505   // Finally, we support a debugging/testing mode where we revisit child loops
1506   // as well. These are not expected to require further optimizations as either
1507   // they or the loop they were cloned from have been directly visited already.
1508   // But the debugging mode allows us to check this assumption.
1509   bool IsCurrentLoopValid = false;
1510   SmallVector<Loop *, 4> SibLoops;
1511   if (ParentL)
1512     SibLoops.append(ParentL->begin(), ParentL->end());
1513   else
1514     SibLoops.append(AR.LI.begin(), AR.LI.end());
1515   erase_if(SibLoops, [&](Loop *SibLoop) {
1516     if (SibLoop == &L) {
1517       IsCurrentLoopValid = true;
1518       return true;
1519     }
1520 
1521     // Otherwise erase the loop from the list if it was in the old loops.
1522     return OldLoops.contains(SibLoop);
1523   });
1524   Updater.addSiblingLoops(SibLoops);
1525 
1526   if (!IsCurrentLoopValid) {
1527     Updater.markLoopAsDeleted(L, LoopName);
1528   } else {
1529     // We can only walk child loops if the current loop remained valid.
1530     if (UnrollRevisitChildLoops) {
1531       // Walk *all* of the child loops.
1532       SmallVector<Loop *, 4> ChildLoops(L.begin(), L.end());
1533       Updater.addChildLoops(ChildLoops);
1534     }
1535   }
1536 
1537   return getLoopPassPreservedAnalyses();
1538 }
1539 
1540 PreservedAnalyses LoopUnrollPass::run(Function &F,
1541                                       FunctionAnalysisManager &AM) {
1542   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1543   auto &LI = AM.getResult<LoopAnalysis>(F);
1544   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1545   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1546   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1547   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1548 
1549   LoopAnalysisManager *LAM = nullptr;
1550   if (auto *LAMProxy = AM.getCachedResult<LoopAnalysisManagerFunctionProxy>(F))
1551     LAM = &LAMProxy->getManager();
1552 
1553   auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1554   ProfileSummaryInfo *PSI =
1555       MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
1556   auto *BFI = (PSI && PSI->hasProfileSummary()) ?
1557       &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
1558 
1559   bool Changed = false;
1560 
1561   // The unroller requires loops to be in simplified form, and also needs LCSSA.
1562   // Since simplification may add new inner loops, it has to run before the
1563   // legality and profitability checks. This means running the loop unroller
1564   // will simplify all loops, regardless of whether anything end up being
1565   // unrolled.
1566   for (auto &L : LI) {
1567     Changed |=
1568         simplifyLoop(L, &DT, &LI, &SE, &AC, nullptr, false /* PreserveLCSSA */);
1569     Changed |= formLCSSARecursively(*L, DT, &LI, &SE);
1570   }
1571 
1572   // Add the loop nests in the reverse order of LoopInfo. See method
1573   // declaration.
1574   SmallPriorityWorklist<Loop *, 4> Worklist;
1575   appendLoopsToWorklist(LI, Worklist);
1576 
1577   while (!Worklist.empty()) {
1578     // Because the LoopInfo stores the loops in RPO, we walk the worklist
1579     // from back to front so that we work forward across the CFG, which
1580     // for unrolling is only needed to get optimization remarks emitted in
1581     // a forward order.
1582     Loop &L = *Worklist.pop_back_val();
1583 #ifndef NDEBUG
1584     Loop *ParentL = L.getParentLoop();
1585 #endif
1586 
1587     // Check if the profile summary indicates that the profiled application
1588     // has a huge working set size, in which case we disable peeling to avoid
1589     // bloating it further.
1590     Optional<bool> LocalAllowPeeling = UnrollOpts.AllowPeeling;
1591     if (PSI && PSI->hasHugeWorkingSetSize())
1592       LocalAllowPeeling = false;
1593     std::string LoopName = std::string(L.getName());
1594     // The API here is quite complex to call and we allow to select some
1595     // flavors of unrolling during construction time (by setting UnrollOpts).
1596     LoopUnrollResult Result = tryToUnrollLoop(
1597         &L, DT, &LI, SE, TTI, AC, ORE, BFI, PSI,
1598         /*PreserveLCSSA*/ true, UnrollOpts.OptLevel, UnrollOpts.OnlyWhenForced,
1599         UnrollOpts.ForgetSCEV, /*Count*/ None,
1600         /*Threshold*/ None, UnrollOpts.AllowPartial, UnrollOpts.AllowRuntime,
1601         UnrollOpts.AllowUpperBound, LocalAllowPeeling,
1602         UnrollOpts.AllowProfileBasedPeeling, UnrollOpts.FullUnrollMaxCount);
1603     Changed |= Result != LoopUnrollResult::Unmodified;
1604 
1605     // The parent must not be damaged by unrolling!
1606 #ifndef NDEBUG
1607     if (Result != LoopUnrollResult::Unmodified && ParentL)
1608       ParentL->verifyLoop();
1609 #endif
1610 
1611     // Clear any cached analysis results for L if we removed it completely.
1612     if (LAM && Result == LoopUnrollResult::FullyUnrolled)
1613       LAM->clear(L, LoopName);
1614   }
1615 
1616   if (!Changed)
1617     return PreservedAnalyses::all();
1618 
1619   return getLoopPassPreservedAnalyses();
1620 }
1621