Add getUnrollingPreferences to TTI
[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 #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"
27 #include <climits>
28
29 using namespace llvm;
30
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"));
34
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"));
38
39 static cl::opt<bool>
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."));
43
44 static cl::opt<bool>
45 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
46   cl::desc("Unroll loops with run-time trip counts"));
47
48 namespace {
49   class LoopUnroll : public LoopPass {
50   public:
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;
56
57       UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
58       UserAllowPartial = (P != -1) ||
59                          (UnrollAllowPartial.getNumOccurrences() > 0);
60       UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
61
62       initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
63     }
64
65     /// A magic value for use with the Threshold parameter to indicate
66     /// that the loop unroll should be performed regardless of how much
67     /// code expansion would result.
68     static const unsigned NoThreshold = UINT_MAX;
69
70     // Threshold to use when optsize is specified (and there is no
71     // explicit -unroll-threshold).
72     static const unsigned OptSizeUnrollThreshold = 50;
73
74     // Default unroll count for loops with run-time trip count if
75     // -unroll-count is not set
76     static const unsigned UnrollRuntimeCount = 8;
77
78     unsigned CurrentCount;
79     unsigned CurrentThreshold;
80     bool     CurrentAllowPartial;
81     bool     UserCount;            // CurrentCount is user-specified.
82     bool     UserThreshold;        // CurrentThreshold is user-specified.
83     bool     UserAllowPartial;     // CurrentAllowPartial is user-specified.
84
85     bool runOnLoop(Loop *L, LPPassManager &LPM);
86
87     /// This transformation requires natural loop information & requires that
88     /// loop preheaders be inserted into the CFG...
89     ///
90     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
91       AU.addRequired<LoopInfo>();
92       AU.addPreserved<LoopInfo>();
93       AU.addRequiredID(LoopSimplifyID);
94       AU.addPreservedID(LoopSimplifyID);
95       AU.addRequiredID(LCSSAID);
96       AU.addPreservedID(LCSSAID);
97       AU.addRequired<ScalarEvolution>();
98       AU.addPreserved<ScalarEvolution>();
99       AU.addRequired<TargetTransformInfo>();
100       // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
101       // If loop unroll does not preserve dom info then LCSSA pass on next
102       // loop will receive invalid dom info.
103       // For now, recreate dom info, if loop is unrolled.
104       AU.addPreserved<DominatorTree>();
105     }
106   };
107 }
108
109 char LoopUnroll::ID = 0;
110 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
111 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
112 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
113 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
114 INITIALIZE_PASS_DEPENDENCY(LCSSA)
115 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
116 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
117
118 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial) {
119   return new LoopUnroll(Threshold, Count, AllowPartial);
120 }
121
122 /// ApproximateLoopSize - Approximate the size of the loop.
123 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
124                                     bool &NotDuplicatable,
125                                     const TargetTransformInfo &TTI) {
126   CodeMetrics Metrics;
127   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
128        I != E; ++I)
129     Metrics.analyzeBasicBlock(*I, TTI);
130   NumCalls = Metrics.NumInlineCandidates;
131   NotDuplicatable = Metrics.notDuplicatable;
132
133   unsigned LoopSize = Metrics.NumInsts;
134
135   // Don't allow an estimate of size zero.  This would allows unrolling of loops
136   // with huge iteration counts, which is a compile time problem even if it's
137   // not a problem for code quality.
138   if (LoopSize == 0) LoopSize = 1;
139
140   return LoopSize;
141 }
142
143 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
144   LoopInfo *LI = &getAnalysis<LoopInfo>();
145   ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
146   const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
147
148   BasicBlock *Header = L->getHeader();
149   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
150         << "] Loop %" << Header->getName() << "\n");
151   (void)Header;
152
153   TargetTransformInfo::UnrollingPreferences UP;
154   UP.Threshold = CurrentThreshold;
155   UP.OptSizeThreshold = OptSizeUnrollThreshold;
156   UP.Count = CurrentCount;
157   UP.Partial = CurrentAllowPartial;
158   UP.Runtime = UnrollRuntime;
159   TTI.getUnrollingPreferences(L, UP);
160
161   // Determine the current unrolling threshold.  While this is normally set
162   // from UnrollThreshold, it is overridden to a smaller value if the current
163   // function is marked as optimize-for-size, and the unroll threshold was
164   // not user specified.
165   unsigned Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
166   if (!UserThreshold &&
167       Header->getParent()->getAttributes().
168         hasAttribute(AttributeSet::FunctionIndex,
169                      Attribute::OptimizeForSize))
170     Threshold = UP.OptSizeThreshold;
171
172   // Find trip count and trip multiple if count is not available
173   unsigned TripCount = 0;
174   unsigned TripMultiple = 1;
175   // Find "latch trip count". UnrollLoop assumes that control cannot exit
176   // via the loop latch on any iteration prior to TripCount. The loop may exit
177   // early via an earlier branch.
178   BasicBlock *LatchBlock = L->getLoopLatch();
179   if (LatchBlock) {
180     TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
181     TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
182   }
183
184   bool Runtime = UnrollRuntime.getNumOccurrences() == 0 ?
185                  UP.Runtime : UnrollRuntime;
186
187   // Use a default unroll-count if the user doesn't specify a value
188   // and the trip count is a run-time value.  The default is different
189   // for run-time or compile-time trip count loops.
190   unsigned Count = UserCount ? CurrentCount : UP.Count;
191   if (Runtime && Count == 0 && TripCount == 0)
192     Count = UnrollRuntimeCount;
193
194   if (Count == 0) {
195     // Conservative heuristic: if we know the trip count, see if we can
196     // completely unroll (subject to the threshold, checked below); otherwise
197     // try to find greatest modulo of the trip count which is still under
198     // threshold value.
199     if (TripCount == 0)
200       return false;
201     Count = TripCount;
202   }
203
204   // Enforce the threshold.
205   if (Threshold != NoThreshold) {
206     unsigned NumInlineCandidates;
207     bool notDuplicatable;
208     unsigned LoopSize = ApproximateLoopSize(L, NumInlineCandidates,
209                                             notDuplicatable, TTI);
210     DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
211     if (notDuplicatable) {
212       DEBUG(dbgs() << "  Not unrolling loop which contains non duplicatable"
213             << " instructions.\n");
214       return false;
215     }
216     if (NumInlineCandidates != 0) {
217       DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
218       return false;
219     }
220     uint64_t Size = (uint64_t)LoopSize*Count;
221     if (TripCount != 1 && Size > Threshold) {
222       DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
223             << " because size: " << Size << ">" << Threshold << "\n");
224       bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
225       if (!AllowPartial && !(Runtime && TripCount == 0)) {
226         DEBUG(dbgs() << "  will not try to unroll partially because "
227               << "-unroll-allow-partial not given\n");
228         return false;
229       }
230       if (TripCount) {
231         // Reduce unroll count to be modulo of TripCount for partial unrolling
232         Count = Threshold / LoopSize;
233         while (Count != 0 && TripCount%Count != 0)
234           Count--;
235       }
236       else if (Runtime) {
237         // Reduce unroll count to be a lower power-of-two value
238         while (Count != 0 && Size > Threshold) {
239           Count >>= 1;
240           Size = LoopSize*Count;
241         }
242       }
243       if (Count < 2) {
244         DEBUG(dbgs() << "  could not unroll partially\n");
245         return false;
246       }
247       DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
248     }
249   }
250
251   // Unroll the loop.
252   if (!UnrollLoop(L, Count, TripCount, Runtime, TripMultiple, LI, &LPM))
253     return false;
254
255   return true;
256 }