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