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