1 //===- LoopUnrollAndJam.cpp - Loop unroll and jam pass --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements an unroll and jam pass. Most of the work is done by
11 // Utils/UnrollLoopAndJam.cpp.
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/CodeMetrics.h"
21 #include "llvm/Analysis/DependenceAnalysis.h"
22 #include "llvm/Analysis/LoopAnalysisManager.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/LoopPass.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/CFG.h"
30 #include "llvm/IR/Constant.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/PassManager.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Scalar.h"
46 #include "llvm/Transforms/Scalar/LoopPassManager.h"
47 #include "llvm/Transforms/Utils.h"
48 #include "llvm/Transforms/Utils/LoopUtils.h"
49 #include "llvm/Transforms/Utils/UnrollLoop.h"
50 #include <algorithm>
51 #include <cassert>
52 #include <cstdint>
53 #include <string>
54 
55 using namespace llvm;
56 
57 #define DEBUG_TYPE "loop-unroll-and-jam"
58 
59 static cl::opt<bool>
60     AllowUnrollAndJam("allow-unroll-and-jam", cl::Hidden,
61                       cl::desc("Allows loops to be unroll-and-jammed."));
62 
63 static cl::opt<unsigned> UnrollAndJamCount(
64     "unroll-and-jam-count", cl::Hidden,
65     cl::desc("Use this unroll count for all loops including those with "
66              "unroll_and_jam_count pragma values, for testing purposes"));
67 
68 static cl::opt<unsigned> UnrollAndJamThreshold(
69     "unroll-and-jam-threshold", cl::init(60), cl::Hidden,
70     cl::desc("Threshold to use for inner loop when doing unroll and jam."));
71 
72 static cl::opt<unsigned> PragmaUnrollAndJamThreshold(
73     "pragma-unroll-and-jam-threshold", cl::init(1024), cl::Hidden,
74     cl::desc("Unrolled size limit for loops with an unroll_and_jam(full) or "
75              "unroll_count pragma."));
76 
77 // Returns the loop hint metadata node with the given name (for example,
78 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
79 // returned.
80 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
81   if (MDNode *LoopID = L->getLoopID())
82     return GetUnrollMetadata(LoopID, Name);
83   return nullptr;
84 }
85 
86 // Returns true if the loop has any metadata starting with Prefix. For example a
87 // Prefix of "llvm.loop.unroll." returns true if we have any unroll metadata.
88 static bool HasAnyUnrollPragma(const Loop *L, StringRef Prefix) {
89   if (MDNode *LoopID = L->getLoopID()) {
90     // First operand should refer to the loop id itself.
91     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
92     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
93 
94     for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
95       MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
96       if (!MD)
97         continue;
98 
99       MDString *S = dyn_cast<MDString>(MD->getOperand(0));
100       if (!S)
101         continue;
102 
103       if (S->getString().startswith(Prefix))
104         return true;
105     }
106   }
107   return false;
108 }
109 
110 // Returns true if the loop has an unroll_and_jam(enable) pragma.
111 static bool HasUnrollAndJamEnablePragma(const Loop *L) {
112   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll_and_jam.enable");
113 }
114 
115 // Returns true if the loop has an unroll_and_jam(disable) pragma.
116 static bool HasUnrollAndJamDisablePragma(const Loop *L) {
117   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll_and_jam.disable");
118 }
119 
120 // If loop has an unroll_and_jam_count pragma return the (necessarily
121 // positive) value from the pragma.  Otherwise return 0.
122 static unsigned UnrollAndJamCountPragmaValue(const Loop *L) {
123   MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll_and_jam.count");
124   if (MD) {
125     assert(MD->getNumOperands() == 2 &&
126            "Unroll count hint metadata should have two operands.");
127     unsigned Count =
128         mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
129     assert(Count >= 1 && "Unroll count must be positive.");
130     return Count;
131   }
132   return 0;
133 }
134 
135 // Returns loop size estimation for unrolled loop.
136 static uint64_t
137 getUnrollAndJammedLoopSize(unsigned LoopSize,
138                            TargetTransformInfo::UnrollingPreferences &UP) {
139   assert(LoopSize >= UP.BEInsns && "LoopSize should not be less than BEInsns!");
140   return static_cast<uint64_t>(LoopSize - UP.BEInsns) * UP.Count + UP.BEInsns;
141 }
142 
143 // Calculates unroll and jam count and writes it to UP.Count. Returns true if
144 // unroll count was set explicitly.
145 static bool computeUnrollAndJamCount(
146     Loop *L, Loop *SubLoop, const TargetTransformInfo &TTI, DominatorTree &DT,
147     LoopInfo *LI, ScalarEvolution &SE,
148     const SmallPtrSetImpl<const Value *> &EphValues,
149     OptimizationRemarkEmitter *ORE, unsigned OuterTripCount,
150     unsigned OuterTripMultiple, unsigned OuterLoopSize, unsigned InnerTripCount,
151     unsigned InnerLoopSize, TargetTransformInfo::UnrollingPreferences &UP) {
152   // First up use computeUnrollCount from the loop unroller to get a count
153   // for unrolling the outer loop, plus any loops requiring explicit
154   // unrolling we leave to the unroller. This uses UP.Threshold /
155   // UP.PartialThreshold / UP.MaxCount to come up with sensible loop values.
156   // We have already checked that the loop has no unroll.* pragmas.
157   unsigned MaxTripCount = 0;
158   bool UseUpperBound = false;
159   bool ExplicitUnroll = computeUnrollCount(
160       L, TTI, DT, LI, SE, EphValues, ORE, OuterTripCount, MaxTripCount,
161       OuterTripMultiple, OuterLoopSize, UP, UseUpperBound);
162   if (ExplicitUnroll || UseUpperBound) {
163     // If the user explicitly set the loop as unrolled, dont UnJ it. Leave it
164     // for the unroller instead.
165     LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; explicit count set by "
166                          "computeUnrollCount\n");
167     UP.Count = 0;
168     return false;
169   }
170 
171   // Override with any explicit Count from the "unroll-and-jam-count" option.
172   bool UserUnrollCount = UnrollAndJamCount.getNumOccurrences() > 0;
173   if (UserUnrollCount) {
174     UP.Count = UnrollAndJamCount;
175     UP.Force = true;
176     if (UP.AllowRemainder &&
177         getUnrollAndJammedLoopSize(OuterLoopSize, UP) < UP.Threshold &&
178         getUnrollAndJammedLoopSize(InnerLoopSize, UP) <
179             UP.UnrollAndJamInnerLoopThreshold)
180       return true;
181   }
182 
183   // Check for unroll_and_jam pragmas
184   unsigned PragmaCount = UnrollAndJamCountPragmaValue(L);
185   if (PragmaCount > 0) {
186     UP.Count = PragmaCount;
187     UP.Runtime = true;
188     UP.Force = true;
189     if ((UP.AllowRemainder || (OuterTripMultiple % PragmaCount == 0)) &&
190         getUnrollAndJammedLoopSize(OuterLoopSize, UP) < UP.Threshold &&
191         getUnrollAndJammedLoopSize(InnerLoopSize, UP) <
192             UP.UnrollAndJamInnerLoopThreshold)
193       return true;
194   }
195 
196   bool PragmaEnableUnroll = HasUnrollAndJamEnablePragma(L);
197   bool ExplicitUnrollAndJamCount = PragmaCount > 0 || UserUnrollCount;
198   bool ExplicitUnrollAndJam = PragmaEnableUnroll || ExplicitUnrollAndJamCount;
199 
200   // If the loop has an unrolling pragma, we want to be more aggressive with
201   // unrolling limits.
202   if (ExplicitUnrollAndJam)
203     UP.UnrollAndJamInnerLoopThreshold = PragmaUnrollAndJamThreshold;
204 
205   if (!UP.AllowRemainder && getUnrollAndJammedLoopSize(InnerLoopSize, UP) >=
206                                 UP.UnrollAndJamInnerLoopThreshold) {
207     LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; can't create remainder and "
208                          "inner loop too large\n");
209     UP.Count = 0;
210     return false;
211   }
212 
213   // We have a sensible limit for the outer loop, now adjust it for the inner
214   // loop and UP.UnrollAndJamInnerLoopThreshold. If the outer limit was set
215   // explicitly, we want to stick to it.
216   if (!ExplicitUnrollAndJamCount && UP.AllowRemainder) {
217     while (UP.Count != 0 && getUnrollAndJammedLoopSize(InnerLoopSize, UP) >=
218                                 UP.UnrollAndJamInnerLoopThreshold)
219       UP.Count--;
220   }
221 
222   // If we are explicitly unroll and jamming, we are done. Otherwise there are a
223   // number of extra performance heuristics to check.
224   if (ExplicitUnrollAndJam)
225     return true;
226 
227   // If the inner loop count is known and small, leave the entire loop nest to
228   // be the unroller
229   if (InnerTripCount && InnerLoopSize * InnerTripCount < UP.Threshold) {
230     LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; small inner loop count is "
231                          "being left for the unroller\n");
232     UP.Count = 0;
233     return false;
234   }
235 
236   // Check for situations where UnJ is likely to be unprofitable. Including
237   // subloops with more than 1 block.
238   if (SubLoop->getBlocks().size() != 1) {
239     LLVM_DEBUG(
240         dbgs() << "Won't unroll-and-jam; More than one inner loop block\n");
241     UP.Count = 0;
242     return false;
243   }
244 
245   // Limit to loops where there is something to gain from unrolling and
246   // jamming the loop. In this case, look for loads that are invariant in the
247   // outer loop and can become shared.
248   unsigned NumInvariant = 0;
249   for (BasicBlock *BB : SubLoop->getBlocks()) {
250     for (Instruction &I : *BB) {
251       if (auto *Ld = dyn_cast<LoadInst>(&I)) {
252         Value *V = Ld->getPointerOperand();
253         const SCEV *LSCEV = SE.getSCEVAtScope(V, L);
254         if (SE.isLoopInvariant(LSCEV, L))
255           NumInvariant++;
256       }
257     }
258   }
259   if (NumInvariant == 0) {
260     LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; No loop invariant loads\n");
261     UP.Count = 0;
262     return false;
263   }
264 
265   return false;
266 }
267 
268 static LoopUnrollResult
269 tryToUnrollAndJamLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
270                       ScalarEvolution &SE, const TargetTransformInfo &TTI,
271                       AssumptionCache &AC, DependenceInfo &DI,
272                       OptimizationRemarkEmitter &ORE, int OptLevel) {
273   // Quick checks of the correct loop form
274   if (!L->isLoopSimplifyForm() || L->getSubLoops().size() != 1)
275     return LoopUnrollResult::Unmodified;
276   Loop *SubLoop = L->getSubLoops()[0];
277   if (!SubLoop->isLoopSimplifyForm())
278     return LoopUnrollResult::Unmodified;
279 
280   BasicBlock *Latch = L->getLoopLatch();
281   BasicBlock *Exit = L->getExitingBlock();
282   BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();
283   BasicBlock *SubLoopExit = SubLoop->getExitingBlock();
284 
285   if (Latch != Exit || SubLoopLatch != SubLoopExit)
286     return LoopUnrollResult::Unmodified;
287 
288   TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
289       L, SE, TTI, OptLevel, None, None, None, None, 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   // A loop with any unroll pragma (enabling/disabling/count/etc) is left for
303   // the unroller, so long as it does not explicitly have unroll_and_jam
304   // metadata. This means #pragma nounroll will disable unroll and jam as well
305   // as unrolling
306   if (HasUnrollAndJamDisablePragma(L) ||
307       (HasAnyUnrollPragma(L, "llvm.loop.unroll.") &&
308        !HasAnyUnrollPragma(L, "llvm.loop.unroll_and_jam."))) {
309     LLVM_DEBUG(dbgs() << "  Disabled due to pragma.\n");
310     return LoopUnrollResult::Unmodified;
311   }
312 
313   if (!isSafeToUnrollAndJam(L, SE, DT, DI)) {
314     LLVM_DEBUG(dbgs() << "  Disabled due to not being safe.\n");
315     return LoopUnrollResult::Unmodified;
316   }
317 
318   // Approximate the loop size and collect useful info
319   unsigned NumInlineCandidates;
320   bool NotDuplicatable;
321   bool Convergent;
322   SmallPtrSet<const Value *, 32> EphValues;
323   CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
324   unsigned InnerLoopSize =
325       ApproximateLoopSize(SubLoop, NumInlineCandidates, NotDuplicatable,
326                           Convergent, TTI, EphValues, UP.BEInsns);
327   unsigned OuterLoopSize =
328       ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
329                           TTI, EphValues, UP.BEInsns);
330   LLVM_DEBUG(dbgs() << "  Outer Loop Size: " << OuterLoopSize << "\n");
331   LLVM_DEBUG(dbgs() << "  Inner Loop Size: " << InnerLoopSize << "\n");
332   if (NotDuplicatable) {
333     LLVM_DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable "
334                          "instructions.\n");
335     return LoopUnrollResult::Unmodified;
336   }
337   if (NumInlineCandidates != 0) {
338     LLVM_DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
339     return LoopUnrollResult::Unmodified;
340   }
341   if (Convergent) {
342     LLVM_DEBUG(
343         dbgs() << "  Not unrolling loop with convergent instructions.\n");
344     return LoopUnrollResult::Unmodified;
345   }
346 
347   // Find trip count and trip multiple
348   unsigned OuterTripCount = SE.getSmallConstantTripCount(L, Latch);
349   unsigned OuterTripMultiple = SE.getSmallConstantTripMultiple(L, Latch);
350   unsigned InnerTripCount = SE.getSmallConstantTripCount(SubLoop, SubLoopLatch);
351 
352   // Decide if, and by how much, to unroll
353   bool IsCountSetExplicitly = computeUnrollAndJamCount(
354       L, SubLoop, TTI, DT, LI, SE, EphValues, &ORE, OuterTripCount,
355       OuterTripMultiple, OuterLoopSize, InnerTripCount, InnerLoopSize, UP);
356   if (UP.Count <= 1)
357     return LoopUnrollResult::Unmodified;
358   // Unroll factor (Count) must be less or equal to TripCount.
359   if (OuterTripCount && UP.Count > OuterTripCount)
360     UP.Count = OuterTripCount;
361 
362   LoopUnrollResult UnrollResult =
363       UnrollAndJamLoop(L, UP.Count, OuterTripCount, OuterTripMultiple,
364                        UP.UnrollRemainder, LI, &SE, &DT, &AC, &ORE);
365 
366   // If loop has an unroll count pragma or unrolled by explicitly set count
367   // mark loop as unrolled to prevent unrolling beyond that requested.
368   if (UnrollResult != LoopUnrollResult::FullyUnrolled && IsCountSetExplicitly)
369     L->setLoopAlreadyUnrolled();
370 
371   return UnrollResult;
372 }
373 
374 namespace {
375 
376 class LoopUnrollAndJam : public LoopPass {
377 public:
378   static char ID; // Pass ID, replacement for typeid
379   unsigned OptLevel;
380 
381   LoopUnrollAndJam(int OptLevel = 2) : LoopPass(ID), OptLevel(OptLevel) {
382     initializeLoopUnrollAndJamPass(*PassRegistry::getPassRegistry());
383   }
384 
385   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
386     if (skipLoop(L))
387       return false;
388 
389     Function &F = *L->getHeader()->getParent();
390 
391     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
392     LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
393     ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
394     const TargetTransformInfo &TTI =
395         getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
396     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
397     auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI();
398     // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
399     // pass.  Function analyses need to be preserved across loop transformations
400     // but ORE cannot be preserved (see comment before the pass definition).
401     OptimizationRemarkEmitter ORE(&F);
402 
403     LoopUnrollResult Result =
404         tryToUnrollAndJamLoop(L, DT, LI, SE, TTI, AC, DI, ORE, OptLevel);
405 
406     if (Result == LoopUnrollResult::FullyUnrolled)
407       LPM.markLoopAsDeleted(*L);
408 
409     return Result != LoopUnrollResult::Unmodified;
410   }
411 
412   /// This transformation requires natural loop information & requires that
413   /// loop preheaders be inserted into the CFG...
414   void getAnalysisUsage(AnalysisUsage &AU) const override {
415     AU.addRequired<AssumptionCacheTracker>();
416     AU.addRequired<TargetTransformInfoWrapperPass>();
417     AU.addRequired<DependenceAnalysisWrapperPass>();
418     getLoopAnalysisUsage(AU);
419   }
420 };
421 
422 } // end anonymous namespace
423 
424 char LoopUnrollAndJam::ID = 0;
425 
426 INITIALIZE_PASS_BEGIN(LoopUnrollAndJam, "loop-unroll-and-jam",
427                       "Unroll and Jam loops", false, false)
428 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
429 INITIALIZE_PASS_DEPENDENCY(LoopPass)
430 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
431 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
432 INITIALIZE_PASS_END(LoopUnrollAndJam, "loop-unroll-and-jam",
433                     "Unroll and Jam loops", false, false)
434 
435 Pass *llvm::createLoopUnrollAndJamPass(int OptLevel) {
436   return new LoopUnrollAndJam(OptLevel);
437 }
438 
439 PreservedAnalyses LoopUnrollAndJamPass::run(Loop &L, LoopAnalysisManager &AM,
440                                             LoopStandardAnalysisResults &AR,
441                                             LPMUpdater &) {
442   const auto &FAM =
443       AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
444   Function *F = L.getHeader()->getParent();
445 
446   auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
447   // FIXME: This should probably be optional rather than required.
448   if (!ORE)
449     report_fatal_error(
450         "LoopUnrollAndJamPass: OptimizationRemarkEmitterAnalysis not cached at "
451         "a higher level");
452 
453   DependenceInfo DI(F, &AR.AA, &AR.SE, &AR.LI);
454 
455   LoopUnrollResult Result = tryToUnrollAndJamLoop(
456       &L, AR.DT, &AR.LI, AR.SE, AR.TTI, AR.AC, DI, *ORE, OptLevel);
457 
458   if (Result == LoopUnrollResult::Unmodified)
459     return PreservedAnalyses::all();
460 
461   return getLoopPassPreservedAnalyses();
462 }
463