LoopInfo.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the LoopInfo class that is used to identify natural loops
  11. // and determine the loop depth of various nodes of the CFG. Note that the
  12. // loops identified may actually be several natural loops that share the same
  13. // header node... not just a single natural loop.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Analysis/LoopInfo.h"
  17. #include "llvm/ADT/DepthFirstIterator.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/Analysis/LoopInfoImpl.h"
  20. #include "llvm/Analysis/LoopIterator.h"
  21. #include "llvm/Analysis/ValueTracking.h"
  22. #include "llvm/IR/CFG.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DebugLoc.h"
  25. #include "llvm/IR/Dominators.h"
  26. #include "llvm/IR/Instructions.h"
  27. #include "llvm/IR/LLVMContext.h"
  28. #include "llvm/IR/Metadata.h"
  29. #include "llvm/IR/PassManager.h"
  30. #include "llvm/Support/CommandLine.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include <algorithm>
  34. using namespace llvm;
  35. // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
  36. template class llvm::LoopBase<BasicBlock, Loop>;
  37. template class llvm::LoopInfoBase<BasicBlock, Loop>;
  38. // Always verify loopinfo if expensive checking is enabled.
  39. #ifdef EXPENSIVE_CHECKS
  40. static bool VerifyLoopInfo = true;
  41. #else
  42. static bool VerifyLoopInfo = false;
  43. #endif
  44. static cl::opt<bool,true>
  45. VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
  46. cl::desc("Verify loop info (time consuming)"));
  47. //===----------------------------------------------------------------------===//
  48. // Loop implementation
  49. //
  50. bool Loop::isLoopInvariant(const Value *V) const {
  51. if (const Instruction *I = dyn_cast<Instruction>(V))
  52. return !contains(I);
  53. return true; // All non-instructions are loop invariant
  54. }
  55. bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
  56. return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
  57. }
  58. bool Loop::makeLoopInvariant(Value *V, bool &Changed,
  59. Instruction *InsertPt) const {
  60. if (Instruction *I = dyn_cast<Instruction>(V))
  61. return makeLoopInvariant(I, Changed, InsertPt);
  62. return true; // All non-instructions are loop-invariant.
  63. }
  64. bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
  65. Instruction *InsertPt) const {
  66. // Test if the value is already loop-invariant.
  67. if (isLoopInvariant(I))
  68. return true;
  69. if (!isSafeToSpeculativelyExecute(I))
  70. return false;
  71. if (I->mayReadFromMemory())
  72. return false;
  73. // EH block instructions are immobile.
  74. if (I->isEHPad())
  75. return false;
  76. // Determine the insertion point, unless one was given.
  77. if (!InsertPt) {
  78. BasicBlock *Preheader = getLoopPreheader();
  79. // Without a preheader, hoisting is not feasible.
  80. if (!Preheader)
  81. return false;
  82. InsertPt = Preheader->getTerminator();
  83. }
  84. // Don't hoist instructions with loop-variant operands.
  85. for (Value *Operand : I->operands())
  86. if (!makeLoopInvariant(Operand, Changed, InsertPt))
  87. return false;
  88. // Hoist.
  89. I->moveBefore(InsertPt);
  90. // There is possibility of hoisting this instruction above some arbitrary
  91. // condition. Any metadata defined on it can be control dependent on this
  92. // condition. Conservatively strip it here so that we don't give any wrong
  93. // information to the optimizer.
  94. I->dropUnknownNonDebugMetadata();
  95. Changed = true;
  96. return true;
  97. }
  98. PHINode *Loop::getCanonicalInductionVariable() const {
  99. BasicBlock *H = getHeader();
  100. BasicBlock *Incoming = nullptr, *Backedge = nullptr;
  101. pred_iterator PI = pred_begin(H);
  102. assert(PI != pred_end(H) &&
  103. "Loop must have at least one backedge!");
  104. Backedge = *PI++;
  105. if (PI == pred_end(H)) return nullptr; // dead loop
  106. Incoming = *PI++;
  107. if (PI != pred_end(H)) return nullptr; // multiple backedges?
  108. if (contains(Incoming)) {
  109. if (contains(Backedge))
  110. return nullptr;
  111. std::swap(Incoming, Backedge);
  112. } else if (!contains(Backedge))
  113. return nullptr;
  114. // Loop over all of the PHI nodes, looking for a canonical indvar.
  115. for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
  116. PHINode *PN = cast<PHINode>(I);
  117. if (ConstantInt *CI =
  118. dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
  119. if (CI->isNullValue())
  120. if (Instruction *Inc =
  121. dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
  122. if (Inc->getOpcode() == Instruction::Add &&
  123. Inc->getOperand(0) == PN)
  124. if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
  125. if (CI->equalsInt(1))
  126. return PN;
  127. }
  128. return nullptr;
  129. }
  130. // Check that 'BB' doesn't have any uses outside of the 'L'
  131. static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
  132. DominatorTree &DT) {
  133. for (const Instruction &I : BB) {
  134. // Tokens can't be used in PHI nodes and live-out tokens prevent loop
  135. // optimizations, so for the purposes of considered LCSSA form, we
  136. // can ignore them.
  137. if (I.getType()->isTokenTy())
  138. continue;
  139. for (const Use &U : I.uses()) {
  140. const Instruction *UI = cast<Instruction>(U.getUser());
  141. const BasicBlock *UserBB = UI->getParent();
  142. if (const PHINode *P = dyn_cast<PHINode>(UI))
  143. UserBB = P->getIncomingBlock(U);
  144. // Check the current block, as a fast-path, before checking whether
  145. // the use is anywhere in the loop. Most values are used in the same
  146. // block they are defined in. Also, blocks not reachable from the
  147. // entry are special; uses in them don't need to go through PHIs.
  148. if (UserBB != &BB && !L.contains(UserBB) &&
  149. DT.isReachableFromEntry(UserBB))
  150. return false;
  151. }
  152. }
  153. return true;
  154. }
  155. bool Loop::isLCSSAForm(DominatorTree &DT) const {
  156. // For each block we check that it doesn't have any uses outside of this loop.
  157. return all_of(this->blocks(), [&](const BasicBlock *BB) {
  158. return isBlockInLCSSAForm(*this, *BB, DT);
  159. });
  160. }
  161. bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const {
  162. // For each block we check that it doesn't have any uses outside of its
  163. // innermost loop. This process will transitively guarantee that the current
  164. // loop and all of the nested loops are in LCSSA form.
  165. return all_of(this->blocks(), [&](const BasicBlock *BB) {
  166. return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT);
  167. });
  168. }
  169. bool Loop::isLoopSimplifyForm() const {
  170. // Normal-form loops have a preheader, a single backedge, and all of their
  171. // exits have all their predecessors inside the loop.
  172. return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
  173. }
  174. // Routines that reform the loop CFG and split edges often fail on indirectbr.
  175. bool Loop::isSafeToClone() const {
  176. // Return false if any loop blocks contain indirectbrs, or there are any calls
  177. // to noduplicate functions.
  178. for (BasicBlock *BB : this->blocks()) {
  179. if (isa<IndirectBrInst>(BB->getTerminator()))
  180. return false;
  181. for (Instruction &I : *BB)
  182. if (auto CS = CallSite(&I))
  183. if (CS.cannotDuplicate())
  184. return false;
  185. }
  186. return true;
  187. }
  188. MDNode *Loop::getLoopID() const {
  189. MDNode *LoopID = nullptr;
  190. if (isLoopSimplifyForm()) {
  191. LoopID = getLoopLatch()->getTerminator()->getMetadata(LLVMContext::MD_loop);
  192. } else {
  193. // Go through each predecessor of the loop header and check the
  194. // terminator for the metadata.
  195. BasicBlock *H = getHeader();
  196. for (BasicBlock *BB : this->blocks()) {
  197. TerminatorInst *TI = BB->getTerminator();
  198. MDNode *MD = nullptr;
  199. // Check if this terminator branches to the loop header.
  200. for (BasicBlock *Successor : TI->successors()) {
  201. if (Successor == H) {
  202. MD = TI->getMetadata(LLVMContext::MD_loop);
  203. break;
  204. }
  205. }
  206. if (!MD)
  207. return nullptr;
  208. if (!LoopID)
  209. LoopID = MD;
  210. else if (MD != LoopID)
  211. return nullptr;
  212. }
  213. }
  214. if (!LoopID || LoopID->getNumOperands() == 0 ||
  215. LoopID->getOperand(0) != LoopID)
  216. return nullptr;
  217. return LoopID;
  218. }
  219. void Loop::setLoopID(MDNode *LoopID) const {
  220. assert(LoopID && "Loop ID should not be null");
  221. assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
  222. assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
  223. if (isLoopSimplifyForm()) {
  224. getLoopLatch()->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
  225. return;
  226. }
  227. BasicBlock *H = getHeader();
  228. for (BasicBlock *BB : this->blocks()) {
  229. TerminatorInst *TI = BB->getTerminator();
  230. for (BasicBlock *Successor : TI->successors()) {
  231. if (Successor == H)
  232. TI->setMetadata(LLVMContext::MD_loop, LoopID);
  233. }
  234. }
  235. }
  236. bool Loop::isAnnotatedParallel() const {
  237. MDNode *DesiredLoopIdMetadata = getLoopID();
  238. if (!DesiredLoopIdMetadata)
  239. return false;
  240. // The loop branch contains the parallel loop metadata. In order to ensure
  241. // that any parallel-loop-unaware optimization pass hasn't added loop-carried
  242. // dependencies (thus converted the loop back to a sequential loop), check
  243. // that all the memory instructions in the loop contain parallelism metadata
  244. // that point to the same unique "loop id metadata" the loop branch does.
  245. for (BasicBlock *BB : this->blocks()) {
  246. for (Instruction &I : *BB) {
  247. if (!I.mayReadOrWriteMemory())
  248. continue;
  249. // The memory instruction can refer to the loop identifier metadata
  250. // directly or indirectly through another list metadata (in case of
  251. // nested parallel loops). The loop identifier metadata refers to
  252. // itself so we can check both cases with the same routine.
  253. MDNode *LoopIdMD =
  254. I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
  255. if (!LoopIdMD)
  256. return false;
  257. bool LoopIdMDFound = false;
  258. for (const MDOperand &MDOp : LoopIdMD->operands()) {
  259. if (MDOp == DesiredLoopIdMetadata) {
  260. LoopIdMDFound = true;
  261. break;
  262. }
  263. }
  264. if (!LoopIdMDFound)
  265. return false;
  266. }
  267. }
  268. return true;
  269. }
  270. DebugLoc Loop::getStartLoc() const {
  271. return getLocRange().getStart();
  272. }
  273. Loop::LocRange Loop::getLocRange() const {
  274. // If we have a debug location in the loop ID, then use it.
  275. if (MDNode *LoopID = getLoopID()) {
  276. DebugLoc Start;
  277. // We use the first DebugLoc in the header as the start location of the loop
  278. // and if there is a second DebugLoc in the header we use it as end location
  279. // of the loop.
  280. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  281. if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
  282. if (!Start)
  283. Start = DebugLoc(L);
  284. else
  285. return LocRange(Start, DebugLoc(L));
  286. }
  287. }
  288. if (Start)
  289. return LocRange(Start);
  290. }
  291. // Try the pre-header first.
  292. if (BasicBlock *PHeadBB = getLoopPreheader())
  293. if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
  294. return LocRange(DL);
  295. // If we have no pre-header or there are no instructions with debug
  296. // info in it, try the header.
  297. if (BasicBlock *HeadBB = getHeader())
  298. return LocRange(HeadBB->getTerminator()->getDebugLoc());
  299. return LocRange();
  300. }
  301. bool Loop::hasDedicatedExits() const {
  302. // Each predecessor of each exit block of a normal loop is contained
  303. // within the loop.
  304. SmallVector<BasicBlock *, 4> ExitBlocks;
  305. getExitBlocks(ExitBlocks);
  306. for (BasicBlock *BB : ExitBlocks)
  307. for (BasicBlock *Predecessor : predecessors(BB))
  308. if (!contains(Predecessor))
  309. return false;
  310. // All the requirements are met.
  311. return true;
  312. }
  313. void
  314. Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
  315. assert(hasDedicatedExits() &&
  316. "getUniqueExitBlocks assumes the loop has canonical form exits!");
  317. SmallVector<BasicBlock *, 32> SwitchExitBlocks;
  318. for (BasicBlock *BB : this->blocks()) {
  319. SwitchExitBlocks.clear();
  320. for (BasicBlock *Successor : successors(BB)) {
  321. // If block is inside the loop then it is not an exit block.
  322. if (contains(Successor))
  323. continue;
  324. pred_iterator PI = pred_begin(Successor);
  325. BasicBlock *FirstPred = *PI;
  326. // If current basic block is this exit block's first predecessor
  327. // then only insert exit block in to the output ExitBlocks vector.
  328. // This ensures that same exit block is not inserted twice into
  329. // ExitBlocks vector.
  330. if (BB != FirstPred)
  331. continue;
  332. // If a terminator has more then two successors, for example SwitchInst,
  333. // then it is possible that there are multiple edges from current block
  334. // to one exit block.
  335. if (std::distance(succ_begin(BB), succ_end(BB)) <= 2) {
  336. ExitBlocks.push_back(Successor);
  337. continue;
  338. }
  339. // In case of multiple edges from current block to exit block, collect
  340. // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
  341. // duplicate edges.
  342. if (!is_contained(SwitchExitBlocks, Successor)) {
  343. SwitchExitBlocks.push_back(Successor);
  344. ExitBlocks.push_back(Successor);
  345. }
  346. }
  347. }
  348. }
  349. BasicBlock *Loop::getUniqueExitBlock() const {
  350. SmallVector<BasicBlock *, 8> UniqueExitBlocks;
  351. getUniqueExitBlocks(UniqueExitBlocks);
  352. if (UniqueExitBlocks.size() == 1)
  353. return UniqueExitBlocks[0];
  354. return nullptr;
  355. }
  356. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  357. LLVM_DUMP_METHOD void Loop::dump() const {
  358. print(dbgs());
  359. }
  360. LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
  361. print(dbgs(), /*Depth=*/ 0, /*Verbose=*/ true);
  362. }
  363. #endif
  364. //===----------------------------------------------------------------------===//
  365. // UnloopUpdater implementation
  366. //
  367. namespace {
  368. /// Find the new parent loop for all blocks within the "unloop" whose last
  369. /// backedges has just been removed.
  370. class UnloopUpdater {
  371. Loop &Unloop;
  372. LoopInfo *LI;
  373. LoopBlocksDFS DFS;
  374. // Map unloop's immediate subloops to their nearest reachable parents. Nested
  375. // loops within these subloops will not change parents. However, an immediate
  376. // subloop's new parent will be the nearest loop reachable from either its own
  377. // exits *or* any of its nested loop's exits.
  378. DenseMap<Loop*, Loop*> SubloopParents;
  379. // Flag the presence of an irreducible backedge whose destination is a block
  380. // directly contained by the original unloop.
  381. bool FoundIB;
  382. public:
  383. UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
  384. Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {}
  385. void updateBlockParents();
  386. void removeBlocksFromAncestors();
  387. void updateSubloopParents();
  388. protected:
  389. Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
  390. };
  391. } // end anonymous namespace
  392. /// Update the parent loop for all blocks that are directly contained within the
  393. /// original "unloop".
  394. void UnloopUpdater::updateBlockParents() {
  395. if (Unloop.getNumBlocks()) {
  396. // Perform a post order CFG traversal of all blocks within this loop,
  397. // propagating the nearest loop from sucessors to predecessors.
  398. LoopBlocksTraversal Traversal(DFS, LI);
  399. for (BasicBlock *POI : Traversal) {
  400. Loop *L = LI->getLoopFor(POI);
  401. Loop *NL = getNearestLoop(POI, L);
  402. if (NL != L) {
  403. // For reducible loops, NL is now an ancestor of Unloop.
  404. assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
  405. "uninitialized successor");
  406. LI->changeLoopFor(POI, NL);
  407. }
  408. else {
  409. // Or the current block is part of a subloop, in which case its parent
  410. // is unchanged.
  411. assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
  412. }
  413. }
  414. }
  415. // Each irreducible loop within the unloop induces a round of iteration using
  416. // the DFS result cached by Traversal.
  417. bool Changed = FoundIB;
  418. for (unsigned NIters = 0; Changed; ++NIters) {
  419. assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
  420. // Iterate over the postorder list of blocks, propagating the nearest loop
  421. // from successors to predecessors as before.
  422. Changed = false;
  423. for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
  424. POE = DFS.endPostorder(); POI != POE; ++POI) {
  425. Loop *L = LI->getLoopFor(*POI);
  426. Loop *NL = getNearestLoop(*POI, L);
  427. if (NL != L) {
  428. assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
  429. "uninitialized successor");
  430. LI->changeLoopFor(*POI, NL);
  431. Changed = true;
  432. }
  433. }
  434. }
  435. }
  436. /// Remove unloop's blocks from all ancestors below their new parents.
  437. void UnloopUpdater::removeBlocksFromAncestors() {
  438. // Remove all unloop's blocks (including those in nested subloops) from
  439. // ancestors below the new parent loop.
  440. for (Loop::block_iterator BI = Unloop.block_begin(),
  441. BE = Unloop.block_end(); BI != BE; ++BI) {
  442. Loop *OuterParent = LI->getLoopFor(*BI);
  443. if (Unloop.contains(OuterParent)) {
  444. while (OuterParent->getParentLoop() != &Unloop)
  445. OuterParent = OuterParent->getParentLoop();
  446. OuterParent = SubloopParents[OuterParent];
  447. }
  448. // Remove blocks from former Ancestors except Unloop itself which will be
  449. // deleted.
  450. for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
  451. OldParent = OldParent->getParentLoop()) {
  452. assert(OldParent && "new loop is not an ancestor of the original");
  453. OldParent->removeBlockFromLoop(*BI);
  454. }
  455. }
  456. }
  457. /// Update the parent loop for all subloops directly nested within unloop.
  458. void UnloopUpdater::updateSubloopParents() {
  459. while (!Unloop.empty()) {
  460. Loop *Subloop = *std::prev(Unloop.end());
  461. Unloop.removeChildLoop(std::prev(Unloop.end()));
  462. assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
  463. if (Loop *Parent = SubloopParents[Subloop])
  464. Parent->addChildLoop(Subloop);
  465. else
  466. LI->addTopLevelLoop(Subloop);
  467. }
  468. }
  469. /// Return the nearest parent loop among this block's successors. If a successor
  470. /// is a subloop header, consider its parent to be the nearest parent of the
  471. /// subloop's exits.
  472. ///
  473. /// For subloop blocks, simply update SubloopParents and return NULL.
  474. Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
  475. // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
  476. // is considered uninitialized.
  477. Loop *NearLoop = BBLoop;
  478. Loop *Subloop = nullptr;
  479. if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
  480. Subloop = NearLoop;
  481. // Find the subloop ancestor that is directly contained within Unloop.
  482. while (Subloop->getParentLoop() != &Unloop) {
  483. Subloop = Subloop->getParentLoop();
  484. assert(Subloop && "subloop is not an ancestor of the original loop");
  485. }
  486. // Get the current nearest parent of the Subloop exits, initially Unloop.
  487. NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
  488. }
  489. succ_iterator I = succ_begin(BB), E = succ_end(BB);
  490. if (I == E) {
  491. assert(!Subloop && "subloop blocks must have a successor");
  492. NearLoop = nullptr; // unloop blocks may now exit the function.
  493. }
  494. for (; I != E; ++I) {
  495. if (*I == BB)
  496. continue; // self loops are uninteresting
  497. Loop *L = LI->getLoopFor(*I);
  498. if (L == &Unloop) {
  499. // This successor has not been processed. This path must lead to an
  500. // irreducible backedge.
  501. assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
  502. FoundIB = true;
  503. }
  504. if (L != &Unloop && Unloop.contains(L)) {
  505. // Successor is in a subloop.
  506. if (Subloop)
  507. continue; // Branching within subloops. Ignore it.
  508. // BB branches from the original into a subloop header.
  509. assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
  510. // Get the current nearest parent of the Subloop's exits.
  511. L = SubloopParents[L];
  512. // L could be Unloop if the only exit was an irreducible backedge.
  513. }
  514. if (L == &Unloop) {
  515. continue;
  516. }
  517. // Handle critical edges from Unloop into a sibling loop.
  518. if (L && !L->contains(&Unloop)) {
  519. L = L->getParentLoop();
  520. }
  521. // Remember the nearest parent loop among successors or subloop exits.
  522. if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
  523. NearLoop = L;
  524. }
  525. if (Subloop) {
  526. SubloopParents[Subloop] = NearLoop;
  527. return BBLoop;
  528. }
  529. return NearLoop;
  530. }
  531. LoopInfo::LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree) {
  532. analyze(DomTree);
  533. }
  534. void LoopInfo::markAsRemoved(Loop *Unloop) {
  535. assert(!Unloop->isInvalid() && "Loop has already been removed");
  536. Unloop->invalidate();
  537. RemovedLoops.push_back(Unloop);
  538. // First handle the special case of no parent loop to simplify the algorithm.
  539. if (!Unloop->getParentLoop()) {
  540. // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
  541. for (Loop::block_iterator I = Unloop->block_begin(),
  542. E = Unloop->block_end();
  543. I != E; ++I) {
  544. // Don't reparent blocks in subloops.
  545. if (getLoopFor(*I) != Unloop)
  546. continue;
  547. // Blocks no longer have a parent but are still referenced by Unloop until
  548. // the Unloop object is deleted.
  549. changeLoopFor(*I, nullptr);
  550. }
  551. // Remove the loop from the top-level LoopInfo object.
  552. for (iterator I = begin();; ++I) {
  553. assert(I != end() && "Couldn't find loop");
  554. if (*I == Unloop) {
  555. removeLoop(I);
  556. break;
  557. }
  558. }
  559. // Move all of the subloops to the top-level.
  560. while (!Unloop->empty())
  561. addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
  562. return;
  563. }
  564. // Update the parent loop for all blocks within the loop. Blocks within
  565. // subloops will not change parents.
  566. UnloopUpdater Updater(Unloop, this);
  567. Updater.updateBlockParents();
  568. // Remove blocks from former ancestor loops.
  569. Updater.removeBlocksFromAncestors();
  570. // Add direct subloops as children in their new parent loop.
  571. Updater.updateSubloopParents();
  572. // Remove unloop from its parent loop.
  573. Loop *ParentLoop = Unloop->getParentLoop();
  574. for (Loop::iterator I = ParentLoop->begin();; ++I) {
  575. assert(I != ParentLoop->end() && "Couldn't find loop");
  576. if (*I == Unloop) {
  577. ParentLoop->removeChildLoop(I);
  578. break;
  579. }
  580. }
  581. }
  582. AnalysisKey LoopAnalysis::Key;
  583. LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
  584. // FIXME: Currently we create a LoopInfo from scratch for every function.
  585. // This may prove to be too wasteful due to deallocating and re-allocating
  586. // memory each time for the underlying map and vector datastructures. At some
  587. // point it may prove worthwhile to use a freelist and recycle LoopInfo
  588. // objects. I don't want to add that kind of complexity until the scope of
  589. // the problem is better understood.
  590. LoopInfo LI;
  591. LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
  592. return LI;
  593. }
  594. PreservedAnalyses LoopPrinterPass::run(Function &F,
  595. FunctionAnalysisManager &AM) {
  596. AM.getResult<LoopAnalysis>(F).print(OS);
  597. return PreservedAnalyses::all();
  598. }
  599. void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) {
  600. OS << Banner;
  601. for (auto *Block : L.blocks())
  602. if (Block)
  603. Block->print(OS);
  604. else
  605. OS << "Printing <null> block";
  606. }
  607. //===----------------------------------------------------------------------===//
  608. // LoopInfo implementation
  609. //
  610. char LoopInfoWrapperPass::ID = 0;
  611. INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
  612. true, true)
  613. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  614. INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
  615. true, true)
  616. bool LoopInfoWrapperPass::runOnFunction(Function &) {
  617. releaseMemory();
  618. LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
  619. return false;
  620. }
  621. void LoopInfoWrapperPass::verifyAnalysis() const {
  622. // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
  623. // function each time verifyAnalysis is called is very expensive. The
  624. // -verify-loop-info option can enable this. In order to perform some
  625. // checking by default, LoopPass has been taught to call verifyLoop manually
  626. // during loop pass sequences.
  627. if (VerifyLoopInfo) {
  628. if (auto *Analysis = getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
  629. auto &DT = Analysis->getDomTree();
  630. LI.verify(DT);
  631. }
  632. }
  633. }
  634. void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  635. AU.setPreservesAll();
  636. AU.addRequired<DominatorTreeWrapperPass>();
  637. }
  638. void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
  639. LI.print(OS);
  640. }
  641. PreservedAnalyses LoopVerifierPass::run(Function &F,
  642. FunctionAnalysisManager &AM) {
  643. LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
  644. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  645. LI.verify(DT);
  646. return PreservedAnalyses::all();
  647. }
  648. //===----------------------------------------------------------------------===//
  649. // LoopBlocksDFS implementation
  650. //
  651. /// Traverse the loop blocks and store the DFS result.
  652. /// Useful for clients that just want the final DFS result and don't need to
  653. /// visit blocks during the initial traversal.
  654. void LoopBlocksDFS::perform(LoopInfo *LI) {
  655. LoopBlocksTraversal Traversal(*this, LI);
  656. for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
  657. POE = Traversal.end(); POI != POE; ++POI) ;
  658. }