fb8027c14fdca8918636f77f87196c1aa24e431c
[oota-llvm.git] / lib / Analysis / LoopInfo.cpp
1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
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 file defines the LoopInfo class that is used to identify natural loops
11 // and determine the loop depth of various nodes of the CFG.  Note that the
12 // loops identified may actually be several natural loops that share the same
13 // header node... not just a single natural loop.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Support/Streams.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include <algorithm>
27 using namespace llvm;
28
29 char LoopInfo::ID = 0;
30 static RegisterPass<LoopInfo>
31 X("loops", "Natural Loop Information", true, true);
32
33 //===----------------------------------------------------------------------===//
34 // Loop implementation
35 //
36
37 /// isLoopInvariant - Return true if the specified value is loop invariant
38 ///
39 bool Loop::isLoopInvariant(Value *V) const {
40   if (Instruction *I = dyn_cast<Instruction>(V))
41     return isLoopInvariant(I);
42   return true;  // All non-instructions are loop invariant
43 }
44
45 /// isLoopInvariant - Return true if the specified instruction is
46 /// loop-invariant.
47 ///
48 bool Loop::isLoopInvariant(Instruction *I) const {
49   return !contains(I->getParent());
50 }
51
52 /// makeLoopInvariant - If the given value is an instruciton inside of the
53 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
54 /// Return true if the value after any hoisting is loop invariant. This
55 /// function can be used as a slightly more aggressive replacement for
56 /// isLoopInvariant.
57 ///
58 /// If InsertPt is specified, it is the point to hoist instructions to.
59 /// If null, the terminator of the loop preheader is used.
60 ///
61 bool Loop::makeLoopInvariant(Value *V, Instruction *InsertPt) const {
62   if (Instruction *I = dyn_cast<Instruction>(V))
63     return makeLoopInvariant(I);
64   return true;  // All non-instructions are loop-invariant.
65 }
66
67 /// makeLoopInvariant - If the given instruction is inside of the
68 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
69 /// Return true if the instruction after any hoisting is loop invariant. This
70 /// function can be used as a slightly more aggressive replacement for
71 /// isLoopInvariant.
72 ///
73 /// If InsertPt is specified, it is the point to hoist instructions to.
74 /// If null, the terminator of the loop preheader is used.
75 ///
76 bool Loop::makeLoopInvariant(Instruction *I, Instruction *InsertPt) const {
77   // Test if the value is already loop-invariant.
78   if (isLoopInvariant(I))
79     return true;
80   // Don't hoist instructions with side-effects.
81   if (I->isTrapping())
82     return false;
83   // Don't hoist PHI nodes.
84   if (isa<PHINode>(I))
85     return false;
86   // Don't hoist allocation instructions.
87   if (isa<AllocationInst>(I))
88     return false;
89   // Determine the insertion point, unless one was given.
90   if (!InsertPt) {
91     BasicBlock *Preheader = getLoopPreheader();
92     // Without a preheader, hoisting is not feasible.
93     if (!Preheader)
94       return false;
95     InsertPt = Preheader->getTerminator();
96   }
97   // Don't hoist instructions with loop-variant operands.
98   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
99     if (!makeLoopInvariant(I->getOperand(i), InsertPt))
100       return false;
101   // Hoist.
102   I->moveBefore(InsertPt);
103   return true;
104 }
105
106 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
107 /// induction variable: an integer recurrence that starts at 0 and increments
108 /// by one each time through the loop.  If so, return the phi node that
109 /// corresponds to it.
110 ///
111 /// The IndVarSimplify pass transforms loops to have a canonical induction
112 /// variable.
113 ///
114 PHINode *Loop::getCanonicalInductionVariable() const {
115   BasicBlock *H = getHeader();
116
117   BasicBlock *Incoming = 0, *Backedge = 0;
118   typedef GraphTraits<Inverse<BasicBlock*> > InvBlockTraits;
119   InvBlockTraits::ChildIteratorType PI = InvBlockTraits::child_begin(H);
120   assert(PI != InvBlockTraits::child_end(H) &&
121          "Loop must have at least one backedge!");
122   Backedge = *PI++;
123   if (PI == InvBlockTraits::child_end(H)) return 0;  // dead loop
124   Incoming = *PI++;
125   if (PI != InvBlockTraits::child_end(H)) return 0;  // multiple backedges?
126
127   if (contains(Incoming)) {
128     if (contains(Backedge))
129       return 0;
130     std::swap(Incoming, Backedge);
131   } else if (!contains(Backedge))
132     return 0;
133
134   // Loop over all of the PHI nodes, looking for a canonical indvar.
135   for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
136     PHINode *PN = cast<PHINode>(I);
137     if (ConstantInt *CI =
138         dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
139       if (CI->isNullValue())
140         if (Instruction *Inc =
141             dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
142           if (Inc->getOpcode() == Instruction::Add &&
143                 Inc->getOperand(0) == PN)
144             if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
145               if (CI->equalsInt(1))
146                 return PN;
147   }
148   return 0;
149 }
150
151 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
152 /// the canonical induction variable value for the "next" iteration of the
153 /// loop.  This always succeeds if getCanonicalInductionVariable succeeds.
154 ///
155 Instruction *Loop::getCanonicalInductionVariableIncrement() const {
156   if (PHINode *PN = getCanonicalInductionVariable()) {
157     bool P1InLoop = contains(PN->getIncomingBlock(1));
158     return cast<Instruction>(PN->getIncomingValue(P1InLoop));
159   }
160   return 0;
161 }
162
163 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
164 /// times the loop will be executed.  Note that this means that the backedge
165 /// of the loop executes N-1 times.  If the trip-count cannot be determined,
166 /// this returns null.
167 ///
168 /// The IndVarSimplify pass transforms loops to have a form that this
169 /// function easily understands.
170 ///
171 Value *Loop::getTripCount() const {
172   // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
173   // canonical induction variable and V is the trip count of the loop.
174   Instruction *Inc = getCanonicalInductionVariableIncrement();
175   if (Inc == 0) return 0;
176   PHINode *IV = cast<PHINode>(Inc->getOperand(0));
177
178   BasicBlock *BackedgeBlock =
179     IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
180
181   if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
182     if (BI->isConditional()) {
183       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
184         if (ICI->getOperand(0) == Inc) {
185           if (BI->getSuccessor(0) == getHeader()) {
186             if (ICI->getPredicate() == ICmpInst::ICMP_NE)
187               return ICI->getOperand(1);
188           } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
189             return ICI->getOperand(1);
190           }
191         }
192       }
193     }
194
195   return 0;
196 }
197
198 /// getSmallConstantTripCount - Returns the trip count of this loop as a
199 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
200 /// of not constant. Will also return 0 if the trip count is very large
201 /// (>= 2^32)
202 unsigned Loop::getSmallConstantTripCount() const {
203   Value* TripCount = this->getTripCount();
204   if (TripCount) {
205     if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCount)) {
206       // Guard against huge trip counts.
207       if (TripCountC->getValue().getActiveBits() <= 32) {
208         return (unsigned)TripCountC->getZExtValue();
209       }
210     }
211   }
212   return 0;
213 }
214
215 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
216 /// trip count of this loop as a normal unsigned value, if possible. This
217 /// means that the actual trip count is always a multiple of the returned
218 /// value (don't forget the trip count could very well be zero as well!).
219 ///
220 /// Returns 1 if the trip count is unknown or not guaranteed to be the
221 /// multiple of a constant (which is also the case if the trip count is simply
222 /// constant, use getSmallConstantTripCount for that case), Will also return 1
223 /// if the trip count is very large (>= 2^32).
224 unsigned Loop::getSmallConstantTripMultiple() const {
225   Value* TripCount = this->getTripCount();
226   // This will hold the ConstantInt result, if any
227   ConstantInt *Result = NULL;
228   if (TripCount) {
229     // See if the trip count is constant itself
230     Result = dyn_cast<ConstantInt>(TripCount);
231     // if not, see if it is a multiplication
232     if (!Result)
233       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCount)) {
234         switch (BO->getOpcode()) {
235         case BinaryOperator::Mul:
236           Result = dyn_cast<ConstantInt>(BO->getOperand(1));
237           break;
238         default:
239           break;
240         }
241       }
242   }
243   // Guard against huge trip counts.
244   if (Result && Result->getValue().getActiveBits() <= 32) {
245     return (unsigned)Result->getZExtValue();
246   } else {
247     return 1;
248   }
249 }
250
251 /// isLCSSAForm - Return true if the Loop is in LCSSA form
252 bool Loop::isLCSSAForm() const {
253   // Sort the blocks vector so that we can use binary search to do quick
254   // lookups.
255   SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
256
257   for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
258     BasicBlock  *BB = *BI;
259     for (BasicBlock ::iterator I = BB->begin(), E = BB->end(); I != E;++I)
260       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
261            ++UI) {
262         BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
263         if (PHINode *P = dyn_cast<PHINode>(*UI)) {
264           UserBB = P->getIncomingBlock(UI);
265         }
266
267         // Check the current block, as a fast-path.  Most values are used in
268         // the same block they are defined in.
269         if (UserBB != BB && !LoopBBs.count(UserBB))
270           return false;
271       }
272   }
273
274   return true;
275 }
276 //===----------------------------------------------------------------------===//
277 // LoopInfo implementation
278 //
279 bool LoopInfo::runOnFunction(Function &) {
280   releaseMemory();
281   LI.Calculate(getAnalysis<DominatorTree>().getBase());    // Update
282   return false;
283 }
284
285 void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
286   AU.setPreservesAll();
287   AU.addRequired<DominatorTree>();
288 }