1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Analysis/CodeMetrics.h"
17 #include "llvm/Analysis/LoopPass.h"
18 #include "llvm/Analysis/ScalarEvolution.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DiagnosticInfo.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Utils/UnrollLoop.h"
33 #define DEBUG_TYPE "loop-unroll"
35 static cl::opt<unsigned>
36 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
37 cl::desc("The cut-off point for automatic loop unrolling"));
39 static cl::opt<unsigned>
40 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
41 cl::desc("Use this unroll count for all loops including those with "
42 "unroll_count pragma values, for testing purposes"));
45 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
46 cl::desc("Allows loops to be partially unrolled until "
47 "-unroll-threshold loop size is reached."));
50 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
51 cl::desc("Unroll loops with run-time trip counts"));
53 static cl::opt<unsigned>
54 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
55 cl::desc("Unrolled size limit for loops with an unroll(full) or "
56 "unroll_count pragma."));
59 class LoopUnroll : public LoopPass {
61 static char ID; // Pass ID, replacement for typeid
62 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
63 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
64 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
65 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
66 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
68 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
69 UserAllowPartial = (P != -1) ||
70 (UnrollAllowPartial.getNumOccurrences() > 0);
71 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
72 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
74 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
77 /// A magic value for use with the Threshold parameter to indicate
78 /// that the loop unroll should be performed regardless of how much
79 /// code expansion would result.
80 static const unsigned NoThreshold = UINT_MAX;
82 // Threshold to use when optsize is specified (and there is no
83 // explicit -unroll-threshold).
84 static const unsigned OptSizeUnrollThreshold = 50;
86 // Default unroll count for loops with run-time trip count if
87 // -unroll-count is not set
88 static const unsigned UnrollRuntimeCount = 8;
90 unsigned CurrentCount;
91 unsigned CurrentThreshold;
92 bool CurrentAllowPartial;
94 bool UserCount; // CurrentCount is user-specified.
95 bool UserThreshold; // CurrentThreshold is user-specified.
96 bool UserAllowPartial; // CurrentAllowPartial is user-specified.
97 bool UserRuntime; // CurrentRuntime is user-specified.
99 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
101 /// This transformation requires natural loop information & requires that
102 /// loop preheaders be inserted into the CFG...
104 void getAnalysisUsage(AnalysisUsage &AU) const override {
105 AU.addRequired<LoopInfo>();
106 AU.addPreserved<LoopInfo>();
107 AU.addRequiredID(LoopSimplifyID);
108 AU.addPreservedID(LoopSimplifyID);
109 AU.addRequiredID(LCSSAID);
110 AU.addPreservedID(LCSSAID);
111 AU.addRequired<ScalarEvolution>();
112 AU.addPreserved<ScalarEvolution>();
113 AU.addRequired<TargetTransformInfo>();
114 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
115 // If loop unroll does not preserve dom info then LCSSA pass on next
116 // loop will receive invalid dom info.
117 // For now, recreate dom info, if loop is unrolled.
118 AU.addPreserved<DominatorTreeWrapperPass>();
121 // Fill in the UnrollingPreferences parameter with values from the
122 // TargetTransformationInfo.
123 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
124 TargetTransformInfo::UnrollingPreferences &UP) {
125 UP.Threshold = CurrentThreshold;
126 UP.OptSizeThreshold = OptSizeUnrollThreshold;
127 UP.PartialThreshold = CurrentThreshold;
128 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
129 UP.Count = CurrentCount;
130 UP.MaxCount = UINT_MAX;
131 UP.Partial = CurrentAllowPartial;
132 UP.Runtime = CurrentRuntime;
133 TTI.getUnrollingPreferences(L, UP);
136 // Select and return an unroll count based on parameters from
137 // user, unroll preferences, unroll pragmas, or a heuristic.
138 // SetExplicitly is set to true if the unroll count is is set by
139 // the user or a pragma rather than selected heuristically.
141 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
142 unsigned PragmaCount,
143 const TargetTransformInfo::UnrollingPreferences &UP,
144 bool &SetExplicitly);
146 // Select threshold values used to limit unrolling based on a
147 // total unrolled size. Parameters Threshold and PartialThreshold
148 // are set to the maximum unrolled size for fully and partially
149 // unrolled loops respectively.
150 void selectThresholds(const Loop *L, bool HasPragma,
151 const TargetTransformInfo::UnrollingPreferences &UP,
152 unsigned &Threshold, unsigned &PartialThreshold) {
153 // Determine the current unrolling threshold. While this is
154 // normally set from UnrollThreshold, it is overridden to a
155 // smaller value if the current function is marked as
156 // optimize-for-size, and the unroll threshold was not user
158 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
159 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
160 if (!UserThreshold &&
161 L->getHeader()->getParent()->getAttributes().
162 hasAttribute(AttributeSet::FunctionIndex,
163 Attribute::OptimizeForSize)) {
164 Threshold = UP.OptSizeThreshold;
165 PartialThreshold = UP.PartialOptSizeThreshold;
168 // If the loop has an unrolling pragma, we want to be more
169 // aggressive with unrolling limits. Set thresholds to at
170 // least the PragmaTheshold value which is larger than the
172 if (Threshold != NoThreshold)
173 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
174 if (PartialThreshold != NoThreshold)
176 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
182 char LoopUnroll::ID = 0;
183 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
184 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
185 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
186 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
187 INITIALIZE_PASS_DEPENDENCY(LCSSA)
188 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
189 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
191 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
193 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
196 Pass *llvm::createSimpleLoopUnrollPass() {
197 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
200 /// ApproximateLoopSize - Approximate the size of the loop.
201 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
202 bool &NotDuplicatable,
203 const TargetTransformInfo &TTI) {
205 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
207 Metrics.analyzeBasicBlock(*I, TTI);
208 NumCalls = Metrics.NumInlineCandidates;
209 NotDuplicatable = Metrics.notDuplicatable;
211 unsigned LoopSize = Metrics.NumInsts;
213 // Don't allow an estimate of size zero. This would allows unrolling of loops
214 // with huge iteration counts, which is a compile time problem even if it's
215 // not a problem for code quality.
216 if (LoopSize == 0) LoopSize = 1;
221 // Returns the loop hint metadata node with the given name (for example,
222 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
224 static const MDNode *GetUnrollMetadata(const Loop *L, StringRef Name) {
225 MDNode *LoopID = L->getLoopID();
229 // First operand should refer to the loop id itself.
230 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
231 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
233 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
234 const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
238 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
242 if (Name.equals(S->getString()))
248 // Returns true if the loop has an unroll(full) pragma.
249 static bool HasUnrollFullPragma(const Loop *L) {
250 return GetUnrollMetadata(L, "llvm.loop.unroll.full");
253 // Returns true if the loop has an unroll(disable) pragma.
254 static bool HasUnrollDisablePragma(const Loop *L) {
255 return GetUnrollMetadata(L, "llvm.loop.unroll.disable");
258 // If loop has an unroll_count pragma return the (necessarily
259 // positive) value from the pragma. Otherwise return 0.
260 static unsigned UnrollCountPragmaValue(const Loop *L) {
261 const MDNode *MD = GetUnrollMetadata(L, "llvm.loop.unroll.count");
263 assert(MD->getNumOperands() == 2 &&
264 "Unroll count hint metadata should have two operands.");
265 unsigned Count = cast<ConstantInt>(MD->getOperand(1))->getZExtValue();
266 assert(Count >= 1 && "Unroll count must be positive.");
272 // Remove existing unroll metadata and add unroll disable metadata to
273 // indicate the loop has already been unrolled. This prevents a loop
274 // from being unrolled more than is directed by a pragma if the loop
275 // unrolling pass is run more than once (which it generally is).
276 static void SetLoopAlreadyUnrolled(Loop *L) {
277 MDNode *LoopID = L->getLoopID();
280 // First remove any existing loop unrolling metadata.
281 SmallVector<Value *, 4> Vals;
282 // Reserve first location for self reference to the LoopID metadata node.
283 Vals.push_back(nullptr);
284 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
285 bool IsUnrollMetadata = false;
286 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
288 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
289 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
291 if (!IsUnrollMetadata) Vals.push_back(LoopID->getOperand(i));
294 // Add unroll(disable) metadata to disable future unrolling.
295 LLVMContext &Context = L->getHeader()->getContext();
296 SmallVector<Value *, 1> DisableOperands;
297 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
298 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
299 Vals.push_back(DisableNode);
301 MDNode *NewLoopID = MDNode::get(Context, Vals);
302 // Set operand 0 to refer to the loop id itself.
303 NewLoopID->replaceOperandWith(0, NewLoopID);
304 L->setLoopID(NewLoopID);
307 unsigned LoopUnroll::selectUnrollCount(
308 const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
309 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
310 bool &SetExplicitly) {
311 SetExplicitly = true;
313 // User-specified count (either as a command-line option or
314 // constructor parameter) has highest precedence.
315 unsigned Count = UserCount ? CurrentCount : 0;
317 // If there is no user-specified count, unroll pragmas have the next
318 // highest precendence.
322 } else if (PragmaFullUnroll) {
331 SetExplicitly = false;
333 // Runtime trip count.
334 Count = UnrollRuntimeCount;
336 // Conservative heuristic: if we know the trip count, see if we can
337 // completely unroll (subject to the threshold, checked below); otherwise
338 // try to find greatest modulo of the trip count which is still under
342 if (TripCount && Count > TripCount)
347 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
348 if (skipOptnoneFunction(L))
351 LoopInfo *LI = &getAnalysis<LoopInfo>();
352 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
353 const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
355 BasicBlock *Header = L->getHeader();
356 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
357 << "] Loop %" << Header->getName() << "\n");
359 if (HasUnrollDisablePragma(L)) {
362 bool PragmaFullUnroll = HasUnrollFullPragma(L);
363 unsigned PragmaCount = UnrollCountPragmaValue(L);
364 bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
366 TargetTransformInfo::UnrollingPreferences UP;
367 getUnrollingPreferences(L, TTI, UP);
369 // Find trip count and trip multiple if count is not available
370 unsigned TripCount = 0;
371 unsigned TripMultiple = 1;
372 // Find "latch trip count". UnrollLoop assumes that control cannot exit
373 // via the loop latch on any iteration prior to TripCount. The loop may exit
374 // early via an earlier branch.
375 BasicBlock *LatchBlock = L->getLoopLatch();
377 TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
378 TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
381 // Select an initial unroll count. This may be reduced later based
382 // on size thresholds.
383 bool CountSetExplicitly;
384 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
385 PragmaCount, UP, CountSetExplicitly);
387 unsigned NumInlineCandidates;
388 bool notDuplicatable;
390 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI);
391 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
392 uint64_t UnrolledSize = (uint64_t)LoopSize * Count;
393 if (notDuplicatable) {
394 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
395 << " instructions.\n");
398 if (NumInlineCandidates != 0) {
399 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
403 unsigned Threshold, PartialThreshold;
404 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold);
406 // Given Count, TripCount and thresholds determine the type of
407 // unrolling which is to be performed.
408 enum { Full = 0, Partial = 1, Runtime = 2 };
410 if (TripCount && Count == TripCount) {
411 if (Threshold != NoThreshold && UnrolledSize > Threshold) {
412 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
413 << " because size: " << UnrolledSize << ">" << Threshold
419 } else if (TripCount && Count < TripCount) {
425 // Reduce count based on the type of unrolling and the threshold values.
426 unsigned OriginalCount = Count;
427 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
428 if (Unrolling == Partial) {
429 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
430 if (!AllowPartial && !CountSetExplicitly) {
431 DEBUG(dbgs() << " will not try to unroll partially because "
432 << "-unroll-allow-partial not given\n");
435 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
436 // Reduce unroll count to be modulo of TripCount for partial unrolling.
437 Count = PartialThreshold / LoopSize;
438 while (Count != 0 && TripCount % Count != 0)
441 } else if (Unrolling == Runtime) {
442 if (!AllowRuntime && !CountSetExplicitly) {
443 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
444 << "-unroll-runtime not given\n");
447 // Reduce unroll count to be the largest power-of-two factor of
448 // the original count which satisfies the threshold limit.
449 while (Count != 0 && UnrolledSize > PartialThreshold) {
451 UnrolledSize = LoopSize * Count;
453 if (Count > UP.MaxCount)
455 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
459 if (PragmaCount != 0)
460 // If loop has an unroll count pragma mark loop as unrolled to prevent
461 // unrolling beyond that requested by the pragma.
462 SetLoopAlreadyUnrolled(L);
464 // Emit optimization remarks if we are unable to unroll the loop
465 // as directed by a pragma.
466 DebugLoc LoopLoc = L->getStartLoc();
467 Function *F = Header->getParent();
468 LLVMContext &Ctx = F->getContext();
469 if (PragmaFullUnroll && PragmaCount == 0) {
470 if (TripCount && Count != TripCount) {
471 emitOptimizationRemarkMissed(
472 Ctx, DEBUG_TYPE, *F, LoopLoc,
473 "Unable to fully unroll loop as directed by unroll(full) pragma "
474 "because unrolled size is too large.");
475 } else if (!TripCount) {
476 emitOptimizationRemarkMissed(
477 Ctx, DEBUG_TYPE, *F, LoopLoc,
478 "Unable to fully unroll loop as directed by unroll(full) pragma "
479 "because loop has a runtime trip count.");
481 } else if (PragmaCount > 0 && Count != OriginalCount) {
482 emitOptimizationRemarkMissed(
483 Ctx, DEBUG_TYPE, *F, LoopLoc,
484 "Unable to unroll loop the number of times directed by "
485 "unroll_count pragma because unrolled size is too large.");
489 if (Unrolling != Full && Count < 2) {
490 // Partial unrolling by 1 is a nop. For full unrolling, a factor
491 // of 1 makes sense because loop control can be eliminated.
496 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this, &LPM))