Make getNumBackEdges more efficient
[oota-llvm.git] / lib / Analysis / LoopInfo.cpp
1 //===- LoopInfo.cpp - Natural Loop Calculator -------------------------------=//
2 //
3 // This file defines the LoopInfo class that is used to identify natural loops
4 // and determine the loop depth of various nodes of the CFG.  Note that the
5 // loops identified may actually be several natural loops that share the same
6 // header node... not just a single natural loop.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Analysis/LoopInfo.h"
11 #include "llvm/Analysis/Dominators.h"
12 #include "llvm/Support/CFG.h"
13 #include "llvm/Assembly/Writer.h"
14 #include "Support/DepthFirstIterator.h"
15 #include <algorithm>
16
17 static RegisterAnalysis<LoopInfo>
18 X("loops", "Natural Loop Construction", true);
19
20 //===----------------------------------------------------------------------===//
21 // Loop implementation
22 //
23 bool Loop::contains(const BasicBlock *BB) const {
24   return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
25 }
26
27 bool Loop::isLoopExit(const BasicBlock *BB) const {
28   for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
29        SI != SE; ++SI) {
30     if (!contains(*SI))
31       return true;
32   }
33   return false;
34 }
35
36 /// getNumBackEdges - Calculate the number of back edges to the loop header.
37 ///
38 unsigned Loop::getNumBackEdges() const {
39   unsigned NumBackEdges = 0;
40   BasicBlock *H = getHeader();
41
42   for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I)
43     if (contains(*I))
44       ++NumBackEdges;
45
46   return NumBackEdges;
47 }
48
49 void Loop::print(std::ostream &OS, unsigned Depth) const {
50   OS << std::string(Depth*2, ' ') << "Loop Containing: ";
51
52   for (unsigned i = 0; i < getBlocks().size(); ++i) {
53     if (i) OS << ",";
54     WriteAsOperand(OS, getBlocks()[i], false);
55   }
56   if (!ExitBlocks.empty()) {
57     OS << "\tExitBlocks: ";
58     for (unsigned i = 0; i < getExitBlocks().size(); ++i) {
59       if (i) OS << ",";
60       WriteAsOperand(OS, getExitBlocks()[i], false);
61     }
62   }
63
64   OS << "\n";
65
66   for (unsigned i = 0, e = getSubLoops().size(); i != e; ++i)
67     getSubLoops()[i]->print(OS, Depth+2);
68 }
69
70 void Loop::dump() const {
71   print(std::cerr);
72 }
73
74
75 //===----------------------------------------------------------------------===//
76 // LoopInfo implementation
77 //
78 void LoopInfo::stub() {}
79
80 bool LoopInfo::runOnFunction(Function &) {
81   releaseMemory();
82   Calculate(getAnalysis<DominatorSet>());    // Update
83   return false;
84 }
85
86 void LoopInfo::releaseMemory() {
87   for (std::vector<Loop*>::iterator I = TopLevelLoops.begin(),
88          E = TopLevelLoops.end(); I != E; ++I)
89     delete *I;   // Delete all of the loops...
90
91   BBMap.clear();                             // Reset internal state of analysis
92   TopLevelLoops.clear();
93 }
94
95
96 void LoopInfo::Calculate(const DominatorSet &DS) {
97   BasicBlock *RootNode = DS.getRoot();
98
99   for (df_iterator<BasicBlock*> NI = df_begin(RootNode),
100          NE = df_end(RootNode); NI != NE; ++NI)
101     if (Loop *L = ConsiderForLoop(*NI, DS))
102       TopLevelLoops.push_back(L);
103
104   for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
105     TopLevelLoops[i]->setLoopDepth(1);
106 }
107
108 void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
109   AU.setPreservesAll();
110   AU.addRequired<DominatorSet>();
111 }
112
113 void LoopInfo::print(std::ostream &OS) const {
114   for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
115     TopLevelLoops[i]->print(OS);
116 #if 0
117   for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
118          E = BBMap.end(); I != E; ++I)
119     OS << "BB '" << I->first->getName() << "' level = "
120        << I->second->LoopDepth << "\n";
121 #endif
122 }
123
124 static bool isNotAlreadyContainedIn(Loop *SubLoop, Loop *ParentLoop) {
125   if (SubLoop == 0) return true;
126   if (SubLoop == ParentLoop) return false;
127   return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
128 }
129
130 Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) {
131   if (BBMap.find(BB) != BBMap.end()) return 0;   // Haven't processed this node?
132
133   std::vector<BasicBlock *> TodoStack;
134
135   // Scan the predecessors of BB, checking to see if BB dominates any of
136   // them.  This identifies backedges which target this node...
137   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
138     if (DS.dominates(BB, *I))   // If BB dominates it's predecessor...
139       TodoStack.push_back(*I);
140
141   if (TodoStack.empty()) return 0;  // No backedges to this block...
142
143   // Create a new loop to represent this basic block...
144   Loop *L = new Loop(BB);
145   BBMap[BB] = L;
146
147   while (!TodoStack.empty()) {  // Process all the nodes in the loop
148     BasicBlock *X = TodoStack.back();
149     TodoStack.pop_back();
150
151     if (!L->contains(X)) {         // As of yet unprocessed??
152       // Check to see if this block already belongs to a loop.  If this occurs
153       // then we have a case where a loop that is supposed to be a child of the
154       // current loop was processed before the current loop.  When this occurs,
155       // this child loop gets added to a part of the current loop, making it a
156       // sibling to the current loop.  We have to reparent this loop.
157       if (Loop *SubLoop = const_cast<Loop*>(getLoopFor(X)))
158         if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
159           // Remove the subloop from it's current parent...
160           assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
161           Loop *SLP = SubLoop->ParentLoop;  // SubLoopParent
162           std::vector<Loop*>::iterator I =
163             std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
164           assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?");
165           SLP->SubLoops.erase(I);   // Remove from parent...
166           
167           // Add the subloop to THIS loop...
168           SubLoop->ParentLoop = L;
169           L->SubLoops.push_back(SubLoop);
170         }
171
172       // Normal case, add the block to our loop...
173       L->Blocks.push_back(X);
174         
175       // Add all of the predecessors of X to the end of the work stack...
176       TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
177     }
178   }
179
180   // If there are any loops nested within this loop, create them now!
181   for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
182          E = L->Blocks.end(); I != E; ++I)
183     if (Loop *NewLoop = ConsiderForLoop(*I, DS)) {
184       L->SubLoops.push_back(NewLoop);
185       NewLoop->ParentLoop = L;
186     }
187
188   // Add the basic blocks that comprise this loop to the BBMap so that this
189   // loop can be found for them.
190   //
191   for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
192          E = L->Blocks.end(); I != E; ++I) {
193     std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I);
194     if (BBMI == BBMap.end() || BBMI->first != *I)  // Not in map yet...
195       BBMap.insert(BBMI, std::make_pair(*I, L));   // Must be at this level
196   }
197
198   // Now that we have a list of all of the child loops of this loop, check to
199   // see if any of them should actually be nested inside of each other.  We can
200   // accidentally pull loops our of their parents, so we must make sure to
201   // organize the loop nests correctly now.
202   {
203     std::map<BasicBlock*, Loop*> ContainingLoops;
204     for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
205       Loop *Child = L->SubLoops[i];
206       assert(Child->getParentLoop() == L && "Not proper child loop?");
207
208       if (Loop *ContainingLoop = ContainingLoops[Child->getHeader()]) {
209         // If there is already a loop which contains this loop, move this loop
210         // into the containing loop.
211         MoveSiblingLoopInto(Child, ContainingLoop);
212         --i;  // The loop got removed from the SubLoops list.
213       } else {
214         // This is currently considered to be a top-level loop.  Check to see if
215         // any of the contained blocks are loop headers for subloops we have
216         // already processed.
217         for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
218           Loop *&BlockLoop = ContainingLoops[Child->Blocks[b]];
219           if (BlockLoop == 0) {   // Child block not processed yet...
220             BlockLoop = Child;
221           } else if (BlockLoop != Child) {
222             Loop *SubLoop = BlockLoop;
223             // Reparent all of the blocks which used to belong to BlockLoops
224             for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
225               ContainingLoops[SubLoop->Blocks[j]] = Child;
226
227             // There is already a loop which contains this block, that means
228             // that we should reparent the loop which the block is currently
229             // considered to belong to to be a child of this loop.
230             MoveSiblingLoopInto(SubLoop, Child);
231             --i;  // We just shrunk the SubLoops list.
232           }
233         }
234       }      
235     }
236   }
237
238   // Now that we know all of the blocks that make up this loop, see if there are
239   // any branches to outside of the loop... building the ExitBlocks list.
240   for (std::vector<BasicBlock*>::iterator BI = L->Blocks.begin(),
241          BE = L->Blocks.end(); BI != BE; ++BI)
242     for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
243       if (!L->contains(*I))               // Not in current loop?
244         L->ExitBlocks.push_back(*I);      // It must be an exit block...
245
246   return L;
247 }
248
249 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of
250 /// the NewParent Loop, instead of being a sibling of it.
251 void LoopInfo::MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent) {
252   Loop *OldParent = NewChild->getParentLoop();
253   assert(OldParent && OldParent == NewParent->getParentLoop() &&
254          NewChild != NewParent && "Not sibling loops!");
255
256   // Remove NewChild from being a child of OldParent
257   std::vector<Loop*>::iterator I =
258     std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild);
259   assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
260   OldParent->SubLoops.erase(I);   // Remove from parent's subloops list
261   NewChild->ParentLoop = 0;
262   
263   InsertLoopInto(NewChild, NewParent);  
264 }
265
266 /// InsertLoopInto - This inserts loop L into the specified parent loop.  If the
267 /// parent loop contains a loop which should contain L, the loop gets inserted
268 /// into L instead.
269 void LoopInfo::InsertLoopInto(Loop *L, Loop *Parent) {
270   BasicBlock *LHeader = L->getHeader();
271   assert(Parent->contains(LHeader) && "This loop should not be inserted here!");
272   
273   // Check to see if it belongs in a child loop...
274   for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i)
275     if (Parent->SubLoops[i]->contains(LHeader)) {
276       InsertLoopInto(L, Parent->SubLoops[i]);
277       return;
278     }      
279
280   // If not, insert it here!
281   Parent->SubLoops.push_back(L);
282   L->ParentLoop = Parent;
283 }
284
285
286
287 /// getLoopPreheader - If there is a preheader for this loop, return it.  A
288 /// loop has a preheader if there is only one edge to the header of the loop
289 /// from outside of the loop.  If this is the case, the block branching to the
290 /// header of the loop is the preheader node.  The "preheaders" pass can be
291 /// "Required" to ensure that there is always a preheader node for every loop.
292 ///
293 /// This method returns null if there is no preheader for the loop (either
294 /// because the loop is dead or because multiple blocks branch to the header
295 /// node of this loop).
296 ///
297 BasicBlock *Loop::getLoopPreheader() const {
298   // Keep track of nodes outside the loop branching to the header...
299   BasicBlock *Out = 0;
300
301   // Loop over the predecessors of the header node...
302   BasicBlock *Header = getHeader();
303   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
304        PI != PE; ++PI)
305     if (!contains(*PI)) {     // If the block is not in the loop...
306       if (Out && Out != *PI)
307         return 0;             // Multiple predecessors outside the loop
308       Out = *PI;
309     }
310   
311   // Make sure there is only one exit out of the preheader...
312   succ_iterator SI = succ_begin(Out);
313   ++SI;
314   if (SI != succ_end(Out))
315     return 0;  // Multiple exits from the block, must not be a preheader.
316
317
318   // If there is exactly one preheader, return it.  If there was zero, then Out
319   // is still null.
320   return Out;
321 }
322
323 /// addBasicBlockToLoop - This function is used by other analyses to update loop
324 /// information.  NewBB is set to be a new member of the current loop.  Because
325 /// of this, it is added as a member of all parent loops, and is added to the
326 /// specified LoopInfo object as being in the current basic block.  It is not
327 /// valid to replace the loop header with this method.
328 ///
329 void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) {
330   assert(LI[getHeader()] == this && "Incorrect LI specified for this loop!");
331   assert(NewBB && "Cannot add a null basic block to the loop!");
332   assert(LI[NewBB] == 0 && "BasicBlock already in the loop!");
333
334   // Add the loop mapping to the LoopInfo object...
335   LI.BBMap[NewBB] = this;
336
337   // Add the basic block to this loop and all parent loops...
338   Loop *L = this;
339   while (L) {
340     L->Blocks.push_back(NewBB);
341     L = L->getParentLoop();
342   }
343 }
344
345 /// changeExitBlock - This method is used to update loop information.  All
346 /// instances of the specified Old basic block are removed from the exit list
347 /// and replaced with New.
348 ///
349 void Loop::changeExitBlock(BasicBlock *Old, BasicBlock *New) {
350   assert(Old != New && "Cannot changeExitBlock to the same thing!");
351   assert(Old && New && "Cannot changeExitBlock to or from a null node!");
352   assert(hasExitBlock(Old) && "Old exit block not found!");
353   std::vector<BasicBlock*>::iterator
354     I = std::find(ExitBlocks.begin(), ExitBlocks.end(), Old);
355   while (I != ExitBlocks.end()) {
356     *I = New;
357     I = std::find(I+1, ExitBlocks.end(), Old);
358   }
359 }