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/IntrinsicInst.h"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/CodeMetrics.h"
20 #include "llvm/Analysis/ScalarEvolution.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Transforms/Utils/UnrollLoop.h"
29 static cl::opt<unsigned>
30 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
31 cl::desc("The cut-off point for automatic loop unrolling"));
33 static cl::opt<unsigned>
34 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
35 cl::desc("Use this unroll count for all loops, for testing purposes"));
38 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
39 cl::desc("Allows loops to be partially unrolled until "
40 "-unroll-threshold loop size is reached."));
43 class LoopUnroll : public LoopPass {
45 static char ID; // Pass ID, replacement for typeid
46 LoopUnroll(int T = -1, int C = -1, int P = -1) : LoopPass(ID) {
47 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
48 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
49 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
51 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
53 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
56 /// A magic value for use with the Threshold parameter to indicate
57 /// that the loop unroll should be performed regardless of how much
58 /// code expansion would result.
59 static const unsigned NoThreshold = UINT_MAX;
61 // Threshold to use when optsize is specified (and there is no
62 // explicit -unroll-threshold).
63 static const unsigned OptSizeUnrollThreshold = 50;
65 unsigned CurrentCount;
66 unsigned CurrentThreshold;
67 bool CurrentAllowPartial;
68 bool UserThreshold; // CurrentThreshold is user-specified.
70 bool runOnLoop(Loop *L, LPPassManager &LPM);
72 /// This transformation requires natural loop information & requires that
73 /// loop preheaders be inserted into the CFG...
75 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addRequired<LoopInfo>();
77 AU.addPreserved<LoopInfo>();
78 AU.addRequiredID(LoopSimplifyID);
79 AU.addPreservedID(LoopSimplifyID);
80 AU.addRequiredID(LCSSAID);
81 AU.addPreservedID(LCSSAID);
82 AU.addRequired<ScalarEvolution>();
83 AU.addPreserved<ScalarEvolution>();
84 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
85 // If loop unroll does not preserve dom info then LCSSA pass on next
86 // loop will receive invalid dom info.
87 // For now, recreate dom info, if loop is unrolled.
88 AU.addPreserved<DominatorTree>();
93 char LoopUnroll::ID = 0;
94 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
95 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
96 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
97 INITIALIZE_PASS_DEPENDENCY(LCSSA)
98 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
100 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial) {
101 return new LoopUnroll(Threshold, Count, AllowPartial);
104 /// ApproximateLoopSize - Approximate the size of the loop.
105 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls) {
107 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
109 Metrics.analyzeBasicBlock(*I);
110 NumCalls = Metrics.NumInlineCandidates;
112 unsigned LoopSize = Metrics.NumInsts;
114 // Don't allow an estimate of size zero. This would allows unrolling of loops
115 // with huge iteration counts, which is a compile time problem even if it's
116 // not a problem for code quality.
117 if (LoopSize == 0) LoopSize = 1;
122 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
123 LoopInfo *LI = &getAnalysis<LoopInfo>();
125 BasicBlock *Header = L->getHeader();
126 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
127 << "] Loop %" << Header->getName() << "\n");
130 // Determine the current unrolling threshold. While this is normally set
131 // from UnrollThreshold, it is overridden to a smaller value if the current
132 // function is marked as optimize-for-size, and the unroll threshold was
133 // not user specified.
134 unsigned Threshold = CurrentThreshold;
135 if (!UserThreshold &&
136 Header->getParent()->hasFnAttr(Attribute::OptimizeForSize))
137 Threshold = OptSizeUnrollThreshold;
140 unsigned TripCount = L->getSmallConstantTripCount();
142 // Find trip multiple if count is not available
143 unsigned TripMultiple = 1;
145 TripMultiple = L->getSmallConstantTripMultiple();
147 // Automatically select an unroll count.
148 unsigned Count = CurrentCount;
150 // Conservative heuristic: if we know the trip count, see if we can
151 // completely unroll (subject to the threshold, checked below); otherwise
152 // try to find greatest modulo of the trip count which is still under
159 // Enforce the threshold.
160 if (Threshold != NoThreshold) {
161 unsigned NumInlineCandidates;
162 unsigned LoopSize = ApproximateLoopSize(L, NumInlineCandidates);
163 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
164 if (NumInlineCandidates != 0) {
165 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
168 uint64_t Size = (uint64_t)LoopSize*Count;
169 if (TripCount != 1 && Size > Threshold) {
170 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
171 << " because size: " << Size << ">" << Threshold << "\n");
172 if (!CurrentAllowPartial) {
173 DEBUG(dbgs() << " will not try to unroll partially because "
174 << "-unroll-allow-partial not given\n");
177 // Reduce unroll count to be modulo of TripCount for partial unrolling
178 Count = Threshold / LoopSize;
179 while (Count != 0 && TripCount%Count != 0) {
183 DEBUG(dbgs() << " could not unroll partially\n");
186 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
191 if (!UnrollLoop(L, Count, TripCount, TripMultiple, LI, &LPM))