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