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();
111 if (!Out) return nullptr;
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 nullptr; // 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...
132 BlockT *Out = nullptr;
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 nullptr; // 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);
163 BlockT *Latch = nullptr;
164 for (; PI != PE; ++PI) {
165 typename InvBlockTraits::NodeType *N = *PI;
167 if (Latch) return nullptr;
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] && "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 && "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 = nullptr;
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 (BlockT *CB : depth_first(EntryBB))
274 for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
275 assert(CB != OutsideLoopPreds[i] &&
276 "Loop has multiple entry points!");
278 assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
279 assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
280 assert(BB != getHeader()->getParent()->begin() &&
281 "Loop contains function entry block!");
286 assert(NumVisited == getNumBlocks() && "Unreachable block in loop");
288 // Check the subloops.
289 for (iterator I = begin(), E = end(); I != E; ++I)
290 // Each block in each subloop should be contained within this loop.
291 for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
293 assert(contains(*BI) &&
294 "Loop does not contain all the blocks of a subloop!");
297 // Check the parent loop pointer.
299 assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
301 "Loop is not a subloop of its parent!");
306 /// verifyLoop - Verify loop structure of this loop and all nested loops.
307 template<class BlockT, class LoopT>
308 void LoopBase<BlockT, LoopT>::verifyLoopNest(
309 DenseSet<const LoopT*> *Loops) const {
310 Loops->insert(static_cast<const LoopT *>(this));
313 // Verify the subloops.
314 for (iterator I = begin(), E = end(); I != E; ++I)
315 (*I)->verifyLoopNest(Loops);
318 template<class BlockT, class LoopT>
319 void LoopBase<BlockT, LoopT>::print(raw_ostream &OS, unsigned Depth) const {
320 OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
323 for (unsigned i = 0; i < getBlocks().size(); ++i) {
325 BlockT *BB = getBlocks()[i];
326 BB->printAsOperand(OS, false);
327 if (BB == getHeader()) OS << "<header>";
328 if (BB == getLoopLatch()) OS << "<latch>";
329 if (isLoopExiting(BB)) OS << "<exiting>";
333 for (iterator I = begin(), E = end(); I != E; ++I)
334 (*I)->print(OS, Depth+2);
337 //===----------------------------------------------------------------------===//
338 /// Stable LoopInfo Analysis - Build a loop tree using stable iterators so the
339 /// result does / not depend on use list (block predecessor) order.
342 /// Discover a subloop with the specified backedges such that: All blocks within
343 /// this loop are mapped to this loop or a subloop. And all subloops within this
344 /// loop have their parent loop set to this loop or a subloop.
345 template<class BlockT, class LoopT>
346 static void discoverAndMapSubloop(LoopT *L, ArrayRef<BlockT*> Backedges,
347 LoopInfoBase<BlockT, LoopT> *LI,
348 DominatorTreeBase<BlockT> &DomTree) {
349 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
351 unsigned NumBlocks = 0;
352 unsigned NumSubloops = 0;
354 // Perform a backward CFG traversal using a worklist.
355 std::vector<BlockT *> ReverseCFGWorklist(Backedges.begin(), Backedges.end());
356 while (!ReverseCFGWorklist.empty()) {
357 BlockT *PredBB = ReverseCFGWorklist.back();
358 ReverseCFGWorklist.pop_back();
360 LoopT *Subloop = LI->getLoopFor(PredBB);
362 if (!DomTree.isReachableFromEntry(PredBB))
365 // This is an undiscovered block. Map it to the current loop.
366 LI->changeLoopFor(PredBB, L);
368 if (PredBB == L->getHeader())
370 // Push all block predecessors on the worklist.
371 ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
372 InvBlockTraits::child_begin(PredBB),
373 InvBlockTraits::child_end(PredBB));
376 // This is a discovered block. Find its outermost discovered loop.
377 while (LoopT *Parent = Subloop->getParentLoop())
380 // If it is already discovered to be a subloop of this loop, continue.
384 // Discover a subloop of this loop.
385 Subloop->setParentLoop(L);
387 NumBlocks += Subloop->getBlocks().capacity();
388 PredBB = Subloop->getHeader();
389 // Continue traversal along predecessors that are not loop-back edges from
390 // within this subloop tree itself. Note that a predecessor may directly
391 // reach another subloop that is not yet discovered to be a subloop of
392 // this loop, which we must traverse.
393 for (typename InvBlockTraits::ChildIteratorType PI =
394 InvBlockTraits::child_begin(PredBB),
395 PE = InvBlockTraits::child_end(PredBB); PI != PE; ++PI) {
396 if (LI->getLoopFor(*PI) != Subloop)
397 ReverseCFGWorklist.push_back(*PI);
401 L->getSubLoopsVector().reserve(NumSubloops);
402 L->reserveBlocks(NumBlocks);
405 /// Populate all loop data in a stable order during a single forward DFS.
406 template<class BlockT, class LoopT>
407 class PopulateLoopsDFS {
408 typedef GraphTraits<BlockT*> BlockTraits;
409 typedef typename BlockTraits::ChildIteratorType SuccIterTy;
411 LoopInfoBase<BlockT, LoopT> *LI;
412 DenseSet<const BlockT *> VisitedBlocks;
413 std::vector<std::pair<BlockT*, SuccIterTy> > DFSStack;
416 PopulateLoopsDFS(LoopInfoBase<BlockT, LoopT> *li):
419 void traverse(BlockT *EntryBlock);
422 void insertIntoLoop(BlockT *Block);
424 BlockT *dfsSource() { return DFSStack.back().first; }
425 SuccIterTy &dfsSucc() { return DFSStack.back().second; }
426 SuccIterTy dfsSuccEnd() { return BlockTraits::child_end(dfsSource()); }
428 void pushBlock(BlockT *Block) {
429 DFSStack.push_back(std::make_pair(Block, BlockTraits::child_begin(Block)));
433 /// Top-level driver for the forward DFS within the loop.
434 template<class BlockT, class LoopT>
435 void PopulateLoopsDFS<BlockT, LoopT>::traverse(BlockT *EntryBlock) {
436 pushBlock(EntryBlock);
437 VisitedBlocks.insert(EntryBlock);
438 while (!DFSStack.empty()) {
439 // Traverse the leftmost path as far as possible.
440 while (dfsSucc() != dfsSuccEnd()) {
441 BlockT *BB = *dfsSucc();
443 if (!VisitedBlocks.insert(BB).second)
446 // Push the next DFS successor onto the stack.
449 // Visit the top of the stack in postorder and backtrack.
450 insertIntoLoop(dfsSource());
455 /// Add a single Block to its ancestor loops in PostOrder. If the block is a
456 /// subloop header, add the subloop to its parent in PostOrder, then reverse the
457 /// Block and Subloop vectors of the now complete subloop to achieve RPO.
458 template<class BlockT, class LoopT>
459 void PopulateLoopsDFS<BlockT, LoopT>::insertIntoLoop(BlockT *Block) {
460 LoopT *Subloop = LI->getLoopFor(Block);
461 if (Subloop && Block == Subloop->getHeader()) {
462 // We reach this point once per subloop after processing all the blocks in
464 if (Subloop->getParentLoop())
465 Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
467 LI->addTopLevelLoop(Subloop);
469 // For convenience, Blocks and Subloops are inserted in postorder. Reverse
470 // the lists, except for the loop header, which is always at the beginning.
471 Subloop->reverseBlock(1);
472 std::reverse(Subloop->getSubLoopsVector().begin(),
473 Subloop->getSubLoopsVector().end());
475 Subloop = Subloop->getParentLoop();
477 for (; Subloop; Subloop = Subloop->getParentLoop())
478 Subloop->addBlockEntry(Block);
481 /// Analyze LoopInfo discovers loops during a postorder DominatorTree traversal
482 /// interleaved with backward CFG traversals within each subloop
483 /// (discoverAndMapSubloop). The backward traversal skips inner subloops, so
484 /// this part of the algorithm is linear in the number of CFG edges. Subloop and
485 /// Block vectors are then populated during a single forward CFG traversal
486 /// (PopulateLoopDFS).
488 /// During the two CFG traversals each block is seen three times:
489 /// 1) Discovered and mapped by a reverse CFG traversal.
490 /// 2) Visited during a forward DFS CFG traversal.
491 /// 3) Reverse-inserted in the loop in postorder following forward DFS.
493 /// The Block vectors are inclusive, so step 3 requires loop-depth number of
494 /// insertions per block.
495 template<class BlockT, class LoopT>
496 void LoopInfoBase<BlockT, LoopT>::
497 Analyze(DominatorTreeBase<BlockT> &DomTree) {
499 // Postorder traversal of the dominator tree.
500 DomTreeNodeBase<BlockT>* DomRoot = DomTree.getRootNode();
501 for (po_iterator<DomTreeNodeBase<BlockT>*> DomIter = po_begin(DomRoot),
502 DomEnd = po_end(DomRoot); DomIter != DomEnd; ++DomIter) {
504 BlockT *Header = DomIter->getBlock();
505 SmallVector<BlockT *, 4> Backedges;
507 // Check each predecessor of the potential loop header.
508 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
509 for (typename InvBlockTraits::ChildIteratorType PI =
510 InvBlockTraits::child_begin(Header),
511 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
513 BlockT *Backedge = *PI;
515 // If Header dominates predBB, this is a new loop. Collect the backedges.
516 if (DomTree.dominates(Header, Backedge)
517 && DomTree.isReachableFromEntry(Backedge)) {
518 Backedges.push_back(Backedge);
521 // Perform a backward CFG traversal to discover and map blocks in this loop.
522 if (!Backedges.empty()) {
523 LoopT *L = new LoopT(Header);
524 discoverAndMapSubloop(L, ArrayRef<BlockT*>(Backedges), this, DomTree);
527 // Perform a single forward CFG traversal to populate block and subloop
528 // vectors for all loops.
529 PopulateLoopsDFS<BlockT, LoopT> DFS(this);
530 DFS.traverse(DomRoot->getBlock());
534 template<class BlockT, class LoopT>
535 void LoopInfoBase<BlockT, LoopT>::print(raw_ostream &OS) const {
536 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
537 TopLevelLoops[i]->print(OS);
539 for (DenseMap<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
540 E = BBMap.end(); I != E; ++I)
541 OS << "BB '" << I->first->getName() << "' level = "
542 << I->second->getLoopDepth() << "\n";
546 template<class BlockT, class LoopT>
547 void LoopInfoBase<BlockT, LoopT>::verify() const {
548 DenseSet<const LoopT*> Loops;
549 for (iterator I = begin(), E = end(); I != E; ++I) {
550 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
551 (*I)->verifyLoopNest(&Loops);
554 // Verify that blocks are mapped to valid loops.
556 for (auto &Entry : BBMap) {
557 BlockT *BB = Entry.first;
558 LoopT *L = Entry.second;
559 assert(Loops.count(L) && "orphaned loop");
560 assert(L->contains(BB) && "orphaned block");
565 } // End llvm namespace