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