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