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