blob: a361e629e1a41e0ff3b75849a39b71ea55b5c773 [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 Lattner420df9b2003-02-22 21:33:11 +000071
Chris Lattnera59cbb22002-07-27 01:12:17 +000072//===----------------------------------------------------------------------===//
73// LoopInfo implementation
74//
Anand Shuklae0b6b782002-08-26 16:45:19 +000075void LoopInfo::stub() {}
Chris Lattnera59cbb22002-07-27 01:12:17 +000076
77bool LoopInfo::runOnFunction(Function &) {
78 releaseMemory();
79 Calculate(getAnalysis<DominatorSet>()); // Update
80 return false;
81}
82
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000083void LoopInfo::releaseMemory() {
Chris Lattner918c4ec2002-04-09 05:43:19 +000084 for (std::vector<Loop*>::iterator I = TopLevelLoops.begin(),
85 E = TopLevelLoops.end(); I != E; ++I)
86 delete *I; // Delete all of the loops...
87
88 BBMap.clear(); // Reset internal state of analysis
89 TopLevelLoops.clear();
90}
91
Chris Lattner93193f82002-01-31 00:42:27 +000092
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000093void LoopInfo::Calculate(const DominatorSet &DS) {
Chris Lattnera298d272002-04-28 00:15:57 +000094 BasicBlock *RootNode = DS.getRoot();
Chris Lattner0bbe58f2001-11-26 18:41:20 +000095
Chris Lattnera298d272002-04-28 00:15:57 +000096 for (df_iterator<BasicBlock*> NI = df_begin(RootNode),
Chris Lattner0bbe58f2001-11-26 18:41:20 +000097 NE = df_end(RootNode); NI != NE; ++NI)
98 if (Loop *L = ConsiderForLoop(*NI, DS))
99 TopLevelLoops.push_back(L);
100
101 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
102 TopLevelLoops[i]->setLoopDepth(1);
103}
104
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000105void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000106 AU.setPreservesAll();
Chris Lattnerdd5b4952002-08-08 19:01:28 +0000107 AU.addRequired<DominatorSet>();
Chris Lattner93193f82002-01-31 00:42:27 +0000108}
109
Chris Lattnera59cbb22002-07-27 01:12:17 +0000110void LoopInfo::print(std::ostream &OS) const {
Chris Lattnerfce46ef2002-09-26 16:15:54 +0000111 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
112 TopLevelLoops[i]->print(OS);
Chris Lattner420df9b2003-02-22 21:33:11 +0000113#if 0
114 for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
115 E = BBMap.end(); I != E; ++I)
116 OS << "BB '" << I->first->getName() << "' level = "
117 << I->second->LoopDepth << "\n";
118#endif
Chris Lattnera59cbb22002-07-27 01:12:17 +0000119}
Chris Lattner93193f82002-01-31 00:42:27 +0000120
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000121Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) {
Chris Lattner699b3052002-09-26 05:32:50 +0000122 if (BBMap.find(BB) != BBMap.end()) return 0; // Haven't processed this node?
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000123
Chris Lattnera298d272002-04-28 00:15:57 +0000124 std::vector<BasicBlock *> TodoStack;
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000125
126 // Scan the predecessors of BB, checking to see if BB dominates any of
127 // them.
Chris Lattnera298d272002-04-28 00:15:57 +0000128 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000129 if (DS.dominates(BB, *I)) // If BB dominates it's predecessor...
130 TodoStack.push_back(*I);
131
132 if (TodoStack.empty()) return 0; // Doesn't dominate any predecessors...
133
134 // Create a new loop to represent this basic block...
135 Loop *L = new Loop(BB);
136 BBMap[BB] = L;
137
138 while (!TodoStack.empty()) { // Process all the nodes in the loop
Chris Lattnera298d272002-04-28 00:15:57 +0000139 BasicBlock *X = TodoStack.back();
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000140 TodoStack.pop_back();
141
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000142 if (!L->contains(X)) { // As of yet unprocessed??
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000143 L->Blocks.push_back(X);
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000144
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000145 // Add all of the predecessors of X to the end of the work stack...
Chris Lattner455889a2002-02-12 22:39:50 +0000146 TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000147 }
148 }
149
Chris Lattner420df9b2003-02-22 21:33:11 +0000150 // If there are any loops nested within this loop, create them now!
151 for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
152 E = L->Blocks.end(); I != E; ++I)
153 if (Loop *NewLoop = ConsiderForLoop(*I, DS)) {
154 L->SubLoops.push_back(NewLoop);
155 NewLoop->ParentLoop = L;
156 }
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000157
Chris Lattner420df9b2003-02-22 21:33:11 +0000158
159 // Add the basic blocks that comprise this loop to the BBMap so that this
160 // loop can be found for them.
161 //
162 for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
163 E = L->Blocks.end(); I != E; ++I) {
164 std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I);
165 if (BBMI == BBMap.end() || BBMI->first != *I) // Not in map yet...
166 BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level
167 }
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000168
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000169 // Now that we know all of the blocks that make up this loop, see if there are
170 // any branches to outside of the loop... building the ExitBlocks list.
171 for (std::vector<BasicBlock*>::iterator BI = L->Blocks.begin(),
172 BE = L->Blocks.end(); BI != BE; ++BI)
173 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
174 if (!L->contains(*I)) // Not in current loop?
175 L->ExitBlocks.push_back(*I); // It must be an exit block...
176
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000177 return L;
178}
Chris Lattner699b3052002-09-26 05:32:50 +0000179
180/// getLoopPreheader - If there is a preheader for this loop, return it. A
181/// loop has a preheader if there is only one edge to the header of the loop
182/// from outside of the loop. If this is the case, the block branching to the
183/// header of the loop is the preheader node. The "preheaders" pass can be
184/// "Required" to ensure that there is always a preheader node for every loop.
185///
186/// This method returns null if there is no preheader for the loop (either
187/// because the loop is dead or because multiple blocks branch to the header
188/// node of this loop).
189///
190BasicBlock *Loop::getLoopPreheader() const {
191 // Keep track of nodes outside the loop branching to the header...
192 BasicBlock *Out = 0;
193
194 // Loop over the predecessors of the header node...
195 BasicBlock *Header = getHeader();
196 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
197 PI != PE; ++PI)
Chris Lattnerc8f25d92002-09-29 22:59:29 +0000198 if (!contains(*PI)) { // If the block is not in the loop...
199 if (Out && Out != *PI)
200 return 0; // Multiple predecessors outside the loop
Chris Lattner699b3052002-09-26 05:32:50 +0000201 Out = *PI;
202 }
203
204 // If there is exactly one preheader, return it. If there was zero, then Out
205 // is still null.
206 return Out;
207}
208
209/// addBasicBlockToLoop - This function is used by other analyses to update loop
210/// information. NewBB is set to be a new member of the current loop. Because
211/// of this, it is added as a member of all parent loops, and is added to the
212/// specified LoopInfo object as being in the current basic block. It is not
213/// valid to replace the loop header with this method.
214///
215void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) {
216 assert(LI[getHeader()] == this && "Incorrect LI specified for this loop!");
217 assert(NewBB && "Cannot add a null basic block to the loop!");
218 assert(LI[NewBB] == 0 && "BasicBlock already in the loop!");
219
220 // Add the loop mapping to the LoopInfo object...
221 LI.BBMap[NewBB] = this;
222
223 // Add the basic block to this loop and all parent loops...
224 Loop *L = this;
225 while (L) {
226 L->Blocks.push_back(NewBB);
227 L = L->getParentLoop();
228 }
229}
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000230
231/// changeExitBlock - This method is used to update loop information. One
232/// instance of the specified Old basic block is removed from the exit list
233/// and replaced with New.
234///
235void Loop::changeExitBlock(BasicBlock *Old, BasicBlock *New) {
236 assert(Old != New && "Cannot changeExitBlock to the same thing!");
237 assert(Old && New && "Cannot changeExitBlock to or from a null node!");
238 std::vector<BasicBlock*>::iterator I =
239 std::find(ExitBlocks.begin(), ExitBlocks.end(), Old);
240 assert(I != ExitBlocks.end() && "Old exit block not found!");
241 *I = New;
242}