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