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