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/LoopPass.h"
26 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
27 #include "llvm/Analysis/ScalarEvolution.h"
28 #include "llvm/Analysis/TargetTransformInfo.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/PassManager.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/Pass.h"
38 #include "llvm/PassRegistry.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Transforms/Scalar.h"
45 #include "llvm/Transforms/Utils/LoopPeel.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.
getUnrollMetadataForLoop(const Loop * L,StringRef Name)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.
hasAnyUnrollPragma(const Loop * L,StringRef Prefix)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.
hasUnrollAndJamEnablePragma(const Loop * L)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.
unrollAndJamCountPragmaValue(const Loop * L)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
getUnrollAndJammedLoopSize(unsigned LoopSize,TargetTransformInfo::UnrollingPreferences & UP)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.
computeUnrollAndJamCount(Loop * L,Loop * SubLoop,const TargetTransformInfo & TTI,DominatorTree & DT,LoopInfo * LI,ScalarEvolution & SE,const SmallPtrSetImpl<const Value * > & EphValues,OptimizationRemarkEmitter * ORE,unsigned OuterTripCount,unsigned OuterTripMultiple,unsigned OuterLoopSize,unsigned InnerTripCount,unsigned InnerLoopSize,TargetTransformInfo::UnrollingPreferences & UP,TargetTransformInfo::PeelingPreferences & PP)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 TargetTransformInfo::PeelingPreferences &PP) {
165 // First up use computeUnrollCount from the loop unroller to get a count
166 // for unrolling the outer loop, plus any loops requiring explicit
167 // unrolling we leave to the unroller. This uses UP.Threshold /
168 // UP.PartialThreshold / UP.MaxCount to come up with sensible loop values.
169 // We have already checked that the loop has no unroll.* pragmas.
170 unsigned MaxTripCount = 0;
171 bool UseUpperBound = false;
172 bool ExplicitUnroll = computeUnrollCount(
173 L, TTI, DT, LI, SE, EphValues, ORE, OuterTripCount, MaxTripCount,
174 /*MaxOrZero*/ false, OuterTripMultiple, OuterLoopSize, UP, PP,
175 UseUpperBound);
176 if (ExplicitUnroll || UseUpperBound) {
177 // If the user explicitly set the loop as unrolled, dont UnJ it. Leave it
178 // for the unroller instead.
179 LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; explicit count set by "
180 "computeUnrollCount\n");
181 UP.Count = 0;
182 return false;
183 }
184
185 // Override with any explicit Count from the "unroll-and-jam-count" option.
186 bool UserUnrollCount = UnrollAndJamCount.getNumOccurrences() > 0;
187 if (UserUnrollCount) {
188 UP.Count = UnrollAndJamCount;
189 UP.Force = true;
190 if (UP.AllowRemainder &&
191 getUnrollAndJammedLoopSize(OuterLoopSize, UP) < UP.Threshold &&
192 getUnrollAndJammedLoopSize(InnerLoopSize, UP) <
193 UP.UnrollAndJamInnerLoopThreshold)
194 return true;
195 }
196
197 // Check for unroll_and_jam pragmas
198 unsigned PragmaCount = unrollAndJamCountPragmaValue(L);
199 if (PragmaCount > 0) {
200 UP.Count = PragmaCount;
201 UP.Runtime = true;
202 UP.Force = true;
203 if ((UP.AllowRemainder || (OuterTripMultiple % PragmaCount == 0)) &&
204 getUnrollAndJammedLoopSize(OuterLoopSize, UP) < UP.Threshold &&
205 getUnrollAndJammedLoopSize(InnerLoopSize, UP) <
206 UP.UnrollAndJamInnerLoopThreshold)
207 return true;
208 }
209
210 bool PragmaEnableUnroll = hasUnrollAndJamEnablePragma(L);
211 bool ExplicitUnrollAndJamCount = PragmaCount > 0 || UserUnrollCount;
212 bool ExplicitUnrollAndJam = PragmaEnableUnroll || ExplicitUnrollAndJamCount;
213
214 // If the loop has an unrolling pragma, we want to be more aggressive with
215 // unrolling limits.
216 if (ExplicitUnrollAndJam)
217 UP.UnrollAndJamInnerLoopThreshold = PragmaUnrollAndJamThreshold;
218
219 if (!UP.AllowRemainder && getUnrollAndJammedLoopSize(InnerLoopSize, UP) >=
220 UP.UnrollAndJamInnerLoopThreshold) {
221 LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; can't create remainder and "
222 "inner loop too large\n");
223 UP.Count = 0;
224 return false;
225 }
226
227 // We have a sensible limit for the outer loop, now adjust it for the inner
228 // loop and UP.UnrollAndJamInnerLoopThreshold. If the outer limit was set
229 // explicitly, we want to stick to it.
230 if (!ExplicitUnrollAndJamCount && UP.AllowRemainder) {
231 while (UP.Count != 0 && getUnrollAndJammedLoopSize(InnerLoopSize, UP) >=
232 UP.UnrollAndJamInnerLoopThreshold)
233 UP.Count--;
234 }
235
236 // If we are explicitly unroll and jamming, we are done. Otherwise there are a
237 // number of extra performance heuristics to check.
238 if (ExplicitUnrollAndJam)
239 return true;
240
241 // If the inner loop count is known and small, leave the entire loop nest to
242 // be the unroller
243 if (InnerTripCount && InnerLoopSize * InnerTripCount < UP.Threshold) {
244 LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; small inner loop count is "
245 "being left for the unroller\n");
246 UP.Count = 0;
247 return false;
248 }
249
250 // Check for situations where UnJ is likely to be unprofitable. Including
251 // subloops with more than 1 block.
252 if (SubLoop->getBlocks().size() != 1) {
253 LLVM_DEBUG(
254 dbgs() << "Won't unroll-and-jam; More than one inner loop block\n");
255 UP.Count = 0;
256 return false;
257 }
258
259 // Limit to loops where there is something to gain from unrolling and
260 // jamming the loop. In this case, look for loads that are invariant in the
261 // outer loop and can become shared.
262 unsigned NumInvariant = 0;
263 for (BasicBlock *BB : SubLoop->getBlocks()) {
264 for (Instruction &I : *BB) {
265 if (auto *Ld = dyn_cast<LoadInst>(&I)) {
266 Value *V = Ld->getPointerOperand();
267 const SCEV *LSCEV = SE.getSCEVAtScope(V, L);
268 if (SE.isLoopInvariant(LSCEV, L))
269 NumInvariant++;
270 }
271 }
272 }
273 if (NumInvariant == 0) {
274 LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; No loop invariant loads\n");
275 UP.Count = 0;
276 return false;
277 }
278
279 return false;
280 }
281
tryToUnrollAndJamLoop(Loop * L,DominatorTree & DT,LoopInfo * LI,ScalarEvolution & SE,const TargetTransformInfo & TTI,AssumptionCache & AC,DependenceInfo & DI,OptimizationRemarkEmitter & ORE,int OptLevel,LPMUpdater * U)282 static LoopUnrollResult tryToUnrollAndJamLoop(
283 Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE,
284 const TargetTransformInfo &TTI, AssumptionCache &AC, DependenceInfo &DI,
285 OptimizationRemarkEmitter &ORE, int OptLevel, LPMUpdater *U) {
286 TargetTransformInfo::UnrollingPreferences UP =
287 gatherUnrollingPreferences(L, SE, TTI, nullptr, nullptr, OptLevel, None,
288 None, None, None, None, None);
289 TargetTransformInfo::PeelingPreferences PP =
290 gatherPeelingPreferences(L, SE, TTI, None, None);
291
292 TransformationMode EnableMode = hasUnrollAndJamTransformation(L);
293 if (EnableMode & TM_Disable)
294 return LoopUnrollResult::Unmodified;
295 if (EnableMode & TM_ForcedByUser)
296 UP.UnrollAndJam = true;
297
298 if (AllowUnrollAndJam.getNumOccurrences() > 0)
299 UP.UnrollAndJam = AllowUnrollAndJam;
300 if (UnrollAndJamThreshold.getNumOccurrences() > 0)
301 UP.UnrollAndJamInnerLoopThreshold = UnrollAndJamThreshold;
302 // Exit early if unrolling is disabled.
303 if (!UP.UnrollAndJam || UP.UnrollAndJamInnerLoopThreshold == 0)
304 return LoopUnrollResult::Unmodified;
305
306 LLVM_DEBUG(dbgs() << "Loop Unroll and Jam: F["
307 << L->getHeader()->getParent()->getName() << "] Loop %"
308 << L->getHeader()->getName() << "\n");
309
310 // A loop with any unroll pragma (enabling/disabling/count/etc) is left for
311 // the unroller, so long as it does not explicitly have unroll_and_jam
312 // metadata. This means #pragma nounroll will disable unroll and jam as well
313 // as unrolling
314 if (hasAnyUnrollPragma(L, "llvm.loop.unroll.") &&
315 !hasAnyUnrollPragma(L, "llvm.loop.unroll_and_jam.")) {
316 LLVM_DEBUG(dbgs() << " Disabled due to pragma.\n");
317 return LoopUnrollResult::Unmodified;
318 }
319
320 if (!isSafeToUnrollAndJam(L, SE, DT, DI, *LI)) {
321 LLVM_DEBUG(dbgs() << " Disabled due to not being safe.\n");
322 return LoopUnrollResult::Unmodified;
323 }
324
325 // Approximate the loop size and collect useful info
326 unsigned NumInlineCandidates;
327 bool NotDuplicatable;
328 bool Convergent;
329 SmallPtrSet<const Value *, 32> EphValues;
330 CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
331 Loop *SubLoop = L->getSubLoops()[0];
332 unsigned InnerLoopSize =
333 ApproximateLoopSize(SubLoop, NumInlineCandidates, NotDuplicatable,
334 Convergent, TTI, EphValues, UP.BEInsns);
335 unsigned OuterLoopSize =
336 ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
337 TTI, EphValues, UP.BEInsns);
338 LLVM_DEBUG(dbgs() << " Outer Loop Size: " << OuterLoopSize << "\n");
339 LLVM_DEBUG(dbgs() << " Inner Loop Size: " << InnerLoopSize << "\n");
340 if (NotDuplicatable) {
341 LLVM_DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable "
342 "instructions.\n");
343 return LoopUnrollResult::Unmodified;
344 }
345 if (NumInlineCandidates != 0) {
346 LLVM_DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
347 return LoopUnrollResult::Unmodified;
348 }
349 if (Convergent) {
350 LLVM_DEBUG(
351 dbgs() << " Not unrolling loop with convergent instructions.\n");
352 return LoopUnrollResult::Unmodified;
353 }
354
355 // Save original loop IDs for after the transformation.
356 MDNode *OrigOuterLoopID = L->getLoopID();
357 MDNode *OrigSubLoopID = SubLoop->getLoopID();
358
359 // To assign the loop id of the epilogue, assign it before unrolling it so it
360 // is applied to every inner loop of the epilogue. We later apply the loop ID
361 // for the jammed inner loop.
362 Optional<MDNode *> NewInnerEpilogueLoopID = makeFollowupLoopID(
363 OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
364 LLVMLoopUnrollAndJamFollowupRemainderInner});
365 if (NewInnerEpilogueLoopID.hasValue())
366 SubLoop->setLoopID(NewInnerEpilogueLoopID.getValue());
367
368 // Find trip count and trip multiple
369 BasicBlock *Latch = L->getLoopLatch();
370 BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();
371 unsigned OuterTripCount = SE.getSmallConstantTripCount(L, Latch);
372 unsigned OuterTripMultiple = SE.getSmallConstantTripMultiple(L, Latch);
373 unsigned InnerTripCount = SE.getSmallConstantTripCount(SubLoop, SubLoopLatch);
374
375 // Decide if, and by how much, to unroll
376 bool IsCountSetExplicitly = computeUnrollAndJamCount(
377 L, SubLoop, TTI, DT, LI, SE, EphValues, &ORE, OuterTripCount,
378 OuterTripMultiple, OuterLoopSize, InnerTripCount, InnerLoopSize, UP, PP);
379 if (UP.Count <= 1)
380 return LoopUnrollResult::Unmodified;
381 // Unroll factor (Count) must be less or equal to TripCount.
382 if (OuterTripCount && UP.Count > OuterTripCount)
383 UP.Count = OuterTripCount;
384
385 Loop *EpilogueOuterLoop = nullptr;
386 LoopUnrollResult UnrollResult = UnrollAndJamLoop(
387 L, UP.Count, OuterTripCount, OuterTripMultiple, UP.UnrollRemainder, LI,
388 &SE, &DT, &AC, &TTI, &ORE, U, &EpilogueOuterLoop);
389
390 // Assign new loop attributes.
391 if (EpilogueOuterLoop) {
392 Optional<MDNode *> NewOuterEpilogueLoopID = makeFollowupLoopID(
393 OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
394 LLVMLoopUnrollAndJamFollowupRemainderOuter});
395 if (NewOuterEpilogueLoopID.hasValue())
396 EpilogueOuterLoop->setLoopID(NewOuterEpilogueLoopID.getValue());
397 }
398
399 Optional<MDNode *> NewInnerLoopID =
400 makeFollowupLoopID(OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
401 LLVMLoopUnrollAndJamFollowupInner});
402 if (NewInnerLoopID.hasValue())
403 SubLoop->setLoopID(NewInnerLoopID.getValue());
404 else
405 SubLoop->setLoopID(OrigSubLoopID);
406
407 if (UnrollResult == LoopUnrollResult::PartiallyUnrolled) {
408 Optional<MDNode *> NewOuterLoopID = makeFollowupLoopID(
409 OrigOuterLoopID,
410 {LLVMLoopUnrollAndJamFollowupAll, LLVMLoopUnrollAndJamFollowupOuter});
411 if (NewOuterLoopID.hasValue()) {
412 L->setLoopID(NewOuterLoopID.getValue());
413
414 // Do not setLoopAlreadyUnrolled if a followup was given.
415 return UnrollResult;
416 }
417 }
418
419 // If loop has an unroll count pragma or unrolled by explicitly set count
420 // mark loop as unrolled to prevent unrolling beyond that requested.
421 if (UnrollResult != LoopUnrollResult::FullyUnrolled && IsCountSetExplicitly)
422 L->setLoopAlreadyUnrolled();
423
424 return UnrollResult;
425 }
426
tryToUnrollAndJamLoop(LoopNest & LN,DominatorTree & DT,LoopInfo & LI,ScalarEvolution & SE,const TargetTransformInfo & TTI,AssumptionCache & AC,DependenceInfo & DI,OptimizationRemarkEmitter & ORE,int OptLevel,LPMUpdater & U)427 static bool tryToUnrollAndJamLoop(LoopNest &LN, DominatorTree &DT, LoopInfo &LI,
428 ScalarEvolution &SE,
429 const TargetTransformInfo &TTI,
430 AssumptionCache &AC, DependenceInfo &DI,
431 OptimizationRemarkEmitter &ORE, int OptLevel,
432 LPMUpdater &U) {
433 bool DidSomething = false;
434 ArrayRef<Loop *> Loops = LN.getLoops();
435
436 // Add the loop nests in the reverse order of LN. See method
437 // declaration.
438 SmallPriorityWorklist<Loop *, 4> Worklist;
439 appendLoopsToWorklist(Loops, Worklist);
440 while (!Worklist.empty()) {
441 Loop *L = Worklist.pop_back_val();
442 LoopUnrollResult Result =
443 tryToUnrollAndJamLoop(L, DT, &LI, SE, TTI, AC, DI, ORE, OptLevel, &U);
444 if (Result != LoopUnrollResult::Unmodified)
445 DidSomething = true;
446 }
447
448 return DidSomething;
449 }
450
451 namespace {
452
453 class LoopUnrollAndJam : public LoopPass {
454 public:
455 static char ID; // Pass ID, replacement for typeid
456 unsigned OptLevel;
457
LoopUnrollAndJam(int OptLevel=2)458 LoopUnrollAndJam(int OptLevel = 2) : LoopPass(ID), OptLevel(OptLevel) {
459 initializeLoopUnrollAndJamPass(*PassRegistry::getPassRegistry());
460 }
461
runOnLoop(Loop * L,LPPassManager & LPM)462 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
463 if (skipLoop(L))
464 return false;
465
466 auto *F = L->getHeader()->getParent();
467 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
468 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
469 auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI();
470 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
471 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*F);
472 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
473 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
474
475 LoopUnrollResult Result = tryToUnrollAndJamLoop(L, DT, LI, SE, TTI, AC, DI,
476 ORE, OptLevel, nullptr);
477
478 if (Result == LoopUnrollResult::FullyUnrolled)
479 LPM.markLoopAsDeleted(*L);
480
481 return Result != LoopUnrollResult::Unmodified;
482 }
483
484 /// This transformation requires natural loop information & requires that
485 /// loop preheaders be inserted into the CFG...
getAnalysisUsage(AnalysisUsage & AU) const486 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
499 char LoopUnrollAndJam::ID = 0;
500
501 INITIALIZE_PASS_BEGIN(LoopUnrollAndJam, "loop-unroll-and-jam",
502 "Unroll and Jam loops", false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)503 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
504 INITIALIZE_PASS_DEPENDENCY(LoopPass)
505 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
506 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
507 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
508 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
509 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
510 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
511 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
512 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
513 INITIALIZE_PASS_END(LoopUnrollAndJam, "loop-unroll-and-jam",
514 "Unroll and Jam loops", false, false)
515
516 Pass *llvm::createLoopUnrollAndJamPass(int OptLevel) {
517 return new LoopUnrollAndJam(OptLevel);
518 }
519
run(LoopNest & LN,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater & U)520 PreservedAnalyses LoopUnrollAndJamPass::run(LoopNest &LN,
521 LoopAnalysisManager &AM,
522 LoopStandardAnalysisResults &AR,
523 LPMUpdater &U) {
524 Function &F = *LN.getParent();
525
526 DependenceInfo DI(&F, &AR.AA, &AR.SE, &AR.LI);
527 OptimizationRemarkEmitter ORE(&F);
528
529 if (!tryToUnrollAndJamLoop(LN, AR.DT, AR.LI, AR.SE, AR.TTI, AR.AC, DI, ORE,
530 OptLevel, U))
531 return PreservedAnalyses::all();
532
533 auto PA = getLoopPassPreservedAnalyses();
534 PA.preserve<LoopNestAnalysis>();
535 return PA;
536 }
537