LoopInfo.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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/Constants.h"
  23. #include "llvm/IR/Dominators.h"
  24. #include "llvm/IR/Instructions.h"
  25. #include "llvm/IR/Metadata.h"
  26. #include "llvm/Support/CFG.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Debug.h"
  29. #include <algorithm>
  30. using namespace llvm;
  31. // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
  32. template class llvm::LoopBase<BasicBlock, Loop>;
  33. template class llvm::LoopInfoBase<BasicBlock, Loop>;
  34. // Always verify loopinfo if expensive checking is enabled.
  35. #ifdef XDEBUG
  36. static bool VerifyLoopInfo = true;
  37. #else
  38. static bool VerifyLoopInfo = false;
  39. #endif
  40. static cl::opt<bool,true>
  41. VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
  42. cl::desc("Verify loop info (time consuming)"));
  43. char LoopInfo::ID = 0;
  44. INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true)
  45. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  46. INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true)
  47. // Loop identifier metadata name.
  48. static const char *const LoopMDName = "llvm.loop";
  49. //===----------------------------------------------------------------------===//
  50. // Loop implementation
  51. //
  52. /// isLoopInvariant - Return true if the specified value is loop invariant
  53. ///
  54. bool Loop::isLoopInvariant(Value *V) const {
  55. if (Instruction *I = dyn_cast<Instruction>(V))
  56. return !contains(I);
  57. return true; // All non-instructions are loop invariant
  58. }
  59. /// hasLoopInvariantOperands - Return true if all the operands of the
  60. /// specified instruction are loop invariant.
  61. bool Loop::hasLoopInvariantOperands(Instruction *I) const {
  62. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  63. if (!isLoopInvariant(I->getOperand(i)))
  64. return false;
  65. return true;
  66. }
  67. /// makeLoopInvariant - If the given value is an instruciton inside of the
  68. /// loop and it can be hoisted, do so to make it trivially loop-invariant.
  69. /// Return true if the value after any hoisting is loop invariant. This
  70. /// function can be used as a slightly more aggressive replacement for
  71. /// isLoopInvariant.
  72. ///
  73. /// If InsertPt is specified, it is the point to hoist instructions to.
  74. /// If null, the terminator of the loop preheader is used.
  75. ///
  76. bool Loop::makeLoopInvariant(Value *V, bool &Changed,
  77. Instruction *InsertPt) const {
  78. if (Instruction *I = dyn_cast<Instruction>(V))
  79. return makeLoopInvariant(I, Changed, InsertPt);
  80. return true; // All non-instructions are loop-invariant.
  81. }
  82. /// makeLoopInvariant - If the given instruction is inside of the
  83. /// loop and it can be hoisted, do so to make it trivially loop-invariant.
  84. /// Return true if the instruction after any hoisting is loop invariant. This
  85. /// function can be used as a slightly more aggressive replacement for
  86. /// isLoopInvariant.
  87. ///
  88. /// If InsertPt is specified, it is the point to hoist instructions to.
  89. /// If null, the terminator of the loop preheader is used.
  90. ///
  91. bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
  92. Instruction *InsertPt) const {
  93. // Test if the value is already loop-invariant.
  94. if (isLoopInvariant(I))
  95. return true;
  96. if (!isSafeToSpeculativelyExecute(I))
  97. return false;
  98. if (I->mayReadFromMemory())
  99. return false;
  100. // The landingpad instruction is immobile.
  101. if (isa<LandingPadInst>(I))
  102. return false;
  103. // Determine the insertion point, unless one was given.
  104. if (!InsertPt) {
  105. BasicBlock *Preheader = getLoopPreheader();
  106. // Without a preheader, hoisting is not feasible.
  107. if (!Preheader)
  108. return false;
  109. InsertPt = Preheader->getTerminator();
  110. }
  111. // Don't hoist instructions with loop-variant operands.
  112. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  113. if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
  114. return false;
  115. // Hoist.
  116. I->moveBefore(InsertPt);
  117. Changed = true;
  118. return true;
  119. }
  120. /// getCanonicalInductionVariable - Check to see if the loop has a canonical
  121. /// induction variable: an integer recurrence that starts at 0 and increments
  122. /// by one each time through the loop. If so, return the phi node that
  123. /// corresponds to it.
  124. ///
  125. /// The IndVarSimplify pass transforms loops to have a canonical induction
  126. /// variable.
  127. ///
  128. PHINode *Loop::getCanonicalInductionVariable() const {
  129. BasicBlock *H = getHeader();
  130. BasicBlock *Incoming = 0, *Backedge = 0;
  131. pred_iterator PI = pred_begin(H);
  132. assert(PI != pred_end(H) &&
  133. "Loop must have at least one backedge!");
  134. Backedge = *PI++;
  135. if (PI == pred_end(H)) return 0; // dead loop
  136. Incoming = *PI++;
  137. if (PI != pred_end(H)) return 0; // multiple backedges?
  138. if (contains(Incoming)) {
  139. if (contains(Backedge))
  140. return 0;
  141. std::swap(Incoming, Backedge);
  142. } else if (!contains(Backedge))
  143. return 0;
  144. // Loop over all of the PHI nodes, looking for a canonical indvar.
  145. for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
  146. PHINode *PN = cast<PHINode>(I);
  147. if (ConstantInt *CI =
  148. dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
  149. if (CI->isNullValue())
  150. if (Instruction *Inc =
  151. dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
  152. if (Inc->getOpcode() == Instruction::Add &&
  153. Inc->getOperand(0) == PN)
  154. if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
  155. if (CI->equalsInt(1))
  156. return PN;
  157. }
  158. return 0;
  159. }
  160. /// isLCSSAForm - Return true if the Loop is in LCSSA form
  161. bool Loop::isLCSSAForm(DominatorTree &DT) const {
  162. for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
  163. BasicBlock *BB = *BI;
  164. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
  165. for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
  166. ++UI) {
  167. User *U = *UI;
  168. BasicBlock *UserBB = cast<Instruction>(U)->getParent();
  169. if (PHINode *P = dyn_cast<PHINode>(U))
  170. UserBB = P->getIncomingBlock(UI);
  171. // Check the current block, as a fast-path, before checking whether
  172. // the use is anywhere in the loop. Most values are used in the same
  173. // block they are defined in. Also, blocks not reachable from the
  174. // entry are special; uses in them don't need to go through PHIs.
  175. if (UserBB != BB &&
  176. !contains(UserBB) &&
  177. DT.isReachableFromEntry(UserBB))
  178. return false;
  179. }
  180. }
  181. return true;
  182. }
  183. /// isLoopSimplifyForm - Return true if the Loop is in the form that
  184. /// the LoopSimplify form transforms loops to, which is sometimes called
  185. /// normal form.
  186. bool Loop::isLoopSimplifyForm() const {
  187. // Normal-form loops have a preheader, a single backedge, and all of their
  188. // exits have all their predecessors inside the loop.
  189. return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
  190. }
  191. /// isSafeToClone - Return true if the loop body is safe to clone in practice.
  192. /// Routines that reform the loop CFG and split edges often fail on indirectbr.
  193. bool Loop::isSafeToClone() const {
  194. // Return false if any loop blocks contain indirectbrs, or there are any calls
  195. // to noduplicate functions.
  196. for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
  197. if (isa<IndirectBrInst>((*I)->getTerminator()))
  198. return false;
  199. if (const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator()))
  200. if (II->hasFnAttr(Attribute::NoDuplicate))
  201. return false;
  202. for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) {
  203. if (const CallInst *CI = dyn_cast<CallInst>(BI)) {
  204. if (CI->hasFnAttr(Attribute::NoDuplicate))
  205. return false;
  206. }
  207. }
  208. }
  209. return true;
  210. }
  211. MDNode *Loop::getLoopID() const {
  212. MDNode *LoopID = 0;
  213. if (isLoopSimplifyForm()) {
  214. LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
  215. } else {
  216. // Go through each predecessor of the loop header and check the
  217. // terminator for the metadata.
  218. BasicBlock *H = getHeader();
  219. for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
  220. TerminatorInst *TI = (*I)->getTerminator();
  221. MDNode *MD = 0;
  222. // Check if this terminator branches to the loop header.
  223. for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
  224. if (TI->getSuccessor(i) == H) {
  225. MD = TI->getMetadata(LoopMDName);
  226. break;
  227. }
  228. }
  229. if (!MD)
  230. return 0;
  231. if (!LoopID)
  232. LoopID = MD;
  233. else if (MD != LoopID)
  234. return 0;
  235. }
  236. }
  237. if (!LoopID || LoopID->getNumOperands() == 0 ||
  238. LoopID->getOperand(0) != LoopID)
  239. return 0;
  240. return LoopID;
  241. }
  242. void Loop::setLoopID(MDNode *LoopID) const {
  243. assert(LoopID && "Loop ID should not be null");
  244. assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
  245. assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
  246. if (isLoopSimplifyForm()) {
  247. getLoopLatch()->getTerminator()->setMetadata(LoopMDName, LoopID);
  248. return;
  249. }
  250. BasicBlock *H = getHeader();
  251. for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
  252. TerminatorInst *TI = (*I)->getTerminator();
  253. for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
  254. if (TI->getSuccessor(i) == H)
  255. TI->setMetadata(LoopMDName, LoopID);
  256. }
  257. }
  258. }
  259. bool Loop::isAnnotatedParallel() const {
  260. MDNode *desiredLoopIdMetadata = getLoopID();
  261. if (!desiredLoopIdMetadata)
  262. return false;
  263. // The loop branch contains the parallel loop metadata. In order to ensure
  264. // that any parallel-loop-unaware optimization pass hasn't added loop-carried
  265. // dependencies (thus converted the loop back to a sequential loop), check
  266. // that all the memory instructions in the loop contain parallelism metadata
  267. // that point to the same unique "loop id metadata" the loop branch does.
  268. for (block_iterator BB = block_begin(), BE = block_end(); BB != BE; ++BB) {
  269. for (BasicBlock::iterator II = (*BB)->begin(), EE = (*BB)->end();
  270. II != EE; II++) {
  271. if (!II->mayReadOrWriteMemory())
  272. continue;
  273. // The memory instruction can refer to the loop identifier metadata
  274. // directly or indirectly through another list metadata (in case of
  275. // nested parallel loops). The loop identifier metadata refers to
  276. // itself so we can check both cases with the same routine.
  277. MDNode *loopIdMD = II->getMetadata("llvm.mem.parallel_loop_access");
  278. if (!loopIdMD)
  279. return false;
  280. bool loopIdMDFound = false;
  281. for (unsigned i = 0, e = loopIdMD->getNumOperands(); i < e; ++i) {
  282. if (loopIdMD->getOperand(i) == desiredLoopIdMetadata) {
  283. loopIdMDFound = true;
  284. break;
  285. }
  286. }
  287. if (!loopIdMDFound)
  288. return false;
  289. }
  290. }
  291. return true;
  292. }
  293. /// hasDedicatedExits - Return true if no exit block for the loop
  294. /// has a predecessor that is outside the loop.
  295. bool Loop::hasDedicatedExits() const {
  296. // Each predecessor of each exit block of a normal loop is contained
  297. // within the loop.
  298. SmallVector<BasicBlock *, 4> ExitBlocks;
  299. getExitBlocks(ExitBlocks);
  300. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
  301. for (pred_iterator PI = pred_begin(ExitBlocks[i]),
  302. PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
  303. if (!contains(*PI))
  304. return false;
  305. // All the requirements are met.
  306. return true;
  307. }
  308. /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
  309. /// These are the blocks _outside of the current loop_ which are branched to.
  310. /// This assumes that loop exits are in canonical form.
  311. ///
  312. void
  313. Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
  314. assert(hasDedicatedExits() &&
  315. "getUniqueExitBlocks assumes the loop has canonical form exits!");
  316. SmallVector<BasicBlock *, 32> switchExitBlocks;
  317. for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
  318. BasicBlock *current = *BI;
  319. switchExitBlocks.clear();
  320. for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
  321. // If block is inside the loop then it is not a exit block.
  322. if (contains(*I))
  323. continue;
  324. pred_iterator PI = pred_begin(*I);
  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 (current != 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(current), succ_end(current)) <= 2) {
  336. ExitBlocks.push_back(*I);
  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 (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
  343. == switchExitBlocks.end()) {
  344. switchExitBlocks.push_back(*I);
  345. ExitBlocks.push_back(*I);
  346. }
  347. }
  348. }
  349. }
  350. /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
  351. /// block, return that block. Otherwise return null.
  352. BasicBlock *Loop::getUniqueExitBlock() const {
  353. SmallVector<BasicBlock *, 8> UniqueExitBlocks;
  354. getUniqueExitBlocks(UniqueExitBlocks);
  355. if (UniqueExitBlocks.size() == 1)
  356. return UniqueExitBlocks[0];
  357. return 0;
  358. }
  359. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  360. void Loop::dump() const {
  361. print(dbgs());
  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. /// updateBlockParents - Update the parent loop for all blocks that are directly
  393. /// contained within the 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 (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
  400. POE = Traversal.end(); POI != POE; ++POI) {
  401. Loop *L = LI->getLoopFor(*POI);
  402. Loop *NL = getNearestLoop(*POI, L);
  403. if (NL != L) {
  404. // For reducible loops, NL is now an ancestor of Unloop.
  405. assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
  406. "uninitialized successor");
  407. LI->changeLoopFor(*POI, NL);
  408. }
  409. else {
  410. // Or the current block is part of a subloop, in which case its parent
  411. // is unchanged.
  412. assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
  413. }
  414. }
  415. }
  416. // Each irreducible loop within the unloop induces a round of iteration using
  417. // the DFS result cached by Traversal.
  418. bool Changed = FoundIB;
  419. for (unsigned NIters = 0; Changed; ++NIters) {
  420. assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
  421. // Iterate over the postorder list of blocks, propagating the nearest loop
  422. // from successors to predecessors as before.
  423. Changed = false;
  424. for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
  425. POE = DFS.endPostorder(); POI != POE; ++POI) {
  426. Loop *L = LI->getLoopFor(*POI);
  427. Loop *NL = getNearestLoop(*POI, L);
  428. if (NL != L) {
  429. assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
  430. "uninitialized successor");
  431. LI->changeLoopFor(*POI, NL);
  432. Changed = true;
  433. }
  434. }
  435. }
  436. }
  437. /// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
  438. /// their new parents.
  439. void UnloopUpdater::removeBlocksFromAncestors() {
  440. // Remove all unloop's blocks (including those in nested subloops) from
  441. // ancestors below the new parent loop.
  442. for (Loop::block_iterator BI = Unloop->block_begin(),
  443. BE = Unloop->block_end(); BI != BE; ++BI) {
  444. Loop *OuterParent = LI->getLoopFor(*BI);
  445. if (Unloop->contains(OuterParent)) {
  446. while (OuterParent->getParentLoop() != Unloop)
  447. OuterParent = OuterParent->getParentLoop();
  448. OuterParent = SubloopParents[OuterParent];
  449. }
  450. // Remove blocks from former Ancestors except Unloop itself which will be
  451. // deleted.
  452. for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
  453. OldParent = OldParent->getParentLoop()) {
  454. assert(OldParent && "new loop is not an ancestor of the original");
  455. OldParent->removeBlockFromLoop(*BI);
  456. }
  457. }
  458. }
  459. /// updateSubloopParents - Update the parent loop for all subloops directly
  460. /// nested within unloop.
  461. void UnloopUpdater::updateSubloopParents() {
  462. while (!Unloop->empty()) {
  463. Loop *Subloop = *std::prev(Unloop->end());
  464. Unloop->removeChildLoop(std::prev(Unloop->end()));
  465. assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
  466. if (Loop *Parent = SubloopParents[Subloop])
  467. Parent->addChildLoop(Subloop);
  468. else
  469. LI->addTopLevelLoop(Subloop);
  470. }
  471. }
  472. /// getNearestLoop - Return the nearest parent loop among this block's
  473. /// successors. If a successor is a subloop header, consider its parent to be
  474. /// the nearest parent of the subloop's exits.
  475. ///
  476. /// For subloop blocks, simply update SubloopParents and return NULL.
  477. Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
  478. // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
  479. // is considered uninitialized.
  480. Loop *NearLoop = BBLoop;
  481. Loop *Subloop = 0;
  482. if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
  483. Subloop = NearLoop;
  484. // Find the subloop ancestor that is directly contained within Unloop.
  485. while (Subloop->getParentLoop() != Unloop) {
  486. Subloop = Subloop->getParentLoop();
  487. assert(Subloop && "subloop is not an ancestor of the original loop");
  488. }
  489. // Get the current nearest parent of the Subloop exits, initially Unloop.
  490. NearLoop =
  491. SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
  492. }
  493. succ_iterator I = succ_begin(BB), E = succ_end(BB);
  494. if (I == E) {
  495. assert(!Subloop && "subloop blocks must have a successor");
  496. NearLoop = 0; // unloop blocks may now exit the function.
  497. }
  498. for (; I != E; ++I) {
  499. if (*I == BB)
  500. continue; // self loops are uninteresting
  501. Loop *L = LI->getLoopFor(*I);
  502. if (L == Unloop) {
  503. // This successor has not been processed. This path must lead to an
  504. // irreducible backedge.
  505. assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
  506. FoundIB = true;
  507. }
  508. if (L != Unloop && Unloop->contains(L)) {
  509. // Successor is in a subloop.
  510. if (Subloop)
  511. continue; // Branching within subloops. Ignore it.
  512. // BB branches from the original into a subloop header.
  513. assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
  514. // Get the current nearest parent of the Subloop's exits.
  515. L = SubloopParents[L];
  516. // L could be Unloop if the only exit was an irreducible backedge.
  517. }
  518. if (L == Unloop) {
  519. continue;
  520. }
  521. // Handle critical edges from Unloop into a sibling loop.
  522. if (L && !L->contains(Unloop)) {
  523. L = L->getParentLoop();
  524. }
  525. // Remember the nearest parent loop among successors or subloop exits.
  526. if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
  527. NearLoop = L;
  528. }
  529. if (Subloop) {
  530. SubloopParents[Subloop] = NearLoop;
  531. return BBLoop;
  532. }
  533. return NearLoop;
  534. }
  535. //===----------------------------------------------------------------------===//
  536. // LoopInfo implementation
  537. //
  538. bool LoopInfo::runOnFunction(Function &) {
  539. releaseMemory();
  540. LI.Analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
  541. return false;
  542. }
  543. /// updateUnloop - The last backedge has been removed from a loop--now the
  544. /// "unloop". Find a new parent for the blocks contained within unloop and
  545. /// update the loop tree. We don't necessarily have valid dominators at this
  546. /// point, but LoopInfo is still valid except for the removal of this loop.
  547. ///
  548. /// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
  549. /// checking first is illegal.
  550. void LoopInfo::updateUnloop(Loop *Unloop) {
  551. // First handle the special case of no parent loop to simplify the algorithm.
  552. if (!Unloop->getParentLoop()) {
  553. // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
  554. for (Loop::block_iterator I = Unloop->block_begin(),
  555. E = Unloop->block_end(); I != E; ++I) {
  556. // Don't reparent blocks in subloops.
  557. if (getLoopFor(*I) != Unloop)
  558. continue;
  559. // Blocks no longer have a parent but are still referenced by Unloop until
  560. // the Unloop object is deleted.
  561. LI.changeLoopFor(*I, 0);
  562. }
  563. // Remove the loop from the top-level LoopInfo object.
  564. for (LoopInfo::iterator I = LI.begin();; ++I) {
  565. assert(I != LI.end() && "Couldn't find loop");
  566. if (*I == Unloop) {
  567. LI.removeLoop(I);
  568. break;
  569. }
  570. }
  571. // Move all of the subloops to the top-level.
  572. while (!Unloop->empty())
  573. LI.addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
  574. return;
  575. }
  576. // Update the parent loop for all blocks within the loop. Blocks within
  577. // subloops will not change parents.
  578. UnloopUpdater Updater(Unloop, this);
  579. Updater.updateBlockParents();
  580. // Remove blocks from former ancestor loops.
  581. Updater.removeBlocksFromAncestors();
  582. // Add direct subloops as children in their new parent loop.
  583. Updater.updateSubloopParents();
  584. // Remove unloop from its parent loop.
  585. Loop *ParentLoop = Unloop->getParentLoop();
  586. for (Loop::iterator I = ParentLoop->begin();; ++I) {
  587. assert(I != ParentLoop->end() && "Couldn't find loop");
  588. if (*I == Unloop) {
  589. ParentLoop->removeChildLoop(I);
  590. break;
  591. }
  592. }
  593. }
  594. void LoopInfo::verifyAnalysis() const {
  595. // LoopInfo is a FunctionPass, but verifying every loop in the function
  596. // each time verifyAnalysis is called is very expensive. The
  597. // -verify-loop-info option can enable this. In order to perform some
  598. // checking by default, LoopPass has been taught to call verifyLoop
  599. // manually during loop pass sequences.
  600. if (!VerifyLoopInfo) return;
  601. DenseSet<const Loop*> Loops;
  602. for (iterator I = begin(), E = end(); I != E; ++I) {
  603. assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
  604. (*I)->verifyLoopNest(&Loops);
  605. }
  606. // Verify that blocks are mapped to valid loops.
  607. for (DenseMap<BasicBlock*, Loop*>::const_iterator I = LI.BBMap.begin(),
  608. E = LI.BBMap.end(); I != E; ++I) {
  609. assert(Loops.count(I->second) && "orphaned loop");
  610. assert(I->second->contains(I->first) && "orphaned block");
  611. }
  612. }
  613. void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
  614. AU.setPreservesAll();
  615. AU.addRequired<DominatorTreeWrapperPass>();
  616. }
  617. void LoopInfo::print(raw_ostream &OS, const Module*) const {
  618. LI.print(OS);
  619. }
  620. //===----------------------------------------------------------------------===//
  621. // LoopBlocksDFS implementation
  622. //
  623. /// Traverse the loop blocks and store the DFS result.
  624. /// Useful for clients that just want the final DFS result and don't need to
  625. /// visit blocks during the initial traversal.
  626. void LoopBlocksDFS::perform(LoopInfo *LI) {
  627. LoopBlocksTraversal Traversal(*this, LI);
  628. for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
  629. POE = Traversal.end(); POI != POE; ++POI) ;
  630. }