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 #define DEBUG_TYPE "loop-unroll"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/ScalarEvolution.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Transforms/Utils/UnrollLoop.h"
31 static cl::opt<unsigned>
32 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
33 cl::desc("The cut-off point for automatic loop unrolling"));
35 static cl::opt<unsigned>
36 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
37 cl::desc("Use this unroll count for all loops, for testing purposes"));
40 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
41 cl::desc("Allows loops to be partially unrolled until "
42 "-unroll-threshold loop size is reached."));
45 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
46 cl::desc("Unroll loops with run-time trip counts"));
49 class LoopUnroll : public LoopPass {
51 static char ID; // Pass ID, replacement for typeid
52 LoopUnroll(int T = -1, int C = -1, int P = -1) : LoopPass(ID) {
53 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
54 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
55 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
57 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
58 UserAllowPartial = (P != -1) ||
59 (UnrollAllowPartial.getNumOccurrences() > 0);
61 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
64 /// A magic value for use with the Threshold parameter to indicate
65 /// that the loop unroll should be performed regardless of how much
66 /// code expansion would result.
67 static const unsigned NoThreshold = UINT_MAX;
69 // Threshold to use when optsize is specified (and there is no
70 // explicit -unroll-threshold).
71 static const unsigned OptSizeUnrollThreshold = 50;
73 // Default unroll count for loops with run-time trip count if
74 // -unroll-count is not set
75 static const unsigned UnrollRuntimeCount = 8;
77 unsigned CurrentCount;
78 unsigned CurrentThreshold;
79 bool CurrentAllowPartial;
80 bool UserThreshold; // CurrentThreshold is user-specified.
81 bool UserAllowPartial; // CurrentAllowPartial is user-specified.
83 bool runOnLoop(Loop *L, LPPassManager &LPM);
85 /// This transformation requires natural loop information & requires that
86 /// loop preheaders be inserted into the CFG...
88 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
89 AU.addRequired<LoopInfo>();
90 AU.addPreserved<LoopInfo>();
91 AU.addRequiredID(LoopSimplifyID);
92 AU.addPreservedID(LoopSimplifyID);
93 AU.addRequiredID(LCSSAID);
94 AU.addPreservedID(LCSSAID);
95 AU.addRequired<ScalarEvolution>();
96 AU.addPreserved<ScalarEvolution>();
97 AU.addRequired<TargetTransformInfo>();
98 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
99 // If loop unroll does not preserve dom info then LCSSA pass on next
100 // loop will receive invalid dom info.
101 // For now, recreate dom info, if loop is unrolled.
102 AU.addPreserved<DominatorTree>();
107 char LoopUnroll::ID = 0;
108 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
109 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
110 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
111 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
112 INITIALIZE_PASS_DEPENDENCY(LCSSA)
113 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
114 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
116 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial) {
117 return new LoopUnroll(Threshold, Count, AllowPartial);
120 /// ApproximateLoopSize - Approximate the size of the loop.
121 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
122 bool &NotDuplicatable,
123 const TargetTransformInfo &TTI) {
125 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
127 Metrics.analyzeBasicBlock(*I, TTI);
128 NumCalls = Metrics.NumInlineCandidates;
129 NotDuplicatable = Metrics.notDuplicatable;
131 unsigned LoopSize = Metrics.NumInsts;
133 // Don't allow an estimate of size zero. This would allows unrolling of loops
134 // with huge iteration counts, which is a compile time problem even if it's
135 // not a problem for code quality.
136 if (LoopSize == 0) LoopSize = 1;
141 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
142 LoopInfo *LI = &getAnalysis<LoopInfo>();
143 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
144 const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
146 BasicBlock *Header = L->getHeader();
147 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
148 << "] Loop %" << Header->getName() << "\n");
151 TargetTransformInfo::UnrollingPreferences UP;
152 bool HasUP = TTI.getUnrollingPreferences(UP);
154 // Determine the current unrolling threshold. While this is normally set
155 // from UnrollThreshold, it is overridden to a smaller value if the current
156 // function is marked as optimize-for-size, and the unroll threshold was
157 // not user specified.
158 unsigned Threshold = (HasUP && !UserThreshold) ? UP.Threshold :
160 if (!UserThreshold &&
161 Header->getParent()->getAttributes().
162 hasAttribute(AttributeSet::FunctionIndex,
163 Attribute::OptimizeForSize))
164 Threshold = HasUP ? UP.OptSizeThreshold : OptSizeUnrollThreshold;
166 // Find trip count and trip multiple if count is not available
167 unsigned TripCount = 0;
168 unsigned TripMultiple = 1;
169 // Find "latch trip count". UnrollLoop assumes that control cannot exit
170 // via the loop latch on any iteration prior to TripCount. The loop may exit
171 // early via an earlier branch.
172 BasicBlock *LatchBlock = L->getLoopLatch();
174 TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
175 TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
177 // Use a default unroll-count if the user doesn't specify a value
178 // and the trip count is a run-time value. The default is different
179 // for run-time or compile-time trip count loops.
180 unsigned Count = CurrentCount;
181 if (UnrollRuntime && CurrentCount == 0 && TripCount == 0)
182 Count = UnrollRuntimeCount;
185 // Conservative heuristic: if we know the trip count, see if we can
186 // completely unroll (subject to the threshold, checked below); otherwise
187 // try to find greatest modulo of the trip count which is still under
194 bool Runtime = (HasUP && UnrollRuntime.getNumOccurrences() == 0) ?
195 UP.Runtime : UnrollRuntime;
197 // Enforce the threshold.
198 if (Threshold != NoThreshold) {
199 unsigned NumInlineCandidates;
200 bool notDuplicatable;
201 unsigned LoopSize = ApproximateLoopSize(L, NumInlineCandidates,
202 notDuplicatable, TTI);
203 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
204 if (notDuplicatable) {
205 DEBUG(dbgs() << " Not unrolling loop which contains non duplicatable"
206 << " instructions.\n");
209 if (NumInlineCandidates != 0) {
210 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
213 uint64_t Size = (uint64_t)LoopSize*Count;
214 if (TripCount != 1 && Size > Threshold) {
215 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
216 << " because size: " << Size << ">" << Threshold << "\n");
217 bool AllowPartial = (HasUP && !UserAllowPartial) ? UP.Partial :
219 if (!AllowPartial && !(Runtime && TripCount == 0)) {
220 DEBUG(dbgs() << " will not try to unroll partially because "
221 << "-unroll-allow-partial not given\n");
225 // Reduce unroll count to be modulo of TripCount for partial unrolling
226 Count = Threshold / LoopSize;
227 while (Count != 0 && TripCount%Count != 0)
231 // Reduce unroll count to be a lower power-of-two value
232 while (Count != 0 && Size > Threshold) {
234 Size = LoopSize*Count;
238 DEBUG(dbgs() << " could not unroll partially\n");
241 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
246 if (!UnrollLoop(L, Count, TripCount, Runtime, TripMultiple, LI, &LPM))