1 //===- llvm/Analysis/LoopInfoImpl.h - Natural Loop Calculator ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the generic implementation of LoopInfo used for both Loops and
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_LOOPINFOIMPL_H
16 #define LLVM_ANALYSIS_LOOPINFOIMPL_H
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/IR/Dominators.h"
26 //===----------------------------------------------------------------------===//
27 // APIs for simple analysis of the loop. See header notes.
29 /// getExitingBlocks - Return all blocks inside the loop that have successors
30 /// outside of the loop. These are the blocks _inside of the current loop_
31 /// which branch out. The returned list is always unique.
33 template<class BlockT, class LoopT>
34 void LoopBase<BlockT, LoopT>::
35 getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
36 typedef GraphTraits<BlockT*> BlockTraits;
37 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
38 for (typename BlockTraits::ChildIteratorType I =
39 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
42 // Not in current loop? It must be an exit block.
43 ExitingBlocks.push_back(*BI);
48 /// getExitingBlock - If getExitingBlocks would return exactly one block,
49 /// return that block. Otherwise return null.
50 template<class BlockT, class LoopT>
51 BlockT *LoopBase<BlockT, LoopT>::getExitingBlock() const {
52 SmallVector<BlockT*, 8> ExitingBlocks;
53 getExitingBlocks(ExitingBlocks);
54 if (ExitingBlocks.size() == 1)
55 return ExitingBlocks[0];
59 /// getExitBlocks - Return all of the successor blocks of this loop. These
60 /// are the blocks _outside of the current loop_ which are branched to.
62 template<class BlockT, class LoopT>
63 void LoopBase<BlockT, LoopT>::
64 getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
65 typedef GraphTraits<BlockT*> BlockTraits;
66 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
67 for (typename BlockTraits::ChildIteratorType I =
68 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
71 // Not in current loop? It must be an exit block.
72 ExitBlocks.push_back(*I);
75 /// getExitBlock - If getExitBlocks would return exactly one block,
76 /// return that block. Otherwise return null.
77 template<class BlockT, class LoopT>
78 BlockT *LoopBase<BlockT, LoopT>::getExitBlock() const {
79 SmallVector<BlockT*, 8> ExitBlocks;
80 getExitBlocks(ExitBlocks);
81 if (ExitBlocks.size() == 1)
86 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
87 template<class BlockT, class LoopT>
88 void LoopBase<BlockT, LoopT>::
89 getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const {
90 typedef GraphTraits<BlockT*> BlockTraits;
91 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
92 for (typename BlockTraits::ChildIteratorType I =
93 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
96 // Not in current loop? It must be an exit block.
97 ExitEdges.push_back(Edge(*BI, *I));
100 /// getLoopPreheader - If there is a preheader for this loop, return it. A
101 /// loop has a preheader if there is only one edge to the header of the loop
102 /// from outside of the loop. If this is the case, the block branching to the
103 /// header of the loop is the preheader node.
105 /// This method returns null if there is no preheader for the loop.
107 template<class BlockT, class LoopT>
108 BlockT *LoopBase<BlockT, LoopT>::getLoopPreheader() const {
109 // Keep track of nodes outside the loop branching to the header...
110 BlockT *Out = getLoopPredecessor();
113 // Make sure there is only one exit out of the preheader.
114 typedef GraphTraits<BlockT*> BlockTraits;
115 typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
117 if (SI != BlockTraits::child_end(Out))
118 return 0; // Multiple exits from the block, must not be a preheader.
120 // The predecessor has exactly one successor, so it is a preheader.
124 /// getLoopPredecessor - If the given loop's header has exactly one unique
125 /// predecessor outside the loop, return it. Otherwise return null.
126 /// This is less strict that the loop "preheader" concept, which requires
127 /// the predecessor to have exactly one successor.
129 template<class BlockT, class LoopT>
130 BlockT *LoopBase<BlockT, LoopT>::getLoopPredecessor() const {
131 // Keep track of nodes outside the loop branching to the header...
134 // Loop over the predecessors of the header node...
135 BlockT *Header = getHeader();
136 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
137 for (typename InvBlockTraits::ChildIteratorType PI =
138 InvBlockTraits::child_begin(Header),
139 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
140 typename InvBlockTraits::NodeType *N = *PI;
141 if (!contains(N)) { // If the block is not in the loop...
143 return 0; // Multiple predecessors outside the loop
148 // Make sure there is only one exit out of the preheader.
149 assert(Out && "Header of loop has no predecessors from outside loop?");
153 /// getLoopLatch - If there is a single latch block for this loop, return it.
154 /// A latch block is a block that contains a branch back to the header.
155 template<class BlockT, class LoopT>
156 BlockT *LoopBase<BlockT, LoopT>::getLoopLatch() const {
157 BlockT *Header = getHeader();
158 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
159 typename InvBlockTraits::ChildIteratorType PI =
160 InvBlockTraits::child_begin(Header);
161 typename InvBlockTraits::ChildIteratorType PE =
162 InvBlockTraits::child_end(Header);
164 for (; PI != PE; ++PI) {
165 typename InvBlockTraits::NodeType *N = *PI;
175 //===----------------------------------------------------------------------===//
176 // APIs for updating loop information after changing the CFG
179 /// addBasicBlockToLoop - This method is used by other analyses to update loop
180 /// information. NewBB is set to be a new member of the current loop.
181 /// Because of this, it is added as a member of all parent loops, and is added
182 /// to the specified LoopInfo object as being in the current basic block. It
183 /// is not valid to replace the loop header with this method.
185 template<class BlockT, class LoopT>
186 void LoopBase<BlockT, LoopT>::
187 addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LIB) {
188 assert((Blocks.empty() || LIB[getHeader()] == this) &&
189 "Incorrect LI specified for this loop!");
190 assert(NewBB && "Cannot add a null basic block to the loop!");
191 assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
193 LoopT *L = static_cast<LoopT *>(this);
195 // Add the loop mapping to the LoopInfo object...
196 LIB.BBMap[NewBB] = L;
198 // Add the basic block to this loop and all parent loops...
200 L->addBlockEntry(NewBB);
201 L = L->getParentLoop();
205 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
206 /// the OldChild entry in our children list with NewChild, and updates the
207 /// parent pointer of OldChild to be null and the NewChild to be this loop.
208 /// This updates the loop depth of the new child.
209 template<class BlockT, class LoopT>
210 void LoopBase<BlockT, LoopT>::
211 replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild) {
212 assert(OldChild->ParentLoop == this && "This loop is already broken!");
213 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
214 typename std::vector<LoopT *>::iterator I =
215 std::find(SubLoops.begin(), SubLoops.end(), OldChild);
216 assert(I != SubLoops.end() && "OldChild not in loop!");
218 OldChild->ParentLoop = 0;
219 NewChild->ParentLoop = static_cast<LoopT *>(this);
222 /// verifyLoop - Verify loop structure
223 template<class BlockT, class LoopT>
224 void LoopBase<BlockT, LoopT>::verifyLoop() const {
226 assert(!Blocks.empty() && "Loop header is missing");
228 // Setup for using a depth-first iterator to visit every block in the loop.
229 SmallVector<BlockT*, 8> ExitBBs;
230 getExitBlocks(ExitBBs);
231 llvm::SmallPtrSet<BlockT*, 8> VisitSet;
232 VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
233 df_ext_iterator<BlockT*, llvm::SmallPtrSet<BlockT*, 8> >
234 BI = df_ext_begin(getHeader(), VisitSet),
235 BE = df_ext_end(getHeader(), VisitSet);
237 // Keep track of the number of BBs visited.
238 unsigned NumVisited = 0;
240 // Check the individual blocks.
241 for ( ; BI != BE; ++BI) {
243 bool HasInsideLoopSuccs = false;
244 bool HasInsideLoopPreds = false;
245 SmallVector<BlockT *, 2> OutsideLoopPreds;
247 typedef GraphTraits<BlockT*> BlockTraits;
248 for (typename BlockTraits::ChildIteratorType SI =
249 BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
252 HasInsideLoopSuccs = true;
255 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
256 for (typename InvBlockTraits::ChildIteratorType PI =
257 InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
261 HasInsideLoopPreds = true;
263 OutsideLoopPreds.push_back(N);
266 if (BB == getHeader()) {
267 assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
268 } else if (!OutsideLoopPreds.empty()) {
269 // A non-header loop shouldn't be reachable from outside the loop,
270 // though it is permitted if the predecessor is not itself actually
272 BlockT *EntryBB = BB->getParent()->begin();
273 for (df_iterator<BlockT *> NI = df_begin(EntryBB),
274 NE = df_end(EntryBB); NI != NE; ++NI)
275 for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
276 assert(*NI != OutsideLoopPreds[i] &&
277 "Loop has multiple entry points!");
279 assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
280 assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
281 assert(BB != getHeader()->getParent()->begin() &&
282 "Loop contains function entry block!");
287 assert(NumVisited == getNumBlocks() && "Unreachable block in loop");
289 // Check the subloops.
290 for (iterator I = begin(), E = end(); I != E; ++I)
291 // Each block in each subloop should be contained within this loop.
292 for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
294 assert(contains(*BI) &&
295 "Loop does not contain all the blocks of a subloop!");
298 // Check the parent loop pointer.
300 assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
302 "Loop is not a subloop of its parent!");
307 /// verifyLoop - Verify loop structure of this loop and all nested loops.
308 template<class BlockT, class LoopT>
309 void LoopBase<BlockT, LoopT>::verifyLoopNest(
310 DenseSet<const LoopT*> *Loops) const {
311 Loops->insert(static_cast<const LoopT *>(this));
314 // Verify the subloops.
315 for (iterator I = begin(), E = end(); I != E; ++I)
316 (*I)->verifyLoopNest(Loops);
319 template<class BlockT, class LoopT>
320 void LoopBase<BlockT, LoopT>::print(raw_ostream &OS, unsigned Depth) const {
321 OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
324 for (unsigned i = 0; i < getBlocks().size(); ++i) {
326 BlockT *BB = getBlocks()[i];
327 BB->printAsOperand(OS, false);
328 if (BB == getHeader()) OS << "<header>";
329 if (BB == getLoopLatch()) OS << "<latch>";
330 if (isLoopExiting(BB)) OS << "<exiting>";
334 for (iterator I = begin(), E = end(); I != E; ++I)
335 (*I)->print(OS, Depth+2);
338 //===----------------------------------------------------------------------===//
339 /// Stable LoopInfo Analysis - Build a loop tree using stable iterators so the
340 /// result does / not depend on use list (block predecessor) order.
343 /// Discover a subloop with the specified backedges such that: All blocks within
344 /// this loop are mapped to this loop or a subloop. And all subloops within this
345 /// loop have their parent loop set to this loop or a subloop.
346 template<class BlockT, class LoopT>
347 static void discoverAndMapSubloop(LoopT *L, ArrayRef<BlockT*> Backedges,
348 LoopInfoBase<BlockT, LoopT> *LI,
349 DominatorTreeBase<BlockT> &DomTree) {
350 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
352 unsigned NumBlocks = 0;
353 unsigned NumSubloops = 0;
355 // Perform a backward CFG traversal using a worklist.
356 std::vector<BlockT *> ReverseCFGWorklist(Backedges.begin(), Backedges.end());
357 while (!ReverseCFGWorklist.empty()) {
358 BlockT *PredBB = ReverseCFGWorklist.back();
359 ReverseCFGWorklist.pop_back();
361 LoopT *Subloop = LI->getLoopFor(PredBB);
363 if (!DomTree.isReachableFromEntry(PredBB))
366 // This is an undiscovered block. Map it to the current loop.
367 LI->changeLoopFor(PredBB, L);
369 if (PredBB == L->getHeader())
371 // Push all block predecessors on the worklist.
372 ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
373 InvBlockTraits::child_begin(PredBB),
374 InvBlockTraits::child_end(PredBB));
377 // This is a discovered block. Find its outermost discovered loop.
378 while (LoopT *Parent = Subloop->getParentLoop())
381 // If it is already discovered to be a subloop of this loop, continue.
385 // Discover a subloop of this loop.
386 Subloop->setParentLoop(L);
388 NumBlocks += Subloop->getBlocks().capacity();
389 PredBB = Subloop->getHeader();
390 // Continue traversal along predecessors that are not loop-back edges from
391 // within this subloop tree itself. Note that a predecessor may directly
392 // reach another subloop that is not yet discovered to be a subloop of
393 // this loop, which we must traverse.
394 for (typename InvBlockTraits::ChildIteratorType PI =
395 InvBlockTraits::child_begin(PredBB),
396 PE = InvBlockTraits::child_end(PredBB); PI != PE; ++PI) {
397 if (LI->getLoopFor(*PI) != Subloop)
398 ReverseCFGWorklist.push_back(*PI);
402 L->getSubLoopsVector().reserve(NumSubloops);
403 L->reserveBlocks(NumBlocks);
407 /// Populate all loop data in a stable order during a single forward DFS.
408 template<class BlockT, class LoopT>
409 class PopulateLoopsDFS {
410 typedef GraphTraits<BlockT*> BlockTraits;
411 typedef typename BlockTraits::ChildIteratorType SuccIterTy;
413 LoopInfoBase<BlockT, LoopT> *LI;
414 DenseSet<const BlockT *> VisitedBlocks;
415 std::vector<std::pair<BlockT*, SuccIterTy> > DFSStack;
418 PopulateLoopsDFS(LoopInfoBase<BlockT, LoopT> *li):
421 void traverse(BlockT *EntryBlock);
424 void insertIntoLoop(BlockT *Block);
426 BlockT *dfsSource() { return DFSStack.back().first; }
427 SuccIterTy &dfsSucc() { return DFSStack.back().second; }
428 SuccIterTy dfsSuccEnd() { return BlockTraits::child_end(dfsSource()); }
430 void pushBlock(BlockT *Block) {
431 DFSStack.push_back(std::make_pair(Block, BlockTraits::child_begin(Block)));
436 /// Top-level driver for the forward DFS within the loop.
437 template<class BlockT, class LoopT>
438 void PopulateLoopsDFS<BlockT, LoopT>::traverse(BlockT *EntryBlock) {
439 pushBlock(EntryBlock);
440 VisitedBlocks.insert(EntryBlock);
441 while (!DFSStack.empty()) {
442 // Traverse the leftmost path as far as possible.
443 while (dfsSucc() != dfsSuccEnd()) {
444 BlockT *BB = *dfsSucc();
446 if (!VisitedBlocks.insert(BB).second)
449 // Push the next DFS successor onto the stack.
452 // Visit the top of the stack in postorder and backtrack.
453 insertIntoLoop(dfsSource());
458 /// Add a single Block to its ancestor loops in PostOrder. If the block is a
459 /// subloop header, add the subloop to its parent in PostOrder, then reverse the
460 /// Block and Subloop vectors of the now complete subloop to achieve RPO.
461 template<class BlockT, class LoopT>
462 void PopulateLoopsDFS<BlockT, LoopT>::insertIntoLoop(BlockT *Block) {
463 LoopT *Subloop = LI->getLoopFor(Block);
464 if (Subloop && Block == Subloop->getHeader()) {
465 // We reach this point once per subloop after processing all the blocks in
467 if (Subloop->getParentLoop())
468 Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
470 LI->addTopLevelLoop(Subloop);
472 // For convenience, Blocks and Subloops are inserted in postorder. Reverse
473 // the lists, except for the loop header, which is always at the beginning.
474 Subloop->reverseBlock(1);
475 std::reverse(Subloop->getSubLoopsVector().begin(),
476 Subloop->getSubLoopsVector().end());
478 Subloop = Subloop->getParentLoop();
480 for (; Subloop; Subloop = Subloop->getParentLoop())
481 Subloop->addBlockEntry(Block);
484 /// Analyze LoopInfo discovers loops during a postorder DominatorTree traversal
485 /// interleaved with backward CFG traversals within each subloop
486 /// (discoverAndMapSubloop). The backward traversal skips inner subloops, so
487 /// this part of the algorithm is linear in the number of CFG edges. Subloop and
488 /// Block vectors are then populated during a single forward CFG traversal
489 /// (PopulateLoopDFS).
491 /// During the two CFG traversals each block is seen three times:
492 /// 1) Discovered and mapped by a reverse CFG traversal.
493 /// 2) Visited during a forward DFS CFG traversal.
494 /// 3) Reverse-inserted in the loop in postorder following forward DFS.
496 /// The Block vectors are inclusive, so step 3 requires loop-depth number of
497 /// insertions per block.
498 template<class BlockT, class LoopT>
499 void LoopInfoBase<BlockT, LoopT>::
500 Analyze(DominatorTreeBase<BlockT> &DomTree) {
502 // Postorder traversal of the dominator tree.
503 DomTreeNodeBase<BlockT>* DomRoot = DomTree.getRootNode();
504 for (po_iterator<DomTreeNodeBase<BlockT>*> DomIter = po_begin(DomRoot),
505 DomEnd = po_end(DomRoot); DomIter != DomEnd; ++DomIter) {
507 BlockT *Header = DomIter->getBlock();
508 SmallVector<BlockT *, 4> Backedges;
510 // Check each predecessor of the potential loop header.
511 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
512 for (typename InvBlockTraits::ChildIteratorType PI =
513 InvBlockTraits::child_begin(Header),
514 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
516 BlockT *Backedge = *PI;
518 // If Header dominates predBB, this is a new loop. Collect the backedges.
519 if (DomTree.dominates(Header, Backedge)
520 && DomTree.isReachableFromEntry(Backedge)) {
521 Backedges.push_back(Backedge);
524 // Perform a backward CFG traversal to discover and map blocks in this loop.
525 if (!Backedges.empty()) {
526 LoopT *L = new LoopT(Header);
527 discoverAndMapSubloop(L, ArrayRef<BlockT*>(Backedges), this, DomTree);
530 // Perform a single forward CFG traversal to populate block and subloop
531 // vectors for all loops.
532 PopulateLoopsDFS<BlockT, LoopT> DFS(this);
533 DFS.traverse(DomRoot->getBlock());
537 template<class BlockT, class LoopT>
538 void LoopInfoBase<BlockT, LoopT>::print(raw_ostream &OS) const {
539 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
540 TopLevelLoops[i]->print(OS);
542 for (DenseMap<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
543 E = BBMap.end(); I != E; ++I)
544 OS << "BB '" << I->first->getName() << "' level = "
545 << I->second->getLoopDepth() << "\n";
549 } // End llvm namespace