LoopInfoImpl.h 27 KB

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