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