blob: 251714cb00291cc624a9cc2b68d6771e04d2a86a [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 {
28 for (BasicBlock::succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
29 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
36unsigned Loop::getNumBackEdges() const {
Chris Lattner5f82b8a2003-02-27 00:38:34 +000037 unsigned NumBackEdges = 0;
38 BasicBlock *H = getHeader();
Misha Brukman6b290a52002-10-11 05:31:10 +000039
Chris Lattnere30c7632003-02-20 00:17:17 +000040 for (std::vector<BasicBlock*>::const_iterator I = Blocks.begin(),
Chris Lattner5f82b8a2003-02-27 00:38:34 +000041 E = Blocks.end(); I != E; ++I)
Chris Lattnere30c7632003-02-20 00:17:17 +000042 for (BasicBlock::succ_iterator SI = succ_begin(*I), SE = succ_end(*I);
43 SI != SE; ++SI)
Chris Lattner5f82b8a2003-02-27 00:38:34 +000044 if (*SI == H)
45 ++NumBackEdges;
46
47 return NumBackEdges;
Misha Brukman6b290a52002-10-11 05:31:10 +000048}
49
Chris Lattnera59cbb22002-07-27 01:12:17 +000050void Loop::print(std::ostream &OS) const {
51 OS << std::string(getLoopDepth()*2, ' ') << "Loop Containing: ";
52
53 for (unsigned i = 0; i < getBlocks().size(); ++i) {
54 if (i) OS << ",";
Chris Lattner5f82b8a2003-02-27 00:38:34 +000055 WriteAsOperand(OS, getBlocks()[i], false);
Chris Lattnera59cbb22002-07-27 01:12:17 +000056 }
Chris Lattner5f82b8a2003-02-27 00:38:34 +000057 if (!ExitBlocks.empty()) {
58 OS << "\tExitBlocks: ";
59 for (unsigned i = 0; i < getExitBlocks().size(); ++i) {
60 if (i) OS << ",";
61 WriteAsOperand(OS, getExitBlocks()[i], false);
62 }
63 }
64
Chris Lattnera59cbb22002-07-27 01:12:17 +000065 OS << "\n";
66
Chris Lattnerb1f8aeb2002-09-29 21:43:04 +000067 for (unsigned i = 0, e = getSubLoops().size(); i != e; ++i)
68 getSubLoops()[i]->print(OS);
Chris Lattnera59cbb22002-07-27 01:12:17 +000069}
70
Chris Lattnerbb05f1e2003-02-28 16:54:45 +000071void Loop::dump() const {
72 print(std::cerr);
73}
74
Chris Lattner420df9b2003-02-22 21:33:11 +000075
Chris Lattnera59cbb22002-07-27 01:12:17 +000076//===----------------------------------------------------------------------===//
77// LoopInfo implementation
78//
Anand Shuklae0b6b782002-08-26 16:45:19 +000079void LoopInfo::stub() {}
Chris Lattnera59cbb22002-07-27 01:12:17 +000080
81bool LoopInfo::runOnFunction(Function &) {
82 releaseMemory();
83 Calculate(getAnalysis<DominatorSet>()); // Update
84 return false;
85}
86
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000087void LoopInfo::releaseMemory() {
Chris Lattner918c4ec2002-04-09 05:43:19 +000088 for (std::vector<Loop*>::iterator I = TopLevelLoops.begin(),
89 E = TopLevelLoops.end(); I != E; ++I)
90 delete *I; // Delete all of the loops...
91
92 BBMap.clear(); // Reset internal state of analysis
93 TopLevelLoops.clear();
94}
95
Chris Lattner93193f82002-01-31 00:42:27 +000096
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000097void LoopInfo::Calculate(const DominatorSet &DS) {
Chris Lattnera298d272002-04-28 00:15:57 +000098 BasicBlock *RootNode = DS.getRoot();
Chris Lattner0bbe58f2001-11-26 18:41:20 +000099
Chris Lattnera298d272002-04-28 00:15:57 +0000100 for (df_iterator<BasicBlock*> NI = df_begin(RootNode),
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000101 NE = df_end(RootNode); NI != NE; ++NI)
102 if (Loop *L = ConsiderForLoop(*NI, DS))
103 TopLevelLoops.push_back(L);
104
105 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
106 TopLevelLoops[i]->setLoopDepth(1);
107}
108
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000109void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000110 AU.setPreservesAll();
Chris Lattnerdd5b4952002-08-08 19:01:28 +0000111 AU.addRequired<DominatorSet>();
Chris Lattner93193f82002-01-31 00:42:27 +0000112}
113
Chris Lattnera59cbb22002-07-27 01:12:17 +0000114void LoopInfo::print(std::ostream &OS) const {
Chris Lattnerfce46ef2002-09-26 16:15:54 +0000115 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
116 TopLevelLoops[i]->print(OS);
Chris Lattner420df9b2003-02-22 21:33:11 +0000117#if 0
118 for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
119 E = BBMap.end(); I != E; ++I)
120 OS << "BB '" << I->first->getName() << "' level = "
121 << I->second->LoopDepth << "\n";
122#endif
Chris Lattnera59cbb22002-07-27 01:12:17 +0000123}
Chris Lattner93193f82002-01-31 00:42:27 +0000124
Chris Lattner39c987a2003-05-15 18:03:51 +0000125static bool isNotAlreadyContainedIn(Loop *SubLoop, Loop *ParentLoop) {
126 if (SubLoop == 0) return true;
127 if (SubLoop == ParentLoop) return false;
128 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
129}
130
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000131Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) {
Chris Lattner699b3052002-09-26 05:32:50 +0000132 if (BBMap.find(BB) != BBMap.end()) return 0; // Haven't processed this node?
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000133
Chris Lattnera298d272002-04-28 00:15:57 +0000134 std::vector<BasicBlock *> TodoStack;
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000135
136 // Scan the predecessors of BB, checking to see if BB dominates any of
Chris Lattner99224ae2003-04-26 19:34:18 +0000137 // them. This identifies backedges which target this node...
Chris Lattnera298d272002-04-28 00:15:57 +0000138 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000139 if (DS.dominates(BB, *I)) // If BB dominates it's predecessor...
140 TodoStack.push_back(*I);
141
Chris Lattner99224ae2003-04-26 19:34:18 +0000142 if (TodoStack.empty()) return 0; // No backedges to this block...
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000143
144 // Create a new loop to represent this basic block...
145 Loop *L = new Loop(BB);
146 BBMap[BB] = L;
147
148 while (!TodoStack.empty()) { // Process all the nodes in the loop
Chris Lattnera298d272002-04-28 00:15:57 +0000149 BasicBlock *X = TodoStack.back();
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000150 TodoStack.pop_back();
151
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000152 if (!L->contains(X)) { // As of yet unprocessed??
Chris Lattner99224ae2003-04-26 19:34:18 +0000153 // Check to see if this block already belongs to a loop. If this occurs
154 // then we have a case where a loop that is supposed to be a child of the
155 // current loop was processed before the current loop. When this occurs,
156 // this child loop gets added to a part of the current loop, making it a
157 // sibling to the current loop. We have to reparent this loop.
158 if (Loop *SubLoop = const_cast<Loop*>(getLoopFor(X)))
Chris Lattner39c987a2003-05-15 18:03:51 +0000159 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
Chris Lattner99224ae2003-04-26 19:34:18 +0000160 // Remove the subloop from it's current parent...
161 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
162 Loop *SLP = SubLoop->ParentLoop; // SubLoopParent
163 std::vector<Loop*>::iterator I =
164 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
165 assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?");
166 SLP->SubLoops.erase(I); // Remove from parent...
167
168 // Add the subloop to THIS loop...
169 SubLoop->ParentLoop = L;
170 L->SubLoops.push_back(SubLoop);
171 }
172
173 // Normal case, add the block to our loop...
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000174 L->Blocks.push_back(X);
Chris Lattner99224ae2003-04-26 19:34:18 +0000175
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000176 // Add all of the predecessors of X to the end of the work stack...
Chris Lattner455889a2002-02-12 22:39:50 +0000177 TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000178 }
179 }
180
Chris Lattner420df9b2003-02-22 21:33:11 +0000181 // If there are any loops nested within this loop, create them now!
182 for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
183 E = L->Blocks.end(); I != E; ++I)
184 if (Loop *NewLoop = ConsiderForLoop(*I, DS)) {
185 L->SubLoops.push_back(NewLoop);
186 NewLoop->ParentLoop = L;
187 }
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000188
Chris Lattner420df9b2003-02-22 21:33:11 +0000189
190 // Add the basic blocks that comprise this loop to the BBMap so that this
191 // loop can be found for them.
192 //
193 for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
194 E = L->Blocks.end(); I != E; ++I) {
195 std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I);
196 if (BBMI == BBMap.end() || BBMI->first != *I) // Not in map yet...
197 BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level
198 }
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000199
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000200 // Now that we know all of the blocks that make up this loop, see if there are
201 // any branches to outside of the loop... building the ExitBlocks list.
202 for (std::vector<BasicBlock*>::iterator BI = L->Blocks.begin(),
203 BE = L->Blocks.end(); BI != BE; ++BI)
204 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
205 if (!L->contains(*I)) // Not in current loop?
206 L->ExitBlocks.push_back(*I); // It must be an exit block...
207
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000208 return L;
209}
Chris Lattner699b3052002-09-26 05:32:50 +0000210
211/// getLoopPreheader - If there is a preheader for this loop, return it. A
212/// loop has a preheader if there is only one edge to the header of the loop
213/// from outside of the loop. If this is the case, the block branching to the
214/// header of the loop is the preheader node. The "preheaders" pass can be
215/// "Required" to ensure that there is always a preheader node for every loop.
216///
217/// This method returns null if there is no preheader for the loop (either
218/// because the loop is dead or because multiple blocks branch to the header
219/// node of this loop).
220///
221BasicBlock *Loop::getLoopPreheader() const {
222 // Keep track of nodes outside the loop branching to the header...
223 BasicBlock *Out = 0;
224
225 // Loop over the predecessors of the header node...
226 BasicBlock *Header = getHeader();
227 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
228 PI != PE; ++PI)
Chris Lattnerc8f25d92002-09-29 22:59:29 +0000229 if (!contains(*PI)) { // If the block is not in the loop...
230 if (Out && Out != *PI)
231 return 0; // Multiple predecessors outside the loop
Chris Lattner699b3052002-09-26 05:32:50 +0000232 Out = *PI;
233 }
Chris Lattner5a8a2912003-02-27 21:51:38 +0000234
235 // Make sure there is only one exit out of the preheader...
236 succ_iterator SI = succ_begin(Out);
237 ++SI;
238 if (SI != succ_end(Out))
239 return 0; // Multiple exits from the block, must not be a preheader.
240
Chris Lattner699b3052002-09-26 05:32:50 +0000241
242 // If there is exactly one preheader, return it. If there was zero, then Out
243 // is still null.
244 return Out;
245}
246
247/// addBasicBlockToLoop - This function is used by other analyses to update loop
248/// information. NewBB is set to be a new member of the current loop. Because
249/// of this, it is added as a member of all parent loops, and is added to the
250/// specified LoopInfo object as being in the current basic block. It is not
251/// valid to replace the loop header with this method.
252///
253void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) {
254 assert(LI[getHeader()] == this && "Incorrect LI specified for this loop!");
255 assert(NewBB && "Cannot add a null basic block to the loop!");
256 assert(LI[NewBB] == 0 && "BasicBlock already in the loop!");
257
258 // Add the loop mapping to the LoopInfo object...
259 LI.BBMap[NewBB] = this;
260
261 // Add the basic block to this loop and all parent loops...
262 Loop *L = this;
263 while (L) {
264 L->Blocks.push_back(NewBB);
265 L = L->getParentLoop();
266 }
267}
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000268
Chris Lattnerf2e29252003-02-27 22:37:44 +0000269/// changeExitBlock - This method is used to update loop information. All
270/// instances of the specified Old basic block are removed from the exit list
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000271/// and replaced with New.
272///
273void Loop::changeExitBlock(BasicBlock *Old, BasicBlock *New) {
274 assert(Old != New && "Cannot changeExitBlock to the same thing!");
275 assert(Old && New && "Cannot changeExitBlock to or from a null node!");
Chris Lattnera94837a2003-02-27 22:48:08 +0000276 assert(hasExitBlock(Old) && "Old exit block not found!");
277 std::vector<BasicBlock*>::iterator
278 I = std::find(ExitBlocks.begin(), ExitBlocks.end(), Old);
Chris Lattnerf2e29252003-02-27 22:37:44 +0000279 while (I != ExitBlocks.end()) {
280 *I = New;
281 I = std::find(I+1, ExitBlocks.end(), Old);
282 }
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000283}