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