5939dea4c0de3f44cb02b711b92e8744eaae6ba5
[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, bool &Changed,
62                              Instruction *InsertPt) const {
63   if (Instruction *I = dyn_cast<Instruction>(V))
64     return makeLoopInvariant(I, Changed, InsertPt);
65   return true;  // All non-instructions are loop-invariant.
66 }
67
68 /// makeLoopInvariant - If the given instruction is inside of the
69 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
70 /// Return true if the instruction after any hoisting is loop invariant. This
71 /// function can be used as a slightly more aggressive replacement for
72 /// isLoopInvariant.
73 ///
74 /// If InsertPt is specified, it is the point to hoist instructions to.
75 /// If null, the terminator of the loop preheader is used.
76 ///
77 bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
78                              Instruction *InsertPt) const {
79   // Test if the value is already loop-invariant.
80   if (isLoopInvariant(I))
81     return true;
82   if (!I->isSafeToSpeculativelyExecute())
83     return false;
84   if (I->mayReadFromMemory())
85     return false;
86   // Determine the insertion point, unless one was given.
87   if (!InsertPt) {
88     BasicBlock *Preheader = getLoopPreheader();
89     // Without a preheader, hoisting is not feasible.
90     if (!Preheader)
91       return false;
92     InsertPt = Preheader->getTerminator();
93   }
94   // Don't hoist instructions with loop-variant operands.
95   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
96     if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
97       return false;
98   // Hoist.
99   I->moveBefore(InsertPt);
100   Changed = true;
101   return true;
102 }
103
104 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
105 /// induction variable: an integer recurrence that starts at 0 and increments
106 /// by one each time through the loop.  If so, return the phi node that
107 /// corresponds to it.
108 ///
109 /// The IndVarSimplify pass transforms loops to have a canonical induction
110 /// variable.
111 ///
112 PHINode *Loop::getCanonicalInductionVariable() const {
113   BasicBlock *H = getHeader();
114
115   BasicBlock *Incoming = 0, *Backedge = 0;
116   typedef GraphTraits<Inverse<BasicBlock*> > InvBlockTraits;
117   InvBlockTraits::ChildIteratorType PI = InvBlockTraits::child_begin(H);
118   assert(PI != InvBlockTraits::child_end(H) &&
119          "Loop must have at least one backedge!");
120   Backedge = *PI++;
121   if (PI == InvBlockTraits::child_end(H)) return 0;  // dead loop
122   Incoming = *PI++;
123   if (PI != InvBlockTraits::child_end(H)) return 0;  // multiple backedges?
124
125   if (contains(Incoming)) {
126     if (contains(Backedge))
127       return 0;
128     std::swap(Incoming, Backedge);
129   } else if (!contains(Backedge))
130     return 0;
131
132   // Loop over all of the PHI nodes, looking for a canonical indvar.
133   for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
134     PHINode *PN = cast<PHINode>(I);
135     if (ConstantInt *CI =
136         dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
137       if (CI->isNullValue())
138         if (Instruction *Inc =
139             dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
140           if (Inc->getOpcode() == Instruction::Add &&
141                 Inc->getOperand(0) == PN)
142             if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
143               if (CI->equalsInt(1))
144                 return PN;
145   }
146   return 0;
147 }
148
149 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
150 /// the canonical induction variable value for the "next" iteration of the
151 /// loop.  This always succeeds if getCanonicalInductionVariable succeeds.
152 ///
153 Instruction *Loop::getCanonicalInductionVariableIncrement() const {
154   if (PHINode *PN = getCanonicalInductionVariable()) {
155     bool P1InLoop = contains(PN->getIncomingBlock(1));
156     return cast<Instruction>(PN->getIncomingValue(P1InLoop));
157   }
158   return 0;
159 }
160
161 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
162 /// times the loop will be executed.  Note that this means that the backedge
163 /// of the loop executes N-1 times.  If the trip-count cannot be determined,
164 /// this returns null.
165 ///
166 /// The IndVarSimplify pass transforms loops to have a form that this
167 /// function easily understands.
168 ///
169 Value *Loop::getTripCount() const {
170   // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
171   // canonical induction variable and V is the trip count of the loop.
172   Instruction *Inc = getCanonicalInductionVariableIncrement();
173   if (Inc == 0) return 0;
174   PHINode *IV = cast<PHINode>(Inc->getOperand(0));
175
176   BasicBlock *BackedgeBlock =
177     IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
178
179   if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
180     if (BI->isConditional()) {
181       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
182         if (ICI->getOperand(0) == Inc) {
183           if (BI->getSuccessor(0) == getHeader()) {
184             if (ICI->getPredicate() == ICmpInst::ICMP_NE)
185               return ICI->getOperand(1);
186           } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
187             return ICI->getOperand(1);
188           }
189         }
190       }
191     }
192
193   return 0;
194 }
195
196 /// getSmallConstantTripCount - Returns the trip count of this loop as a
197 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
198 /// of not constant. Will also return 0 if the trip count is very large
199 /// (>= 2^32)
200 unsigned Loop::getSmallConstantTripCount() const {
201   Value* TripCount = this->getTripCount();
202   if (TripCount) {
203     if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCount)) {
204       // Guard against huge trip counts.
205       if (TripCountC->getValue().getActiveBits() <= 32) {
206         return (unsigned)TripCountC->getZExtValue();
207       }
208     }
209   }
210   return 0;
211 }
212
213 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
214 /// trip count of this loop as a normal unsigned value, if possible. This
215 /// means that the actual trip count is always a multiple of the returned
216 /// value (don't forget the trip count could very well be zero as well!).
217 ///
218 /// Returns 1 if the trip count is unknown or not guaranteed to be the
219 /// multiple of a constant (which is also the case if the trip count is simply
220 /// constant, use getSmallConstantTripCount for that case), Will also return 1
221 /// if the trip count is very large (>= 2^32).
222 unsigned Loop::getSmallConstantTripMultiple() const {
223   Value* TripCount = this->getTripCount();
224   // This will hold the ConstantInt result, if any
225   ConstantInt *Result = NULL;
226   if (TripCount) {
227     // See if the trip count is constant itself
228     Result = dyn_cast<ConstantInt>(TripCount);
229     // if not, see if it is a multiplication
230     if (!Result)
231       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCount)) {
232         switch (BO->getOpcode()) {
233         case BinaryOperator::Mul:
234           Result = dyn_cast<ConstantInt>(BO->getOperand(1));
235           break;
236         default:
237           break;
238         }
239       }
240   }
241   // Guard against huge trip counts.
242   if (Result && Result->getValue().getActiveBits() <= 32) {
243     return (unsigned)Result->getZExtValue();
244   } else {
245     return 1;
246   }
247 }
248
249 /// isLCSSAForm - Return true if the Loop is in LCSSA form
250 bool Loop::isLCSSAForm() const {
251   // Sort the blocks vector so that we can use binary search to do quick
252   // lookups.
253   SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
254
255   for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
256     BasicBlock  *BB = *BI;
257     for (BasicBlock ::iterator I = BB->begin(), E = BB->end(); I != E;++I)
258       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
259            ++UI) {
260         BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
261         if (PHINode *P = dyn_cast<PHINode>(*UI)) {
262           UserBB = P->getIncomingBlock(UI);
263         }
264
265         // Check the current block, as a fast-path.  Most values are used in
266         // the same block they are defined in.
267         if (UserBB != BB && !LoopBBs.count(UserBB))
268           return false;
269       }
270   }
271
272   return true;
273 }
274
275 /// isLoopSimplifyForm - Return true if the Loop is in the form that
276 /// the LoopSimplify form transforms loops to, which is sometimes called
277 /// normal form.
278 bool Loop::isLoopSimplifyForm() const {
279   // Normal-form loops have a preheader.
280   if (!getLoopPreheader())
281     return false;
282   // Normal-form loops have a single backedge.
283   if (!getLoopLatch())
284     return false;
285   // Each predecessor of each exit block of a normal loop is contained
286   // within the loop.
287   SmallVector<BasicBlock *, 4> ExitBlocks;
288   getExitBlocks(ExitBlocks);
289   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
290     for (pred_iterator PI = pred_begin(ExitBlocks[i]),
291          PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
292       if (!contains(*PI))
293         return false;
294   // All the requirements are met.
295   return true;
296 }
297
298 //===----------------------------------------------------------------------===//
299 // LoopInfo implementation
300 //
301 bool LoopInfo::runOnFunction(Function &) {
302   releaseMemory();
303   LI.Calculate(getAnalysis<DominatorTree>().getBase());    // Update
304   return false;
305 }
306
307 void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
308   AU.setPreservesAll();
309   AU.addRequired<DominatorTree>();
310 }
311
312 void LoopInfo::print(raw_ostream &OS, const Module*) const {
313   LI.print(OS);
314 }
315