Remove code to update loop depths
[oota-llvm.git] / lib / Analysis / LoopInfo.cpp
1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "Support/DepthFirstIterator.h"
24 #include <algorithm>
25 using namespace llvm;
26
27 static RegisterAnalysis<LoopInfo>
28 X("loops", "Natural Loop Construction", true);
29
30 //===----------------------------------------------------------------------===//
31 // Loop implementation
32 //
33 bool Loop::contains(const BasicBlock *BB) const {
34   return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
35 }
36
37 bool Loop::isLoopExit(const BasicBlock *BB) const {
38   for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
39        SI != SE; ++SI) {
40     if (!contains(*SI))
41       return true;
42   }
43   return false;
44 }
45
46 /// getNumBackEdges - Calculate the number of back edges to the loop header.
47 ///
48 unsigned Loop::getNumBackEdges() const {
49   unsigned NumBackEdges = 0;
50   BasicBlock *H = getHeader();
51
52   for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I)
53     if (contains(*I))
54       ++NumBackEdges;
55
56   return NumBackEdges;
57 }
58
59 /// isLoopInvariant - Return true if the specified value is loop invariant
60 ///
61 bool Loop::isLoopInvariant(Value *V) const {
62   if (Instruction *I = dyn_cast<Instruction>(V))
63     return !contains(I->getParent());
64   return true;  // All non-instructions are loop invariant
65 }
66
67 void Loop::print(std::ostream &OS, unsigned Depth) const {
68   OS << std::string(Depth*2, ' ') << "Loop Containing: ";
69
70   for (unsigned i = 0; i < getBlocks().size(); ++i) {
71     if (i) OS << ",";
72     WriteAsOperand(OS, getBlocks()[i], false);
73   }
74   OS << "\n";
75
76   for (iterator I = begin(), E = end(); I != E; ++I)
77     (*I)->print(OS, Depth+2);
78 }
79
80 void Loop::dump() const {
81   print(std::cerr);
82 }
83
84
85 //===----------------------------------------------------------------------===//
86 // LoopInfo implementation
87 //
88 void LoopInfo::stub() {}
89
90 bool LoopInfo::runOnFunction(Function &) {
91   releaseMemory();
92   Calculate(getAnalysis<DominatorSet>());    // Update
93   return false;
94 }
95
96 void LoopInfo::releaseMemory() {
97   for (std::vector<Loop*>::iterator I = TopLevelLoops.begin(),
98          E = TopLevelLoops.end(); I != E; ++I)
99     delete *I;   // Delete all of the loops...
100
101   BBMap.clear();                             // Reset internal state of analysis
102   TopLevelLoops.clear();
103 }
104
105
106 void LoopInfo::Calculate(const DominatorSet &DS) {
107   BasicBlock *RootNode = DS.getRoot();
108
109   for (df_iterator<BasicBlock*> NI = df_begin(RootNode),
110          NE = df_end(RootNode); NI != NE; ++NI)
111     if (Loop *L = ConsiderForLoop(*NI, DS))
112       TopLevelLoops.push_back(L);
113 }
114
115 void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
116   AU.setPreservesAll();
117   AU.addRequired<DominatorSet>();
118 }
119
120 void LoopInfo::print(std::ostream &OS) const {
121   for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
122     TopLevelLoops[i]->print(OS);
123 #if 0
124   for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
125          E = BBMap.end(); I != E; ++I)
126     OS << "BB '" << I->first->getName() << "' level = "
127        << I->second->getLoopDepth() << "\n";
128 #endif
129 }
130
131 static bool isNotAlreadyContainedIn(Loop *SubLoop, Loop *ParentLoop) {
132   if (SubLoop == 0) return true;
133   if (SubLoop == ParentLoop) return false;
134   return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
135 }
136
137 Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) {
138   if (BBMap.find(BB) != BBMap.end()) return 0;   // Haven't processed this node?
139
140   std::vector<BasicBlock *> TodoStack;
141
142   // Scan the predecessors of BB, checking to see if BB dominates any of
143   // them.  This identifies backedges which target this node...
144   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
145     if (DS.dominates(BB, *I))   // If BB dominates it's predecessor...
146       TodoStack.push_back(*I);
147
148   if (TodoStack.empty()) return 0;  // No backedges to this block...
149
150   // Create a new loop to represent this basic block...
151   Loop *L = new Loop(BB);
152   BBMap[BB] = L;
153
154   BasicBlock *EntryBlock = &BB->getParent()->getEntryBlock();
155
156   while (!TodoStack.empty()) {  // Process all the nodes in the loop
157     BasicBlock *X = TodoStack.back();
158     TodoStack.pop_back();
159
160     if (!L->contains(X) &&         // As of yet unprocessed??
161         DS.dominates(EntryBlock, X)) {   // X is reachable from entry block?
162       // Check to see if this block already belongs to a loop.  If this occurs
163       // then we have a case where a loop that is supposed to be a child of the
164       // current loop was processed before the current loop.  When this occurs,
165       // this child loop gets added to a part of the current loop, making it a
166       // sibling to the current loop.  We have to reparent this loop.
167       if (Loop *SubLoop = const_cast<Loop*>(getLoopFor(X)))
168         if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
169           // Remove the subloop from it's current parent...
170           assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
171           Loop *SLP = SubLoop->ParentLoop;  // SubLoopParent
172           std::vector<Loop*>::iterator I =
173             std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
174           assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?");
175           SLP->SubLoops.erase(I);   // Remove from parent...
176           
177           // Add the subloop to THIS loop...
178           SubLoop->ParentLoop = L;
179           L->SubLoops.push_back(SubLoop);
180         }
181
182       // Normal case, add the block to our loop...
183       L->Blocks.push_back(X);
184         
185       // Add all of the predecessors of X to the end of the work stack...
186       TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
187     }
188   }
189
190   // If there are any loops nested within this loop, create them now!
191   for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
192          E = L->Blocks.end(); I != E; ++I)
193     if (Loop *NewLoop = ConsiderForLoop(*I, DS)) {
194       L->SubLoops.push_back(NewLoop);
195       NewLoop->ParentLoop = L;
196     }
197
198   // Add the basic blocks that comprise this loop to the BBMap so that this
199   // loop can be found for them.
200   //
201   for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
202          E = L->Blocks.end(); I != E; ++I) {
203     std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I);
204     if (BBMI == BBMap.end() || BBMI->first != *I)  // Not in map yet...
205       BBMap.insert(BBMI, std::make_pair(*I, L));   // Must be at this level
206   }
207
208   // Now that we have a list of all of the child loops of this loop, check to
209   // see if any of them should actually be nested inside of each other.  We can
210   // accidentally pull loops our of their parents, so we must make sure to
211   // organize the loop nests correctly now.
212   {
213     std::map<BasicBlock*, Loop*> ContainingLoops;
214     for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
215       Loop *Child = L->SubLoops[i];
216       assert(Child->getParentLoop() == L && "Not proper child loop?");
217
218       if (Loop *ContainingLoop = ContainingLoops[Child->getHeader()]) {
219         // If there is already a loop which contains this loop, move this loop
220         // into the containing loop.
221         MoveSiblingLoopInto(Child, ContainingLoop);
222         --i;  // The loop got removed from the SubLoops list.
223       } else {
224         // This is currently considered to be a top-level loop.  Check to see if
225         // any of the contained blocks are loop headers for subloops we have
226         // already processed.
227         for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
228           Loop *&BlockLoop = ContainingLoops[Child->Blocks[b]];
229           if (BlockLoop == 0) {   // Child block not processed yet...
230             BlockLoop = Child;
231           } else if (BlockLoop != Child) {
232             Loop *SubLoop = BlockLoop;
233             // Reparent all of the blocks which used to belong to BlockLoops
234             for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
235               ContainingLoops[SubLoop->Blocks[j]] = Child;
236
237             // There is already a loop which contains this block, that means
238             // that we should reparent the loop which the block is currently
239             // considered to belong to to be a child of this loop.
240             MoveSiblingLoopInto(SubLoop, Child);
241             --i;  // We just shrunk the SubLoops list.
242           }
243         }
244       }      
245     }
246   }
247
248   return L;
249 }
250
251 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of
252 /// the NewParent Loop, instead of being a sibling of it.
253 void LoopInfo::MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent) {
254   Loop *OldParent = NewChild->getParentLoop();
255   assert(OldParent && OldParent == NewParent->getParentLoop() &&
256          NewChild != NewParent && "Not sibling loops!");
257
258   // Remove NewChild from being a child of OldParent
259   std::vector<Loop*>::iterator I =
260     std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild);
261   assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
262   OldParent->SubLoops.erase(I);   // Remove from parent's subloops list
263   NewChild->ParentLoop = 0;
264   
265   InsertLoopInto(NewChild, NewParent);  
266 }
267
268 /// InsertLoopInto - This inserts loop L into the specified parent loop.  If the
269 /// parent loop contains a loop which should contain L, the loop gets inserted
270 /// into L instead.
271 void LoopInfo::InsertLoopInto(Loop *L, Loop *Parent) {
272   BasicBlock *LHeader = L->getHeader();
273   assert(Parent->contains(LHeader) && "This loop should not be inserted here!");
274   
275   // Check to see if it belongs in a child loop...
276   for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i)
277     if (Parent->SubLoops[i]->contains(LHeader)) {
278       InsertLoopInto(L, Parent->SubLoops[i]);
279       return;
280     }      
281
282   // If not, insert it here!
283   Parent->SubLoops.push_back(L);
284   L->ParentLoop = Parent;
285 }
286
287 /// changeLoopFor - Change the top-level loop that contains BB to the
288 /// specified loop.  This should be used by transformations that restructure
289 /// the loop hierarchy tree.
290 void LoopInfo::changeLoopFor(BasicBlock *BB, Loop *L) {
291   Loop *&OldLoop = BBMap[BB];
292   assert(OldLoop && "Block not in a loop yet!");
293   OldLoop = L;
294 }
295
296 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
297 /// list with the indicated loop.
298 void LoopInfo::changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
299   std::vector<Loop*>::iterator I = std::find(TopLevelLoops.begin(),
300                                              TopLevelLoops.end(), OldLoop);
301   assert(I != TopLevelLoops.end() && "Old loop not at top level!");
302   *I = NewLoop;
303   assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
304          "Loops already embedded into a subloop!");
305 }
306
307 /// removeLoop - This removes the specified top-level loop from this loop info
308 /// object.  The loop is not deleted, as it will presumably be inserted into
309 /// another loop.
310 Loop *LoopInfo::removeLoop(iterator I) {
311   assert(I != end() && "Cannot remove end iterator!");
312   Loop *L = *I;
313   assert(L->getParentLoop() == 0 && "Not a top-level loop!");
314   TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
315   return L;
316 }
317
318 /// removeBlock - This method completely removes BB from all data structures,
319 /// including all of the Loop objects it is nested in and our mapping from
320 /// BasicBlocks to loops.
321 void LoopInfo::removeBlock(BasicBlock *BB) {
322   std::map<BasicBlock *, Loop*>::iterator I = BBMap.find(BB);
323   if (I != BBMap.end()) {
324     for (Loop *L = I->second; L; L = L->getParentLoop())
325       L->removeBlockFromLoop(BB);
326     
327     BBMap.erase(I);
328   }
329 }
330
331
332 //===----------------------------------------------------------------------===//
333 // APIs for simple analysis of the loop.
334 //
335
336 /// getExitBlocks - Return all of the successor blocks of this loop.  These
337 /// are the blocks _outside of the current loop_ which are branched to.
338 ///
339 void Loop::getExitBlocks(std::vector<BasicBlock*> &ExitBlocks) const {
340   for (std::vector<BasicBlock*>::const_iterator BI = Blocks.begin(),
341          BE = Blocks.end(); BI != BE; ++BI)
342     for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
343       if (!contains(*I))               // Not in current loop?
344         ExitBlocks.push_back(*I);          // It must be an exit block...
345 }
346
347
348 /// getLoopPreheader - If there is a preheader for this loop, return it.  A
349 /// loop has a preheader if there is only one edge to the header of the loop
350 /// from outside of the loop.  If this is the case, the block branching to the
351 /// header of the loop is the preheader node.
352 ///
353 /// This method returns null if there is no preheader for the loop.
354 ///
355 BasicBlock *Loop::getLoopPreheader() const {
356   // Keep track of nodes outside the loop branching to the header...
357   BasicBlock *Out = 0;
358
359   // Loop over the predecessors of the header node...
360   BasicBlock *Header = getHeader();
361   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
362        PI != PE; ++PI)
363     if (!contains(*PI)) {     // If the block is not in the loop...
364       if (Out && Out != *PI)
365         return 0;             // Multiple predecessors outside the loop
366       Out = *PI;
367     }
368   
369   // Make sure there is only one exit out of the preheader...
370   succ_iterator SI = succ_begin(Out);
371   ++SI;
372   if (SI != succ_end(Out))
373     return 0;  // Multiple exits from the block, must not be a preheader.
374
375
376   // If there is exactly one preheader, return it.  If there was zero, then Out
377   // is still null.
378   return Out;
379 }
380
381 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
382 /// induction variable: an integer recurrence that starts at 0 and increments by
383 /// one each time through the loop.  If so, return the phi node that corresponds
384 /// to it.
385 ///
386 PHINode *Loop::getCanonicalInductionVariable() const {
387   BasicBlock *H = getHeader();
388
389   BasicBlock *Incoming = 0, *Backedge = 0;
390   pred_iterator PI = pred_begin(H);
391   assert(PI != pred_end(H) && "Loop must have at least one backedge!");
392   Backedge = *PI++;
393   if (PI == pred_end(H)) return 0;  // dead loop
394   Incoming = *PI++;
395   if (PI != pred_end(H)) return 0;  // multiple backedges?
396
397   if (contains(Incoming)) {
398     if (contains(Backedge))
399       return 0;
400     std::swap(Incoming, Backedge);
401   } else if (!contains(Backedge))
402     return 0;
403
404   // Loop over all of the PHI nodes, looking for a canonical indvar.
405   for (BasicBlock::iterator I = H->begin();
406        PHINode *PN = dyn_cast<PHINode>(I); ++I)
407     if (Instruction *Inc =
408         dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
409       if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
410         if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
411           if (CI->equalsInt(1))
412             return PN;
413
414   return 0;
415 }
416
417 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
418 /// the canonical induction variable value for the "next" iteration of the loop.
419 /// This always succeeds if getCanonicalInductionVariable succeeds.
420 ///
421 Instruction *Loop::getCanonicalInductionVariableIncrement() const {
422   if (PHINode *PN = getCanonicalInductionVariable()) {
423     bool P1InLoop = contains(PN->getIncomingBlock(1));
424     return cast<Instruction>(PN->getIncomingValue(P1InLoop));
425   }
426   return 0;
427 }
428
429 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
430 /// times the loop will be executed.  Note that this means that the backedge of
431 /// the loop executes N-1 times.  If the trip-count cannot be determined, this
432 /// returns null.
433 ///
434 Value *Loop::getTripCount() const {
435   // Canonical loops will end with a 'setne I, V', where I is the incremented
436   // canonical induction variable and V is the trip count of the loop.
437   Instruction *Inc = getCanonicalInductionVariableIncrement();
438   if (Inc == 0) return 0;
439   PHINode *IV = cast<PHINode>(Inc->getOperand(0));
440   
441   BasicBlock *BackedgeBlock =
442     IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
443
444   if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
445     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
446       if (SCI->getOperand(0) == Inc)
447         if (BI->getSuccessor(0) == getHeader()) {
448           if (SCI->getOpcode() == Instruction::SetNE)
449             return SCI->getOperand(1);
450         } else if (SCI->getOpcode() == Instruction::SetEQ) {
451           return SCI->getOperand(1);
452         }
453   
454   return 0;
455 }
456
457
458 //===-------------------------------------------------------------------===//
459 // APIs for updating loop information after changing the CFG
460 //
461
462 /// addBasicBlockToLoop - This function is used by other analyses to update loop
463 /// information.  NewBB is set to be a new member of the current loop.  Because
464 /// of this, it is added as a member of all parent loops, and is added to the
465 /// specified LoopInfo object as being in the current basic block.  It is not
466 /// valid to replace the loop header with this method.
467 ///
468 void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) {
469   assert((Blocks.empty() || LI[getHeader()] == this) &&
470          "Incorrect LI specified for this loop!");
471   assert(NewBB && "Cannot add a null basic block to the loop!");
472   assert(LI[NewBB] == 0 && "BasicBlock already in the loop!");
473
474   // Add the loop mapping to the LoopInfo object...
475   LI.BBMap[NewBB] = this;
476
477   // Add the basic block to this loop and all parent loops...
478   Loop *L = this;
479   while (L) {
480     L->Blocks.push_back(NewBB);
481     L = L->getParentLoop();
482   }
483 }
484
485 /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
486 /// the OldChild entry in our children list with NewChild, and updates the
487 /// parent pointers of the two loops as appropriate.
488 void Loop::replaceChildLoopWith(Loop *OldChild, Loop *NewChild) {
489   assert(OldChild->ParentLoop == this && "This loop is already broken!");
490   assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
491   std::vector<Loop*>::iterator I = std::find(SubLoops.begin(), SubLoops.end(),
492                                              OldChild);
493   assert(I != SubLoops.end() && "OldChild not in loop!");
494   *I = NewChild;
495   OldChild->ParentLoop = 0;
496   NewChild->ParentLoop = this;
497 }
498
499 /// addChildLoop - Add the specified loop to be a child of this loop.
500 ///
501 void Loop::addChildLoop(Loop *NewChild) {
502   assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
503   NewChild->ParentLoop = this;
504   SubLoops.push_back(NewChild);
505 }
506
507 template<typename T>
508 static void RemoveFromVector(std::vector<T*> &V, T *N) {
509   typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
510   assert(I != V.end() && "N is not in this list!");
511   V.erase(I);
512 }
513
514 /// removeChildLoop - This removes the specified child from being a subloop of
515 /// this loop.  The loop is not deleted, as it will presumably be inserted
516 /// into another loop.
517 Loop *Loop::removeChildLoop(iterator I) {
518   assert(I != SubLoops.end() && "Cannot remove end iterator!");
519   Loop *Child = *I;
520   assert(Child->ParentLoop == this && "Child is not a child of this loop!");
521   SubLoops.erase(SubLoops.begin()+(I-begin()));
522   Child->ParentLoop = 0;
523   return Child;
524 }
525
526
527 /// removeBlockFromLoop - This removes the specified basic block from the
528 /// current loop, updating the Blocks and ExitBlocks lists as appropriate.  This
529 /// does not update the mapping in the LoopInfo class.
530 void Loop::removeBlockFromLoop(BasicBlock *BB) {
531   RemoveFromVector(Blocks, BB);
532 }