]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Analysis/LoopInfoImpl.h
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/ADT/SetVector.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/IR/Dominators.h"
24
25 namespace llvm {
26
27 //===----------------------------------------------------------------------===//
28 // APIs for simple analysis of the loop. See header notes.
29
30 /// getExitingBlocks - Return all blocks inside the loop that have successors
31 /// outside of the loop.  These are the blocks _inside of the current loop_
32 /// which branch out.  The returned list is always unique.
33 ///
34 template <class BlockT, class LoopT>
35 void LoopBase<BlockT, LoopT>::getExitingBlocks(
36     SmallVectorImpl<BlockT *> &ExitingBlocks) const {
37   assert(!isInvalid() && "Loop not in a valid state!");
38   for (const auto BB : blocks())
39     for (const auto &Succ : children<BlockT *>(BB))
40       if (!contains(Succ)) {
41         // Not in current loop? It must be an exit block.
42         ExitingBlocks.push_back(BB);
43         break;
44       }
45 }
46
47 /// getExitingBlock - If getExitingBlocks would return exactly one block,
48 /// return that block. Otherwise return null.
49 template <class BlockT, class LoopT>
50 BlockT *LoopBase<BlockT, LoopT>::getExitingBlock() const {
51   assert(!isInvalid() && "Loop not in a valid state!");
52   SmallVector<BlockT *, 8> ExitingBlocks;
53   getExitingBlocks(ExitingBlocks);
54   if (ExitingBlocks.size() == 1)
55     return ExitingBlocks[0];
56   return nullptr;
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>::getExitBlocks(
64     SmallVectorImpl<BlockT *> &ExitBlocks) const {
65   assert(!isInvalid() && "Loop not in a valid state!");
66   for (const auto BB : blocks())
67     for (const auto &Succ : children<BlockT *>(BB))
68       if (!contains(Succ))
69         // Not in current loop? It must be an exit block.
70         ExitBlocks.push_back(Succ);
71 }
72
73 /// getExitBlock - If getExitBlocks would return exactly one block,
74 /// return that block. Otherwise return null.
75 template <class BlockT, class LoopT>
76 BlockT *LoopBase<BlockT, LoopT>::getExitBlock() const {
77   assert(!isInvalid() && "Loop not in a valid state!");
78   SmallVector<BlockT *, 8> ExitBlocks;
79   getExitBlocks(ExitBlocks);
80   if (ExitBlocks.size() == 1)
81     return ExitBlocks[0];
82   return nullptr;
83 }
84
85 template <class BlockT, class LoopT>
86 bool LoopBase<BlockT, LoopT>::hasDedicatedExits() const {
87   // Each predecessor of each exit block of a normal loop is contained
88   // within the loop.
89   SmallVector<BlockT *, 4> ExitBlocks;
90   getExitBlocks(ExitBlocks);
91   for (BlockT *EB : ExitBlocks)
92     for (BlockT *Predecessor : children<Inverse<BlockT *>>(EB))
93       if (!contains(Predecessor))
94         return false;
95   // All the requirements are met.
96   return true;
97 }
98
99 template <class BlockT, class LoopT>
100 void LoopBase<BlockT, LoopT>::getUniqueExitBlocks(
101     SmallVectorImpl<BlockT *> &ExitBlocks) const {
102   typedef GraphTraits<BlockT *> BlockTraits;
103   typedef GraphTraits<Inverse<BlockT *>> InvBlockTraits;
104
105   assert(hasDedicatedExits() &&
106          "getUniqueExitBlocks assumes the loop has canonical form exits!");
107
108   SmallVector<BlockT *, 32> SwitchExitBlocks;
109   for (BlockT *Block : this->blocks()) {
110     SwitchExitBlocks.clear();
111     for (BlockT *Successor : children<BlockT *>(Block)) {
112       // If block is inside the loop then it is not an exit block.
113       if (contains(Successor))
114         continue;
115
116       BlockT *FirstPred = *InvBlockTraits::child_begin(Successor);
117
118       // If current basic block is this exit block's first predecessor then only
119       // insert exit block in to the output ExitBlocks vector. This ensures that
120       // same exit block is not inserted twice into ExitBlocks vector.
121       if (Block != FirstPred)
122         continue;
123
124       // If a terminator has more then two successors, for example SwitchInst,
125       // then it is possible that there are multiple edges from current block to
126       // one exit block.
127       if (std::distance(BlockTraits::child_begin(Block),
128                         BlockTraits::child_end(Block)) <= 2) {
129         ExitBlocks.push_back(Successor);
130         continue;
131       }
132
133       // In case of multiple edges from current block to exit block, collect
134       // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
135       // duplicate edges.
136       if (!is_contained(SwitchExitBlocks, Successor)) {
137         SwitchExitBlocks.push_back(Successor);
138         ExitBlocks.push_back(Successor);
139       }
140     }
141   }
142 }
143
144 template <class BlockT, class LoopT>
145 BlockT *LoopBase<BlockT, LoopT>::getUniqueExitBlock() const {
146   SmallVector<BlockT *, 8> UniqueExitBlocks;
147   getUniqueExitBlocks(UniqueExitBlocks);
148   if (UniqueExitBlocks.size() == 1)
149     return UniqueExitBlocks[0];
150   return nullptr;
151 }
152
153 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
154 template <class BlockT, class LoopT>
155 void LoopBase<BlockT, LoopT>::getExitEdges(
156     SmallVectorImpl<Edge> &ExitEdges) const {
157   assert(!isInvalid() && "Loop not in a valid state!");
158   for (const auto BB : blocks())
159     for (const auto &Succ : children<BlockT *>(BB))
160       if (!contains(Succ))
161         // Not in current loop? It must be an exit block.
162         ExitEdges.emplace_back(BB, Succ);
163 }
164
165 /// getLoopPreheader - If there is a preheader for this loop, return it.  A
166 /// loop has a preheader if there is only one edge to the header of the loop
167 /// from outside of the loop and it is legal to hoist instructions into the
168 /// predecessor. If this is the case, the block branching to the header of the
169 /// loop is the preheader node.
170 ///
171 /// This method returns null if there is no preheader for the loop.
172 ///
173 template <class BlockT, class LoopT>
174 BlockT *LoopBase<BlockT, LoopT>::getLoopPreheader() const {
175   assert(!isInvalid() && "Loop not in a valid state!");
176   // Keep track of nodes outside the loop branching to the header...
177   BlockT *Out = getLoopPredecessor();
178   if (!Out)
179     return nullptr;
180
181   // Make sure we are allowed to hoist instructions into the predecessor.
182   if (!Out->isLegalToHoistInto())
183     return nullptr;
184
185   // Make sure there is only one exit out of the preheader.
186   typedef GraphTraits<BlockT *> BlockTraits;
187   typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
188   ++SI;
189   if (SI != BlockTraits::child_end(Out))
190     return nullptr; // Multiple exits from the block, must not be a preheader.
191
192   // The predecessor has exactly one successor, so it is a preheader.
193   return Out;
194 }
195
196 /// getLoopPredecessor - If the given loop's header has exactly one unique
197 /// predecessor outside the loop, return it. Otherwise return null.
198 /// This is less strict that the loop "preheader" concept, which requires
199 /// the predecessor to have exactly one successor.
200 ///
201 template <class BlockT, class LoopT>
202 BlockT *LoopBase<BlockT, LoopT>::getLoopPredecessor() const {
203   assert(!isInvalid() && "Loop not in a valid state!");
204   // Keep track of nodes outside the loop branching to the header...
205   BlockT *Out = nullptr;
206
207   // Loop over the predecessors of the header node...
208   BlockT *Header = getHeader();
209   for (const auto Pred : children<Inverse<BlockT *>>(Header)) {
210     if (!contains(Pred)) { // If the block is not in the loop...
211       if (Out && Out != Pred)
212         return nullptr; // Multiple predecessors outside the loop
213       Out = Pred;
214     }
215   }
216
217   // Make sure there is only one exit out of the preheader.
218   assert(Out && "Header of loop has no predecessors from outside loop?");
219   return Out;
220 }
221
222 /// getLoopLatch - If there is a single latch block for this loop, return it.
223 /// A latch block is a block that contains a branch back to the header.
224 template <class BlockT, class LoopT>
225 BlockT *LoopBase<BlockT, LoopT>::getLoopLatch() const {
226   assert(!isInvalid() && "Loop not in a valid state!");
227   BlockT *Header = getHeader();
228   BlockT *Latch = nullptr;
229   for (const auto Pred : children<Inverse<BlockT *>>(Header)) {
230     if (contains(Pred)) {
231       if (Latch)
232         return nullptr;
233       Latch = Pred;
234     }
235   }
236
237   return Latch;
238 }
239
240 //===----------------------------------------------------------------------===//
241 // APIs for updating loop information after changing the CFG
242 //
243
244 /// addBasicBlockToLoop - This method is used by other analyses to update loop
245 /// information.  NewBB is set to be a new member of the current loop.
246 /// Because of this, it is added as a member of all parent loops, and is added
247 /// to the specified LoopInfo object as being in the current basic block.  It
248 /// is not valid to replace the loop header with this method.
249 ///
250 template <class BlockT, class LoopT>
251 void LoopBase<BlockT, LoopT>::addBasicBlockToLoop(
252     BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LIB) {
253   assert(!isInvalid() && "Loop not in a valid state!");
254 #ifndef NDEBUG
255   if (!Blocks.empty()) {
256     auto SameHeader = LIB[getHeader()];
257     assert(contains(SameHeader) && getHeader() == SameHeader->getHeader() &&
258            "Incorrect LI specified for this loop!");
259   }
260 #endif
261   assert(NewBB && "Cannot add a null basic block to the loop!");
262   assert(!LIB[NewBB] && "BasicBlock already in the loop!");
263
264   LoopT *L = static_cast<LoopT *>(this);
265
266   // Add the loop mapping to the LoopInfo object...
267   LIB.BBMap[NewBB] = L;
268
269   // Add the basic block to this loop and all parent loops...
270   while (L) {
271     L->addBlockEntry(NewBB);
272     L = L->getParentLoop();
273   }
274 }
275
276 /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
277 /// the OldChild entry in our children list with NewChild, and updates the
278 /// parent pointer of OldChild to be null and the NewChild to be this loop.
279 /// This updates the loop depth of the new child.
280 template <class BlockT, class LoopT>
281 void LoopBase<BlockT, LoopT>::replaceChildLoopWith(LoopT *OldChild,
282                                                    LoopT *NewChild) {
283   assert(!isInvalid() && "Loop not in a valid state!");
284   assert(OldChild->ParentLoop == this && "This loop is already broken!");
285   assert(!NewChild->ParentLoop && "NewChild already has a parent!");
286   typename std::vector<LoopT *>::iterator I = find(SubLoops, OldChild);
287   assert(I != SubLoops.end() && "OldChild not in loop!");
288   *I = NewChild;
289   OldChild->ParentLoop = nullptr;
290   NewChild->ParentLoop = static_cast<LoopT *>(this);
291 }
292
293 /// verifyLoop - Verify loop structure
294 template <class BlockT, class LoopT>
295 void LoopBase<BlockT, LoopT>::verifyLoop() const {
296   assert(!isInvalid() && "Loop not in a valid state!");
297 #ifndef NDEBUG
298   assert(!Blocks.empty() && "Loop header is missing");
299
300   // Setup for using a depth-first iterator to visit every block in the loop.
301   SmallVector<BlockT *, 8> ExitBBs;
302   getExitBlocks(ExitBBs);
303   df_iterator_default_set<BlockT *> VisitSet;
304   VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
305   df_ext_iterator<BlockT *, df_iterator_default_set<BlockT *>>
306       BI = df_ext_begin(getHeader(), VisitSet),
307       BE = df_ext_end(getHeader(), VisitSet);
308
309   // Keep track of the BBs visited.
310   SmallPtrSet<BlockT *, 8> VisitedBBs;
311
312   // Check the individual blocks.
313   for (; BI != BE; ++BI) {
314     BlockT *BB = *BI;
315
316     assert(std::any_of(GraphTraits<BlockT *>::child_begin(BB),
317                        GraphTraits<BlockT *>::child_end(BB),
318                        [&](BlockT *B) { return contains(B); }) &&
319            "Loop block has no in-loop successors!");
320
321     assert(std::any_of(GraphTraits<Inverse<BlockT *>>::child_begin(BB),
322                        GraphTraits<Inverse<BlockT *>>::child_end(BB),
323                        [&](BlockT *B) { return contains(B); }) &&
324            "Loop block has no in-loop predecessors!");
325
326     SmallVector<BlockT *, 2> OutsideLoopPreds;
327     std::for_each(GraphTraits<Inverse<BlockT *>>::child_begin(BB),
328                   GraphTraits<Inverse<BlockT *>>::child_end(BB),
329                   [&](BlockT *B) {
330                     if (!contains(B))
331                       OutsideLoopPreds.push_back(B);
332                   });
333
334     if (BB == getHeader()) {
335       assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
336     } else if (!OutsideLoopPreds.empty()) {
337       // A non-header loop shouldn't be reachable from outside the loop,
338       // though it is permitted if the predecessor is not itself actually
339       // reachable.
340       BlockT *EntryBB = &BB->getParent()->front();
341       for (BlockT *CB : depth_first(EntryBB))
342         for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
343           assert(CB != OutsideLoopPreds[i] &&
344                  "Loop has multiple entry points!");
345     }
346     assert(BB != &getHeader()->getParent()->front() &&
347            "Loop contains function entry block!");
348
349     VisitedBBs.insert(BB);
350   }
351
352   if (VisitedBBs.size() != getNumBlocks()) {
353     dbgs() << "The following blocks are unreachable in the loop: ";
354     for (auto BB : Blocks) {
355       if (!VisitedBBs.count(BB)) {
356         dbgs() << *BB << "\n";
357       }
358     }
359     assert(false && "Unreachable block in loop");
360   }
361
362   // Check the subloops.
363   for (iterator I = begin(), E = end(); I != E; ++I)
364     // Each block in each subloop should be contained within this loop.
365     for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
366          BI != BE; ++BI) {
367       assert(contains(*BI) &&
368              "Loop does not contain all the blocks of a subloop!");
369     }
370
371   // Check the parent loop pointer.
372   if (ParentLoop) {
373     assert(is_contained(*ParentLoop, this) &&
374            "Loop is not a subloop of its parent!");
375   }
376 #endif
377 }
378
379 /// verifyLoop - Verify loop structure of this loop and all nested loops.
380 template <class BlockT, class LoopT>
381 void LoopBase<BlockT, LoopT>::verifyLoopNest(
382     DenseSet<const LoopT *> *Loops) const {
383   assert(!isInvalid() && "Loop not in a valid state!");
384   Loops->insert(static_cast<const LoopT *>(this));
385   // Verify this loop.
386   verifyLoop();
387   // Verify the subloops.
388   for (iterator I = begin(), E = end(); I != E; ++I)
389     (*I)->verifyLoopNest(Loops);
390 }
391
392 template <class BlockT, class LoopT>
393 void LoopBase<BlockT, LoopT>::print(raw_ostream &OS, unsigned Depth,
394                                     bool Verbose) const {
395   OS.indent(Depth * 2);
396   if (static_cast<const LoopT *>(this)->isAnnotatedParallel())
397     OS << "Parallel ";
398   OS << "Loop at depth " << getLoopDepth() << " containing: ";
399
400   BlockT *H = getHeader();
401   for (unsigned i = 0; i < getBlocks().size(); ++i) {
402     BlockT *BB = getBlocks()[i];
403     if (!Verbose) {
404       if (i)
405         OS << ",";
406       BB->printAsOperand(OS, false);
407     } else
408       OS << "\n";
409
410     if (BB == H)
411       OS << "<header>";
412     if (isLoopLatch(BB))
413       OS << "<latch>";
414     if (isLoopExiting(BB))
415       OS << "<exiting>";
416     if (Verbose)
417       BB->print(OS);
418   }
419   OS << "\n";
420
421   for (iterator I = begin(), E = end(); I != E; ++I)
422     (*I)->print(OS, Depth + 2);
423 }
424
425 //===----------------------------------------------------------------------===//
426 /// Stable LoopInfo Analysis - Build a loop tree using stable iterators so the
427 /// result does / not depend on use list (block predecessor) order.
428 ///
429
430 /// Discover a subloop with the specified backedges such that: All blocks within
431 /// this loop are mapped to this loop or a subloop. And all subloops within this
432 /// loop have their parent loop set to this loop or a subloop.
433 template <class BlockT, class LoopT>
434 static void discoverAndMapSubloop(LoopT *L, ArrayRef<BlockT *> Backedges,
435                                   LoopInfoBase<BlockT, LoopT> *LI,
436                                   const DomTreeBase<BlockT> &DomTree) {
437   typedef GraphTraits<Inverse<BlockT *>> InvBlockTraits;
438
439   unsigned NumBlocks = 0;
440   unsigned NumSubloops = 0;
441
442   // Perform a backward CFG traversal using a worklist.
443   std::vector<BlockT *> ReverseCFGWorklist(Backedges.begin(), Backedges.end());
444   while (!ReverseCFGWorklist.empty()) {
445     BlockT *PredBB = ReverseCFGWorklist.back();
446     ReverseCFGWorklist.pop_back();
447
448     LoopT *Subloop = LI->getLoopFor(PredBB);
449     if (!Subloop) {
450       if (!DomTree.isReachableFromEntry(PredBB))
451         continue;
452
453       // This is an undiscovered block. Map it to the current loop.
454       LI->changeLoopFor(PredBB, L);
455       ++NumBlocks;
456       if (PredBB == L->getHeader())
457         continue;
458       // Push all block predecessors on the worklist.
459       ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
460                                 InvBlockTraits::child_begin(PredBB),
461                                 InvBlockTraits::child_end(PredBB));
462     } else {
463       // This is a discovered block. Find its outermost discovered loop.
464       while (LoopT *Parent = Subloop->getParentLoop())
465         Subloop = Parent;
466
467       // If it is already discovered to be a subloop of this loop, continue.
468       if (Subloop == L)
469         continue;
470
471       // Discover a subloop of this loop.
472       Subloop->setParentLoop(L);
473       ++NumSubloops;
474       NumBlocks += Subloop->getBlocksVector().capacity();
475       PredBB = Subloop->getHeader();
476       // Continue traversal along predecessors that are not loop-back edges from
477       // within this subloop tree itself. Note that a predecessor may directly
478       // reach another subloop that is not yet discovered to be a subloop of
479       // this loop, which we must traverse.
480       for (const auto Pred : children<Inverse<BlockT *>>(PredBB)) {
481         if (LI->getLoopFor(Pred) != Subloop)
482           ReverseCFGWorklist.push_back(Pred);
483       }
484     }
485   }
486   L->getSubLoopsVector().reserve(NumSubloops);
487   L->reserveBlocks(NumBlocks);
488 }
489
490 /// Populate all loop data in a stable order during a single forward DFS.
491 template <class BlockT, class LoopT> class PopulateLoopsDFS {
492   typedef GraphTraits<BlockT *> BlockTraits;
493   typedef typename BlockTraits::ChildIteratorType SuccIterTy;
494
495   LoopInfoBase<BlockT, LoopT> *LI;
496
497 public:
498   PopulateLoopsDFS(LoopInfoBase<BlockT, LoopT> *li) : LI(li) {}
499
500   void traverse(BlockT *EntryBlock);
501
502 protected:
503   void insertIntoLoop(BlockT *Block);
504 };
505
506 /// Top-level driver for the forward DFS within the loop.
507 template <class BlockT, class LoopT>
508 void PopulateLoopsDFS<BlockT, LoopT>::traverse(BlockT *EntryBlock) {
509   for (BlockT *BB : post_order(EntryBlock))
510     insertIntoLoop(BB);
511 }
512
513 /// Add a single Block to its ancestor loops in PostOrder. If the block is a
514 /// subloop header, add the subloop to its parent in PostOrder, then reverse the
515 /// Block and Subloop vectors of the now complete subloop to achieve RPO.
516 template <class BlockT, class LoopT>
517 void PopulateLoopsDFS<BlockT, LoopT>::insertIntoLoop(BlockT *Block) {
518   LoopT *Subloop = LI->getLoopFor(Block);
519   if (Subloop && Block == Subloop->getHeader()) {
520     // We reach this point once per subloop after processing all the blocks in
521     // the subloop.
522     if (Subloop->getParentLoop())
523       Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
524     else
525       LI->addTopLevelLoop(Subloop);
526
527     // For convenience, Blocks and Subloops are inserted in postorder. Reverse
528     // the lists, except for the loop header, which is always at the beginning.
529     Subloop->reverseBlock(1);
530     std::reverse(Subloop->getSubLoopsVector().begin(),
531                  Subloop->getSubLoopsVector().end());
532
533     Subloop = Subloop->getParentLoop();
534   }
535   for (; Subloop; Subloop = Subloop->getParentLoop())
536     Subloop->addBlockEntry(Block);
537 }
538
539 /// Analyze LoopInfo discovers loops during a postorder DominatorTree traversal
540 /// interleaved with backward CFG traversals within each subloop
541 /// (discoverAndMapSubloop). The backward traversal skips inner subloops, so
542 /// this part of the algorithm is linear in the number of CFG edges. Subloop and
543 /// Block vectors are then populated during a single forward CFG traversal
544 /// (PopulateLoopDFS).
545 ///
546 /// During the two CFG traversals each block is seen three times:
547 /// 1) Discovered and mapped by a reverse CFG traversal.
548 /// 2) Visited during a forward DFS CFG traversal.
549 /// 3) Reverse-inserted in the loop in postorder following forward DFS.
550 ///
551 /// The Block vectors are inclusive, so step 3 requires loop-depth number of
552 /// insertions per block.
553 template <class BlockT, class LoopT>
554 void LoopInfoBase<BlockT, LoopT>::analyze(const DomTreeBase<BlockT> &DomTree) {
555   // Postorder traversal of the dominator tree.
556   const DomTreeNodeBase<BlockT> *DomRoot = DomTree.getRootNode();
557   for (auto DomNode : post_order(DomRoot)) {
558
559     BlockT *Header = DomNode->getBlock();
560     SmallVector<BlockT *, 4> Backedges;
561
562     // Check each predecessor of the potential loop header.
563     for (const auto Backedge : children<Inverse<BlockT *>>(Header)) {
564       // If Header dominates predBB, this is a new loop. Collect the backedges.
565       if (DomTree.dominates(Header, Backedge) &&
566           DomTree.isReachableFromEntry(Backedge)) {
567         Backedges.push_back(Backedge);
568       }
569     }
570     // Perform a backward CFG traversal to discover and map blocks in this loop.
571     if (!Backedges.empty()) {
572       LoopT *L = AllocateLoop(Header);
573       discoverAndMapSubloop(L, ArrayRef<BlockT *>(Backedges), this, DomTree);
574     }
575   }
576   // Perform a single forward CFG traversal to populate block and subloop
577   // vectors for all loops.
578   PopulateLoopsDFS<BlockT, LoopT> DFS(this);
579   DFS.traverse(DomRoot->getBlock());
580 }
581
582 template <class BlockT, class LoopT>
583 SmallVector<LoopT *, 4> LoopInfoBase<BlockT, LoopT>::getLoopsInPreorder() {
584   SmallVector<LoopT *, 4> PreOrderLoops, PreOrderWorklist;
585   // The outer-most loop actually goes into the result in the same relative
586   // order as we walk it. But LoopInfo stores the top level loops in reverse
587   // program order so for here we reverse it to get forward program order.
588   // FIXME: If we change the order of LoopInfo we will want to remove the
589   // reverse here.
590   for (LoopT *RootL : reverse(*this)) {
591     assert(PreOrderWorklist.empty() &&
592            "Must start with an empty preorder walk worklist.");
593     PreOrderWorklist.push_back(RootL);
594     do {
595       LoopT *L = PreOrderWorklist.pop_back_val();
596       // Sub-loops are stored in forward program order, but will process the
597       // worklist backwards so append them in reverse order.
598       PreOrderWorklist.append(L->rbegin(), L->rend());
599       PreOrderLoops.push_back(L);
600     } while (!PreOrderWorklist.empty());
601   }
602
603   return PreOrderLoops;
604 }
605
606 template <class BlockT, class LoopT>
607 SmallVector<LoopT *, 4>
608 LoopInfoBase<BlockT, LoopT>::getLoopsInReverseSiblingPreorder() {
609   SmallVector<LoopT *, 4> PreOrderLoops, PreOrderWorklist;
610   // The outer-most loop actually goes into the result in the same relative
611   // order as we walk it. LoopInfo stores the top level loops in reverse
612   // program order so we walk in order here.
613   // FIXME: If we change the order of LoopInfo we will want to add a reverse
614   // here.
615   for (LoopT *RootL : *this) {
616     assert(PreOrderWorklist.empty() &&
617            "Must start with an empty preorder walk worklist.");
618     PreOrderWorklist.push_back(RootL);
619     do {
620       LoopT *L = PreOrderWorklist.pop_back_val();
621       // Sub-loops are stored in forward program order, but will process the
622       // worklist backwards so we can just append them in order.
623       PreOrderWorklist.append(L->begin(), L->end());
624       PreOrderLoops.push_back(L);
625     } while (!PreOrderWorklist.empty());
626   }
627
628   return PreOrderLoops;
629 }
630
631 // Debugging
632 template <class BlockT, class LoopT>
633 void LoopInfoBase<BlockT, LoopT>::print(raw_ostream &OS) const {
634   for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
635     TopLevelLoops[i]->print(OS);
636 #if 0
637   for (DenseMap<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
638          E = BBMap.end(); I != E; ++I)
639     OS << "BB '" << I->first->getName() << "' level = "
640        << I->second->getLoopDepth() << "\n";
641 #endif
642 }
643
644 template <typename T>
645 bool compareVectors(std::vector<T> &BB1, std::vector<T> &BB2) {
646   llvm::sort(BB1);
647   llvm::sort(BB2);
648   return BB1 == BB2;
649 }
650
651 template <class BlockT, class LoopT>
652 void addInnerLoopsToHeadersMap(DenseMap<BlockT *, const LoopT *> &LoopHeaders,
653                                const LoopInfoBase<BlockT, LoopT> &LI,
654                                const LoopT &L) {
655   LoopHeaders[L.getHeader()] = &L;
656   for (LoopT *SL : L)
657     addInnerLoopsToHeadersMap(LoopHeaders, LI, *SL);
658 }
659
660 #ifndef NDEBUG
661 template <class BlockT, class LoopT>
662 static void compareLoops(const LoopT *L, const LoopT *OtherL,
663                          DenseMap<BlockT *, const LoopT *> &OtherLoopHeaders) {
664   BlockT *H = L->getHeader();
665   BlockT *OtherH = OtherL->getHeader();
666   assert(H == OtherH &&
667          "Mismatched headers even though found in the same map entry!");
668
669   assert(L->getLoopDepth() == OtherL->getLoopDepth() &&
670          "Mismatched loop depth!");
671   const LoopT *ParentL = L, *OtherParentL = OtherL;
672   do {
673     assert(ParentL->getHeader() == OtherParentL->getHeader() &&
674            "Mismatched parent loop headers!");
675     ParentL = ParentL->getParentLoop();
676     OtherParentL = OtherParentL->getParentLoop();
677   } while (ParentL);
678
679   for (const LoopT *SubL : *L) {
680     BlockT *SubH = SubL->getHeader();
681     const LoopT *OtherSubL = OtherLoopHeaders.lookup(SubH);
682     assert(OtherSubL && "Inner loop is missing in computed loop info!");
683     OtherLoopHeaders.erase(SubH);
684     compareLoops(SubL, OtherSubL, OtherLoopHeaders);
685   }
686
687   std::vector<BlockT *> BBs = L->getBlocks();
688   std::vector<BlockT *> OtherBBs = OtherL->getBlocks();
689   assert(compareVectors(BBs, OtherBBs) &&
690          "Mismatched basic blocks in the loops!");
691
692   const SmallPtrSetImpl<const BlockT *> &BlocksSet = L->getBlocksSet();
693   const SmallPtrSetImpl<const BlockT *> &OtherBlocksSet = L->getBlocksSet();
694   assert(BlocksSet.size() == OtherBlocksSet.size() &&
695          std::all_of(BlocksSet.begin(), BlocksSet.end(),
696                      [&OtherBlocksSet](const BlockT *BB) {
697                        return OtherBlocksSet.count(BB);
698                      }) &&
699          "Mismatched basic blocks in BlocksSets!");
700 }
701 #endif
702
703 template <class BlockT, class LoopT>
704 void LoopInfoBase<BlockT, LoopT>::verify(
705     const DomTreeBase<BlockT> &DomTree) const {
706   DenseSet<const LoopT *> Loops;
707   for (iterator I = begin(), E = end(); I != E; ++I) {
708     assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
709     (*I)->verifyLoopNest(&Loops);
710   }
711
712 // Verify that blocks are mapped to valid loops.
713 #ifndef NDEBUG
714   for (auto &Entry : BBMap) {
715     const BlockT *BB = Entry.first;
716     LoopT *L = Entry.second;
717     assert(Loops.count(L) && "orphaned loop");
718     assert(L->contains(BB) && "orphaned block");
719     for (LoopT *ChildLoop : *L)
720       assert(!ChildLoop->contains(BB) &&
721              "BBMap should point to the innermost loop containing BB");
722   }
723
724   // Recompute LoopInfo to verify loops structure.
725   LoopInfoBase<BlockT, LoopT> OtherLI;
726   OtherLI.analyze(DomTree);
727
728   // Build a map we can use to move from our LI to the computed one. This
729   // allows us to ignore the particular order in any layer of the loop forest
730   // while still comparing the structure.
731   DenseMap<BlockT *, const LoopT *> OtherLoopHeaders;
732   for (LoopT *L : OtherLI)
733     addInnerLoopsToHeadersMap(OtherLoopHeaders, OtherLI, *L);
734
735   // Walk the top level loops and ensure there is a corresponding top-level
736   // loop in the computed version and then recursively compare those loop
737   // nests.
738   for (LoopT *L : *this) {
739     BlockT *Header = L->getHeader();
740     const LoopT *OtherL = OtherLoopHeaders.lookup(Header);
741     assert(OtherL && "Top level loop is missing in computed loop info!");
742     // Now that we've matched this loop, erase its header from the map.
743     OtherLoopHeaders.erase(Header);
744     // And recursively compare these loops.
745     compareLoops(L, OtherL, OtherLoopHeaders);
746   }
747
748   // Any remaining entries in the map are loops which were found when computing
749   // a fresh LoopInfo but not present in the current one.
750   if (!OtherLoopHeaders.empty()) {
751     for (const auto &HeaderAndLoop : OtherLoopHeaders)
752       dbgs() << "Found new loop: " << *HeaderAndLoop.second << "\n";
753     llvm_unreachable("Found new loops when recomputing LoopInfo!");
754   }
755 #endif
756 }
757
758 } // End llvm namespace
759
760 #endif