PageRenderTime 25ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/src/freebsd/contrib/llvm/lib/Analysis/LoopInfo.cpp

https://bitbucket.org/killerpenguinassassins/open_distrib_devel
C++ | 705 lines | 413 code | 84 blank | 208 comment | 178 complexity | 636794d56598b62bfa9eb1c82d58d778 MD5 | raw file
Possible License(s): CC0-1.0, MIT, LGPL-2.0, LGPL-3.0, WTFPL, GPL-2.0, BSD-2-Clause, AGPL-3.0, CC-BY-SA-3.0, MPL-2.0, JSON, BSD-3-Clause-No-Nuclear-License-2014, LGPL-2.1, CPL-1.0, AGPL-1.0, 0BSD, ISC, Apache-2.0, GPL-3.0, IPL-1.0, MPL-2.0-no-copyleft-exception, BSD-3-Clause
  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/Constants.h"
  18. #include "llvm/Instructions.h"
  19. #include "llvm/Analysis/Dominators.h"
  20. #include "llvm/Analysis/LoopIterator.h"
  21. #include "llvm/Assembly/Writer.h"
  22. #include "llvm/Support/CFG.h"
  23. #include "llvm/Support/CommandLine.h"
  24. #include "llvm/Support/Debug.h"
  25. #include "llvm/ADT/DepthFirstIterator.h"
  26. #include "llvm/ADT/SmallPtrSet.h"
  27. #include <algorithm>
  28. using namespace llvm;
  29. // Always verify loopinfo if expensive checking is enabled.
  30. #ifdef XDEBUG
  31. static bool VerifyLoopInfo = true;
  32. #else
  33. static bool VerifyLoopInfo = false;
  34. #endif
  35. static cl::opt<bool,true>
  36. VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
  37. cl::desc("Verify loop info (time consuming)"));
  38. char LoopInfo::ID = 0;
  39. INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true)
  40. INITIALIZE_PASS_DEPENDENCY(DominatorTree)
  41. INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true)
  42. //===----------------------------------------------------------------------===//
  43. // Loop implementation
  44. //
  45. /// isLoopInvariant - Return true if the specified value is loop invariant
  46. ///
  47. bool Loop::isLoopInvariant(Value *V) const {
  48. if (Instruction *I = dyn_cast<Instruction>(V))
  49. return !contains(I);
  50. return true; // All non-instructions are loop invariant
  51. }
  52. /// hasLoopInvariantOperands - Return true if all the operands of the
  53. /// specified instruction are loop invariant.
  54. bool Loop::hasLoopInvariantOperands(Instruction *I) const {
  55. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  56. if (!isLoopInvariant(I->getOperand(i)))
  57. return false;
  58. return true;
  59. }
  60. /// makeLoopInvariant - If the given value is an instruciton inside of the
  61. /// loop and it can be hoisted, do so to make it trivially loop-invariant.
  62. /// Return true if the value after any hoisting is loop invariant. This
  63. /// function can be used as a slightly more aggressive replacement for
  64. /// isLoopInvariant.
  65. ///
  66. /// If InsertPt is specified, it is the point to hoist instructions to.
  67. /// If null, the terminator of the loop preheader is used.
  68. ///
  69. bool Loop::makeLoopInvariant(Value *V, bool &Changed,
  70. Instruction *InsertPt) const {
  71. if (Instruction *I = dyn_cast<Instruction>(V))
  72. return makeLoopInvariant(I, Changed, InsertPt);
  73. return true; // All non-instructions are loop-invariant.
  74. }
  75. /// makeLoopInvariant - If the given instruction is inside of the
  76. /// loop and it can be hoisted, do so to make it trivially loop-invariant.
  77. /// Return true if the instruction after any hoisting is loop invariant. This
  78. /// function can be used as a slightly more aggressive replacement for
  79. /// isLoopInvariant.
  80. ///
  81. /// If InsertPt is specified, it is the point to hoist instructions to.
  82. /// If null, the terminator of the loop preheader is used.
  83. ///
  84. bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
  85. Instruction *InsertPt) const {
  86. // Test if the value is already loop-invariant.
  87. if (isLoopInvariant(I))
  88. return true;
  89. if (!I->isSafeToSpeculativelyExecute())
  90. return false;
  91. if (I->mayReadFromMemory())
  92. return false;
  93. // The landingpad instruction is immobile.
  94. if (isa<LandingPadInst>(I))
  95. return false;
  96. // Determine the insertion point, unless one was given.
  97. if (!InsertPt) {
  98. BasicBlock *Preheader = getLoopPreheader();
  99. // Without a preheader, hoisting is not feasible.
  100. if (!Preheader)
  101. return false;
  102. InsertPt = Preheader->getTerminator();
  103. }
  104. // Don't hoist instructions with loop-variant operands.
  105. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  106. if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
  107. return false;
  108. // Hoist.
  109. I->moveBefore(InsertPt);
  110. Changed = true;
  111. return true;
  112. }
  113. /// getCanonicalInductionVariable - Check to see if the loop has a canonical
  114. /// induction variable: an integer recurrence that starts at 0 and increments
  115. /// by one each time through the loop. If so, return the phi node that
  116. /// corresponds to it.
  117. ///
  118. /// The IndVarSimplify pass transforms loops to have a canonical induction
  119. /// variable.
  120. ///
  121. PHINode *Loop::getCanonicalInductionVariable() const {
  122. BasicBlock *H = getHeader();
  123. BasicBlock *Incoming = 0, *Backedge = 0;
  124. pred_iterator PI = pred_begin(H);
  125. assert(PI != pred_end(H) &&
  126. "Loop must have at least one backedge!");
  127. Backedge = *PI++;
  128. if (PI == pred_end(H)) return 0; // dead loop
  129. Incoming = *PI++;
  130. if (PI != pred_end(H)) return 0; // multiple backedges?
  131. if (contains(Incoming)) {
  132. if (contains(Backedge))
  133. return 0;
  134. std::swap(Incoming, Backedge);
  135. } else if (!contains(Backedge))
  136. return 0;
  137. // Loop over all of the PHI nodes, looking for a canonical indvar.
  138. for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
  139. PHINode *PN = cast<PHINode>(I);
  140. if (ConstantInt *CI =
  141. dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
  142. if (CI->isNullValue())
  143. if (Instruction *Inc =
  144. dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
  145. if (Inc->getOpcode() == Instruction::Add &&
  146. Inc->getOperand(0) == PN)
  147. if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
  148. if (CI->equalsInt(1))
  149. return PN;
  150. }
  151. return 0;
  152. }
  153. /// getTripCount - Return a loop-invariant LLVM value indicating the number of
  154. /// times the loop will be executed. Note that this means that the backedge
  155. /// of the loop executes N-1 times. If the trip-count cannot be determined,
  156. /// this returns null.
  157. ///
  158. /// The IndVarSimplify pass transforms loops to have a form that this
  159. /// function easily understands.
  160. ///
  161. Value *Loop::getTripCount() const {
  162. // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
  163. // canonical induction variable and V is the trip count of the loop.
  164. PHINode *IV = getCanonicalInductionVariable();
  165. if (IV == 0 || IV->getNumIncomingValues() != 2) return 0;
  166. bool P0InLoop = contains(IV->getIncomingBlock(0));
  167. Value *Inc = IV->getIncomingValue(!P0InLoop);
  168. BasicBlock *BackedgeBlock = IV->getIncomingBlock(!P0InLoop);
  169. if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
  170. if (BI->isConditional()) {
  171. if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
  172. if (ICI->getOperand(0) == Inc) {
  173. if (BI->getSuccessor(0) == getHeader()) {
  174. if (ICI->getPredicate() == ICmpInst::ICMP_NE)
  175. return ICI->getOperand(1);
  176. } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
  177. return ICI->getOperand(1);
  178. }
  179. }
  180. }
  181. }
  182. return 0;
  183. }
  184. /// getSmallConstantTripCount - Returns the trip count of this loop as a
  185. /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
  186. /// or not constant. Will also return 0 if the trip count is very large
  187. /// (>= 2^32)
  188. unsigned Loop::getSmallConstantTripCount() const {
  189. Value* TripCount = this->getTripCount();
  190. if (TripCount) {
  191. if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCount)) {
  192. // Guard against huge trip counts.
  193. if (TripCountC->getValue().getActiveBits() <= 32) {
  194. return (unsigned)TripCountC->getZExtValue();
  195. }
  196. }
  197. }
  198. return 0;
  199. }
  200. /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
  201. /// trip count of this loop as a normal unsigned value, if possible. This
  202. /// means that the actual trip count is always a multiple of the returned
  203. /// value (don't forget the trip count could very well be zero as well!).
  204. ///
  205. /// Returns 1 if the trip count is unknown or not guaranteed to be the
  206. /// multiple of a constant (which is also the case if the trip count is simply
  207. /// constant, use getSmallConstantTripCount for that case), Will also return 1
  208. /// if the trip count is very large (>= 2^32).
  209. unsigned Loop::getSmallConstantTripMultiple() const {
  210. Value* TripCount = this->getTripCount();
  211. // This will hold the ConstantInt result, if any
  212. ConstantInt *Result = NULL;
  213. if (TripCount) {
  214. // See if the trip count is constant itself
  215. Result = dyn_cast<ConstantInt>(TripCount);
  216. // if not, see if it is a multiplication
  217. if (!Result)
  218. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCount)) {
  219. switch (BO->getOpcode()) {
  220. case BinaryOperator::Mul:
  221. Result = dyn_cast<ConstantInt>(BO->getOperand(1));
  222. break;
  223. case BinaryOperator::Shl:
  224. if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
  225. if (CI->getValue().getActiveBits() <= 5)
  226. return 1u << CI->getZExtValue();
  227. break;
  228. default:
  229. break;
  230. }
  231. }
  232. }
  233. // Guard against huge trip counts.
  234. if (Result && Result->getValue().getActiveBits() <= 32) {
  235. return (unsigned)Result->getZExtValue();
  236. } else {
  237. return 1;
  238. }
  239. }
  240. /// isLCSSAForm - Return true if the Loop is in LCSSA form
  241. bool Loop::isLCSSAForm(DominatorTree &DT) const {
  242. // Sort the blocks vector so that we can use binary search to do quick
  243. // lookups.
  244. SmallPtrSet<BasicBlock*, 16> LoopBBs(block_begin(), block_end());
  245. for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
  246. BasicBlock *BB = *BI;
  247. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
  248. for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
  249. ++UI) {
  250. User *U = *UI;
  251. BasicBlock *UserBB = cast<Instruction>(U)->getParent();
  252. if (PHINode *P = dyn_cast<PHINode>(U))
  253. UserBB = P->getIncomingBlock(UI);
  254. // Check the current block, as a fast-path, before checking whether
  255. // the use is anywhere in the loop. Most values are used in the same
  256. // block they are defined in. Also, blocks not reachable from the
  257. // entry are special; uses in them don't need to go through PHIs.
  258. if (UserBB != BB &&
  259. !LoopBBs.count(UserBB) &&
  260. DT.isReachableFromEntry(UserBB))
  261. return false;
  262. }
  263. }
  264. return true;
  265. }
  266. /// isLoopSimplifyForm - Return true if the Loop is in the form that
  267. /// the LoopSimplify form transforms loops to, which is sometimes called
  268. /// normal form.
  269. bool Loop::isLoopSimplifyForm() const {
  270. // Normal-form loops have a preheader, a single backedge, and all of their
  271. // exits have all their predecessors inside the loop.
  272. return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
  273. }
  274. /// hasDedicatedExits - Return true if no exit block for the loop
  275. /// has a predecessor that is outside the loop.
  276. bool Loop::hasDedicatedExits() const {
  277. // Sort the blocks vector so that we can use binary search to do quick
  278. // lookups.
  279. SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
  280. // Each predecessor of each exit block of a normal loop is contained
  281. // within the loop.
  282. SmallVector<BasicBlock *, 4> ExitBlocks;
  283. getExitBlocks(ExitBlocks);
  284. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
  285. for (pred_iterator PI = pred_begin(ExitBlocks[i]),
  286. PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
  287. if (!LoopBBs.count(*PI))
  288. return false;
  289. // All the requirements are met.
  290. return true;
  291. }
  292. /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
  293. /// These are the blocks _outside of the current loop_ which are branched to.
  294. /// This assumes that loop exits are in canonical form.
  295. ///
  296. void
  297. Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
  298. assert(hasDedicatedExits() &&
  299. "getUniqueExitBlocks assumes the loop has canonical form exits!");
  300. // Sort the blocks vector so that we can use binary search to do quick
  301. // lookups.
  302. SmallVector<BasicBlock *, 128> LoopBBs(block_begin(), block_end());
  303. std::sort(LoopBBs.begin(), LoopBBs.end());
  304. SmallVector<BasicBlock *, 32> switchExitBlocks;
  305. for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
  306. BasicBlock *current = *BI;
  307. switchExitBlocks.clear();
  308. for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
  309. // If block is inside the loop then it is not a exit block.
  310. if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
  311. continue;
  312. pred_iterator PI = pred_begin(*I);
  313. BasicBlock *firstPred = *PI;
  314. // If current basic block is this exit block's first predecessor
  315. // then only insert exit block in to the output ExitBlocks vector.
  316. // This ensures that same exit block is not inserted twice into
  317. // ExitBlocks vector.
  318. if (current != firstPred)
  319. continue;
  320. // If a terminator has more then two successors, for example SwitchInst,
  321. // then it is possible that there are multiple edges from current block
  322. // to one exit block.
  323. if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
  324. ExitBlocks.push_back(*I);
  325. continue;
  326. }
  327. // In case of multiple edges from current block to exit block, collect
  328. // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
  329. // duplicate edges.
  330. if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
  331. == switchExitBlocks.end()) {
  332. switchExitBlocks.push_back(*I);
  333. ExitBlocks.push_back(*I);
  334. }
  335. }
  336. }
  337. }
  338. /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
  339. /// block, return that block. Otherwise return null.
  340. BasicBlock *Loop::getUniqueExitBlock() const {
  341. SmallVector<BasicBlock *, 8> UniqueExitBlocks;
  342. getUniqueExitBlocks(UniqueExitBlocks);
  343. if (UniqueExitBlocks.size() == 1)
  344. return UniqueExitBlocks[0];
  345. return 0;
  346. }
  347. void Loop::dump() const {
  348. print(dbgs());
  349. }
  350. //===----------------------------------------------------------------------===//
  351. // UnloopUpdater implementation
  352. //
  353. namespace {
  354. /// Find the new parent loop for all blocks within the "unloop" whose last
  355. /// backedges has just been removed.
  356. class UnloopUpdater {
  357. Loop *Unloop;
  358. LoopInfo *LI;
  359. LoopBlocksDFS DFS;
  360. // Map unloop's immediate subloops to their nearest reachable parents. Nested
  361. // loops within these subloops will not change parents. However, an immediate
  362. // subloop's new parent will be the nearest loop reachable from either its own
  363. // exits *or* any of its nested loop's exits.
  364. DenseMap<Loop*, Loop*> SubloopParents;
  365. // Flag the presence of an irreducible backedge whose destination is a block
  366. // directly contained by the original unloop.
  367. bool FoundIB;
  368. public:
  369. UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
  370. Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
  371. void updateBlockParents();
  372. void removeBlocksFromAncestors();
  373. void updateSubloopParents();
  374. protected:
  375. Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
  376. };
  377. } // end anonymous namespace
  378. /// updateBlockParents - Update the parent loop for all blocks that are directly
  379. /// contained within the original "unloop".
  380. void UnloopUpdater::updateBlockParents() {
  381. if (Unloop->getNumBlocks()) {
  382. // Perform a post order CFG traversal of all blocks within this loop,
  383. // propagating the nearest loop from sucessors to predecessors.
  384. LoopBlocksTraversal Traversal(DFS, LI);
  385. for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
  386. POE = Traversal.end(); POI != POE; ++POI) {
  387. Loop *L = LI->getLoopFor(*POI);
  388. Loop *NL = getNearestLoop(*POI, L);
  389. if (NL != L) {
  390. // For reducible loops, NL is now an ancestor of Unloop.
  391. assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
  392. "uninitialized successor");
  393. LI->changeLoopFor(*POI, NL);
  394. }
  395. else {
  396. // Or the current block is part of a subloop, in which case its parent
  397. // is unchanged.
  398. assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
  399. }
  400. }
  401. }
  402. // Each irreducible loop within the unloop induces a round of iteration using
  403. // the DFS result cached by Traversal.
  404. bool Changed = FoundIB;
  405. for (unsigned NIters = 0; Changed; ++NIters) {
  406. assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
  407. // Iterate over the postorder list of blocks, propagating the nearest loop
  408. // from successors to predecessors as before.
  409. Changed = false;
  410. for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
  411. POE = DFS.endPostorder(); POI != POE; ++POI) {
  412. Loop *L = LI->getLoopFor(*POI);
  413. Loop *NL = getNearestLoop(*POI, L);
  414. if (NL != L) {
  415. assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
  416. "uninitialized successor");
  417. LI->changeLoopFor(*POI, NL);
  418. Changed = true;
  419. }
  420. }
  421. }
  422. }
  423. /// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
  424. /// their new parents.
  425. void UnloopUpdater::removeBlocksFromAncestors() {
  426. // Remove unloop's blocks from all ancestors below their new parents.
  427. for (Loop::block_iterator BI = Unloop->block_begin(),
  428. BE = Unloop->block_end(); BI != BE; ++BI) {
  429. Loop *NewParent = LI->getLoopFor(*BI);
  430. // If this block is an immediate subloop, remove all blocks (including
  431. // nested subloops) from ancestors below the new parent loop.
  432. // Otherwise, if this block is in a nested subloop, skip it.
  433. if (SubloopParents.count(NewParent))
  434. NewParent = SubloopParents[NewParent];
  435. else if (Unloop->contains(NewParent))
  436. continue;
  437. // Remove blocks from former Ancestors except Unloop itself which will be
  438. // deleted.
  439. for (Loop *OldParent = Unloop->getParentLoop(); OldParent != NewParent;
  440. OldParent = OldParent->getParentLoop()) {
  441. assert(OldParent && "new loop is not an ancestor of the original");
  442. OldParent->removeBlockFromLoop(*BI);
  443. }
  444. }
  445. }
  446. /// updateSubloopParents - Update the parent loop for all subloops directly
  447. /// nested within unloop.
  448. void UnloopUpdater::updateSubloopParents() {
  449. while (!Unloop->empty()) {
  450. Loop *Subloop = *llvm::prior(Unloop->end());
  451. Unloop->removeChildLoop(llvm::prior(Unloop->end()));
  452. assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
  453. if (SubloopParents[Subloop])
  454. SubloopParents[Subloop]->addChildLoop(Subloop);
  455. else
  456. LI->addTopLevelLoop(Subloop);
  457. }
  458. }
  459. /// getNearestLoop - Return the nearest parent loop among this block's
  460. /// successors. If a successor is a subloop header, consider its parent to be
  461. /// the nearest parent of the subloop's exits.
  462. ///
  463. /// For subloop blocks, simply update SubloopParents and return NULL.
  464. Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
  465. // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
  466. // is considered uninitialized.
  467. Loop *NearLoop = BBLoop;
  468. Loop *Subloop = 0;
  469. if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
  470. Subloop = NearLoop;
  471. // Find the subloop ancestor that is directly contained within Unloop.
  472. while (Subloop->getParentLoop() != Unloop) {
  473. Subloop = Subloop->getParentLoop();
  474. assert(Subloop && "subloop is not an ancestor of the original loop");
  475. }
  476. // Get the current nearest parent of the Subloop exits, initially Unloop.
  477. if (!SubloopParents.count(Subloop))
  478. SubloopParents[Subloop] = Unloop;
  479. NearLoop = SubloopParents[Subloop];
  480. }
  481. succ_iterator I = succ_begin(BB), E = succ_end(BB);
  482. if (I == E) {
  483. assert(!Subloop && "subloop blocks must have a successor");
  484. NearLoop = 0; // unloop blocks may now exit the function.
  485. }
  486. for (; I != E; ++I) {
  487. if (*I == BB)
  488. continue; // self loops are uninteresting
  489. Loop *L = LI->getLoopFor(*I);
  490. if (L == Unloop) {
  491. // This successor has not been processed. This path must lead to an
  492. // irreducible backedge.
  493. assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
  494. FoundIB = true;
  495. }
  496. if (L != Unloop && Unloop->contains(L)) {
  497. // Successor is in a subloop.
  498. if (Subloop)
  499. continue; // Branching within subloops. Ignore it.
  500. // BB branches from the original into a subloop header.
  501. assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
  502. // Get the current nearest parent of the Subloop's exits.
  503. L = SubloopParents[L];
  504. // L could be Unloop if the only exit was an irreducible backedge.
  505. }
  506. if (L == Unloop) {
  507. continue;
  508. }
  509. // Handle critical edges from Unloop into a sibling loop.
  510. if (L && !L->contains(Unloop)) {
  511. L = L->getParentLoop();
  512. }
  513. // Remember the nearest parent loop among successors or subloop exits.
  514. if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
  515. NearLoop = L;
  516. }
  517. if (Subloop) {
  518. SubloopParents[Subloop] = NearLoop;
  519. return BBLoop;
  520. }
  521. return NearLoop;
  522. }
  523. //===----------------------------------------------------------------------===//
  524. // LoopInfo implementation
  525. //
  526. bool LoopInfo::runOnFunction(Function &) {
  527. releaseMemory();
  528. LI.Calculate(getAnalysis<DominatorTree>().getBase()); // Update
  529. return false;
  530. }
  531. /// updateUnloop - The last backedge has been removed from a loop--now the
  532. /// "unloop". Find a new parent for the blocks contained within unloop and
  533. /// update the loop tree. We don't necessarily have valid dominators at this
  534. /// point, but LoopInfo is still valid except for the removal of this loop.
  535. ///
  536. /// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
  537. /// checking first is illegal.
  538. void LoopInfo::updateUnloop(Loop *Unloop) {
  539. // First handle the special case of no parent loop to simplify the algorithm.
  540. if (!Unloop->getParentLoop()) {
  541. // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
  542. for (Loop::block_iterator I = Unloop->block_begin(),
  543. E = Unloop->block_end(); 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. LI.changeLoopFor(*I, 0);
  550. }
  551. // Remove the loop from the top-level LoopInfo object.
  552. for (LoopInfo::iterator I = LI.begin();; ++I) {
  553. assert(I != LI.end() && "Couldn't find loop");
  554. if (*I == Unloop) {
  555. LI.removeLoop(I);
  556. break;
  557. }
  558. }
  559. // Move all of the subloops to the top-level.
  560. while (!Unloop->empty())
  561. LI.addTopLevelLoop(Unloop->removeChildLoop(llvm::prior(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. void LoopInfo::verifyAnalysis() const {
  583. // LoopInfo is a FunctionPass, but verifying every loop in the function
  584. // each time verifyAnalysis is called is very expensive. The
  585. // -verify-loop-info option can enable this. In order to perform some
  586. // checking by default, LoopPass has been taught to call verifyLoop
  587. // manually during loop pass sequences.
  588. if (!VerifyLoopInfo) return;
  589. DenseSet<const Loop*> Loops;
  590. for (iterator I = begin(), E = end(); I != E; ++I) {
  591. assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
  592. (*I)->verifyLoopNest(&Loops);
  593. }
  594. // Verify that blocks are mapped to valid loops.
  595. //
  596. // FIXME: With an up-to-date DFS (see LoopIterator.h) and DominatorTree, we
  597. // could also verify that the blocks are still in the correct loops.
  598. for (DenseMap<BasicBlock*, Loop*>::const_iterator I = LI.BBMap.begin(),
  599. E = LI.BBMap.end(); I != E; ++I) {
  600. assert(Loops.count(I->second) && "orphaned loop");
  601. assert(I->second->contains(I->first) && "orphaned block");
  602. }
  603. }
  604. void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
  605. AU.setPreservesAll();
  606. AU.addRequired<DominatorTree>();
  607. }
  608. void LoopInfo::print(raw_ostream &OS, const Module*) const {
  609. LI.print(OS);
  610. }
  611. //===----------------------------------------------------------------------===//
  612. // LoopBlocksDFS implementation
  613. //
  614. /// Traverse the loop blocks and store the DFS result.
  615. /// Useful for clients that just want the final DFS result and don't need to
  616. /// visit blocks during the initial traversal.
  617. void LoopBlocksDFS::perform(LoopInfo *LI) {
  618. LoopBlocksTraversal Traversal(*this, LI);
  619. for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
  620. POE = Traversal.end(); POI != POE; ++POI) ;
  621. }