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