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