1 //===- LoopUnrollAndJam.cpp - Loop unroll and jam 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 an unroll and jam pass. Most of the work is done by
10 // Utils/UnrollLoopAndJam.cpp.
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/PriorityWorklist.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/CodeMetrics.h"
22 #include "llvm/Analysis/DependenceAnalysis.h"
23 #include "llvm/Analysis/LoopAnalysisManager.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/Analysis/TargetTransformInfo.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Metadata.h"
34 #include "llvm/IR/PassManager.h"
35 #include "llvm/InitializePasses.h"
36 #include "llvm/Pass.h"
37 #include "llvm/PassRegistry.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Transforms/Scalar.h"
44 #include "llvm/Transforms/Utils/LoopSimplify.h"
45 #include "llvm/Transforms/Utils/LoopUtils.h"
46 #include "llvm/Transforms/Utils/UnrollLoop.h"
47 #include <cassert>
48 #include <cstdint>
49 #include <vector>
50 
51 namespace llvm {
52 class Instruction;
53 class Value;
54 } // namespace llvm
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "loop-unroll-and-jam"
59 
60 /// @{
61 /// Metadata attribute names
62 static const char *const LLVMLoopUnrollAndJamFollowupAll =
63     "llvm.loop.unroll_and_jam.followup_all";
64 static const char *const LLVMLoopUnrollAndJamFollowupInner =
65     "llvm.loop.unroll_and_jam.followup_inner";
66 static const char *const LLVMLoopUnrollAndJamFollowupOuter =
67     "llvm.loop.unroll_and_jam.followup_outer";
68 static const char *const LLVMLoopUnrollAndJamFollowupRemainderInner =
69     "llvm.loop.unroll_and_jam.followup_remainder_inner";
70 static const char *const LLVMLoopUnrollAndJamFollowupRemainderOuter =
71     "llvm.loop.unroll_and_jam.followup_remainder_outer";
72 /// @}
73 
74 static cl::opt<bool>
75     AllowUnrollAndJam("allow-unroll-and-jam", cl::Hidden,
76                       cl::desc("Allows loops to be unroll-and-jammed."));
77 
78 static cl::opt<unsigned> UnrollAndJamCount(
79     "unroll-and-jam-count", cl::Hidden,
80     cl::desc("Use this unroll count for all loops including those with "
81              "unroll_and_jam_count pragma values, for testing purposes"));
82 
83 static cl::opt<unsigned> UnrollAndJamThreshold(
84     "unroll-and-jam-threshold", cl::init(60), cl::Hidden,
85     cl::desc("Threshold to use for inner loop when doing unroll and jam."));
86 
87 static cl::opt<unsigned> PragmaUnrollAndJamThreshold(
88     "pragma-unroll-and-jam-threshold", cl::init(1024), cl::Hidden,
89     cl::desc("Unrolled size limit for loops with an unroll_and_jam(full) or "
90              "unroll_count pragma."));
91 
92 // Returns the loop hint metadata node with the given name (for example,
93 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
94 // returned.
95 static MDNode *getUnrollMetadataForLoop(const Loop *L, StringRef Name) {
96   if (MDNode *LoopID = L->getLoopID())
97     return GetUnrollMetadata(LoopID, Name);
98   return nullptr;
99 }
100 
101 // Returns true if the loop has any metadata starting with Prefix. For example a
102 // Prefix of "llvm.loop.unroll." returns true if we have any unroll metadata.
103 static bool hasAnyUnrollPragma(const Loop *L, StringRef Prefix) {
104   if (MDNode *LoopID = L->getLoopID()) {
105     // First operand should refer to the loop id itself.
106     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
107     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
108 
109     for (unsigned I = 1, E = LoopID->getNumOperands(); I < E; ++I) {
110       MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(I));
111       if (!MD)
112         continue;
113 
114       MDString *S = dyn_cast<MDString>(MD->getOperand(0));
115       if (!S)
116         continue;
117 
118       if (S->getString().startswith(Prefix))
119         return true;
120     }
121   }
122   return false;
123 }
124 
125 // Returns true if the loop has an unroll_and_jam(enable) pragma.
126 static bool hasUnrollAndJamEnablePragma(const Loop *L) {
127   return getUnrollMetadataForLoop(L, "llvm.loop.unroll_and_jam.enable");
128 }
129 
130 // If loop has an unroll_and_jam_count pragma return the (necessarily
131 // positive) value from the pragma.  Otherwise return 0.
132 static unsigned unrollAndJamCountPragmaValue(const Loop *L) {
133   MDNode *MD = getUnrollMetadataForLoop(L, "llvm.loop.unroll_and_jam.count");
134   if (MD) {
135     assert(MD->getNumOperands() == 2 &&
136            "Unroll count hint metadata should have two operands.");
137     unsigned Count =
138         mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
139     assert(Count >= 1 && "Unroll count must be positive.");
140     return Count;
141   }
142   return 0;
143 }
144 
145 // Returns loop size estimation for unrolled loop.
146 static uint64_t
147 getUnrollAndJammedLoopSize(unsigned LoopSize,
148                            TargetTransformInfo::UnrollingPreferences &UP) {
149   assert(LoopSize >= UP.BEInsns && "LoopSize should not be less than BEInsns!");
150   return static_cast<uint64_t>(LoopSize - UP.BEInsns) * UP.Count + UP.BEInsns;
151 }
152 
153 // Calculates unroll and jam count and writes it to UP.Count. Returns true if
154 // unroll count was set explicitly.
155 static bool computeUnrollAndJamCount(
156     Loop *L, Loop *SubLoop, const TargetTransformInfo &TTI, DominatorTree &DT,
157     LoopInfo *LI, ScalarEvolution &SE,
158     const SmallPtrSetImpl<const Value *> &EphValues,
159     OptimizationRemarkEmitter *ORE, unsigned OuterTripCount,
160     unsigned OuterTripMultiple, unsigned OuterLoopSize, unsigned InnerTripCount,
161     unsigned InnerLoopSize, TargetTransformInfo::UnrollingPreferences &UP) {
162   // First up use computeUnrollCount from the loop unroller to get a count
163   // for unrolling the outer loop, plus any loops requiring explicit
164   // unrolling we leave to the unroller. This uses UP.Threshold /
165   // UP.PartialThreshold / UP.MaxCount to come up with sensible loop values.
166   // We have already checked that the loop has no unroll.* pragmas.
167   unsigned MaxTripCount = 0;
168   bool UseUpperBound = false;
169   bool ExplicitUnroll = computeUnrollCount(
170       L, TTI, DT, LI, SE, EphValues, ORE, OuterTripCount, MaxTripCount,
171       /*MaxOrZero*/ false, OuterTripMultiple, OuterLoopSize, UP, UseUpperBound);
172   if (ExplicitUnroll || UseUpperBound) {
173     // If the user explicitly set the loop as unrolled, dont UnJ it. Leave it
174     // for the unroller instead.
175     LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; explicit count set by "
176                          "computeUnrollCount\n");
177     UP.Count = 0;
178     return false;
179   }
180 
181   // Override with any explicit Count from the "unroll-and-jam-count" option.
182   bool UserUnrollCount = UnrollAndJamCount.getNumOccurrences() > 0;
183   if (UserUnrollCount) {
184     UP.Count = UnrollAndJamCount;
185     UP.Force = true;
186     if (UP.AllowRemainder &&
187         getUnrollAndJammedLoopSize(OuterLoopSize, UP) < UP.Threshold &&
188         getUnrollAndJammedLoopSize(InnerLoopSize, UP) <
189             UP.UnrollAndJamInnerLoopThreshold)
190       return true;
191   }
192 
193   // Check for unroll_and_jam pragmas
194   unsigned PragmaCount = unrollAndJamCountPragmaValue(L);
195   if (PragmaCount > 0) {
196     UP.Count = PragmaCount;
197     UP.Runtime = true;
198     UP.Force = true;
199     if ((UP.AllowRemainder || (OuterTripMultiple % PragmaCount == 0)) &&
200         getUnrollAndJammedLoopSize(OuterLoopSize, UP) < UP.Threshold &&
201         getUnrollAndJammedLoopSize(InnerLoopSize, UP) <
202             UP.UnrollAndJamInnerLoopThreshold)
203       return true;
204   }
205 
206   bool PragmaEnableUnroll = hasUnrollAndJamEnablePragma(L);
207   bool ExplicitUnrollAndJamCount = PragmaCount > 0 || UserUnrollCount;
208   bool ExplicitUnrollAndJam = PragmaEnableUnroll || ExplicitUnrollAndJamCount;
209 
210   // If the loop has an unrolling pragma, we want to be more aggressive with
211   // unrolling limits.
212   if (ExplicitUnrollAndJam)
213     UP.UnrollAndJamInnerLoopThreshold = PragmaUnrollAndJamThreshold;
214 
215   if (!UP.AllowRemainder && getUnrollAndJammedLoopSize(InnerLoopSize, UP) >=
216                                 UP.UnrollAndJamInnerLoopThreshold) {
217     LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; can't create remainder and "
218                          "inner loop too large\n");
219     UP.Count = 0;
220     return false;
221   }
222 
223   // We have a sensible limit for the outer loop, now adjust it for the inner
224   // loop and UP.UnrollAndJamInnerLoopThreshold. If the outer limit was set
225   // explicitly, we want to stick to it.
226   if (!ExplicitUnrollAndJamCount && UP.AllowRemainder) {
227     while (UP.Count != 0 && getUnrollAndJammedLoopSize(InnerLoopSize, UP) >=
228                                 UP.UnrollAndJamInnerLoopThreshold)
229       UP.Count--;
230   }
231 
232   // If we are explicitly unroll and jamming, we are done. Otherwise there are a
233   // number of extra performance heuristics to check.
234   if (ExplicitUnrollAndJam)
235     return true;
236 
237   // If the inner loop count is known and small, leave the entire loop nest to
238   // be the unroller
239   if (InnerTripCount && InnerLoopSize * InnerTripCount < UP.Threshold) {
240     LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; small inner loop count is "
241                          "being left for the unroller\n");
242     UP.Count = 0;
243     return false;
244   }
245 
246   // Check for situations where UnJ is likely to be unprofitable. Including
247   // subloops with more than 1 block.
248   if (SubLoop->getBlocks().size() != 1) {
249     LLVM_DEBUG(
250         dbgs() << "Won't unroll-and-jam; More than one inner loop block\n");
251     UP.Count = 0;
252     return false;
253   }
254 
255   // Limit to loops where there is something to gain from unrolling and
256   // jamming the loop. In this case, look for loads that are invariant in the
257   // outer loop and can become shared.
258   unsigned NumInvariant = 0;
259   for (BasicBlock *BB : SubLoop->getBlocks()) {
260     for (Instruction &I : *BB) {
261       if (auto *Ld = dyn_cast<LoadInst>(&I)) {
262         Value *V = Ld->getPointerOperand();
263         const SCEV *LSCEV = SE.getSCEVAtScope(V, L);
264         if (SE.isLoopInvariant(LSCEV, L))
265           NumInvariant++;
266       }
267     }
268   }
269   if (NumInvariant == 0) {
270     LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; No loop invariant loads\n");
271     UP.Count = 0;
272     return false;
273   }
274 
275   return false;
276 }
277 
278 static LoopUnrollResult
279 tryToUnrollAndJamLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
280                       ScalarEvolution &SE, const TargetTransformInfo &TTI,
281                       AssumptionCache &AC, DependenceInfo &DI,
282                       OptimizationRemarkEmitter &ORE, int OptLevel) {
283   // Quick checks of the correct loop form
284   if (!L->isLoopSimplifyForm() || L->getSubLoops().size() != 1)
285     return LoopUnrollResult::Unmodified;
286   Loop *SubLoop = L->getSubLoops()[0];
287   if (!SubLoop->isLoopSimplifyForm())
288     return LoopUnrollResult::Unmodified;
289 
290   BasicBlock *Latch = L->getLoopLatch();
291   BasicBlock *Exit = L->getExitingBlock();
292   BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();
293   BasicBlock *SubLoopExit = SubLoop->getExitingBlock();
294 
295   if (Latch != Exit || SubLoopLatch != SubLoopExit)
296     return LoopUnrollResult::Unmodified;
297 
298   TargetTransformInfo::UnrollingPreferences UP =
299       gatherUnrollingPreferences(L, SE, TTI, nullptr, nullptr, OptLevel, None,
300                                  None, None, None, None, None, None, None);
301   if (AllowUnrollAndJam.getNumOccurrences() > 0)
302     UP.UnrollAndJam = AllowUnrollAndJam;
303   if (UnrollAndJamThreshold.getNumOccurrences() > 0)
304     UP.UnrollAndJamInnerLoopThreshold = UnrollAndJamThreshold;
305   // Exit early if unrolling is disabled.
306   if (!UP.UnrollAndJam || UP.UnrollAndJamInnerLoopThreshold == 0)
307     return LoopUnrollResult::Unmodified;
308 
309   LLVM_DEBUG(dbgs() << "Loop Unroll and Jam: F["
310                     << L->getHeader()->getParent()->getName() << "] Loop %"
311                     << L->getHeader()->getName() << "\n");
312 
313   TransformationMode EnableMode = hasUnrollAndJamTransformation(L);
314   if (EnableMode & TM_Disable)
315     return LoopUnrollResult::Unmodified;
316 
317   // A loop with any unroll pragma (enabling/disabling/count/etc) is left for
318   // the unroller, so long as it does not explicitly have unroll_and_jam
319   // metadata. This means #pragma nounroll will disable unroll and jam as well
320   // as unrolling
321   if (hasAnyUnrollPragma(L, "llvm.loop.unroll.") &&
322       !hasAnyUnrollPragma(L, "llvm.loop.unroll_and_jam.")) {
323     LLVM_DEBUG(dbgs() << "  Disabled due to pragma.\n");
324     return LoopUnrollResult::Unmodified;
325   }
326 
327   if (!isSafeToUnrollAndJam(L, SE, DT, DI)) {
328     LLVM_DEBUG(dbgs() << "  Disabled due to not being safe.\n");
329     return LoopUnrollResult::Unmodified;
330   }
331 
332   // Approximate the loop size and collect useful info
333   unsigned NumInlineCandidates;
334   bool NotDuplicatable;
335   bool Convergent;
336   SmallPtrSet<const Value *, 32> EphValues;
337   CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
338   unsigned InnerLoopSize =
339       ApproximateLoopSize(SubLoop, NumInlineCandidates, NotDuplicatable,
340                           Convergent, TTI, EphValues, UP.BEInsns);
341   unsigned OuterLoopSize =
342       ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
343                           TTI, EphValues, UP.BEInsns);
344   LLVM_DEBUG(dbgs() << "  Outer Loop Size: " << OuterLoopSize << "\n");
345   LLVM_DEBUG(dbgs() << "  Inner Loop Size: " << InnerLoopSize << "\n");
346   if (NotDuplicatable) {
347     LLVM_DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable "
348                          "instructions.\n");
349     return LoopUnrollResult::Unmodified;
350   }
351   if (NumInlineCandidates != 0) {
352     LLVM_DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
353     return LoopUnrollResult::Unmodified;
354   }
355   if (Convergent) {
356     LLVM_DEBUG(
357         dbgs() << "  Not unrolling loop with convergent instructions.\n");
358     return LoopUnrollResult::Unmodified;
359   }
360 
361   // Save original loop IDs for after the transformation.
362   MDNode *OrigOuterLoopID = L->getLoopID();
363   MDNode *OrigSubLoopID = SubLoop->getLoopID();
364 
365   // To assign the loop id of the epilogue, assign it before unrolling it so it
366   // is applied to every inner loop of the epilogue. We later apply the loop ID
367   // for the jammed inner loop.
368   Optional<MDNode *> NewInnerEpilogueLoopID = makeFollowupLoopID(
369       OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
370                         LLVMLoopUnrollAndJamFollowupRemainderInner});
371   if (NewInnerEpilogueLoopID.hasValue())
372     SubLoop->setLoopID(NewInnerEpilogueLoopID.getValue());
373 
374   // Find trip count and trip multiple
375   unsigned OuterTripCount = SE.getSmallConstantTripCount(L, Latch);
376   unsigned OuterTripMultiple = SE.getSmallConstantTripMultiple(L, Latch);
377   unsigned InnerTripCount = SE.getSmallConstantTripCount(SubLoop, SubLoopLatch);
378 
379   // Decide if, and by how much, to unroll
380   bool IsCountSetExplicitly = computeUnrollAndJamCount(
381       L, SubLoop, TTI, DT, LI, SE, EphValues, &ORE, OuterTripCount,
382       OuterTripMultiple, OuterLoopSize, InnerTripCount, InnerLoopSize, UP);
383   if (UP.Count <= 1)
384     return LoopUnrollResult::Unmodified;
385   // Unroll factor (Count) must be less or equal to TripCount.
386   if (OuterTripCount && UP.Count > OuterTripCount)
387     UP.Count = OuterTripCount;
388 
389   Loop *EpilogueOuterLoop = nullptr;
390   LoopUnrollResult UnrollResult = UnrollAndJamLoop(
391       L, UP.Count, OuterTripCount, OuterTripMultiple, UP.UnrollRemainder, LI,
392       &SE, &DT, &AC, &TTI, &ORE, &EpilogueOuterLoop);
393 
394   // Assign new loop attributes.
395   if (EpilogueOuterLoop) {
396     Optional<MDNode *> NewOuterEpilogueLoopID = makeFollowupLoopID(
397         OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
398                           LLVMLoopUnrollAndJamFollowupRemainderOuter});
399     if (NewOuterEpilogueLoopID.hasValue())
400       EpilogueOuterLoop->setLoopID(NewOuterEpilogueLoopID.getValue());
401   }
402 
403   Optional<MDNode *> NewInnerLoopID =
404       makeFollowupLoopID(OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
405                                            LLVMLoopUnrollAndJamFollowupInner});
406   if (NewInnerLoopID.hasValue())
407     SubLoop->setLoopID(NewInnerLoopID.getValue());
408   else
409     SubLoop->setLoopID(OrigSubLoopID);
410 
411   if (UnrollResult == LoopUnrollResult::PartiallyUnrolled) {
412     Optional<MDNode *> NewOuterLoopID = makeFollowupLoopID(
413         OrigOuterLoopID,
414         {LLVMLoopUnrollAndJamFollowupAll, LLVMLoopUnrollAndJamFollowupOuter});
415     if (NewOuterLoopID.hasValue()) {
416       L->setLoopID(NewOuterLoopID.getValue());
417 
418       // Do not setLoopAlreadyUnrolled if a followup was given.
419       return UnrollResult;
420     }
421   }
422 
423   // If loop has an unroll count pragma or unrolled by explicitly set count
424   // mark loop as unrolled to prevent unrolling beyond that requested.
425   if (UnrollResult != LoopUnrollResult::FullyUnrolled && IsCountSetExplicitly)
426     L->setLoopAlreadyUnrolled();
427 
428   return UnrollResult;
429 }
430 
431 static bool tryToUnrollAndJamLoop(Function &F, DominatorTree &DT, LoopInfo &LI,
432                                   ScalarEvolution &SE,
433                                   const TargetTransformInfo &TTI,
434                                   AssumptionCache &AC, DependenceInfo &DI,
435                                   OptimizationRemarkEmitter &ORE,
436                                   int OptLevel) {
437   bool DidSomething = false;
438 
439   // The loop unroll and jam pass requires loops to be in simplified form, and
440   // also needs LCSSA. Since simplification may add new inner loops, it has to
441   // run before the legality and profitability checks. This means running the
442   // loop unroll and jam pass will simplify all loops, regardless of whether
443   // anything end up being unroll and jammed.
444   for (auto &L : LI) {
445     DidSomething |=
446         simplifyLoop(L, &DT, &LI, &SE, &AC, nullptr, false /* PreserveLCSSA */);
447     DidSomething |= formLCSSARecursively(*L, DT, &LI, &SE);
448   }
449 
450   // Add the loop nests in the reverse order of LoopInfo. See method
451   // declaration.
452   SmallPriorityWorklist<Loop *, 4> Worklist;
453   appendLoopsToWorklist(LI, Worklist);
454   while (!Worklist.empty()) {
455     Loop *L = Worklist.pop_back_val();
456     LoopUnrollResult Result =
457         tryToUnrollAndJamLoop(L, DT, &LI, SE, TTI, AC, DI, ORE, OptLevel);
458     if (Result != LoopUnrollResult::Unmodified)
459       DidSomething = true;
460   }
461 
462   return DidSomething;
463 }
464 
465 namespace {
466 
467 class LoopUnrollAndJam : public FunctionPass {
468 public:
469   static char ID; // Pass ID, replacement for typeid
470   unsigned OptLevel;
471 
472   LoopUnrollAndJam(int OptLevel = 2) : FunctionPass(ID), OptLevel(OptLevel) {
473     initializeLoopUnrollAndJamPass(*PassRegistry::getPassRegistry());
474   }
475 
476   bool runOnFunction(Function &F) override {
477     if (skipFunction(F))
478       return false;
479 
480     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
481     LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
482     ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
483     const TargetTransformInfo &TTI =
484         getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
485     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
486     auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI();
487     auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
488 
489     return tryToUnrollAndJamLoop(F, DT, LI, SE, TTI, AC, DI, ORE, OptLevel);
490   }
491 
492   /// This transformation requires natural loop information & requires that
493   /// loop preheaders be inserted into the CFG...
494   void getAnalysisUsage(AnalysisUsage &AU) const override {
495     AU.addRequired<DominatorTreeWrapperPass>();
496     AU.addRequired<LoopInfoWrapperPass>();
497     AU.addRequired<ScalarEvolutionWrapperPass>();
498     AU.addRequired<TargetTransformInfoWrapperPass>();
499     AU.addRequired<AssumptionCacheTracker>();
500     AU.addRequired<DependenceAnalysisWrapperPass>();
501     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
502   }
503 };
504 
505 } // end anonymous namespace
506 
507 char LoopUnrollAndJam::ID = 0;
508 
509 INITIALIZE_PASS_BEGIN(LoopUnrollAndJam, "loop-unroll-and-jam",
510                       "Unroll and Jam loops", false, false)
511 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
512 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
513 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
514 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
515 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
516 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
517 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
518 INITIALIZE_PASS_END(LoopUnrollAndJam, "loop-unroll-and-jam",
519                     "Unroll and Jam loops", false, false)
520 
521 Pass *llvm::createLoopUnrollAndJamPass(int OptLevel) {
522   return new LoopUnrollAndJam(OptLevel);
523 }
524 
525 PreservedAnalyses LoopUnrollAndJamPass::run(Function &F,
526                                             FunctionAnalysisManager &AM) {
527   ScalarEvolution &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
528   LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
529   TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F);
530   AssumptionCache &AC = AM.getResult<AssumptionAnalysis>(F);
531   DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
532   DependenceInfo &DI = AM.getResult<DependenceAnalysis>(F);
533   OptimizationRemarkEmitter &ORE =
534       AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
535 
536   if (!tryToUnrollAndJamLoop(F, DT, LI, SE, TTI, AC, DI, ORE, OptLevel))
537     return PreservedAnalyses::all();
538 
539   return getLoopPassPreservedAnalyses();
540 }
541