934f7cf9a097ee2180e8068c38432c9c6ab2e560
[oota-llvm.git] / include / llvm / Analysis / LoopInfoImpl.h
1 //===- llvm/Analysis/LoopInfoImpl.h - Natural Loop Calculator ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the generic implementation of LoopInfo used for both Loops and
11 // MachineLoops.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_LOOPINFOIMPL_H
16 #define LLVM_ANALYSIS_LOOPINFOIMPL_H
17
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Analysis/LoopInfo.h"
23
24 namespace llvm {
25
26 //===----------------------------------------------------------------------===//
27 // APIs for simple analysis of the loop. See header notes.
28
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.
32 ///
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);
40          I != E; ++I)
41       if (!contains(*I)) {
42         // Not in current loop? It must be an exit block.
43         ExitingBlocks.push_back(*BI);
44         break;
45       }
46 }
47
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];
56   return 0;
57 }
58
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.
61 ///
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);
69          I != E; ++I)
70       if (!contains(*I))
71         // Not in current loop? It must be an exit block.
72         ExitBlocks.push_back(*I);
73 }
74
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)
82     return ExitBlocks[0];
83   return 0;
84 }
85
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);
94          I != E; ++I)
95       if (!contains(*I))
96         // Not in current loop? It must be an exit block.
97         ExitEdges.push_back(Edge(*BI, *I));
98 }
99
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.
104 ///
105 /// This method returns null if there is no preheader for the loop.
106 ///
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 0;
112
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);
116   ++SI;
117   if (SI != BlockTraits::child_end(Out))
118     return 0;  // Multiple exits from the block, must not be a preheader.
119
120   // The predecessor has exactly one successor, so it is a preheader.
121   return Out;
122 }
123
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.
128 ///
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 = 0;
133
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...
142       if (Out && Out != N)
143         return 0;             // Multiple predecessors outside the loop
144       Out = N;
145     }
146   }
147
148   // Make sure there is only one exit out of the preheader.
149   assert(Out && "Header of loop has no predecessors from outside loop?");
150   return Out;
151 }
152
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 = 0;
164   for (; PI != PE; ++PI) {
165     typename InvBlockTraits::NodeType *N = *PI;
166     if (contains(N)) {
167       if (Latch) return 0;
168       Latch = N;
169     }
170   }
171
172   return Latch;
173 }
174
175 //===----------------------------------------------------------------------===//
176 // APIs for updating loop information after changing the CFG
177 //
178
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.
184 ///
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!");
192
193   LoopT *L = static_cast<LoopT *>(this);
194
195   // Add the loop mapping to the LoopInfo object...
196   LIB.BBMap[NewBB] = L;
197
198   // Add the basic block to this loop and all parent loops...
199   while (L) {
200     L->addBlockEntry(NewBB);
201     L = L->getParentLoop();
202   }
203 }
204
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!");
217   *I = NewChild;
218   OldChild->ParentLoop = 0;
219   NewChild->ParentLoop = static_cast<LoopT *>(this);
220 }
221
222 /// verifyLoop - Verify loop structure
223 template<class BlockT, class LoopT>
224 void LoopBase<BlockT, LoopT>::verifyLoop() const {
225 #ifndef NDEBUG
226   assert(!Blocks.empty() && "Loop header is missing");
227
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);
236
237   // Keep track of the number of BBs visited.
238   unsigned NumVisited = 0;
239
240   // Check the individual blocks.
241   for ( ; BI != BE; ++BI) {
242     BlockT *BB = *BI;
243     bool HasInsideLoopSuccs = false;
244     bool HasInsideLoopPreds = false;
245     SmallVector<BlockT *, 2> OutsideLoopPreds;
246
247     typedef GraphTraits<BlockT*> BlockTraits;
248     for (typename BlockTraits::ChildIteratorType SI =
249            BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
250          SI != SE; ++SI)
251       if (contains(*SI)) {
252         HasInsideLoopSuccs = true;
253         break;
254       }
255     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
256     for (typename InvBlockTraits::ChildIteratorType PI =
257            InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
258          PI != PE; ++PI) {
259       BlockT *N = *PI;
260       if (contains(N))
261         HasInsideLoopPreds = true;
262       else
263         OutsideLoopPreds.push_back(N);
264     }
265
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
271       // reachable.
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!");
278     }
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!");
283
284     NumVisited++;
285   }
286
287   assert(NumVisited == getNumBlocks() && "Unreachable block in loop");
288
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();
293          BI != BE; ++BI) {
294         assert(contains(*BI) &&
295                "Loop does not contain all the blocks of a subloop!");
296     }
297
298   // Check the parent loop pointer.
299   if (ParentLoop) {
300     assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
301            ParentLoop->end() &&
302            "Loop is not a subloop of its parent!");
303   }
304 #endif
305 }
306
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));
312   // Verify this loop.
313   verifyLoop();
314   // Verify the subloops.
315   for (iterator I = begin(), E = end(); I != E; ++I)
316     (*I)->verifyLoopNest(Loops);
317 }
318
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()
322        << " containing: ";
323
324   for (unsigned i = 0; i < getBlocks().size(); ++i) {
325     if (i) OS << ",";
326     BlockT *BB = getBlocks()[i];
327     WriteAsOperand(OS, BB, false);
328     if (BB == getHeader())    OS << "<header>";
329     if (BB == getLoopLatch()) OS << "<latch>";
330     if (isLoopExiting(BB))    OS << "<exiting>";
331   }
332   OS << "\n";
333
334   for (iterator I = begin(), E = end(); I != E; ++I)
335     (*I)->print(OS, Depth+2);
336 }
337
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.
341 ///
342
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;
351
352   unsigned NumBlocks = 0;
353   unsigned NumSubloops = 0;
354
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();
360
361     LoopT *Subloop = LI->getLoopFor(PredBB);
362     if (!Subloop) {
363       if (!DomTree.isReachableFromEntry(PredBB))
364         continue;
365
366       // This is an undiscovered block. Map it to the current loop.
367       LI->changeLoopFor(PredBB, L);
368       ++NumBlocks;
369       if (PredBB == L->getHeader())
370           continue;
371       // Push all block predecessors on the worklist.
372       ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
373                                 InvBlockTraits::child_begin(PredBB),
374                                 InvBlockTraits::child_end(PredBB));
375     }
376     else {
377       // This is a discovered block. Find its outermost discovered loop.
378       while (LoopT *Parent = Subloop->getParentLoop())
379         Subloop = Parent;
380
381       // If it is already discovered to be a subloop of this loop, continue.
382       if (Subloop == L)
383         continue;
384
385       // Discover a subloop of this loop.
386       Subloop->setParentLoop(L);
387       ++NumSubloops;
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);
399       }
400     }
401   }
402   L->getSubLoopsVector().reserve(NumSubloops);
403   L->reserveBlocks(NumBlocks);
404 }
405
406 namespace {
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;
412
413   LoopInfoBase<BlockT, LoopT> *LI;
414   DenseSet<const BlockT *> VisitedBlocks;
415   std::vector<std::pair<BlockT*, SuccIterTy> > DFSStack;
416
417 public:
418   PopulateLoopsDFS(LoopInfoBase<BlockT, LoopT> *li):
419     LI(li) {}
420
421   void traverse(BlockT *EntryBlock);
422
423 protected:
424   void insertIntoLoop(BlockT *Block);
425
426   BlockT *dfsSource() { return DFSStack.back().first; }
427   SuccIterTy &dfsSucc() { return DFSStack.back().second; }
428   SuccIterTy dfsSuccEnd() { return BlockTraits::child_end(dfsSource()); }
429
430   void pushBlock(BlockT *Block) {
431     DFSStack.push_back(std::make_pair(Block, BlockTraits::child_begin(Block)));
432   }
433 };
434 } // anonymous
435
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();
445       ++dfsSucc();
446       if (!VisitedBlocks.insert(BB).second)
447         continue;
448
449       // Push the next DFS successor onto the stack.
450       pushBlock(BB);
451     }
452     // Visit the top of the stack in postorder and backtrack.
453     insertIntoLoop(dfsSource());
454     DFSStack.pop_back();
455   }
456 }
457
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
466     // the subloop.
467     if (Subloop->getParentLoop())
468       Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
469     else
470       LI->addTopLevelLoop(Subloop);
471
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());
477
478     Subloop = Subloop->getParentLoop();
479   }
480   for (; Subloop; Subloop = Subloop->getParentLoop())
481     Subloop->addBlockEntry(Block);
482 }
483
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).
490 ///
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.
495 ///
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) {
501
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) {
506
507     BlockT *Header = DomIter->getBlock();
508     SmallVector<BlockT *, 4> Backedges;
509
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) {
515
516       BlockT *Backedge = *PI;
517
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);
522       }
523     }
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);
528     }
529   }
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());
534 }
535
536 // Debugging
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);
541 #if 0
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";
546 #endif
547 }
548
549 } // End llvm namespace
550
551 #endif