LoopDeletion.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. //===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===//
  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 implements the Dead Loop Deletion Pass. This pass is responsible
  11. // for eliminating loops with non-infinite computable trip counts that have no
  12. // side effects or volatile instructions, and do not contribute to the
  13. // computation of the function's return value.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Transforms/Scalar.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/LoopPass.h"
  20. #include "llvm/Analysis/ScalarEvolution.h"
  21. #include "llvm/IR/Dominators.h"
  22. using namespace llvm;
  23. #define DEBUG_TYPE "loop-delete"
  24. STATISTIC(NumDeleted, "Number of loops deleted");
  25. namespace {
  26. class LoopDeletion : public LoopPass {
  27. public:
  28. static char ID; // Pass ID, replacement for typeid
  29. LoopDeletion() : LoopPass(ID) {
  30. initializeLoopDeletionPass(*PassRegistry::getPassRegistry());
  31. }
  32. // Possibly eliminate loop L if it is dead.
  33. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  34. void getAnalysisUsage(AnalysisUsage &AU) const override {
  35. AU.addRequired<DominatorTreeWrapperPass>();
  36. AU.addRequired<LoopInfoWrapperPass>();
  37. AU.addRequired<ScalarEvolution>();
  38. AU.addRequiredID(LoopSimplifyID);
  39. AU.addRequiredID(LCSSAID);
  40. AU.addPreserved<ScalarEvolution>();
  41. AU.addPreserved<DominatorTreeWrapperPass>();
  42. AU.addPreserved<LoopInfoWrapperPass>();
  43. AU.addPreservedID(LoopSimplifyID);
  44. AU.addPreservedID(LCSSAID);
  45. }
  46. private:
  47. bool isLoopDead(Loop *L, SmallVectorImpl<BasicBlock *> &exitingBlocks,
  48. SmallVectorImpl<BasicBlock *> &exitBlocks,
  49. bool &Changed, BasicBlock *Preheader);
  50. };
  51. }
  52. char LoopDeletion::ID = 0;
  53. INITIALIZE_PASS_BEGIN(LoopDeletion, "loop-deletion",
  54. "Delete dead loops", false, false)
  55. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  56. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  57. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  58. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  59. INITIALIZE_PASS_DEPENDENCY(LCSSA)
  60. INITIALIZE_PASS_END(LoopDeletion, "loop-deletion",
  61. "Delete dead loops", false, false)
  62. Pass *llvm::createLoopDeletionPass() {
  63. return new LoopDeletion();
  64. }
  65. /// isLoopDead - Determined if a loop is dead. This assumes that we've already
  66. /// checked for unique exit and exiting blocks, and that the code is in LCSSA
  67. /// form.
  68. bool LoopDeletion::isLoopDead(Loop *L,
  69. SmallVectorImpl<BasicBlock *> &exitingBlocks,
  70. SmallVectorImpl<BasicBlock *> &exitBlocks,
  71. bool &Changed, BasicBlock *Preheader) {
  72. BasicBlock *exitBlock = exitBlocks[0];
  73. // Make sure that all PHI entries coming from the loop are loop invariant.
  74. // Because the code is in LCSSA form, any values used outside of the loop
  75. // must pass through a PHI in the exit block, meaning that this check is
  76. // sufficient to guarantee that no loop-variant values are used outside
  77. // of the loop.
  78. BasicBlock::iterator BI = exitBlock->begin();
  79. while (PHINode *P = dyn_cast<PHINode>(BI)) {
  80. Value *incoming = P->getIncomingValueForBlock(exitingBlocks[0]);
  81. // Make sure all exiting blocks produce the same incoming value for the exit
  82. // block. If there are different incoming values for different exiting
  83. // blocks, then it is impossible to statically determine which value should
  84. // be used.
  85. for (unsigned i = 1, e = exitingBlocks.size(); i < e; ++i) {
  86. if (incoming != P->getIncomingValueForBlock(exitingBlocks[i]))
  87. return false;
  88. }
  89. if (Instruction *I = dyn_cast<Instruction>(incoming))
  90. if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator()))
  91. return false;
  92. ++BI;
  93. }
  94. // Make sure that no instructions in the block have potential side-effects.
  95. // This includes instructions that could write to memory, and loads that are
  96. // marked volatile. This could be made more aggressive by using aliasing
  97. // information to identify readonly and readnone calls.
  98. for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
  99. LI != LE; ++LI) {
  100. for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end();
  101. BI != BE; ++BI) {
  102. if (BI->mayHaveSideEffects())
  103. return false;
  104. }
  105. }
  106. return true;
  107. }
  108. /// runOnLoop - Remove dead loops, by which we mean loops that do not impact the
  109. /// observable behavior of the program other than finite running time. Note
  110. /// we do ensure that this never remove a loop that might be infinite, as doing
  111. /// so could change the halting/non-halting nature of a program.
  112. /// NOTE: This entire process relies pretty heavily on LoopSimplify and LCSSA
  113. /// in order to make various safety checks work.
  114. bool LoopDeletion::runOnLoop(Loop *L, LPPassManager &LPM) {
  115. if (skipOptnoneFunction(L))
  116. return false;
  117. // We can only remove the loop if there is a preheader that we can
  118. // branch from after removing it.
  119. BasicBlock *preheader = L->getLoopPreheader();
  120. if (!preheader)
  121. return false;
  122. // If LoopSimplify form is not available, stay out of trouble.
  123. if (!L->hasDedicatedExits())
  124. return false;
  125. // We can't remove loops that contain subloops. If the subloops were dead,
  126. // they would already have been removed in earlier executions of this pass.
  127. if (L->begin() != L->end())
  128. return false;
  129. SmallVector<BasicBlock*, 4> exitingBlocks;
  130. L->getExitingBlocks(exitingBlocks);
  131. SmallVector<BasicBlock*, 4> exitBlocks;
  132. L->getUniqueExitBlocks(exitBlocks);
  133. // We require that the loop only have a single exit block. Otherwise, we'd
  134. // be in the situation of needing to be able to solve statically which exit
  135. // block will be branched to, or trying to preserve the branching logic in
  136. // a loop invariant manner.
  137. if (exitBlocks.size() != 1)
  138. return false;
  139. // Finally, we have to check that the loop really is dead.
  140. bool Changed = false;
  141. if (!isLoopDead(L, exitingBlocks, exitBlocks, Changed, preheader))
  142. return Changed;
  143. // Don't remove loops for which we can't solve the trip count.
  144. // They could be infinite, in which case we'd be changing program behavior.
  145. ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
  146. const SCEV *S = SE.getMaxBackedgeTakenCount(L);
  147. if (isa<SCEVCouldNotCompute>(S))
  148. return Changed;
  149. // Now that we know the removal is safe, remove the loop by changing the
  150. // branch from the preheader to go to the single exit block.
  151. BasicBlock *exitBlock = exitBlocks[0];
  152. // Because we're deleting a large chunk of code at once, the sequence in which
  153. // we remove things is very important to avoid invalidation issues. Don't
  154. // mess with this unless you have good reason and know what you're doing.
  155. // Tell ScalarEvolution that the loop is deleted. Do this before
  156. // deleting the loop so that ScalarEvolution can look at the loop
  157. // to determine what it needs to clean up.
  158. SE.forgetLoop(L);
  159. // Connect the preheader directly to the exit block.
  160. TerminatorInst *TI = preheader->getTerminator();
  161. TI->replaceUsesOfWith(L->getHeader(), exitBlock);
  162. // Rewrite phis in the exit block to get their inputs from
  163. // the preheader instead of the exiting block.
  164. BasicBlock *exitingBlock = exitingBlocks[0];
  165. BasicBlock::iterator BI = exitBlock->begin();
  166. while (PHINode *P = dyn_cast<PHINode>(BI)) {
  167. int j = P->getBasicBlockIndex(exitingBlock);
  168. assert(j >= 0 && "Can't find exiting block in exit block's phi node!");
  169. P->setIncomingBlock(j, preheader);
  170. for (unsigned i = 1; i < exitingBlocks.size(); ++i)
  171. P->removeIncomingValue(exitingBlocks[i]);
  172. ++BI;
  173. }
  174. // Update the dominator tree and remove the instructions and blocks that will
  175. // be deleted from the reference counting scheme.
  176. DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  177. SmallVector<DomTreeNode*, 8> ChildNodes;
  178. for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
  179. LI != LE; ++LI) {
  180. // Move all of the block's children to be children of the preheader, which
  181. // allows us to remove the domtree entry for the block.
  182. ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end());
  183. for (SmallVectorImpl<DomTreeNode *>::iterator DI = ChildNodes.begin(),
  184. DE = ChildNodes.end(); DI != DE; ++DI) {
  185. DT.changeImmediateDominator(*DI, DT[preheader]);
  186. }
  187. ChildNodes.clear();
  188. DT.eraseNode(*LI);
  189. // Remove the block from the reference counting scheme, so that we can
  190. // delete it freely later.
  191. (*LI)->dropAllReferences();
  192. }
  193. // Erase the instructions and the blocks without having to worry
  194. // about ordering because we already dropped the references.
  195. // NOTE: This iteration is safe because erasing the block does not remove its
  196. // entry from the loop's block list. We do that in the next section.
  197. for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
  198. LI != LE; ++LI)
  199. (*LI)->eraseFromParent();
  200. // Finally, the blocks from loopinfo. This has to happen late because
  201. // otherwise our loop iterators won't work.
  202. LoopInfo &loopInfo = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  203. SmallPtrSet<BasicBlock*, 8> blocks;
  204. blocks.insert(L->block_begin(), L->block_end());
  205. for (BasicBlock *BB : blocks)
  206. loopInfo.removeBlock(BB);
  207. // The last step is to inform the loop pass manager that we've
  208. // eliminated this loop.
  209. LPM.deleteLoopFromQueue(L);
  210. Changed = true;
  211. ++NumDeleted;
  212. return Changed;
  213. }