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
51namespace llvm {
52class Instruction;
53class Value;
54} // namespace llvm
55
56using namespace llvm;
57
58#define DEBUG_TYPE "loop-unroll-and-jam"
59
60/// @{
61/// Metadata attribute names
62static const char *const LLVMLoopUnrollAndJamFollowupAll =
63    "llvm.loop.unroll_and_jam.followup_all";
64static const char *const LLVMLoopUnrollAndJamFollowupInner =
65    "llvm.loop.unroll_and_jam.followup_inner";
66static const char *const LLVMLoopUnrollAndJamFollowupOuter =
67    "llvm.loop.unroll_and_jam.followup_outer";
68static const char *const LLVMLoopUnrollAndJamFollowupRemainderInner =
69    "llvm.loop.unroll_and_jam.followup_remainder_inner";
70static const char *const LLVMLoopUnrollAndJamFollowupRemainderOuter =
71    "llvm.loop.unroll_and_jam.followup_remainder_outer";
72/// @}
73
74static cl::opt<bool>
75    AllowUnrollAndJam("allow-unroll-and-jam", cl::Hidden,
76                      cl::desc("Allows loops to be unroll-and-jammed."));
77
78static 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
83static 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
87static 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.
95static 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.
103static 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.
126static 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.
132static 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.
146static uint64_t
147getUnrollAndJammedLoopSize(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.
155static 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    TargetTransformInfo::PeelingPreferences &PP) {
163  // First up use computeUnrollCount from the loop unroller to get a count
164  // for unrolling the outer loop, plus any loops requiring explicit
165  // unrolling we leave to the unroller. This uses UP.Threshold /
166  // UP.PartialThreshold / UP.MaxCount to come up with sensible loop values.
167  // We have already checked that the loop has no unroll.* pragmas.
168  unsigned MaxTripCount = 0;
169  bool UseUpperBound = false;
170  bool ExplicitUnroll = computeUnrollCount(
171      L, TTI, DT, LI, SE, EphValues, ORE, OuterTripCount, MaxTripCount,
172      /*MaxOrZero*/ false, OuterTripMultiple, OuterLoopSize, UP, PP,
173      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
280static LoopUnrollResult
281tryToUnrollAndJamLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
282                      ScalarEvolution &SE, const TargetTransformInfo &TTI,
283                      AssumptionCache &AC, DependenceInfo &DI,
284                      OptimizationRemarkEmitter &ORE, int OptLevel) {
285  TargetTransformInfo::UnrollingPreferences UP =
286      gatherUnrollingPreferences(L, SE, TTI, nullptr, nullptr, OptLevel, None,
287                                 None, None, None, None, None);
288  TargetTransformInfo::PeelingPreferences PP =
289      gatherPeelingPreferences(L, SE, TTI, None, None);
290  if (AllowUnrollAndJam.getNumOccurrences() > 0)
291    UP.UnrollAndJam = AllowUnrollAndJam;
292  if (UnrollAndJamThreshold.getNumOccurrences() > 0)
293    UP.UnrollAndJamInnerLoopThreshold = UnrollAndJamThreshold;
294  // Exit early if unrolling is disabled.
295  if (!UP.UnrollAndJam || UP.UnrollAndJamInnerLoopThreshold == 0)
296    return LoopUnrollResult::Unmodified;
297
298  LLVM_DEBUG(dbgs() << "Loop Unroll and Jam: F["
299                    << L->getHeader()->getParent()->getName() << "] Loop %"
300                    << L->getHeader()->getName() << "\n");
301
302  TransformationMode EnableMode = hasUnrollAndJamTransformation(L);
303  if (EnableMode & TM_Disable)
304    return LoopUnrollResult::Unmodified;
305
306  // A loop with any unroll pragma (enabling/disabling/count/etc) is left for
307  // the unroller, so long as it does not explicitly have unroll_and_jam
308  // metadata. This means #pragma nounroll will disable unroll and jam as well
309  // as unrolling
310  if (hasAnyUnrollPragma(L, "llvm.loop.unroll.") &&
311      !hasAnyUnrollPragma(L, "llvm.loop.unroll_and_jam.")) {
312    LLVM_DEBUG(dbgs() << "  Disabled due to pragma.\n");
313    return LoopUnrollResult::Unmodified;
314  }
315
316  if (!isSafeToUnrollAndJam(L, SE, DT, DI, *LI)) {
317    LLVM_DEBUG(dbgs() << "  Disabled due to not being safe.\n");
318    return LoopUnrollResult::Unmodified;
319  }
320
321  // Approximate the loop size and collect useful info
322  unsigned NumInlineCandidates;
323  bool NotDuplicatable;
324  bool Convergent;
325  SmallPtrSet<const Value *, 32> EphValues;
326  CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
327  Loop *SubLoop = L->getSubLoops()[0];
328  unsigned InnerLoopSize =
329      ApproximateLoopSize(SubLoop, NumInlineCandidates, NotDuplicatable,
330                          Convergent, TTI, EphValues, UP.BEInsns);
331  unsigned OuterLoopSize =
332      ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
333                          TTI, EphValues, UP.BEInsns);
334  LLVM_DEBUG(dbgs() << "  Outer Loop Size: " << OuterLoopSize << "\n");
335  LLVM_DEBUG(dbgs() << "  Inner Loop Size: " << InnerLoopSize << "\n");
336  if (NotDuplicatable) {
337    LLVM_DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable "
338                         "instructions.\n");
339    return LoopUnrollResult::Unmodified;
340  }
341  if (NumInlineCandidates != 0) {
342    LLVM_DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
343    return LoopUnrollResult::Unmodified;
344  }
345  if (Convergent) {
346    LLVM_DEBUG(
347        dbgs() << "  Not unrolling loop with convergent instructions.\n");
348    return LoopUnrollResult::Unmodified;
349  }
350
351  // Save original loop IDs for after the transformation.
352  MDNode *OrigOuterLoopID = L->getLoopID();
353  MDNode *OrigSubLoopID = SubLoop->getLoopID();
354
355  // To assign the loop id of the epilogue, assign it before unrolling it so it
356  // is applied to every inner loop of the epilogue. We later apply the loop ID
357  // for the jammed inner loop.
358  Optional<MDNode *> NewInnerEpilogueLoopID = makeFollowupLoopID(
359      OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
360                        LLVMLoopUnrollAndJamFollowupRemainderInner});
361  if (NewInnerEpilogueLoopID.hasValue())
362    SubLoop->setLoopID(NewInnerEpilogueLoopID.getValue());
363
364  // Find trip count and trip multiple
365  BasicBlock *Latch = L->getLoopLatch();
366  BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();
367  unsigned OuterTripCount = SE.getSmallConstantTripCount(L, Latch);
368  unsigned OuterTripMultiple = SE.getSmallConstantTripMultiple(L, Latch);
369  unsigned InnerTripCount = SE.getSmallConstantTripCount(SubLoop, SubLoopLatch);
370
371  // Decide if, and by how much, to unroll
372  bool IsCountSetExplicitly = computeUnrollAndJamCount(
373      L, SubLoop, TTI, DT, LI, SE, EphValues, &ORE, OuterTripCount,
374      OuterTripMultiple, OuterLoopSize, InnerTripCount, InnerLoopSize, UP, PP);
375  if (UP.Count <= 1)
376    return LoopUnrollResult::Unmodified;
377  // Unroll factor (Count) must be less or equal to TripCount.
378  if (OuterTripCount && UP.Count > OuterTripCount)
379    UP.Count = OuterTripCount;
380
381  Loop *EpilogueOuterLoop = nullptr;
382  LoopUnrollResult UnrollResult = UnrollAndJamLoop(
383      L, UP.Count, OuterTripCount, OuterTripMultiple, UP.UnrollRemainder, LI,
384      &SE, &DT, &AC, &TTI, &ORE, &EpilogueOuterLoop);
385
386  // Assign new loop attributes.
387  if (EpilogueOuterLoop) {
388    Optional<MDNode *> NewOuterEpilogueLoopID = makeFollowupLoopID(
389        OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
390                          LLVMLoopUnrollAndJamFollowupRemainderOuter});
391    if (NewOuterEpilogueLoopID.hasValue())
392      EpilogueOuterLoop->setLoopID(NewOuterEpilogueLoopID.getValue());
393  }
394
395  Optional<MDNode *> NewInnerLoopID =
396      makeFollowupLoopID(OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
397                                           LLVMLoopUnrollAndJamFollowupInner});
398  if (NewInnerLoopID.hasValue())
399    SubLoop->setLoopID(NewInnerLoopID.getValue());
400  else
401    SubLoop->setLoopID(OrigSubLoopID);
402
403  if (UnrollResult == LoopUnrollResult::PartiallyUnrolled) {
404    Optional<MDNode *> NewOuterLoopID = makeFollowupLoopID(
405        OrigOuterLoopID,
406        {LLVMLoopUnrollAndJamFollowupAll, LLVMLoopUnrollAndJamFollowupOuter});
407    if (NewOuterLoopID.hasValue()) {
408      L->setLoopID(NewOuterLoopID.getValue());
409
410      // Do not setLoopAlreadyUnrolled if a followup was given.
411      return UnrollResult;
412    }
413  }
414
415  // If loop has an unroll count pragma or unrolled by explicitly set count
416  // mark loop as unrolled to prevent unrolling beyond that requested.
417  if (UnrollResult != LoopUnrollResult::FullyUnrolled && IsCountSetExplicitly)
418    L->setLoopAlreadyUnrolled();
419
420  return UnrollResult;
421}
422
423static bool tryToUnrollAndJamLoop(Function &F, DominatorTree &DT, LoopInfo &LI,
424                                  ScalarEvolution &SE,
425                                  const TargetTransformInfo &TTI,
426                                  AssumptionCache &AC, DependenceInfo &DI,
427                                  OptimizationRemarkEmitter &ORE,
428                                  int OptLevel) {
429  bool DidSomething = false;
430
431  // The loop unroll and jam pass requires loops to be in simplified form, and
432  // also needs LCSSA. Since simplification may add new inner loops, it has to
433  // run before the legality and profitability checks. This means running the
434  // loop unroll and jam pass will simplify all loops, regardless of whether
435  // anything end up being unroll and jammed.
436  for (auto &L : LI) {
437    DidSomething |=
438        simplifyLoop(L, &DT, &LI, &SE, &AC, nullptr, false /* PreserveLCSSA */);
439    DidSomething |= formLCSSARecursively(*L, DT, &LI, &SE);
440  }
441
442  // Add the loop nests in the reverse order of LoopInfo. See method
443  // declaration.
444  SmallPriorityWorklist<Loop *, 4> Worklist;
445  appendLoopsToWorklist(LI, Worklist);
446  while (!Worklist.empty()) {
447    Loop *L = Worklist.pop_back_val();
448    LoopUnrollResult Result =
449        tryToUnrollAndJamLoop(L, DT, &LI, SE, TTI, AC, DI, ORE, OptLevel);
450    if (Result != LoopUnrollResult::Unmodified)
451      DidSomething = true;
452  }
453
454  return DidSomething;
455}
456
457namespace {
458
459class LoopUnrollAndJam : public FunctionPass {
460public:
461  static char ID; // Pass ID, replacement for typeid
462  unsigned OptLevel;
463
464  LoopUnrollAndJam(int OptLevel = 2) : FunctionPass(ID), OptLevel(OptLevel) {
465    initializeLoopUnrollAndJamPass(*PassRegistry::getPassRegistry());
466  }
467
468  bool runOnFunction(Function &F) override {
469    if (skipFunction(F))
470      return false;
471
472    auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
473    LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
474    ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
475    const TargetTransformInfo &TTI =
476        getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
477    auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
478    auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI();
479    auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
480
481    return tryToUnrollAndJamLoop(F, DT, LI, SE, TTI, AC, DI, ORE, OptLevel);
482  }
483
484  /// This transformation requires natural loop information & requires that
485  /// loop preheaders be inserted into the CFG...
486  void getAnalysisUsage(AnalysisUsage &AU) const override {
487    AU.addRequired<DominatorTreeWrapperPass>();
488    AU.addRequired<LoopInfoWrapperPass>();
489    AU.addRequired<ScalarEvolutionWrapperPass>();
490    AU.addRequired<TargetTransformInfoWrapperPass>();
491    AU.addRequired<AssumptionCacheTracker>();
492    AU.addRequired<DependenceAnalysisWrapperPass>();
493    AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
494  }
495};
496
497} // end anonymous namespace
498
499char LoopUnrollAndJam::ID = 0;
500
501INITIALIZE_PASS_BEGIN(LoopUnrollAndJam, "loop-unroll-and-jam",
502                      "Unroll and Jam loops", false, false)
503INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
504INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
505INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
506INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
507INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
508INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
509INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
510INITIALIZE_PASS_END(LoopUnrollAndJam, "loop-unroll-and-jam",
511                    "Unroll and Jam loops", false, false)
512
513Pass *llvm::createLoopUnrollAndJamPass(int OptLevel) {
514  return new LoopUnrollAndJam(OptLevel);
515}
516
517PreservedAnalyses LoopUnrollAndJamPass::run(Function &F,
518                                            FunctionAnalysisManager &AM) {
519  ScalarEvolution &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
520  LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
521  TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F);
522  AssumptionCache &AC = AM.getResult<AssumptionAnalysis>(F);
523  DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
524  DependenceInfo &DI = AM.getResult<DependenceAnalysis>(F);
525  OptimizationRemarkEmitter &ORE =
526      AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
527
528  if (!tryToUnrollAndJamLoop(F, DT, LI, SE, TTI, AC, DI, ORE, OptLevel))
529    return PreservedAnalyses::all();
530
531  return getLoopPassPreservedAnalyses();
532}
533