blob: 2277a1561429019f26ba7f840d082dba2d3ca16b [file] [log] [blame]
Chris Lattnercf3056d2003-10-13 03:32:08 +00001//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Chris Lattner0bbe58f2001-11-26 18:41:20 +00009//
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"
Chris Lattner221d6882002-02-12 21:07:25 +000019#include "llvm/Support/CFG.h"
Chris Lattnera59cbb22002-07-27 01:12:17 +000020#include "llvm/Assembly/Writer.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000021#include "Support/DepthFirstIterator.h"
Chris Lattner0bbe58f2001-11-26 18:41:20 +000022#include <algorithm>
23
Chris Lattner1e435162002-07-26 21:12:44 +000024static RegisterAnalysis<LoopInfo>
Chris Lattner17689df2002-07-30 16:27:52 +000025X("loops", "Natural Loop Construction", true);
Chris Lattner93193f82002-01-31 00:42:27 +000026
27//===----------------------------------------------------------------------===//
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000028// Loop implementation
Chris Lattner93193f82002-01-31 00:42:27 +000029//
Chris Lattner0f995552002-06-03 22:10:52 +000030bool Loop::contains(const BasicBlock *BB) const {
Chris Lattner0bbe58f2001-11-26 18:41:20 +000031 return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
32}
33
Misha Brukman6b290a52002-10-11 05:31:10 +000034bool Loop::isLoopExit(const BasicBlock *BB) const {
Chris Lattner03f252f2003-09-24 22:18:35 +000035 for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
Misha Brukman6b290a52002-10-11 05:31:10 +000036 SI != SE; ++SI) {
Chris Lattner5f82b8a2003-02-27 00:38:34 +000037 if (!contains(*SI))
Misha Brukman6b290a52002-10-11 05:31:10 +000038 return true;
39 }
40 return false;
41}
42
Chris Lattner2ef12362003-10-12 22:14:27 +000043/// getNumBackEdges - Calculate the number of back edges to the loop header.
44///
Misha Brukman6b290a52002-10-11 05:31:10 +000045unsigned Loop::getNumBackEdges() const {
Chris Lattner5f82b8a2003-02-27 00:38:34 +000046 unsigned NumBackEdges = 0;
47 BasicBlock *H = getHeader();
Misha Brukman6b290a52002-10-11 05:31:10 +000048
Chris Lattner2ef12362003-10-12 22:14:27 +000049 for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I)
50 if (contains(*I))
51 ++NumBackEdges;
52
Chris Lattner5f82b8a2003-02-27 00:38:34 +000053 return NumBackEdges;
Misha Brukman6b290a52002-10-11 05:31:10 +000054}
55
Chris Lattner7dd46b02003-08-16 20:57:16 +000056void Loop::print(std::ostream &OS, unsigned Depth) const {
57 OS << std::string(Depth*2, ' ') << "Loop Containing: ";
Chris Lattnera59cbb22002-07-27 01:12:17 +000058
59 for (unsigned i = 0; i < getBlocks().size(); ++i) {
60 if (i) OS << ",";
Chris Lattner5f82b8a2003-02-27 00:38:34 +000061 WriteAsOperand(OS, getBlocks()[i], false);
Chris Lattnera59cbb22002-07-27 01:12:17 +000062 }
Chris Lattner5f82b8a2003-02-27 00:38:34 +000063 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
Chris Lattnera59cbb22002-07-27 01:12:17 +000071 OS << "\n";
72
Chris Lattnerb1f8aeb2002-09-29 21:43:04 +000073 for (unsigned i = 0, e = getSubLoops().size(); i != e; ++i)
Chris Lattner7dd46b02003-08-16 20:57:16 +000074 getSubLoops()[i]->print(OS, Depth+2);
Chris Lattnera59cbb22002-07-27 01:12:17 +000075}
76
Chris Lattnerbb05f1e2003-02-28 16:54:45 +000077void Loop::dump() const {
78 print(std::cerr);
79}
80
Chris Lattner420df9b2003-02-22 21:33:11 +000081
Chris Lattnera59cbb22002-07-27 01:12:17 +000082//===----------------------------------------------------------------------===//
83// LoopInfo implementation
84//
Anand Shuklae0b6b782002-08-26 16:45:19 +000085void LoopInfo::stub() {}
Chris Lattnera59cbb22002-07-27 01:12:17 +000086
87bool LoopInfo::runOnFunction(Function &) {
88 releaseMemory();
89 Calculate(getAnalysis<DominatorSet>()); // Update
90 return false;
91}
92
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000093void LoopInfo::releaseMemory() {
Chris Lattner918c4ec2002-04-09 05:43:19 +000094 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
Chris Lattner93193f82002-01-31 00:42:27 +0000102
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000103void LoopInfo::Calculate(const DominatorSet &DS) {
Chris Lattnera298d272002-04-28 00:15:57 +0000104 BasicBlock *RootNode = DS.getRoot();
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000105
Chris Lattnera298d272002-04-28 00:15:57 +0000106 for (df_iterator<BasicBlock*> NI = df_begin(RootNode),
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000107 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
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000115void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000116 AU.setPreservesAll();
Chris Lattnerdd5b4952002-08-08 19:01:28 +0000117 AU.addRequired<DominatorSet>();
Chris Lattner93193f82002-01-31 00:42:27 +0000118}
119
Chris Lattnera59cbb22002-07-27 01:12:17 +0000120void LoopInfo::print(std::ostream &OS) const {
Chris Lattnerfce46ef2002-09-26 16:15:54 +0000121 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
122 TopLevelLoops[i]->print(OS);
Chris Lattner420df9b2003-02-22 21:33:11 +0000123#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
Chris Lattnera59cbb22002-07-27 01:12:17 +0000129}
Chris Lattner93193f82002-01-31 00:42:27 +0000130
Chris Lattner39c987a2003-05-15 18:03:51 +0000131static 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
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000137Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) {
Chris Lattner699b3052002-09-26 05:32:50 +0000138 if (BBMap.find(BB) != BBMap.end()) return 0; // Haven't processed this node?
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000139
Chris Lattnera298d272002-04-28 00:15:57 +0000140 std::vector<BasicBlock *> TodoStack;
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000141
142 // Scan the predecessors of BB, checking to see if BB dominates any of
Chris Lattner99224ae2003-04-26 19:34:18 +0000143 // them. This identifies backedges which target this node...
Chris Lattnera298d272002-04-28 00:15:57 +0000144 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000145 if (DS.dominates(BB, *I)) // If BB dominates it's predecessor...
146 TodoStack.push_back(*I);
147
Chris Lattner99224ae2003-04-26 19:34:18 +0000148 if (TodoStack.empty()) return 0; // No backedges to this block...
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000149
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
Chris Lattnera298d272002-04-28 00:15:57 +0000155 BasicBlock *X = TodoStack.back();
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000156 TodoStack.pop_back();
157
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000158 if (!L->contains(X)) { // As of yet unprocessed??
Chris Lattner99224ae2003-04-26 19:34:18 +0000159 // 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)))
Chris Lattner39c987a2003-05-15 18:03:51 +0000165 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
Chris Lattner99224ae2003-04-26 19:34:18 +0000166 // 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...
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000180 L->Blocks.push_back(X);
Chris Lattner99224ae2003-04-26 19:34:18 +0000181
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000182 // Add all of the predecessors of X to the end of the work stack...
Chris Lattner455889a2002-02-12 22:39:50 +0000183 TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000184 }
185 }
186
Chris Lattner420df9b2003-02-22 21:33:11 +0000187 // 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 }
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000194
Chris Lattner420df9b2003-02-22 21:33:11 +0000195 // 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 }
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000204
Chris Lattner7dd46b02003-08-16 20:57:16 +0000205 // 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) {
Chris Lattner169db9d2003-08-17 21:47:33 +0000229 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
Chris Lattner7dd46b02003-08-16 20:57:16 +0000234 // 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.
Chris Lattner169db9d2003-08-17 21:47:33 +0000237 MoveSiblingLoopInto(SubLoop, Child);
Chris Lattner7dd46b02003-08-16 20:57:16 +0000238 --i; // We just shrunk the SubLoops list.
239 }
240 }
241 }
242 }
243 }
244
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000245 // 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
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000253 return L;
254}
Chris Lattner699b3052002-09-26 05:32:50 +0000255
Chris Lattner7dd46b02003-08-16 20:57:16 +0000256/// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of
257/// the NewParent Loop, instead of being a sibling of it.
258void 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.
276void 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
Chris Lattner699b3052002-09-26 05:32:50 +0000294/// 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///
304BasicBlock *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)
Chris Lattnerc8f25d92002-09-29 22:59:29 +0000312 if (!contains(*PI)) { // If the block is not in the loop...
313 if (Out && Out != *PI)
314 return 0; // Multiple predecessors outside the loop
Chris Lattner699b3052002-09-26 05:32:50 +0000315 Out = *PI;
316 }
Chris Lattner5a8a2912003-02-27 21:51:38 +0000317
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
Chris Lattner699b3052002-09-26 05:32:50 +0000324
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///
336void 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}
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000351
Chris Lattnerf2e29252003-02-27 22:37:44 +0000352/// changeExitBlock - This method is used to update loop information. All
353/// instances of the specified Old basic block are removed from the exit list
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000354/// and replaced with New.
355///
356void 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!");
Chris Lattnera94837a2003-02-27 22:48:08 +0000359 assert(hasExitBlock(Old) && "Old exit block not found!");
360 std::vector<BasicBlock*>::iterator
361 I = std::find(ExitBlocks.begin(), ExitBlocks.end(), Old);
Chris Lattnerf2e29252003-02-27 22:37:44 +0000362 while (I != ExitBlocks.end()) {
363 *I = New;
364 I = std::find(I+1, ExitBlocks.end(), Old);
365 }
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000366}