blob: e92f10d49c3d6e555ae13ed9acda511d906bb3bc [file] [log] [blame]
Chris Lattner0bbe58f2001-11-26 18:41:20 +00001//===- 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"
Chris Lattner221d6882002-02-12 21:07:25 +000012#include "llvm/Support/CFG.h"
Chris Lattnera59cbb22002-07-27 01:12:17 +000013#include "llvm/Assembly/Writer.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000014#include "Support/DepthFirstIterator.h"
Chris Lattner0bbe58f2001-11-26 18:41:20 +000015#include <algorithm>
16
Chris Lattner1e435162002-07-26 21:12:44 +000017static RegisterAnalysis<LoopInfo>
Chris Lattner17689df2002-07-30 16:27:52 +000018X("loops", "Natural Loop Construction", true);
Chris Lattner93193f82002-01-31 00:42:27 +000019
20//===----------------------------------------------------------------------===//
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000021// Loop implementation
Chris Lattner93193f82002-01-31 00:42:27 +000022//
Chris Lattner0f995552002-06-03 22:10:52 +000023bool Loop::contains(const BasicBlock *BB) const {
Chris Lattner0bbe58f2001-11-26 18:41:20 +000024 return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
25}
26
Misha Brukman6b290a52002-10-11 05:31:10 +000027bool Loop::isLoopExit(const BasicBlock *BB) const {
Chris Lattner03f252f2003-09-24 22:18:35 +000028 for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
Misha Brukman6b290a52002-10-11 05:31:10 +000029 SI != SE; ++SI) {
Chris Lattner5f82b8a2003-02-27 00:38:34 +000030 if (!contains(*SI))
Misha Brukman6b290a52002-10-11 05:31:10 +000031 return true;
32 }
33 return false;
34}
35
Chris Lattner2ef12362003-10-12 22:14:27 +000036/// getNumBackEdges - Calculate the number of back edges to the loop header.
37///
Misha Brukman6b290a52002-10-11 05:31:10 +000038unsigned Loop::getNumBackEdges() const {
Chris Lattner5f82b8a2003-02-27 00:38:34 +000039 unsigned NumBackEdges = 0;
40 BasicBlock *H = getHeader();
Misha Brukman6b290a52002-10-11 05:31:10 +000041
Chris Lattner2ef12362003-10-12 22:14:27 +000042 for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I)
43 if (contains(*I))
44 ++NumBackEdges;
45
Chris Lattner5f82b8a2003-02-27 00:38:34 +000046 return NumBackEdges;
Misha Brukman6b290a52002-10-11 05:31:10 +000047}
48
Chris Lattner7dd46b02003-08-16 20:57:16 +000049void Loop::print(std::ostream &OS, unsigned Depth) const {
50 OS << std::string(Depth*2, ' ') << "Loop Containing: ";
Chris Lattnera59cbb22002-07-27 01:12:17 +000051
52 for (unsigned i = 0; i < getBlocks().size(); ++i) {
53 if (i) OS << ",";
Chris Lattner5f82b8a2003-02-27 00:38:34 +000054 WriteAsOperand(OS, getBlocks()[i], false);
Chris Lattnera59cbb22002-07-27 01:12:17 +000055 }
Chris Lattner5f82b8a2003-02-27 00:38:34 +000056 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
Chris Lattnera59cbb22002-07-27 01:12:17 +000064 OS << "\n";
65
Chris Lattnerb1f8aeb2002-09-29 21:43:04 +000066 for (unsigned i = 0, e = getSubLoops().size(); i != e; ++i)
Chris Lattner7dd46b02003-08-16 20:57:16 +000067 getSubLoops()[i]->print(OS, Depth+2);
Chris Lattnera59cbb22002-07-27 01:12:17 +000068}
69
Chris Lattnerbb05f1e2003-02-28 16:54:45 +000070void Loop::dump() const {
71 print(std::cerr);
72}
73
Chris Lattner420df9b2003-02-22 21:33:11 +000074
Chris Lattnera59cbb22002-07-27 01:12:17 +000075//===----------------------------------------------------------------------===//
76// LoopInfo implementation
77//
Anand Shuklae0b6b782002-08-26 16:45:19 +000078void LoopInfo::stub() {}
Chris Lattnera59cbb22002-07-27 01:12:17 +000079
80bool LoopInfo::runOnFunction(Function &) {
81 releaseMemory();
82 Calculate(getAnalysis<DominatorSet>()); // Update
83 return false;
84}
85
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000086void LoopInfo::releaseMemory() {
Chris Lattner918c4ec2002-04-09 05:43:19 +000087 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
Chris Lattner93193f82002-01-31 00:42:27 +000095
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000096void LoopInfo::Calculate(const DominatorSet &DS) {
Chris Lattnera298d272002-04-28 00:15:57 +000097 BasicBlock *RootNode = DS.getRoot();
Chris Lattner0bbe58f2001-11-26 18:41:20 +000098
Chris Lattnera298d272002-04-28 00:15:57 +000099 for (df_iterator<BasicBlock*> NI = df_begin(RootNode),
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000100 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
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000108void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000109 AU.setPreservesAll();
Chris Lattnerdd5b4952002-08-08 19:01:28 +0000110 AU.addRequired<DominatorSet>();
Chris Lattner93193f82002-01-31 00:42:27 +0000111}
112
Chris Lattnera59cbb22002-07-27 01:12:17 +0000113void LoopInfo::print(std::ostream &OS) const {
Chris Lattnerfce46ef2002-09-26 16:15:54 +0000114 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
115 TopLevelLoops[i]->print(OS);
Chris Lattner420df9b2003-02-22 21:33:11 +0000116#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
Chris Lattnera59cbb22002-07-27 01:12:17 +0000122}
Chris Lattner93193f82002-01-31 00:42:27 +0000123
Chris Lattner39c987a2003-05-15 18:03:51 +0000124static 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
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000130Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) {
Chris Lattner699b3052002-09-26 05:32:50 +0000131 if (BBMap.find(BB) != BBMap.end()) return 0; // Haven't processed this node?
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000132
Chris Lattnera298d272002-04-28 00:15:57 +0000133 std::vector<BasicBlock *> TodoStack;
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000134
135 // Scan the predecessors of BB, checking to see if BB dominates any of
Chris Lattner99224ae2003-04-26 19:34:18 +0000136 // them. This identifies backedges which target this node...
Chris Lattnera298d272002-04-28 00:15:57 +0000137 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000138 if (DS.dominates(BB, *I)) // If BB dominates it's predecessor...
139 TodoStack.push_back(*I);
140
Chris Lattner99224ae2003-04-26 19:34:18 +0000141 if (TodoStack.empty()) return 0; // No backedges to this block...
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000142
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
Chris Lattnera298d272002-04-28 00:15:57 +0000148 BasicBlock *X = TodoStack.back();
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000149 TodoStack.pop_back();
150
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000151 if (!L->contains(X)) { // As of yet unprocessed??
Chris Lattner99224ae2003-04-26 19:34:18 +0000152 // 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)))
Chris Lattner39c987a2003-05-15 18:03:51 +0000158 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
Chris Lattner99224ae2003-04-26 19:34:18 +0000159 // 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...
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000173 L->Blocks.push_back(X);
Chris Lattner99224ae2003-04-26 19:34:18 +0000174
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000175 // Add all of the predecessors of X to the end of the work stack...
Chris Lattner455889a2002-02-12 22:39:50 +0000176 TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000177 }
178 }
179
Chris Lattner420df9b2003-02-22 21:33:11 +0000180 // 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 }
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000187
Chris Lattner420df9b2003-02-22 21:33:11 +0000188 // 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 }
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000197
Chris Lattner7dd46b02003-08-16 20:57:16 +0000198 // 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) {
Chris Lattner169db9d2003-08-17 21:47:33 +0000222 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
Chris Lattner7dd46b02003-08-16 20:57:16 +0000227 // 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.
Chris Lattner169db9d2003-08-17 21:47:33 +0000230 MoveSiblingLoopInto(SubLoop, Child);
Chris Lattner7dd46b02003-08-16 20:57:16 +0000231 --i; // We just shrunk the SubLoops list.
232 }
233 }
234 }
235 }
236 }
237
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000238 // 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
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000246 return L;
247}
Chris Lattner699b3052002-09-26 05:32:50 +0000248
Chris Lattner7dd46b02003-08-16 20:57:16 +0000249/// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of
250/// the NewParent Loop, instead of being a sibling of it.
251void 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.
269void 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
Chris Lattner699b3052002-09-26 05:32:50 +0000287/// 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///
297BasicBlock *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)
Chris Lattnerc8f25d92002-09-29 22:59:29 +0000305 if (!contains(*PI)) { // If the block is not in the loop...
306 if (Out && Out != *PI)
307 return 0; // Multiple predecessors outside the loop
Chris Lattner699b3052002-09-26 05:32:50 +0000308 Out = *PI;
309 }
Chris Lattner5a8a2912003-02-27 21:51:38 +0000310
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
Chris Lattner699b3052002-09-26 05:32:50 +0000317
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///
329void 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}
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000344
Chris Lattnerf2e29252003-02-27 22:37:44 +0000345/// changeExitBlock - This method is used to update loop information. All
346/// instances of the specified Old basic block are removed from the exit list
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000347/// and replaced with New.
348///
349void 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!");
Chris Lattnera94837a2003-02-27 22:48:08 +0000352 assert(hasExitBlock(Old) && "Old exit block not found!");
353 std::vector<BasicBlock*>::iterator
354 I = std::find(ExitBlocks.begin(), ExitBlocks.end(), Old);
Chris Lattnerf2e29252003-02-27 22:37:44 +0000355 while (I != ExitBlocks.end()) {
356 *I = New;
357 I = std::find(I+1, ExitBlocks.end(), Old);
358 }
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000359}