xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp (revision 963a6d9c69c9d18b57543f751d5de05f9578dc1d)
1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements a simple loop unroller.  It works best when loops have
11 // been canonicalized by the -indvars pass, allowing it to determine the trip
12 // counts of loops easily.
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/Analysis/AssumptionCache.h"
17 #include "llvm/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/GlobalsModRef.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/LoopUnrollAnalyzer.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/InstVisitor.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/Transforms/Utils/LoopUtils.h"
36 #include "llvm/Transforms/Utils/UnrollLoop.h"
37 #include <climits>
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "loop-unroll"
42 
43 static cl::opt<unsigned>
44     UnrollThreshold("unroll-threshold", cl::Hidden,
45                     cl::desc("The baseline cost threshold for loop unrolling"));
46 
47 static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold(
48     "unroll-percent-dynamic-cost-saved-threshold", cl::Hidden,
49     cl::desc("The percentage of estimated dynamic cost which must be saved by "
50              "unrolling to allow unrolling up to the max threshold."));
51 
52 static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount(
53     "unroll-dynamic-cost-savings-discount", cl::Hidden,
54     cl::desc("This is the amount discounted from the total unroll cost when "
55              "the unrolled form has a high dynamic cost savings (triggered by "
56              "the '-unroll-perecent-dynamic-cost-saved-threshold' flag)."));
57 
58 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
59     "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
60     cl::desc("Don't allow loop unrolling to simulate more than this number of"
61              "iterations when checking full unroll profitability"));
62 
63 static cl::opt<unsigned> UnrollCount(
64     "unroll-count", cl::Hidden,
65     cl::desc("Use this unroll count for all loops including those with "
66              "unroll_count pragma values, for testing purposes"));
67 
68 static cl::opt<unsigned> UnrollMaxCount(
69     "unroll-max-count", cl::Hidden,
70     cl::desc("Set the max unroll count for partial and runtime unrolling, for"
71              "testing purposes"));
72 
73 static cl::opt<unsigned> UnrollFullMaxCount(
74     "unroll-full-max-count", cl::Hidden,
75     cl::desc(
76         "Set the max unroll count for full unrolling, for testing purposes"));
77 
78 static cl::opt<bool>
79     UnrollAllowPartial("unroll-allow-partial", cl::Hidden,
80                        cl::desc("Allows loops to be partially unrolled until "
81                                 "-unroll-threshold loop size is reached."));
82 
83 static cl::opt<bool>
84     UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden,
85                   cl::desc("Unroll loops with run-time trip counts"));
86 
87 static cl::opt<unsigned> PragmaUnrollThreshold(
88     "pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
89     cl::desc("Unrolled size limit for loops with an unroll(full) or "
90              "unroll_count pragma."));
91 
92 /// A magic value for use with the Threshold parameter to indicate
93 /// that the loop unroll should be performed regardless of how much
94 /// code expansion would result.
95 static const unsigned NoThreshold = UINT_MAX;
96 
97 /// Default unroll count for loops with run-time trip count if
98 /// -unroll-count is not set
99 static const unsigned DefaultUnrollRuntimeCount = 8;
100 
101 /// Gather the various unrolling parameters based on the defaults, compiler
102 /// flags, TTI overrides, pragmas, and user specified parameters.
103 static TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences(
104     Loop *L, const TargetTransformInfo &TTI, Optional<unsigned> UserThreshold,
105     Optional<unsigned> UserCount, Optional<bool> UserAllowPartial,
106     Optional<bool> UserRuntime, unsigned PragmaCount, bool PragmaFullUnroll,
107     bool PragmaEnableUnroll, unsigned TripCount) {
108   TargetTransformInfo::UnrollingPreferences UP;
109 
110   // Set up the defaults
111   UP.Threshold = 150;
112   UP.PercentDynamicCostSavedThreshold = 20;
113   UP.DynamicCostSavingsDiscount = 2000;
114   UP.OptSizeThreshold = 0;
115   UP.PartialThreshold = UP.Threshold;
116   UP.PartialOptSizeThreshold = 0;
117   UP.Count = 0;
118   UP.MaxCount = UINT_MAX;
119   UP.FullUnrollMaxCount = UINT_MAX;
120   UP.Partial = false;
121   UP.Runtime = false;
122   UP.AllowExpensiveTripCount = false;
123 
124   // Override with any target specific settings
125   TTI.getUnrollingPreferences(L, UP);
126 
127   // Apply size attributes
128   if (L->getHeader()->getParent()->optForSize()) {
129     UP.Threshold = UP.OptSizeThreshold;
130     UP.PartialThreshold = UP.PartialOptSizeThreshold;
131   }
132 
133   // Apply unroll count pragmas
134   if (PragmaCount)
135     UP.Count = PragmaCount;
136   else if (PragmaFullUnroll)
137     UP.Count = TripCount;
138 
139   // Apply any user values specified by cl::opt
140   if (UnrollThreshold.getNumOccurrences() > 0) {
141     UP.Threshold = UnrollThreshold;
142     UP.PartialThreshold = UnrollThreshold;
143   }
144   if (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0)
145     UP.PercentDynamicCostSavedThreshold =
146         UnrollPercentDynamicCostSavedThreshold;
147   if (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0)
148     UP.DynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount;
149   if (UnrollCount.getNumOccurrences() > 0)
150     UP.Count = UnrollCount;
151   if (UnrollMaxCount.getNumOccurrences() > 0)
152     UP.MaxCount = UnrollMaxCount;
153   if (UnrollFullMaxCount.getNumOccurrences() > 0)
154     UP.FullUnrollMaxCount = UnrollFullMaxCount;
155   if (UnrollAllowPartial.getNumOccurrences() > 0)
156     UP.Partial = UnrollAllowPartial;
157   if (UnrollRuntime.getNumOccurrences() > 0)
158     UP.Runtime = UnrollRuntime;
159 
160   // Apply user values provided by argument
161   if (UserThreshold.hasValue()) {
162     UP.Threshold = *UserThreshold;
163     UP.PartialThreshold = *UserThreshold;
164   }
165   if (UserCount.hasValue())
166     UP.Count = *UserCount;
167   if (UserAllowPartial.hasValue())
168     UP.Partial = *UserAllowPartial;
169   if (UserRuntime.hasValue())
170     UP.Runtime = *UserRuntime;
171 
172   if (PragmaCount > 0 ||
173       ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount != 0)) {
174     // If the loop has an unrolling pragma, we want to be more aggressive with
175     // unrolling limits. Set thresholds to at least the PragmaTheshold value
176     // which is larger than the default limits.
177     if (UP.Threshold != NoThreshold)
178       UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold);
179     if (UP.PartialThreshold != NoThreshold)
180       UP.PartialThreshold =
181           std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold);
182   }
183 
184   return UP;
185 }
186 
187 namespace {
188 /// A struct to densely store the state of an instruction after unrolling at
189 /// each iteration.
190 ///
191 /// This is designed to work like a tuple of <Instruction *, int> for the
192 /// purposes of hashing and lookup, but to be able to associate two boolean
193 /// states with each key.
194 struct UnrolledInstState {
195   Instruction *I;
196   int Iteration : 30;
197   unsigned IsFree : 1;
198   unsigned IsCounted : 1;
199 };
200 
201 /// Hashing and equality testing for a set of the instruction states.
202 struct UnrolledInstStateKeyInfo {
203   typedef DenseMapInfo<Instruction *> PtrInfo;
204   typedef DenseMapInfo<std::pair<Instruction *, int>> PairInfo;
205   static inline UnrolledInstState getEmptyKey() {
206     return {PtrInfo::getEmptyKey(), 0, 0, 0};
207   }
208   static inline UnrolledInstState getTombstoneKey() {
209     return {PtrInfo::getTombstoneKey(), 0, 0, 0};
210   }
211   static inline unsigned getHashValue(const UnrolledInstState &S) {
212     return PairInfo::getHashValue({S.I, S.Iteration});
213   }
214   static inline bool isEqual(const UnrolledInstState &LHS,
215                              const UnrolledInstState &RHS) {
216     return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration});
217   }
218 };
219 }
220 
221 namespace {
222 struct EstimatedUnrollCost {
223   /// \brief The estimated cost after unrolling.
224   int UnrolledCost;
225 
226   /// \brief The estimated dynamic cost of executing the instructions in the
227   /// rolled form.
228   int RolledDynamicCost;
229 };
230 }
231 
232 /// \brief Figure out if the loop is worth full unrolling.
233 ///
234 /// Complete loop unrolling can make some loads constant, and we need to know
235 /// if that would expose any further optimization opportunities.  This routine
236 /// estimates this optimization.  It computes cost of unrolled loop
237 /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
238 /// dynamic cost we mean that we won't count costs of blocks that are known not
239 /// to be executed (i.e. if we have a branch in the loop and we know that at the
240 /// given iteration its condition would be resolved to true, we won't add up the
241 /// cost of the 'false'-block).
242 /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
243 /// the analysis failed (no benefits expected from the unrolling, or the loop is
244 /// too big to analyze), the returned value is None.
245 static Optional<EstimatedUnrollCost>
246 analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT,
247                       ScalarEvolution &SE, const TargetTransformInfo &TTI,
248                       int MaxUnrolledLoopSize) {
249   // We want to be able to scale offsets by the trip count and add more offsets
250   // to them without checking for overflows, and we already don't want to
251   // analyze *massive* trip counts, so we force the max to be reasonably small.
252   assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
253          "The unroll iterations max is too large!");
254 
255   // Only analyze inner loops. We can't properly estimate cost of nested loops
256   // and we won't visit inner loops again anyway.
257   if (!L->empty())
258     return None;
259 
260   // Don't simulate loops with a big or unknown tripcount
261   if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
262       TripCount > UnrollMaxIterationsCountToAnalyze)
263     return None;
264 
265   SmallSetVector<BasicBlock *, 16> BBWorklist;
266   SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist;
267   DenseMap<Value *, Constant *> SimplifiedValues;
268   SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
269 
270   // The estimated cost of the unrolled form of the loop. We try to estimate
271   // this by simplifying as much as we can while computing the estimate.
272   int UnrolledCost = 0;
273 
274   // We also track the estimated dynamic (that is, actually executed) cost in
275   // the rolled form. This helps identify cases when the savings from unrolling
276   // aren't just exposing dead control flows, but actual reduced dynamic
277   // instructions due to the simplifications which we expect to occur after
278   // unrolling.
279   int RolledDynamicCost = 0;
280 
281   // We track the simplification of each instruction in each iteration. We use
282   // this to recursively merge costs into the unrolled cost on-demand so that
283   // we don't count the cost of any dead code. This is essentially a map from
284   // <instruction, int> to <bool, bool>, but stored as a densely packed struct.
285   DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap;
286 
287   // A small worklist used to accumulate cost of instructions from each
288   // observable and reached root in the loop.
289   SmallVector<Instruction *, 16> CostWorklist;
290 
291   // PHI-used worklist used between iterations while accumulating cost.
292   SmallVector<Instruction *, 4> PHIUsedList;
293 
294   // Helper function to accumulate cost for instructions in the loop.
295   auto AddCostRecursively = [&](Instruction &RootI, int Iteration) {
296     assert(Iteration >= 0 && "Cannot have a negative iteration!");
297     assert(CostWorklist.empty() && "Must start with an empty cost list");
298     assert(PHIUsedList.empty() && "Must start with an empty phi used list");
299     CostWorklist.push_back(&RootI);
300     for (;; --Iteration) {
301       do {
302         Instruction *I = CostWorklist.pop_back_val();
303 
304         // InstCostMap only uses I and Iteration as a key, the other two values
305         // don't matter here.
306         auto CostIter = InstCostMap.find({I, Iteration, 0, 0});
307         if (CostIter == InstCostMap.end())
308           // If an input to a PHI node comes from a dead path through the loop
309           // we may have no cost data for it here. What that actually means is
310           // that it is free.
311           continue;
312         auto &Cost = *CostIter;
313         if (Cost.IsCounted)
314           // Already counted this instruction.
315           continue;
316 
317         // Mark that we are counting the cost of this instruction now.
318         Cost.IsCounted = true;
319 
320         // If this is a PHI node in the loop header, just add it to the PHI set.
321         if (auto *PhiI = dyn_cast<PHINode>(I))
322           if (PhiI->getParent() == L->getHeader()) {
323             assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they "
324                                   "inherently simplify during unrolling.");
325             if (Iteration == 0)
326               continue;
327 
328             // Push the incoming value from the backedge into the PHI used list
329             // if it is an in-loop instruction. We'll use this to populate the
330             // cost worklist for the next iteration (as we count backwards).
331             if (auto *OpI = dyn_cast<Instruction>(
332                     PhiI->getIncomingValueForBlock(L->getLoopLatch())))
333               if (L->contains(OpI))
334                 PHIUsedList.push_back(OpI);
335             continue;
336           }
337 
338         // First accumulate the cost of this instruction.
339         if (!Cost.IsFree) {
340           UnrolledCost += TTI.getUserCost(I);
341           DEBUG(dbgs() << "Adding cost of instruction (iteration " << Iteration
342                        << "): ");
343           DEBUG(I->dump());
344         }
345 
346         // We must count the cost of every operand which is not free,
347         // recursively. If we reach a loop PHI node, simply add it to the set
348         // to be considered on the next iteration (backwards!).
349         for (Value *Op : I->operands()) {
350           // Check whether this operand is free due to being a constant or
351           // outside the loop.
352           auto *OpI = dyn_cast<Instruction>(Op);
353           if (!OpI || !L->contains(OpI))
354             continue;
355 
356           // Otherwise accumulate its cost.
357           CostWorklist.push_back(OpI);
358         }
359       } while (!CostWorklist.empty());
360 
361       if (PHIUsedList.empty())
362         // We've exhausted the search.
363         break;
364 
365       assert(Iteration > 0 &&
366              "Cannot track PHI-used values past the first iteration!");
367       CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end());
368       PHIUsedList.clear();
369     }
370   };
371 
372   // Ensure that we don't violate the loop structure invariants relied on by
373   // this analysis.
374   assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
375   assert(L->isLCSSAForm(DT) &&
376          "Must have loops in LCSSA form to track live-out values.");
377 
378   DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
379 
380   // Simulate execution of each iteration of the loop counting instructions,
381   // which would be simplified.
382   // Since the same load will take different values on different iterations,
383   // we literally have to go through all loop's iterations.
384   for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
385     DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
386 
387     // Prepare for the iteration by collecting any simplified entry or backedge
388     // inputs.
389     for (Instruction &I : *L->getHeader()) {
390       auto *PHI = dyn_cast<PHINode>(&I);
391       if (!PHI)
392         break;
393 
394       // The loop header PHI nodes must have exactly two input: one from the
395       // loop preheader and one from the loop latch.
396       assert(
397           PHI->getNumIncomingValues() == 2 &&
398           "Must have an incoming value only for the preheader and the latch.");
399 
400       Value *V = PHI->getIncomingValueForBlock(
401           Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
402       Constant *C = dyn_cast<Constant>(V);
403       if (Iteration != 0 && !C)
404         C = SimplifiedValues.lookup(V);
405       if (C)
406         SimplifiedInputValues.push_back({PHI, C});
407     }
408 
409     // Now clear and re-populate the map for the next iteration.
410     SimplifiedValues.clear();
411     while (!SimplifiedInputValues.empty())
412       SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
413 
414     UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L);
415 
416     BBWorklist.clear();
417     BBWorklist.insert(L->getHeader());
418     // Note that we *must not* cache the size, this loop grows the worklist.
419     for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
420       BasicBlock *BB = BBWorklist[Idx];
421 
422       // Visit all instructions in the given basic block and try to simplify
423       // it.  We don't change the actual IR, just count optimization
424       // opportunities.
425       for (Instruction &I : *BB) {
426         // Track this instruction's expected baseline cost when executing the
427         // rolled loop form.
428         RolledDynamicCost += TTI.getUserCost(&I);
429 
430         // Visit the instruction to analyze its loop cost after unrolling,
431         // and if the visitor returns true, mark the instruction as free after
432         // unrolling and continue.
433         bool IsFree = Analyzer.visit(I);
434         bool Inserted = InstCostMap.insert({&I, (int)Iteration,
435                                            (unsigned)IsFree,
436                                            /*IsCounted*/ false}).second;
437         (void)Inserted;
438         assert(Inserted && "Cannot have a state for an unvisited instruction!");
439 
440         if (IsFree)
441           continue;
442 
443         // If the instruction might have a side-effect recursively account for
444         // the cost of it and all the instructions leading up to it.
445         if (I.mayHaveSideEffects())
446           AddCostRecursively(I, Iteration);
447 
448         // Can't properly model a cost of a call.
449         // FIXME: With a proper cost model we should be able to do it.
450         if(isa<CallInst>(&I))
451           return None;
452 
453         // If unrolled body turns out to be too big, bail out.
454         if (UnrolledCost > MaxUnrolledLoopSize) {
455           DEBUG(dbgs() << "  Exceeded threshold.. exiting.\n"
456                        << "  UnrolledCost: " << UnrolledCost
457                        << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
458                        << "\n");
459           return None;
460         }
461       }
462 
463       TerminatorInst *TI = BB->getTerminator();
464 
465       // Add in the live successors by first checking whether we have terminator
466       // that may be simplified based on the values simplified by this call.
467       if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
468         if (BI->isConditional()) {
469           if (Constant *SimpleCond =
470                   SimplifiedValues.lookup(BI->getCondition())) {
471             BasicBlock *Succ = nullptr;
472             // Just take the first successor if condition is undef
473             if (isa<UndefValue>(SimpleCond))
474               Succ = BI->getSuccessor(0);
475             else
476               Succ = BI->getSuccessor(
477                   cast<ConstantInt>(SimpleCond)->isZero() ? 1 : 0);
478             if (L->contains(Succ))
479               BBWorklist.insert(Succ);
480             else
481               ExitWorklist.insert({BB, Succ});
482             continue;
483           }
484         }
485       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
486         if (Constant *SimpleCond =
487                 SimplifiedValues.lookup(SI->getCondition())) {
488           BasicBlock *Succ = nullptr;
489           // Just take the first successor if condition is undef
490           if (isa<UndefValue>(SimpleCond))
491             Succ = SI->getSuccessor(0);
492           else
493             Succ = SI->findCaseValue(cast<ConstantInt>(SimpleCond))
494                        .getCaseSuccessor();
495           if (L->contains(Succ))
496             BBWorklist.insert(Succ);
497           else
498             ExitWorklist.insert({BB, Succ});
499           continue;
500         }
501       }
502 
503       // Add BB's successors to the worklist.
504       for (BasicBlock *Succ : successors(BB))
505         if (L->contains(Succ))
506           BBWorklist.insert(Succ);
507         else
508           ExitWorklist.insert({BB, Succ});
509     }
510 
511     // If we found no optimization opportunities on the first iteration, we
512     // won't find them on later ones too.
513     if (UnrolledCost == RolledDynamicCost) {
514       DEBUG(dbgs() << "  No opportunities found.. exiting.\n"
515                    << "  UnrolledCost: " << UnrolledCost << "\n");
516       return None;
517     }
518   }
519 
520   while (!ExitWorklist.empty()) {
521     BasicBlock *ExitingBB, *ExitBB;
522     std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val();
523 
524     for (Instruction &I : *ExitBB) {
525       auto *PN = dyn_cast<PHINode>(&I);
526       if (!PN)
527         break;
528 
529       Value *Op = PN->getIncomingValueForBlock(ExitingBB);
530       if (auto *OpI = dyn_cast<Instruction>(Op))
531         if (L->contains(OpI))
532           AddCostRecursively(*OpI, TripCount - 1);
533     }
534   }
535 
536   DEBUG(dbgs() << "Analysis finished:\n"
537                << "UnrolledCost: " << UnrolledCost << ", "
538                << "RolledDynamicCost: " << RolledDynamicCost << "\n");
539   return {{UnrolledCost, RolledDynamicCost}};
540 }
541 
542 /// ApproximateLoopSize - Approximate the size of the loop.
543 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
544                                     bool &NotDuplicatable, bool &Convergent,
545                                     const TargetTransformInfo &TTI,
546                                     AssumptionCache *AC) {
547   SmallPtrSet<const Value *, 32> EphValues;
548   CodeMetrics::collectEphemeralValues(L, AC, EphValues);
549 
550   CodeMetrics Metrics;
551   for (BasicBlock *BB : L->blocks())
552     Metrics.analyzeBasicBlock(BB, TTI, EphValues);
553   NumCalls = Metrics.NumInlineCandidates;
554   NotDuplicatable = Metrics.notDuplicatable;
555   Convergent = Metrics.convergent;
556 
557   unsigned LoopSize = Metrics.NumInsts;
558 
559   // Don't allow an estimate of size zero.  This would allows unrolling of loops
560   // with huge iteration counts, which is a compile time problem even if it's
561   // not a problem for code quality. Also, the code using this size may assume
562   // that each loop has at least three instructions (likely a conditional
563   // branch, a comparison feeding that branch, and some kind of loop increment
564   // feeding that comparison instruction).
565   LoopSize = std::max(LoopSize, 3u);
566 
567   return LoopSize;
568 }
569 
570 // Returns the loop hint metadata node with the given name (for example,
571 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
572 // returned.
573 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
574   if (MDNode *LoopID = L->getLoopID())
575     return GetUnrollMetadata(LoopID, Name);
576   return nullptr;
577 }
578 
579 // Returns true if the loop has an unroll(full) pragma.
580 static bool HasUnrollFullPragma(const Loop *L) {
581   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
582 }
583 
584 // Returns true if the loop has an unroll(enable) pragma. This metadata is used
585 // for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
586 static bool HasUnrollEnablePragma(const Loop *L) {
587   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
588 }
589 
590 // Returns true if the loop has an unroll(disable) pragma.
591 static bool HasUnrollDisablePragma(const Loop *L) {
592   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
593 }
594 
595 // Returns true if the loop has an runtime unroll(disable) pragma.
596 static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
597   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
598 }
599 
600 // If loop has an unroll_count pragma return the (necessarily
601 // positive) value from the pragma.  Otherwise return 0.
602 static unsigned UnrollCountPragmaValue(const Loop *L) {
603   MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
604   if (MD) {
605     assert(MD->getNumOperands() == 2 &&
606            "Unroll count hint metadata should have two operands.");
607     unsigned Count =
608         mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
609     assert(Count >= 1 && "Unroll count must be positive.");
610     return Count;
611   }
612   return 0;
613 }
614 
615 // Remove existing unroll metadata and add unroll disable metadata to
616 // indicate the loop has already been unrolled.  This prevents a loop
617 // from being unrolled more than is directed by a pragma if the loop
618 // unrolling pass is run more than once (which it generally is).
619 static void SetLoopAlreadyUnrolled(Loop *L) {
620   MDNode *LoopID = L->getLoopID();
621   if (!LoopID)
622     return;
623 
624   // First remove any existing loop unrolling metadata.
625   SmallVector<Metadata *, 4> MDs;
626   // Reserve first location for self reference to the LoopID metadata node.
627   MDs.push_back(nullptr);
628   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
629     bool IsUnrollMetadata = false;
630     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
631     if (MD) {
632       const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
633       IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
634     }
635     if (!IsUnrollMetadata)
636       MDs.push_back(LoopID->getOperand(i));
637   }
638 
639   // Add unroll(disable) metadata to disable future unrolling.
640   LLVMContext &Context = L->getHeader()->getContext();
641   SmallVector<Metadata *, 1> DisableOperands;
642   DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
643   MDNode *DisableNode = MDNode::get(Context, DisableOperands);
644   MDs.push_back(DisableNode);
645 
646   MDNode *NewLoopID = MDNode::get(Context, MDs);
647   // Set operand 0 to refer to the loop id itself.
648   NewLoopID->replaceOperandWith(0, NewLoopID);
649   L->setLoopID(NewLoopID);
650 }
651 
652 static bool canUnrollCompletely(Loop *L, unsigned Threshold,
653                                 unsigned PercentDynamicCostSavedThreshold,
654                                 unsigned DynamicCostSavingsDiscount,
655                                 uint64_t UnrolledCost,
656                                 uint64_t RolledDynamicCost) {
657   if (Threshold == NoThreshold) {
658     DEBUG(dbgs() << "  Can fully unroll, because no threshold is set.\n");
659     return true;
660   }
661 
662   if (UnrolledCost <= Threshold) {
663     DEBUG(dbgs() << "  Can fully unroll, because unrolled cost: "
664                  << UnrolledCost << "<" << Threshold << "\n");
665     return true;
666   }
667 
668   assert(UnrolledCost && "UnrolledCost can't be 0 at this point.");
669   assert(RolledDynamicCost >= UnrolledCost &&
670          "Cannot have a higher unrolled cost than a rolled cost!");
671 
672   // Compute the percentage of the dynamic cost in the rolled form that is
673   // saved when unrolled. If unrolling dramatically reduces the estimated
674   // dynamic cost of the loop, we use a higher threshold to allow more
675   // unrolling.
676   unsigned PercentDynamicCostSaved =
677       (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost;
678 
679   if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold &&
680       (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <=
681           (int64_t)Threshold) {
682     DEBUG(dbgs() << "  Can fully unroll, because unrolling will reduce the "
683                     "expected dynamic cost by "
684                  << PercentDynamicCostSaved << "% (threshold: "
685                  << PercentDynamicCostSavedThreshold << "%)\n"
686                  << "  and the unrolled cost (" << UnrolledCost
687                  << ") is less than the max threshold ("
688                  << DynamicCostSavingsDiscount << ").\n");
689     return true;
690   }
691 
692   DEBUG(dbgs() << "  Too large to fully unroll:\n");
693   DEBUG(dbgs() << "    Threshold: " << Threshold << "\n");
694   DEBUG(dbgs() << "    Max threshold: " << DynamicCostSavingsDiscount << "\n");
695   DEBUG(dbgs() << "    Percent cost saved threshold: "
696                << PercentDynamicCostSavedThreshold << "%\n");
697   DEBUG(dbgs() << "    Unrolled cost: " << UnrolledCost << "\n");
698   DEBUG(dbgs() << "    Rolled dynamic cost: " << RolledDynamicCost << "\n");
699   DEBUG(dbgs() << "    Percent cost saved: " << PercentDynamicCostSaved
700                << "\n");
701   return false;
702 }
703 
704 static bool tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
705                             ScalarEvolution *SE, const TargetTransformInfo &TTI,
706                             AssumptionCache &AC, bool PreserveLCSSA,
707                             Optional<unsigned> ProvidedCount,
708                             Optional<unsigned> ProvidedThreshold,
709                             Optional<bool> ProvidedAllowPartial,
710                             Optional<bool> ProvidedRuntime) {
711   BasicBlock *Header = L->getHeader();
712   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
713                << "] Loop %" << Header->getName() << "\n");
714 
715   if (HasUnrollDisablePragma(L)) {
716     return false;
717   }
718   bool PragmaFullUnroll = HasUnrollFullPragma(L);
719   bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
720   unsigned PragmaCount = UnrollCountPragmaValue(L);
721   bool HasPragma = PragmaFullUnroll || PragmaEnableUnroll || PragmaCount > 0;
722 
723   // Find trip count and trip multiple if count is not available
724   unsigned TripCount = 0;
725   unsigned TripMultiple = 1;
726   // If there are multiple exiting blocks but one of them is the latch, use the
727   // latch for the trip count estimation. Otherwise insist on a single exiting
728   // block for the trip count estimation.
729   BasicBlock *ExitingBlock = L->getLoopLatch();
730   if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
731     ExitingBlock = L->getExitingBlock();
732   if (ExitingBlock) {
733     TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
734     TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
735   }
736 
737   TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
738       L, TTI, ProvidedThreshold, ProvidedCount, ProvidedAllowPartial,
739       ProvidedRuntime, PragmaCount, PragmaFullUnroll, PragmaEnableUnroll,
740       TripCount);
741 
742   unsigned Count = UP.Count;
743   bool CountSetExplicitly = Count != 0;
744   // Use a heuristic count if we didn't set anything explicitly.
745   if (!CountSetExplicitly)
746     Count = TripCount == 0 ? DefaultUnrollRuntimeCount : TripCount;
747   if (TripCount && Count > TripCount)
748     Count = TripCount;
749   Count = std::min(Count, UP.FullUnrollMaxCount);
750 
751   unsigned NumInlineCandidates;
752   bool NotDuplicatable;
753   bool Convergent;
754   unsigned LoopSize = ApproximateLoopSize(
755       L, NumInlineCandidates, NotDuplicatable, Convergent, TTI, &AC);
756   DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
757 
758   // When computing the unrolled size, note that the conditional branch on the
759   // backedge and the comparison feeding it are not replicated like the rest of
760   // the loop body (which is why 2 is subtracted).
761   uint64_t UnrolledSize = (uint64_t)(LoopSize - 2) * Count + 2;
762   if (NotDuplicatable) {
763     DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
764                  << " instructions.\n");
765     return false;
766   }
767   if (NumInlineCandidates != 0) {
768     DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
769     return false;
770   }
771 
772   // Given Count, TripCount and thresholds determine the type of
773   // unrolling which is to be performed.
774   enum { Full = 0, Partial = 1, Runtime = 2 };
775   int Unrolling;
776   if (TripCount && Count == TripCount) {
777     Unrolling = Partial;
778     // If the loop is really small, we don't need to run an expensive analysis.
779     if (canUnrollCompletely(L, UP.Threshold, 100, UP.DynamicCostSavingsDiscount,
780                             UnrolledSize, UnrolledSize)) {
781       Unrolling = Full;
782     } else {
783       // The loop isn't that small, but we still can fully unroll it if that
784       // helps to remove a significant number of instructions.
785       // To check that, run additional analysis on the loop.
786       if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
787               L, TripCount, DT, *SE, TTI,
788               UP.Threshold + UP.DynamicCostSavingsDiscount))
789         if (canUnrollCompletely(L, UP.Threshold,
790                                 UP.PercentDynamicCostSavedThreshold,
791                                 UP.DynamicCostSavingsDiscount,
792                                 Cost->UnrolledCost, Cost->RolledDynamicCost)) {
793           Unrolling = Full;
794         }
795     }
796   } else if (TripCount && Count < TripCount) {
797     Unrolling = Partial;
798   } else {
799     Unrolling = Runtime;
800   }
801 
802   // Reduce count based on the type of unrolling and the threshold values.
803   unsigned OriginalCount = Count;
804   bool AllowRuntime = PragmaEnableUnroll || (PragmaCount > 0) || UP.Runtime;
805   // Don't unroll a runtime trip count loop with unroll full pragma.
806   if (HasRuntimeUnrollDisablePragma(L) || PragmaFullUnroll) {
807     AllowRuntime = false;
808   }
809   bool DecreasedCountDueToConvergence = false;
810   if (Unrolling == Partial) {
811     bool AllowPartial = PragmaEnableUnroll || UP.Partial;
812     if (!AllowPartial && !CountSetExplicitly) {
813       DEBUG(dbgs() << "  will not try to unroll partially because "
814                    << "-unroll-allow-partial not given\n");
815       return false;
816     }
817     if (UP.PartialThreshold != NoThreshold && Count > 1) {
818       // Reduce unroll count to be modulo of TripCount for partial unrolling.
819       if (UnrolledSize > UP.PartialThreshold)
820         Count = (std::max(UP.PartialThreshold, 3u) - 2) / (LoopSize - 2);
821       if (Count > UP.MaxCount)
822         Count = UP.MaxCount;
823       while (Count != 0 && TripCount % Count != 0)
824         Count--;
825       if (AllowRuntime && Count <= 1) {
826         // If there is no Count that is modulo of TripCount, set Count to
827         // largest power-of-two factor that satisfies the threshold limit.
828         // As we'll create fixup loop, do the type of unrolling only if
829         // runtime unrolling is allowed.
830         Count = DefaultUnrollRuntimeCount;
831         UnrolledSize = (LoopSize - 2) * Count + 2;
832         while (Count != 0 && UnrolledSize > UP.PartialThreshold) {
833           Count >>= 1;
834           UnrolledSize = (LoopSize - 2) * Count + 2;
835         }
836       }
837     }
838   } else if (Unrolling == Runtime) {
839     if (!AllowRuntime && !CountSetExplicitly) {
840       DEBUG(dbgs() << "  will not try to unroll loop with runtime trip count "
841                    << "-unroll-runtime not given\n");
842       return false;
843     }
844 
845     // Reduce unroll count to be the largest power-of-two factor of
846     // the original count which satisfies the threshold limit.
847     while (Count != 0 && UnrolledSize > UP.PartialThreshold) {
848       Count >>= 1;
849       UnrolledSize = (LoopSize - 2) * Count + 2;
850     }
851 
852     if (Count > UP.MaxCount)
853       Count = UP.MaxCount;
854 
855     // If the loop contains a convergent operation, the prelude we'd add
856     // to do the first few instructions before we hit the unrolled loop
857     // is unsafe -- it adds a control-flow dependency to the convergent
858     // operation.  Therefore Count must divide TripMultiple.
859     //
860     // TODO: This is quite conservative.  In practice, convergent_op()
861     // is likely to be called unconditionally in the loop.  In this
862     // case, the program would be ill-formed (on most architectures)
863     // unless n were the same on all threads in a thread group.
864     // Assuming n is the same on all threads, any kind of unrolling is
865     // safe.  But currently llvm's notion of convergence isn't powerful
866     // enough to express this.
867     unsigned OrigCount = Count;
868     while (Convergent && Count != 0 && TripMultiple % Count != 0) {
869       DecreasedCountDueToConvergence = true;
870       Count >>= 1;
871     }
872     if (OrigCount > Count) {
873       DEBUG(dbgs() << "  loop contains a convergent instruction, so unroll "
874                       "count must divide the trip multiple, "
875                    << TripMultiple << ".  Reducing unroll count from "
876                    << OrigCount << " to " << Count << ".\n");
877     }
878     DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
879   }
880 
881   if (HasPragma) {
882     // Emit optimization remarks if we are unable to unroll the loop
883     // as directed by a pragma.
884     DebugLoc LoopLoc = L->getStartLoc();
885     Function *F = Header->getParent();
886     LLVMContext &Ctx = F->getContext();
887     if (PragmaCount > 0 && DecreasedCountDueToConvergence) {
888       emitOptimizationRemarkMissed(
889           Ctx, DEBUG_TYPE, *F, LoopLoc,
890           Twine("Unable to unroll loop the number of times directed by "
891                 "unroll_count pragma because the loop contains a convergent "
892                 "instruction, and so must have an unroll count that divides "
893                 "the loop trip multiple of ") +
894               Twine(TripMultiple) + ".  Unrolling instead " + Twine(Count) +
895               " time(s).");
896     } else if ((PragmaCount > 0) && Count != OriginalCount) {
897       emitOptimizationRemarkMissed(
898           Ctx, DEBUG_TYPE, *F, LoopLoc,
899           "Unable to unroll loop the number of times directed by "
900           "unroll_count pragma because unrolled size is too large.");
901     } else if (PragmaFullUnroll && !TripCount) {
902       emitOptimizationRemarkMissed(
903           Ctx, DEBUG_TYPE, *F, LoopLoc,
904           "Unable to fully unroll loop as directed by unroll(full) pragma "
905           "because loop has a runtime trip count.");
906     } else if (PragmaEnableUnroll && Count != TripCount && Count < 2) {
907       emitOptimizationRemarkMissed(
908           Ctx, DEBUG_TYPE, *F, LoopLoc,
909           "Unable to unroll loop as directed by unroll(enable) pragma because "
910           "unrolled size is too large.");
911     } else if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
912                Count != TripCount) {
913       emitOptimizationRemarkMissed(
914           Ctx, DEBUG_TYPE, *F, LoopLoc,
915           "Unable to fully unroll loop as directed by unroll pragma because "
916           "unrolled size is too large.");
917     }
918   }
919 
920   if (Unrolling != Full && Count < 2) {
921     // Partial unrolling by 1 is a nop.  For full unrolling, a factor
922     // of 1 makes sense because loop control can be eliminated.
923     return false;
924   }
925 
926   // Unroll the loop.
927   if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
928                   TripMultiple, LI, SE, &DT, &AC, PreserveLCSSA))
929     return false;
930 
931   // If loop has an unroll count pragma mark loop as unrolled to prevent
932   // unrolling beyond that requested by the pragma.
933   if (HasPragma && PragmaCount != 0)
934     SetLoopAlreadyUnrolled(L);
935   return true;
936 }
937 
938 namespace {
939 class LoopUnroll : public LoopPass {
940 public:
941   static char ID; // Pass ID, replacement for typeid
942   LoopUnroll(Optional<unsigned> Threshold = None,
943              Optional<unsigned> Count = None,
944              Optional<bool> AllowPartial = None, Optional<bool> Runtime = None)
945       : LoopPass(ID), ProvidedCount(Count), ProvidedThreshold(Threshold),
946         ProvidedAllowPartial(AllowPartial), ProvidedRuntime(Runtime) {
947     initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
948   }
949 
950   Optional<unsigned> ProvidedCount;
951   Optional<unsigned> ProvidedThreshold;
952   Optional<bool> ProvidedAllowPartial;
953   Optional<bool> ProvidedRuntime;
954 
955   bool runOnLoop(Loop *L, LPPassManager &) override {
956     if (skipLoop(L))
957       return false;
958 
959     Function &F = *L->getHeader()->getParent();
960 
961     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
962     LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
963     ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
964     const TargetTransformInfo &TTI =
965         getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
966     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
967     bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
968 
969     return tryToUnrollLoop(L, DT, LI, SE, TTI, AC, PreserveLCSSA, ProvidedCount,
970                            ProvidedThreshold, ProvidedAllowPartial,
971                            ProvidedRuntime);
972   }
973 
974   /// This transformation requires natural loop information & requires that
975   /// loop preheaders be inserted into the CFG...
976   ///
977   void getAnalysisUsage(AnalysisUsage &AU) const override {
978     AU.addRequired<AssumptionCacheTracker>();
979     AU.addRequired<TargetTransformInfoWrapperPass>();
980     // FIXME: Loop passes are required to preserve domtree, and for now we just
981     // recreate dom info if anything gets unrolled.
982     getLoopAnalysisUsage(AU);
983   }
984 };
985 }
986 
987 char LoopUnroll::ID = 0;
988 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
989 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
990 INITIALIZE_PASS_DEPENDENCY(LoopPass)
991 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
992 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
993 
994 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
995                                  int Runtime) {
996   // TODO: It would make more sense for this function to take the optionals
997   // directly, but that's dangerous since it would silently break out of tree
998   // callers.
999   return new LoopUnroll(Threshold == -1 ? None : Optional<unsigned>(Threshold),
1000                         Count == -1 ? None : Optional<unsigned>(Count),
1001                         AllowPartial == -1 ? None
1002                                            : Optional<bool>(AllowPartial),
1003                         Runtime == -1 ? None : Optional<bool>(Runtime));
1004 }
1005 
1006 Pass *llvm::createSimpleLoopUnrollPass() {
1007   return llvm::createLoopUnrollPass(-1, -1, 0, 0);
1008 }
1009