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