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
61       initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
62     }
63
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;
68
69     // Threshold to use when optsize is specified (and there is no
70     // explicit -unroll-threshold).
71     static const unsigned OptSizeUnrollThreshold = 50;
72
73     // Default unroll count for loops with run-time trip count if
74     // -unroll-count is not set
75     static const unsigned UnrollRuntimeCount = 8;
76
77     unsigned CurrentCount;
78     unsigned CurrentThreshold;
79     bool     CurrentAllowPartial;
80     bool     UserThreshold;        // CurrentThreshold is user-specified.
81     bool     UserAllowPartial;     // CurrentAllowPartial is user-specified.
82
83     bool runOnLoop(Loop *L, LPPassManager &LPM);
84
85     /// This transformation requires natural loop information & requires that
86     /// loop preheaders be inserted into the CFG...
87     ///
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>();
103     }
104   };
105 }
106
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)
115
116 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial) {
117   return new LoopUnroll(Threshold, Count, AllowPartial);
118 }
119
120 /// ApproximateLoopSize - Approximate the size of the loop.
121 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
122                                     bool &NotDuplicatable,
123                                     const TargetTransformInfo &TTI) {
124   CodeMetrics Metrics;
125   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
126        I != E; ++I)
127     Metrics.analyzeBasicBlock(*I, TTI);
128   NumCalls = Metrics.NumInlineCandidates;
129   NotDuplicatable = Metrics.notDuplicatable;
130
131   unsigned LoopSize = Metrics.NumInsts;
132
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;
137
138   return LoopSize;
139 }
140
141 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
142   LoopInfo *LI = &getAnalysis<LoopInfo>();
143   ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
144   const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
145
146   BasicBlock *Header = L->getHeader();
147   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
148         << "] Loop %" << Header->getName() << "\n");
149   (void)Header;
150
151   TargetTransformInfo::UnrollingPreferences UP;
152   bool HasUP = TTI.getUnrollingPreferences(UP);
153
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 :
159                                                    CurrentThreshold;
160   if (!UserThreshold &&
161       Header->getParent()->getAttributes().
162         hasAttribute(AttributeSet::FunctionIndex,
163                      Attribute::OptimizeForSize))
164     Threshold = HasUP ? UP.OptSizeThreshold : OptSizeUnrollThreshold;
165
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();
173   if (LatchBlock) {
174     TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
175     TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
176   }
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;
183
184   if (Count == 0) {
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
188     // threshold value.
189     if (TripCount == 0)
190       return false;
191     Count = TripCount;
192   }
193
194   bool Runtime = (HasUP && UnrollRuntime.getNumOccurrences() == 0) ?
195                  UP.Runtime : UnrollRuntime;
196
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");
207       return false;
208     }
209     if (NumInlineCandidates != 0) {
210       DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
211       return false;
212     }
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 :
218                                                          CurrentAllowPartial;
219       if (!AllowPartial && !(Runtime && TripCount == 0)) {
220         DEBUG(dbgs() << "  will not try to unroll partially because "
221               << "-unroll-allow-partial not given\n");
222         return false;
223       }
224       if (TripCount) {
225         // Reduce unroll count to be modulo of TripCount for partial unrolling
226         Count = Threshold / LoopSize;
227         while (Count != 0 && TripCount%Count != 0)
228           Count--;
229       }
230       else if (Runtime) {
231         // Reduce unroll count to be a lower power-of-two value
232         while (Count != 0 && Size > Threshold) {
233           Count >>= 1;
234           Size = LoopSize*Count;
235         }
236       }
237       if (Count < 2) {
238         DEBUG(dbgs() << "  could not unroll partially\n");
239         return false;
240       }
241       DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
242     }
243   }
244
245   // Unroll the loop.
246   if (!UnrollLoop(L, Count, TripCount, Runtime, TripMultiple, LI, &LPM))
247     return false;
248
249   return true;
250 }