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