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/AssumptionCache.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"
35 #define DEBUG_TYPE "loop-unroll"
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"));
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"));
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."));
52 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
53 cl::desc("Unroll loops with run-time trip counts"));
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."));
61 class LoopUnroll : public LoopPass {
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;
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);
76 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
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;
84 // Threshold to use when optsize is specified (and there is no
85 // explicit -unroll-threshold).
86 static const unsigned OptSizeUnrollThreshold = 50;
88 // Default unroll count for loops with run-time trip count if
89 // -unroll-count is not set
90 static const unsigned UnrollRuntimeCount = 8;
92 unsigned CurrentCount;
93 unsigned CurrentThreshold;
94 bool CurrentAllowPartial;
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.
101 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
103 /// This transformation requires natural loop information & requires that
104 /// loop preheaders be inserted into the CFG...
106 void getAnalysisUsage(AnalysisUsage &AU) const override {
107 AU.addRequired<AssumptionCacheTracker>();
108 AU.addRequired<LoopInfoWrapperPass>();
109 AU.addPreserved<LoopInfoWrapperPass>();
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<TargetTransformInfoWrapperPass>();
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>();
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);
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.
145 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
146 unsigned PragmaCount,
147 const TargetTransformInfo::UnrollingPreferences &UP,
148 bool &SetExplicitly);
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
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;
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
176 if (Threshold != NoThreshold)
177 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
178 if (PartialThreshold != NoThreshold)
180 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
186 char LoopUnroll::ID = 0;
187 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
188 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
189 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
190 INITIALIZE_PASS_DEPENDENCY(FunctionTargetTransformInfo)
191 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
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)
197 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
199 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
202 Pass *llvm::createSimpleLoopUnrollPass() {
203 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
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 AssumptionCache *AC) {
211 SmallPtrSet<const Value *, 32> EphValues;
212 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
215 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
217 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
218 NumCalls = Metrics.NumInlineCandidates;
219 NotDuplicatable = Metrics.notDuplicatable;
221 unsigned LoopSize = Metrics.NumInsts;
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. Also, the code using this size may assume
226 // that each loop has at least three instructions (likely a conditional
227 // branch, a comparison feeding that branch, and some kind of loop increment
228 // feeding that comparison instruction).
229 LoopSize = std::max(LoopSize, 3u);
234 // Returns the loop hint metadata node with the given name (for example,
235 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
237 static const MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
238 MDNode *LoopID = L->getLoopID();
241 return GetUnrollMetadata(LoopID, Name);
244 // Returns true if the loop has an unroll(full) pragma.
245 static bool HasUnrollFullPragma(const Loop *L) {
246 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
249 // Returns true if the loop has an unroll(disable) pragma.
250 static bool HasUnrollDisablePragma(const Loop *L) {
251 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
254 // If loop has an unroll_count pragma return the (necessarily
255 // positive) value from the pragma. Otherwise return 0.
256 static unsigned UnrollCountPragmaValue(const Loop *L) {
257 const MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
259 assert(MD->getNumOperands() == 2 &&
260 "Unroll count hint metadata should have two operands.");
262 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
263 assert(Count >= 1 && "Unroll count must be positive.");
269 // Remove existing unroll metadata and add unroll disable metadata to
270 // indicate the loop has already been unrolled. This prevents a loop
271 // from being unrolled more than is directed by a pragma if the loop
272 // unrolling pass is run more than once (which it generally is).
273 static void SetLoopAlreadyUnrolled(Loop *L) {
274 MDNode *LoopID = L->getLoopID();
277 // First remove any existing loop unrolling metadata.
278 SmallVector<Metadata *, 4> MDs;
279 // Reserve first location for self reference to the LoopID metadata node.
280 MDs.push_back(nullptr);
281 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
282 bool IsUnrollMetadata = false;
283 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
285 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
286 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
288 if (!IsUnrollMetadata)
289 MDs.push_back(LoopID->getOperand(i));
292 // Add unroll(disable) metadata to disable future unrolling.
293 LLVMContext &Context = L->getHeader()->getContext();
294 SmallVector<Metadata *, 1> DisableOperands;
295 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
296 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
297 MDs.push_back(DisableNode);
299 MDNode *NewLoopID = MDNode::get(Context, MDs);
300 // Set operand 0 to refer to the loop id itself.
301 NewLoopID->replaceOperandWith(0, NewLoopID);
302 L->setLoopID(NewLoopID);
305 unsigned LoopUnroll::selectUnrollCount(
306 const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
307 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
308 bool &SetExplicitly) {
309 SetExplicitly = true;
311 // User-specified count (either as a command-line option or
312 // constructor parameter) has highest precedence.
313 unsigned Count = UserCount ? CurrentCount : 0;
315 // If there is no user-specified count, unroll pragmas have the next
316 // highest precendence.
320 } else if (PragmaFullUnroll) {
329 SetExplicitly = false;
331 // Runtime trip count.
332 Count = UnrollRuntimeCount;
334 // Conservative heuristic: if we know the trip count, see if we can
335 // completely unroll (subject to the threshold, checked below); otherwise
336 // try to find greatest modulo of the trip count which is still under
340 if (TripCount && Count > TripCount)
345 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
346 if (skipOptnoneFunction(L))
349 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
350 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
351 const TargetTransformInfo &TTI =
352 getAnalysis<TargetTransformInfoWrapperPass>().getTTI();
353 const FunctionTargetTransformInfo &FTTI =
354 getAnalysis<FunctionTargetTransformInfo>();
355 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
356 *L->getHeader()->getParent());
358 BasicBlock *Header = L->getHeader();
359 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
360 << "] Loop %" << Header->getName() << "\n");
362 if (HasUnrollDisablePragma(L)) {
365 bool PragmaFullUnroll = HasUnrollFullPragma(L);
366 unsigned PragmaCount = UnrollCountPragmaValue(L);
367 bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
369 TargetTransformInfo::UnrollingPreferences UP;
370 getUnrollingPreferences(L, FTTI, UP);
372 // Find trip count and trip multiple if count is not available
373 unsigned TripCount = 0;
374 unsigned TripMultiple = 1;
375 // If there are multiple exiting blocks but one of them is the latch, use the
376 // latch for the trip count estimation. Otherwise insist on a single exiting
377 // block for the trip count estimation.
378 BasicBlock *ExitingBlock = L->getLoopLatch();
379 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
380 ExitingBlock = L->getExitingBlock();
382 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
383 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
386 // Select an initial unroll count. This may be reduced later based
387 // on size thresholds.
388 bool CountSetExplicitly;
389 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
390 PragmaCount, UP, CountSetExplicitly);
392 unsigned NumInlineCandidates;
393 bool notDuplicatable;
395 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
396 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
398 // When computing the unrolled size, note that the conditional branch on the
399 // backedge and the comparison feeding it are not replicated like the rest of
400 // the loop body (which is why 2 is subtracted).
401 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
402 if (notDuplicatable) {
403 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
404 << " instructions.\n");
407 if (NumInlineCandidates != 0) {
408 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
412 unsigned Threshold, PartialThreshold;
413 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold);
415 // Given Count, TripCount and thresholds determine the type of
416 // unrolling which is to be performed.
417 enum { Full = 0, Partial = 1, Runtime = 2 };
419 if (TripCount && Count == TripCount) {
420 if (Threshold != NoThreshold && UnrolledSize > Threshold) {
421 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
422 << " because size: " << UnrolledSize << ">" << Threshold
428 } else if (TripCount && Count < TripCount) {
434 // Reduce count based on the type of unrolling and the threshold values.
435 unsigned OriginalCount = Count;
436 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
437 if (Unrolling == Partial) {
438 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
439 if (!AllowPartial && !CountSetExplicitly) {
440 DEBUG(dbgs() << " will not try to unroll partially because "
441 << "-unroll-allow-partial not given\n");
444 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
445 // Reduce unroll count to be modulo of TripCount for partial unrolling.
446 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
447 while (Count != 0 && TripCount % Count != 0)
450 } else if (Unrolling == Runtime) {
451 if (!AllowRuntime && !CountSetExplicitly) {
452 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
453 << "-unroll-runtime not given\n");
456 // Reduce unroll count to be the largest power-of-two factor of
457 // the original count which satisfies the threshold limit.
458 while (Count != 0 && UnrolledSize > PartialThreshold) {
460 UnrolledSize = (LoopSize-2) * Count + 2;
462 if (Count > UP.MaxCount)
464 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
468 if (PragmaCount != 0)
469 // If loop has an unroll count pragma mark loop as unrolled to prevent
470 // unrolling beyond that requested by the pragma.
471 SetLoopAlreadyUnrolled(L);
473 // Emit optimization remarks if we are unable to unroll the loop
474 // as directed by a pragma.
475 DebugLoc LoopLoc = L->getStartLoc();
476 Function *F = Header->getParent();
477 LLVMContext &Ctx = F->getContext();
478 if (PragmaFullUnroll && PragmaCount == 0) {
479 if (TripCount && Count != TripCount) {
480 emitOptimizationRemarkMissed(
481 Ctx, DEBUG_TYPE, *F, LoopLoc,
482 "Unable to fully unroll loop as directed by unroll(full) pragma "
483 "because unrolled size is too large.");
484 } else if (!TripCount) {
485 emitOptimizationRemarkMissed(
486 Ctx, DEBUG_TYPE, *F, LoopLoc,
487 "Unable to fully unroll loop as directed by unroll(full) pragma "
488 "because loop has a runtime trip count.");
490 } else if (PragmaCount > 0 && Count != OriginalCount) {
491 emitOptimizationRemarkMissed(
492 Ctx, DEBUG_TYPE, *F, LoopLoc,
493 "Unable to unroll loop the number of times directed by "
494 "unroll_count pragma because unrolled size is too large.");
498 if (Unrolling != Full && Count < 2) {
499 // Partial unrolling by 1 is a nop. For full unrolling, a factor
500 // of 1 makes sense because loop control can be eliminated.
505 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this,