Fix typo in code to cap the loop code size reduction calculation.
[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/IntrinsicInst.h"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/InlineCost.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"
25 #include <climits>
26
27 using namespace llvm;
28
29 static cl::opt<unsigned>
30 UnrollThreshold("unroll-threshold", cl::init(0), cl::Hidden,
31   cl::desc("The cut-off point for automatic loop unrolling"));
32
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"));
36
37 static cl::opt<bool>
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."));
41
42 namespace {
43   class LoopUnroll : public LoopPass {
44   public:
45     static char ID; // Pass ID, replacement for typeid
46     LoopUnroll() : LoopPass(ID) {}
47
48     /// A magic value for use with the Threshold parameter to indicate
49     /// that the loop unroll should be performed regardless of how much
50     /// code expansion would result.
51     static const unsigned NoThreshold = UINT_MAX;
52     
53     // Threshold to use when optsize is specified (and there is no
54     // explicit -unroll-threshold).
55     static const unsigned OptSizeUnrollThreshold = 50;
56     
57     unsigned CurrentThreshold;
58
59     bool runOnLoop(Loop *L, LPPassManager &LPM);
60
61     /// This transformation requires natural loop information & requires that
62     /// loop preheaders be inserted into the CFG...
63     ///
64     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65       AU.addRequired<LoopInfo>();
66       AU.addPreserved<LoopInfo>();
67       AU.addRequiredID(LoopSimplifyID);
68       AU.addPreservedID(LoopSimplifyID);
69       AU.addRequiredID(LCSSAID);
70       AU.addPreservedID(LCSSAID);
71       AU.addPreserved<ScalarEvolution>();
72       // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
73       // If loop unroll does not preserve dom info then LCSSA pass on next
74       // loop will receive invalid dom info.
75       // For now, recreate dom info, if loop is unrolled.
76       AU.addPreserved<DominatorTree>();
77     }
78   };
79 }
80
81 char LoopUnroll::ID = 0;
82 INITIALIZE_PASS(LoopUnroll, "loop-unroll", "Unroll loops", false, false);
83
84 Pass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
85
86 /// ApproximateLoopSize - Approximate the size of the loop.
87 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls) {
88   CodeMetrics Metrics;
89   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
90        I != E; ++I)
91     Metrics.analyzeBasicBlock(*I);
92   NumCalls = Metrics.NumCalls;
93   
94   unsigned LoopSize = Metrics.NumInsts;
95   
96   // If we can identify the induction variable, we know that it will become
97   // constant when we unroll the loop, so factor that into our loop size 
98   // estimate.
99   // FIXME: We have to divide by InlineConstants::InstrCost because the
100   // measure returned by CountCodeReductionForConstant is not an instruction
101   // count, but rather a weight as defined by InlineConstants.  It would 
102   // probably be a good idea to standardize on a single weighting scheme by
103   // pushing more of the logic for weighting into CodeMetrics.
104   if (PHINode *IndVar = L->getCanonicalInductionVariable()) {
105     unsigned SizeDecrease = Metrics.CountCodeReductionForConstant(IndVar);
106     // NOTE: Because SizeDecrease is a fuzzy estimate, we don't want to allow
107     // it to totally negate the cost of unrolling a loop.
108     SizeDecrease = SizeDecrease > LoopSize / 2 ? LoopSize / 2 : SizeDecrease;
109   }
110   
111   // Don't allow an estimate of size zero.  This would allows unrolling of loops
112   // with huge iteration counts, which is a compile time problem even if it's
113   // not a problem for code quality.
114   if (LoopSize == 0) LoopSize = 1;
115   
116   return LoopSize;
117 }
118
119 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
120   
121   LoopInfo *LI = &getAnalysis<LoopInfo>();
122
123   BasicBlock *Header = L->getHeader();
124   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
125         << "] Loop %" << Header->getName() << "\n");
126   (void)Header;
127   
128   // Determine the current unrolling threshold.  While this is normally set
129   // from UnrollThreshold, it is overridden to a smaller value if the current
130   // function is marked as optimize-for-size, and the unroll threshold was
131   // not user specified.
132   CurrentThreshold = UnrollThreshold;
133   if (Header->getParent()->hasFnAttr(Attribute::OptimizeForSize) &&
134       UnrollThreshold.getNumOccurrences() == 0)
135     CurrentThreshold = OptSizeUnrollThreshold;
136
137   // Find trip count
138   unsigned TripCount = L->getSmallConstantTripCount();
139   unsigned Count = UnrollCount;
140
141   // Automatically select an unroll count.
142   if (Count == 0) {
143     // Conservative heuristic: if we know the trip count, see if we can
144     // completely unroll (subject to the threshold, checked below); otherwise
145     // try to find greatest modulo of the trip count which is still under
146     // threshold value.
147     if (TripCount == 0)
148       return false;
149     Count = TripCount;
150   }
151
152   // Enforce the threshold.
153   if (CurrentThreshold != NoThreshold) {
154     unsigned NumCalls;
155     unsigned LoopSize = ApproximateLoopSize(L, NumCalls);
156     DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
157     if (NumCalls != 0) {
158       // Even for a loop that contains calls, it can still be profitable to
159       // unroll if the loop is really, REALLY small.
160       DEBUG(dbgs() <<"  Using lower threshold for loop with function calls.\n");
161       CurrentThreshold = OptSizeUnrollThreshold;
162     }
163     uint64_t Size = (uint64_t)LoopSize*Count;
164     if (TripCount != 1 && Size > CurrentThreshold) {
165       DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
166             << " because size: " << Size << ">" << CurrentThreshold << "\n");
167       if (!UnrollAllowPartial) {
168         DEBUG(dbgs() << "  will not try to unroll partially because "
169               << "-unroll-allow-partial not given\n");
170         return false;
171       }
172       // Reduce unroll count to be modulo of TripCount for partial unrolling
173       Count = CurrentThreshold / LoopSize;
174       while (Count != 0 && TripCount%Count != 0) {
175         Count--;
176       }
177       if (Count < 2) {
178         DEBUG(dbgs() << "  could not unroll partially\n");
179         return false;
180       }
181       DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
182     }
183   }
184
185   // Unroll the loop.
186   Function *F = L->getHeader()->getParent();
187   if (!UnrollLoop(L, Count, LI, &LPM))
188     return false;
189
190   // FIXME: Reconstruct dom info, because it is not preserved properly.
191   if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
192     DT->runOnFunction(*F);
193   return true;
194 }