1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
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"
24 static RegisterAnalysis<LoopInfo>
25 X("loops", "Natural Loop Construction", true);
27 //===----------------------------------------------------------------------===//
28 // Loop implementation
30 bool Loop::contains(const BasicBlock *BB) const {
31 return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
34 bool Loop::isLoopExit(const BasicBlock *BB) const {
35 for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
43 /// getNumBackEdges - Calculate the number of back edges to the loop header.
45 unsigned Loop::getNumBackEdges() const {
46 unsigned NumBackEdges = 0;
47 BasicBlock *H = getHeader();
49 for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I)
56 void Loop::print(std::ostream &OS, unsigned Depth) const {
57 OS << std::string(Depth*2, ' ') << "Loop Containing: ";
59 for (unsigned i = 0; i < getBlocks().size(); ++i) {
61 WriteAsOperand(OS, getBlocks()[i], false);
63 if (!ExitBlocks.empty()) {
64 OS << "\tExitBlocks: ";
65 for (unsigned i = 0; i < getExitBlocks().size(); ++i) {
67 WriteAsOperand(OS, getExitBlocks()[i], false);
73 for (unsigned i = 0, e = getSubLoops().size(); i != e; ++i)
74 getSubLoops()[i]->print(OS, Depth+2);
77 void Loop::dump() const {
82 //===----------------------------------------------------------------------===//
83 // LoopInfo implementation
85 void LoopInfo::stub() {}
87 bool LoopInfo::runOnFunction(Function &) {
89 Calculate(getAnalysis<DominatorSet>()); // Update
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...
98 BBMap.clear(); // Reset internal state of analysis
99 TopLevelLoops.clear();
103 void LoopInfo::Calculate(const DominatorSet &DS) {
104 BasicBlock *RootNode = DS.getRoot();
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);
111 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
112 TopLevelLoops[i]->setLoopDepth(1);
115 void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
116 AU.setPreservesAll();
117 AU.addRequired<DominatorSet>();
120 void LoopInfo::print(std::ostream &OS) const {
121 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
122 TopLevelLoops[i]->print(OS);
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";
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);
137 Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) {
138 if (BBMap.find(BB) != BBMap.end()) return 0; // Haven't processed this node?
140 std::vector<BasicBlock *> TodoStack;
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);
148 if (TodoStack.empty()) return 0; // No backedges to this block...
150 // Create a new loop to represent this basic block...
151 Loop *L = new Loop(BB);
154 BasicBlock *EntryBlock = &BB->getParent()->getEntryBlock();
156 while (!TodoStack.empty()) { // Process all the nodes in the loop
157 BasicBlock *X = TodoStack.back();
158 TodoStack.pop_back();
160 if (!L->contains(X) && // As of yet unprocessed??
161 DS.dominates(EntryBlock, X)) { // X is reachable from entry block?
162 // Check to see if this block already belongs to a loop. If this occurs
163 // then we have a case where a loop that is supposed to be a child of the
164 // current loop was processed before the current loop. When this occurs,
165 // this child loop gets added to a part of the current loop, making it a
166 // sibling to the current loop. We have to reparent this loop.
167 if (Loop *SubLoop = const_cast<Loop*>(getLoopFor(X)))
168 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
169 // Remove the subloop from it's current parent...
170 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
171 Loop *SLP = SubLoop->ParentLoop; // SubLoopParent
172 std::vector<Loop*>::iterator I =
173 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
174 assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?");
175 SLP->SubLoops.erase(I); // Remove from parent...
177 // Add the subloop to THIS loop...
178 SubLoop->ParentLoop = L;
179 L->SubLoops.push_back(SubLoop);
182 // Normal case, add the block to our loop...
183 L->Blocks.push_back(X);
185 // Add all of the predecessors of X to the end of the work stack...
186 TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
190 // If there are any loops nested within this loop, create them now!
191 for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
192 E = L->Blocks.end(); I != E; ++I)
193 if (Loop *NewLoop = ConsiderForLoop(*I, DS)) {
194 L->SubLoops.push_back(NewLoop);
195 NewLoop->ParentLoop = L;
198 // Add the basic blocks that comprise this loop to the BBMap so that this
199 // loop can be found for them.
201 for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
202 E = L->Blocks.end(); I != E; ++I) {
203 std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I);
204 if (BBMI == BBMap.end() || BBMI->first != *I) // Not in map yet...
205 BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level
208 // Now that we have a list of all of the child loops of this loop, check to
209 // see if any of them should actually be nested inside of each other. We can
210 // accidentally pull loops our of their parents, so we must make sure to
211 // organize the loop nests correctly now.
213 std::map<BasicBlock*, Loop*> ContainingLoops;
214 for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
215 Loop *Child = L->SubLoops[i];
216 assert(Child->getParentLoop() == L && "Not proper child loop?");
218 if (Loop *ContainingLoop = ContainingLoops[Child->getHeader()]) {
219 // If there is already a loop which contains this loop, move this loop
220 // into the containing loop.
221 MoveSiblingLoopInto(Child, ContainingLoop);
222 --i; // The loop got removed from the SubLoops list.
224 // This is currently considered to be a top-level loop. Check to see if
225 // any of the contained blocks are loop headers for subloops we have
226 // already processed.
227 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
228 Loop *&BlockLoop = ContainingLoops[Child->Blocks[b]];
229 if (BlockLoop == 0) { // Child block not processed yet...
231 } else if (BlockLoop != Child) {
232 Loop *SubLoop = BlockLoop;
233 // Reparent all of the blocks which used to belong to BlockLoops
234 for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
235 ContainingLoops[SubLoop->Blocks[j]] = Child;
237 // There is already a loop which contains this block, that means
238 // that we should reparent the loop which the block is currently
239 // considered to belong to to be a child of this loop.
240 MoveSiblingLoopInto(SubLoop, Child);
241 --i; // We just shrunk the SubLoops list.
248 // Now that we know all of the blocks that make up this loop, see if there are
249 // any branches to outside of the loop... building the ExitBlocks list.
250 for (std::vector<BasicBlock*>::iterator BI = L->Blocks.begin(),
251 BE = L->Blocks.end(); BI != BE; ++BI)
252 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
253 if (!L->contains(*I)) // Not in current loop?
254 L->ExitBlocks.push_back(*I); // It must be an exit block...
259 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of
260 /// the NewParent Loop, instead of being a sibling of it.
261 void LoopInfo::MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent) {
262 Loop *OldParent = NewChild->getParentLoop();
263 assert(OldParent && OldParent == NewParent->getParentLoop() &&
264 NewChild != NewParent && "Not sibling loops!");
266 // Remove NewChild from being a child of OldParent
267 std::vector<Loop*>::iterator I =
268 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild);
269 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
270 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
271 NewChild->ParentLoop = 0;
273 InsertLoopInto(NewChild, NewParent);
276 /// InsertLoopInto - This inserts loop L into the specified parent loop. If the
277 /// parent loop contains a loop which should contain L, the loop gets inserted
279 void LoopInfo::InsertLoopInto(Loop *L, Loop *Parent) {
280 BasicBlock *LHeader = L->getHeader();
281 assert(Parent->contains(LHeader) && "This loop should not be inserted here!");
283 // Check to see if it belongs in a child loop...
284 for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i)
285 if (Parent->SubLoops[i]->contains(LHeader)) {
286 InsertLoopInto(L, Parent->SubLoops[i]);
290 // If not, insert it here!
291 Parent->SubLoops.push_back(L);
292 L->ParentLoop = Parent;
297 /// getLoopPreheader - If there is a preheader for this loop, return it. A
298 /// loop has a preheader if there is only one edge to the header of the loop
299 /// from outside of the loop. If this is the case, the block branching to the
300 /// header of the loop is the preheader node. The "preheaders" pass can be
301 /// "Required" to ensure that there is always a preheader node for every loop.
303 /// This method returns null if there is no preheader for the loop (either
304 /// because the loop is dead or because multiple blocks branch to the header
305 /// node of this loop).
307 BasicBlock *Loop::getLoopPreheader() const {
308 // Keep track of nodes outside the loop branching to the header...
311 // Loop over the predecessors of the header node...
312 BasicBlock *Header = getHeader();
313 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
315 if (!contains(*PI)) { // If the block is not in the loop...
316 if (Out && Out != *PI)
317 return 0; // Multiple predecessors outside the loop
321 // Make sure there is only one exit out of the preheader...
322 succ_iterator SI = succ_begin(Out);
324 if (SI != succ_end(Out))
325 return 0; // Multiple exits from the block, must not be a preheader.
328 // If there is exactly one preheader, return it. If there was zero, then Out
333 /// addBasicBlockToLoop - This function is used by other analyses to update loop
334 /// information. NewBB is set to be a new member of the current loop. Because
335 /// of this, it is added as a member of all parent loops, and is added to the
336 /// specified LoopInfo object as being in the current basic block. It is not
337 /// valid to replace the loop header with this method.
339 void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) {
340 assert(LI[getHeader()] == this && "Incorrect LI specified for this loop!");
341 assert(NewBB && "Cannot add a null basic block to the loop!");
342 assert(LI[NewBB] == 0 && "BasicBlock already in the loop!");
344 // Add the loop mapping to the LoopInfo object...
345 LI.BBMap[NewBB] = this;
347 // Add the basic block to this loop and all parent loops...
350 L->Blocks.push_back(NewBB);
351 L = L->getParentLoop();
355 /// changeExitBlock - This method is used to update loop information. All
356 /// instances of the specified Old basic block are removed from the exit list
357 /// and replaced with New.
359 void Loop::changeExitBlock(BasicBlock *Old, BasicBlock *New) {
360 assert(Old != New && "Cannot changeExitBlock to the same thing!");
361 assert(Old && New && "Cannot changeExitBlock to or from a null node!");
362 assert(hasExitBlock(Old) && "Old exit block not found!");
363 std::vector<BasicBlock*>::iterator
364 I = std::find(ExitBlocks.begin(), ExitBlocks.end(), Old);
365 while (I != ExitBlocks.end()) {
367 I = std::find(I+1, ExitBlocks.end(), Old);