[SCEV] Add some asserts to the recently improved trip count computation
[oota-llvm.git] / lib / Transforms / Scalar / LoopUnrollPass.cpp
1 //===-- LoopUnroll.cpp - Loop unroller 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 a simple loop unroller.  It works best when loops have
11 // been canonicalized by the -indvars pass, allowing it to determine the trip
12 // counts of loops easily.
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Analysis/AssumptionTracker.h"
17 #include "llvm/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/FunctionTargetTransformInfo.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/ScalarEvolution.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DiagnosticInfo.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Metadata.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Transforms/Utils/UnrollLoop.h"
31 #include <climits>
32
33 using namespace llvm;
34
35 #define DEBUG_TYPE "loop-unroll"
36
37 static cl::opt<unsigned>
38 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
39   cl::desc("The cut-off point for automatic loop unrolling"));
40
41 static cl::opt<unsigned>
42 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
43   cl::desc("Use this unroll count for all loops including those with "
44            "unroll_count pragma values, for testing purposes"));
45
46 static cl::opt<bool>
47 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
48   cl::desc("Allows loops to be partially unrolled until "
49            "-unroll-threshold loop size is reached."));
50
51 static cl::opt<bool>
52 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
53   cl::desc("Unroll loops with run-time trip counts"));
54
55 static cl::opt<unsigned>
56 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
57   cl::desc("Unrolled size limit for loops with an unroll(full) or "
58            "unroll_count pragma."));
59
60 namespace {
61   class LoopUnroll : public LoopPass {
62   public:
63     static char ID; // Pass ID, replacement for typeid
64     LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
65       CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
66       CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
67       CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
68       CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
69
70       UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
71       UserAllowPartial = (P != -1) ||
72                          (UnrollAllowPartial.getNumOccurrences() > 0);
73       UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
74       UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
75
76       initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
77     }
78
79     /// A magic value for use with the Threshold parameter to indicate
80     /// that the loop unroll should be performed regardless of how much
81     /// code expansion would result.
82     static const unsigned NoThreshold = UINT_MAX;
83
84     // Threshold to use when optsize is specified (and there is no
85     // explicit -unroll-threshold).
86     static const unsigned OptSizeUnrollThreshold = 50;
87
88     // Default unroll count for loops with run-time trip count if
89     // -unroll-count is not set
90     static const unsigned UnrollRuntimeCount = 8;
91
92     unsigned CurrentCount;
93     unsigned CurrentThreshold;
94     bool     CurrentAllowPartial;
95     bool     CurrentRuntime;
96     bool     UserCount;            // CurrentCount is user-specified.
97     bool     UserThreshold;        // CurrentThreshold is user-specified.
98     bool     UserAllowPartial;     // CurrentAllowPartial is user-specified.
99     bool     UserRuntime;          // CurrentRuntime is user-specified.
100
101     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
102
103     /// This transformation requires natural loop information & requires that
104     /// loop preheaders be inserted into the CFG...
105     ///
106     void getAnalysisUsage(AnalysisUsage &AU) const override {
107       AU.addRequired<AssumptionTracker>();
108       AU.addRequired<LoopInfo>();
109       AU.addPreserved<LoopInfo>();
110       AU.addRequiredID(LoopSimplifyID);
111       AU.addPreservedID(LoopSimplifyID);
112       AU.addRequiredID(LCSSAID);
113       AU.addPreservedID(LCSSAID);
114       AU.addRequired<ScalarEvolution>();
115       AU.addPreserved<ScalarEvolution>();
116       AU.addRequired<TargetTransformInfo>();
117       AU.addRequired<FunctionTargetTransformInfo>();
118       // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
119       // If loop unroll does not preserve dom info then LCSSA pass on next
120       // loop will receive invalid dom info.
121       // For now, recreate dom info, if loop is unrolled.
122       AU.addPreserved<DominatorTreeWrapperPass>();
123     }
124
125     // Fill in the UnrollingPreferences parameter with values from the
126     // TargetTransformationInfo.
127     void getUnrollingPreferences(Loop *L, const FunctionTargetTransformInfo &FTTI,
128                                  TargetTransformInfo::UnrollingPreferences &UP) {
129       UP.Threshold = CurrentThreshold;
130       UP.OptSizeThreshold = OptSizeUnrollThreshold;
131       UP.PartialThreshold = CurrentThreshold;
132       UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
133       UP.Count = CurrentCount;
134       UP.MaxCount = UINT_MAX;
135       UP.Partial = CurrentAllowPartial;
136       UP.Runtime = CurrentRuntime;
137       FTTI.getUnrollingPreferences(L, UP);
138     }
139
140     // Select and return an unroll count based on parameters from
141     // user, unroll preferences, unroll pragmas, or a heuristic.
142     // SetExplicitly is set to true if the unroll count is is set by
143     // the user or a pragma rather than selected heuristically.
144     unsigned
145     selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
146                       unsigned PragmaCount,
147                       const TargetTransformInfo::UnrollingPreferences &UP,
148                       bool &SetExplicitly);
149
150     // Select threshold values used to limit unrolling based on a
151     // total unrolled size.  Parameters Threshold and PartialThreshold
152     // are set to the maximum unrolled size for fully and partially
153     // unrolled loops respectively.
154     void selectThresholds(const Loop *L, bool HasPragma,
155                           const TargetTransformInfo::UnrollingPreferences &UP,
156                           unsigned &Threshold, unsigned &PartialThreshold) {
157       // Determine the current unrolling threshold.  While this is
158       // normally set from UnrollThreshold, it is overridden to a
159       // smaller value if the current function is marked as
160       // optimize-for-size, and the unroll threshold was not user
161       // specified.
162       Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
163       PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
164       if (!UserThreshold &&
165           L->getHeader()->getParent()->getAttributes().
166               hasAttribute(AttributeSet::FunctionIndex,
167                            Attribute::OptimizeForSize)) {
168         Threshold = UP.OptSizeThreshold;
169         PartialThreshold = UP.PartialOptSizeThreshold;
170       }
171       if (HasPragma) {
172         // If the loop has an unrolling pragma, we want to be more
173         // aggressive with unrolling limits.  Set thresholds to at
174         // least the PragmaTheshold value which is larger than the
175         // default limits.
176         if (Threshold != NoThreshold)
177           Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
178         if (PartialThreshold != NoThreshold)
179           PartialThreshold =
180               std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
181       }
182     }
183   };
184 }
185
186 char LoopUnroll::ID = 0;
187 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
188 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
189 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
190 INITIALIZE_PASS_DEPENDENCY(FunctionTargetTransformInfo)
191 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
192 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
193 INITIALIZE_PASS_DEPENDENCY(LCSSA)
194 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
195 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
196
197 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
198                                  int Runtime) {
199   return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
200 }
201
202 Pass *llvm::createSimpleLoopUnrollPass() {
203   return llvm::createLoopUnrollPass(-1, -1, 0, 0);
204 }
205
206 /// ApproximateLoopSize - Approximate the size of the loop.
207 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
208                                     bool &NotDuplicatable,
209                                     const TargetTransformInfo &TTI,
210                                     AssumptionTracker *AT) {
211   SmallPtrSet<const Value *, 32> EphValues;
212   CodeMetrics::collectEphemeralValues(L, AT, EphValues);
213
214   CodeMetrics Metrics;
215   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
216        I != E; ++I)
217     Metrics.analyzeBasicBlock(*I, TTI, EphValues);
218   NumCalls = Metrics.NumInlineCandidates;
219   NotDuplicatable = Metrics.notDuplicatable;
220
221   unsigned LoopSize = Metrics.NumInsts;
222
223   // Don't allow an estimate of size zero.  This would allows unrolling of loops
224   // with huge iteration counts, which is a compile time problem even if it's
225   // not a problem for code quality.
226   if (LoopSize == 0) LoopSize = 1;
227
228   return LoopSize;
229 }
230
231 // Returns the loop hint metadata node with the given name (for example,
232 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
233 // returned.
234 static const MDNode *GetUnrollMetadata(const Loop *L, StringRef Name) {
235   MDNode *LoopID = L->getLoopID();
236   if (!LoopID)
237     return nullptr;
238
239   // First operand should refer to the loop id itself.
240   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
241   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
242
243   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
244     const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
245     if (!MD)
246       continue;
247
248     const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
249     if (!S)
250       continue;
251
252     if (Name.equals(S->getString()))
253       return MD;
254   }
255   return nullptr;
256 }
257
258 // Returns true if the loop has an unroll(full) pragma.
259 static bool HasUnrollFullPragma(const Loop *L) {
260   return GetUnrollMetadata(L, "llvm.loop.unroll.full");
261 }
262
263 // Returns true if the loop has an unroll(disable) pragma.
264 static bool HasUnrollDisablePragma(const Loop *L) {
265   return GetUnrollMetadata(L, "llvm.loop.unroll.disable");
266 }
267
268 // If loop has an unroll_count pragma return the (necessarily
269 // positive) value from the pragma.  Otherwise return 0.
270 static unsigned UnrollCountPragmaValue(const Loop *L) {
271   const MDNode *MD = GetUnrollMetadata(L, "llvm.loop.unroll.count");
272   if (MD) {
273     assert(MD->getNumOperands() == 2 &&
274            "Unroll count hint metadata should have two operands.");
275     unsigned Count = cast<ConstantInt>(MD->getOperand(1))->getZExtValue();
276     assert(Count >= 1 && "Unroll count must be positive.");
277     return Count;
278   }
279   return 0;
280 }
281
282 // Remove existing unroll metadata and add unroll disable metadata to
283 // indicate the loop has already been unrolled.  This prevents a loop
284 // from being unrolled more than is directed by a pragma if the loop
285 // unrolling pass is run more than once (which it generally is).
286 static void SetLoopAlreadyUnrolled(Loop *L) {
287   MDNode *LoopID = L->getLoopID();
288   if (!LoopID) return;
289
290   // First remove any existing loop unrolling metadata.
291   SmallVector<Value *, 4> Vals;
292   // Reserve first location for self reference to the LoopID metadata node.
293   Vals.push_back(nullptr);
294   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
295     bool IsUnrollMetadata = false;
296     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
297     if (MD) {
298       const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
299       IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
300     }
301     if (!IsUnrollMetadata) Vals.push_back(LoopID->getOperand(i));
302   }
303
304   // Add unroll(disable) metadata to disable future unrolling.
305   LLVMContext &Context = L->getHeader()->getContext();
306   SmallVector<Value *, 1> DisableOperands;
307   DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
308   MDNode *DisableNode = MDNode::get(Context, DisableOperands);
309   Vals.push_back(DisableNode);
310
311   MDNode *NewLoopID = MDNode::get(Context, Vals);
312   // Set operand 0 to refer to the loop id itself.
313   NewLoopID->replaceOperandWith(0, NewLoopID);
314   L->setLoopID(NewLoopID);
315 }
316
317 unsigned LoopUnroll::selectUnrollCount(
318     const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
319     unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
320     bool &SetExplicitly) {
321   SetExplicitly = true;
322
323   // User-specified count (either as a command-line option or
324   // constructor parameter) has highest precedence.
325   unsigned Count = UserCount ? CurrentCount : 0;
326
327   // If there is no user-specified count, unroll pragmas have the next
328   // highest precendence.
329   if (Count == 0) {
330     if (PragmaCount) {
331       Count = PragmaCount;
332     } else if (PragmaFullUnroll) {
333       Count = TripCount;
334     }
335   }
336
337   if (Count == 0)
338     Count = UP.Count;
339
340   if (Count == 0) {
341     SetExplicitly = false;
342     if (TripCount == 0)
343       // Runtime trip count.
344       Count = UnrollRuntimeCount;
345     else
346       // Conservative heuristic: if we know the trip count, see if we can
347       // completely unroll (subject to the threshold, checked below); otherwise
348       // try to find greatest modulo of the trip count which is still under
349       // threshold value.
350       Count = TripCount;
351   }
352   if (TripCount && Count > TripCount)
353     return TripCount;
354   return Count;
355 }
356
357 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
358   if (skipOptnoneFunction(L))
359     return false;
360
361   LoopInfo *LI = &getAnalysis<LoopInfo>();
362   ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
363   const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
364   const FunctionTargetTransformInfo &FTTI =
365       getAnalysis<FunctionTargetTransformInfo>();
366   AssumptionTracker *AT = &getAnalysis<AssumptionTracker>();
367
368   BasicBlock *Header = L->getHeader();
369   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
370         << "] Loop %" << Header->getName() << "\n");
371
372   if (HasUnrollDisablePragma(L)) {
373     return false;
374   }
375   bool PragmaFullUnroll = HasUnrollFullPragma(L);
376   unsigned PragmaCount = UnrollCountPragmaValue(L);
377   bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
378
379   TargetTransformInfo::UnrollingPreferences UP;
380   getUnrollingPreferences(L, FTTI, UP);
381
382   // Find trip count and trip multiple if count is not available
383   unsigned TripCount = 0;
384   unsigned TripMultiple = 1;
385   // If there are multiple exiting blocks but one of them is the latch, use the
386   // latch for the trip count estimation. Otherwise insist on a single exiting
387   // block for the trip count estimation.
388   BasicBlock *ExitingBlock = L->getLoopLatch();
389   if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
390     ExitingBlock = L->getExitingBlock();
391   if (ExitingBlock) {
392     TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
393     TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
394   }
395
396   // Select an initial unroll count.  This may be reduced later based
397   // on size thresholds.
398   bool CountSetExplicitly;
399   unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
400                                      PragmaCount, UP, CountSetExplicitly);
401
402   unsigned NumInlineCandidates;
403   bool notDuplicatable;
404   unsigned LoopSize =
405       ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, AT);
406   DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
407   uint64_t UnrolledSize = (uint64_t)LoopSize * Count;
408   if (notDuplicatable) {
409     DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
410                  << " instructions.\n");
411     return false;
412   }
413   if (NumInlineCandidates != 0) {
414     DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
415     return false;
416   }
417
418   unsigned Threshold, PartialThreshold;
419   selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold);
420
421   // Given Count, TripCount and thresholds determine the type of
422   // unrolling which is to be performed.
423   enum { Full = 0, Partial = 1, Runtime = 2 };
424   int Unrolling;
425   if (TripCount && Count == TripCount) {
426     if (Threshold != NoThreshold && UnrolledSize > Threshold) {
427       DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
428                    << " because size: " << UnrolledSize << ">" << Threshold
429                    << "\n");
430       Unrolling = Partial;
431     } else {
432       Unrolling = Full;
433     }
434   } else if (TripCount && Count < TripCount) {
435     Unrolling = Partial;
436   } else {
437     Unrolling = Runtime;
438   }
439
440   // Reduce count based on the type of unrolling and the threshold values.
441   unsigned OriginalCount = Count;
442   bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
443   if (Unrolling == Partial) {
444     bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
445     if (!AllowPartial && !CountSetExplicitly) {
446       DEBUG(dbgs() << "  will not try to unroll partially because "
447                    << "-unroll-allow-partial not given\n");
448       return false;
449     }
450     if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
451       // Reduce unroll count to be modulo of TripCount for partial unrolling.
452       Count = PartialThreshold / LoopSize;
453       while (Count != 0 && TripCount % Count != 0)
454         Count--;
455     }
456   } else if (Unrolling == Runtime) {
457     if (!AllowRuntime && !CountSetExplicitly) {
458       DEBUG(dbgs() << "  will not try to unroll loop with runtime trip count "
459                    << "-unroll-runtime not given\n");
460       return false;
461     }
462     // Reduce unroll count to be the largest power-of-two factor of
463     // the original count which satisfies the threshold limit.
464     while (Count != 0 && UnrolledSize > PartialThreshold) {
465       Count >>= 1;
466       UnrolledSize = LoopSize * Count;
467     }
468     if (Count > UP.MaxCount)
469       Count = UP.MaxCount;
470     DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
471   }
472
473   if (HasPragma) {
474     if (PragmaCount != 0)
475       // If loop has an unroll count pragma mark loop as unrolled to prevent
476       // unrolling beyond that requested by the pragma.
477       SetLoopAlreadyUnrolled(L);
478
479     // Emit optimization remarks if we are unable to unroll the loop
480     // as directed by a pragma.
481     DebugLoc LoopLoc = L->getStartLoc();
482     Function *F = Header->getParent();
483     LLVMContext &Ctx = F->getContext();
484     if (PragmaFullUnroll && PragmaCount == 0) {
485       if (TripCount && Count != TripCount) {
486         emitOptimizationRemarkMissed(
487             Ctx, DEBUG_TYPE, *F, LoopLoc,
488             "Unable to fully unroll loop as directed by unroll(full) pragma "
489             "because unrolled size is too large.");
490       } else if (!TripCount) {
491         emitOptimizationRemarkMissed(
492             Ctx, DEBUG_TYPE, *F, LoopLoc,
493             "Unable to fully unroll loop as directed by unroll(full) pragma "
494             "because loop has a runtime trip count.");
495       }
496     } else if (PragmaCount > 0 && Count != OriginalCount) {
497       emitOptimizationRemarkMissed(
498           Ctx, DEBUG_TYPE, *F, LoopLoc,
499           "Unable to unroll loop the number of times directed by "
500           "unroll_count pragma because unrolled size is too large.");
501     }
502   }
503
504   if (Unrolling != Full && Count < 2) {
505     // Partial unrolling by 1 is a nop.  For full unrolling, a factor
506     // of 1 makes sense because loop control can be eliminated.
507     return false;
508   }
509
510   // Unroll the loop.
511   if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this,
512                   &LPM, AT))
513     return false;
514
515   return true;
516 }