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/IR/PatternMatch.h" 24 #include "llvm/Transforms/Scalar.h" 25 #include "llvm/Transforms/Scalar/LoopPassManager.h" 26 #include "llvm/Transforms/Utils/LoopUtils.h" 27 using namespace llvm; 28 29 #define DEBUG_TYPE "loop-delete" 30 31 STATISTIC(NumDeleted, "Number of loops deleted"); 32 33 /// This function deletes dead loops. The caller of this function needs to 34 /// guarantee that the loop is infact dead. Here we handle two kinds of dead 35 /// loop. The first kind (\p isLoopDead) is where only invariant values from 36 /// within the loop are used outside of it. The second kind (\p 37 /// isLoopNeverExecuted) is where the loop is provably never executed. We can 38 /// always remove never executed loops since they will not cause any difference 39 /// to program behaviour. 40 /// 41 /// This also updates the relevant analysis information in \p DT, \p SE, and \p 42 /// LI. It also updates the loop PM if an updater struct is provided. 43 // TODO: This function will be used by loop-simplifyCFG as well. So, move this 44 // to LoopUtils.cpp 45 static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE, 46 LoopInfo &LI, LPMUpdater *Updater = nullptr); 47 /// Determines if a loop is dead. 48 /// 49 /// This assumes that we've already checked for unique exit and exiting blocks, 50 /// and that the code is in LCSSA form. 51 static bool isLoopDead(Loop *L, ScalarEvolution &SE, 52 SmallVectorImpl<BasicBlock *> &ExitingBlocks, 53 BasicBlock *ExitBlock, bool &Changed, 54 BasicBlock *Preheader) { 55 // Make sure that all PHI entries coming from the loop are loop invariant. 56 // Because the code is in LCSSA form, any values used outside of the loop 57 // must pass through a PHI in the exit block, meaning that this check is 58 // sufficient to guarantee that no loop-variant values are used outside 59 // of the loop. 60 BasicBlock::iterator BI = ExitBlock->begin(); 61 bool AllEntriesInvariant = true; 62 bool AllOutgoingValuesSame = true; 63 while (PHINode *P = dyn_cast<PHINode>(BI)) { 64 Value *incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); 65 66 // Make sure all exiting blocks produce the same incoming value for the exit 67 // block. If there are different incoming values for different exiting 68 // blocks, then it is impossible to statically determine which value should 69 // be used. 70 AllOutgoingValuesSame = 71 all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) { 72 return incoming == P->getIncomingValueForBlock(BB); 73 }); 74 75 if (!AllOutgoingValuesSame) 76 break; 77 78 if (Instruction *I = dyn_cast<Instruction>(incoming)) 79 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) { 80 AllEntriesInvariant = false; 81 break; 82 } 83 84 ++BI; 85 } 86 87 if (Changed) 88 SE.forgetLoopDispositions(L); 89 90 if (!AllEntriesInvariant || !AllOutgoingValuesSame) 91 return false; 92 93 // Make sure that no instructions in the block have potential side-effects. 94 // This includes instructions that could write to memory, and loads that are 95 // marked volatile. 96 for (auto &I : L->blocks()) 97 if (any_of(*I, [](Instruction &I) { return I.mayHaveSideEffects(); })) 98 return false; 99 return true; 100 } 101 102 /// This function returns true if there is no viable path from the 103 /// entry block to the header of \p L. Right now, it only does 104 /// a local search to save compile time. 105 static bool isLoopNeverExecuted(Loop *L) { 106 using namespace PatternMatch; 107 108 auto *Preheader = L->getLoopPreheader(); 109 // TODO: We can relax this constraint, since we just need a loop 110 // predecessor. 111 assert(Preheader && "Needs preheader!"); 112 113 if (Preheader == &Preheader->getParent()->getEntryBlock()) 114 return false; 115 // All predecessors of the preheader should have a constant conditional 116 // branch, with the loop's preheader as not-taken. 117 for (auto *Pred: predecessors(Preheader)) { 118 BasicBlock *Taken, *NotTaken; 119 ConstantInt *Cond; 120 if (!match(Pred->getTerminator(), 121 m_Br(m_ConstantInt(Cond), Taken, NotTaken))) 122 return false; 123 if (!Cond->getZExtValue()) 124 std::swap(Taken, NotTaken); 125 if (Taken == Preheader) 126 return false; 127 } 128 assert(!pred_empty(Preheader) && 129 "Preheader should have predecessors at this point!"); 130 // All the predecessors have the loop preheader as not-taken target. 131 return true; 132 } 133 134 /// Remove a loop if it is dead. 135 /// 136 /// A loop is considered dead if it does not impact the observable behavior of 137 /// the program other than finite running time. This never removes a loop that 138 /// might be infinite (unless it is never executed), as doing so could change 139 /// the halting/non-halting nature of a program. 140 /// 141 /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in 142 /// order to make various safety checks work. 143 /// 144 /// \returns true if any changes were made. This may mutate the loop even if it 145 /// is unable to delete it due to hoisting trivially loop invariant 146 /// instructions out of the loop. 147 static bool deleteLoopIfDead(Loop *L, DominatorTree &DT, ScalarEvolution &SE, 148 LoopInfo &LI, LPMUpdater *Updater = nullptr) { 149 assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); 150 151 // We can only remove the loop if there is a preheader that we can branch from 152 // after removing it. Also, if LoopSimplify form is not available, stay out 153 // of trouble. 154 BasicBlock *Preheader = L->getLoopPreheader(); 155 if (!Preheader || !L->hasDedicatedExits()) { 156 DEBUG(dbgs() 157 << "Deletion requires Loop with preheader and dedicated exits.\n"); 158 return false; 159 } 160 // We can't remove loops that contain subloops. If the subloops were dead, 161 // they would already have been removed in earlier executions of this pass. 162 if (L->begin() != L->end()) { 163 DEBUG(dbgs() << "Loop contains subloops.\n"); 164 return false; 165 } 166 167 168 BasicBlock *ExitBlock = L->getUniqueExitBlock(); 169 170 if (ExitBlock && isLoopNeverExecuted(L)) { 171 DEBUG(dbgs() << "Loop is proven to never execute, delete it!"); 172 // Set incoming value to undef for phi nodes in the exit block. 173 BasicBlock::iterator BI = ExitBlock->begin(); 174 while (PHINode *P = dyn_cast<PHINode>(BI)) { 175 for (unsigned i = 0; i < P->getNumIncomingValues(); i++) 176 P->setIncomingValue(i, UndefValue::get(P->getType())); 177 BI++; 178 } 179 deleteDeadLoop(L, DT, SE, LI, Updater); 180 ++NumDeleted; 181 return true; 182 } 183 184 // The remaining checks below are for a loop being dead because all statements 185 // in the loop are invariant. 186 SmallVector<BasicBlock *, 4> ExitingBlocks; 187 L->getExitingBlocks(ExitingBlocks); 188 189 // We require that the loop only have a single exit block. Otherwise, we'd 190 // be in the situation of needing to be able to solve statically which exit 191 // block will be branched to, or trying to preserve the branching logic in 192 // a loop invariant manner. 193 if (!ExitBlock) { 194 DEBUG(dbgs() << "Deletion requires single exit block\n"); 195 return false; 196 } 197 // Finally, we have to check that the loop really is dead. 198 bool Changed = false; 199 if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) { 200 DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n"); 201 return Changed; 202 } 203 204 // Don't remove loops for which we can't solve the trip count. 205 // They could be infinite, in which case we'd be changing program behavior. 206 const SCEV *S = SE.getMaxBackedgeTakenCount(L); 207 if (isa<SCEVCouldNotCompute>(S)) { 208 DEBUG(dbgs() << "Could not compute SCEV MaxBackedgeTakenCount.\n"); 209 return Changed; 210 } 211 212 DEBUG(dbgs() << "Loop is invariant, delete it!"); 213 deleteDeadLoop(L, DT, SE, LI, Updater); 214 ++NumDeleted; 215 216 return true; 217 } 218 219 static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE, 220 LoopInfo &LI, LPMUpdater *Updater) { 221 assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); 222 auto *Preheader = L->getLoopPreheader(); 223 assert(Preheader && "Preheader should exist!"); 224 225 // Now that we know the removal is safe, remove the loop by changing the 226 // branch from the preheader to go to the single exit block. 227 // 228 // Because we're deleting a large chunk of code at once, the sequence in which 229 // we remove things is very important to avoid invalidation issues. 230 231 // If we have an LPM updater, tell it about the loop being removed. 232 if (Updater) 233 Updater->markLoopAsDeleted(*L); 234 235 // Tell ScalarEvolution that the loop is deleted. Do this before 236 // deleting the loop so that ScalarEvolution can look at the loop 237 // to determine what it needs to clean up. 238 SE.forgetLoop(L); 239 240 auto *ExitBlock = L->getUniqueExitBlock(); 241 assert(ExitBlock && "Should have a unique exit block!"); 242 243 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!"); 244 245 // Connect the preheader directly to the exit block. 246 // Even when the loop is never executed, we cannot remove the edge from the 247 // source block to the exit block. Consider the case where the unexecuted loop 248 // branches back to an outer loop. If we deleted the loop and removed the edge 249 // coming to this inner loop, this will break the outer loop structure (by 250 // deleting the backedge of the outer loop). If the outer loop is indeed a 251 // non-loop, it will be deleted in a future iteration of loop deletion pass. 252 Preheader->getTerminator()->replaceUsesOfWith(L->getHeader(), ExitBlock); 253 254 // Rewrite phis in the exit block to get their inputs from the Preheader 255 // instead of the exiting block. 256 BasicBlock::iterator BI = ExitBlock->begin(); 257 while (PHINode *P = dyn_cast<PHINode>(BI)) { 258 // Set the zero'th element of Phi to be from the preheader and remove all 259 // other incoming values. Given the loop has dedicated exits, all other 260 // incoming values must be from the exiting blocks. 261 int PredIndex = 0; 262 P->setIncomingBlock(PredIndex, Preheader); 263 // Removes all incoming values from all other exiting blocks (including 264 // duplicate values from an exiting block). 265 // Nuke all entries except the zero'th entry which is the preheader entry. 266 // NOTE! We need to remove Incoming Values in the reverse order as done 267 // below, to keep the indices valid for deletion (removeIncomingValues 268 // updates getNumIncomingValues and shifts all values down into the operand 269 // being deleted). 270 for (unsigned i = 0, e = P->getNumIncomingValues() - 1; i != e; ++i) 271 P->removeIncomingValue(e-i, false); 272 273 assert((P->getNumIncomingValues() == 1 && 274 P->getIncomingBlock(PredIndex) == Preheader) && 275 "Should have exactly one value and that's from the preheader!"); 276 ++BI; 277 } 278 279 // Update the dominator tree and remove the instructions and blocks that will 280 // be deleted from the reference counting scheme. 281 SmallVector<DomTreeNode*, 8> ChildNodes; 282 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 283 LI != LE; ++LI) { 284 // Move all of the block's children to be children of the Preheader, which 285 // allows us to remove the domtree entry for the block. 286 ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end()); 287 for (DomTreeNode *ChildNode : ChildNodes) { 288 DT.changeImmediateDominator(ChildNode, DT[Preheader]); 289 } 290 291 ChildNodes.clear(); 292 DT.eraseNode(*LI); 293 294 // Remove the block from the reference counting scheme, so that we can 295 // delete it freely later. 296 (*LI)->dropAllReferences(); 297 } 298 299 // Erase the instructions and the blocks without having to worry 300 // about ordering because we already dropped the references. 301 // NOTE: This iteration is safe because erasing the block does not remove its 302 // entry from the loop's block list. We do that in the next section. 303 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 304 LI != LE; ++LI) 305 (*LI)->eraseFromParent(); 306 307 // Finally, the blocks from loopinfo. This has to happen late because 308 // otherwise our loop iterators won't work. 309 310 SmallPtrSet<BasicBlock *, 8> blocks; 311 blocks.insert(L->block_begin(), L->block_end()); 312 for (BasicBlock *BB : blocks) 313 LI.removeBlock(BB); 314 315 // The last step is to update LoopInfo now that we've eliminated this loop. 316 LI.markAsRemoved(L); 317 } 318 319 PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM, 320 LoopStandardAnalysisResults &AR, 321 LPMUpdater &Updater) { 322 323 DEBUG(dbgs() << "Analyzing Loop for deletion: "); 324 DEBUG(L.dump()); 325 if (!deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, &Updater)) 326 return PreservedAnalyses::all(); 327 328 return getLoopPassPreservedAnalyses(); 329 } 330 331 namespace { 332 class LoopDeletionLegacyPass : public LoopPass { 333 public: 334 static char ID; // Pass ID, replacement for typeid 335 LoopDeletionLegacyPass() : LoopPass(ID) { 336 initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry()); 337 } 338 339 // Possibly eliminate loop L if it is dead. 340 bool runOnLoop(Loop *L, LPPassManager &) override; 341 342 void getAnalysisUsage(AnalysisUsage &AU) const override { 343 getLoopAnalysisUsage(AU); 344 } 345 }; 346 } 347 348 char LoopDeletionLegacyPass::ID = 0; 349 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion", 350 "Delete dead loops", false, false) 351 INITIALIZE_PASS_DEPENDENCY(LoopPass) 352 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion", 353 "Delete dead loops", false, false) 354 355 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); } 356 357 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &) { 358 if (skipLoop(L)) 359 return false; 360 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 361 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 362 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 363 364 DEBUG(dbgs() << "Analyzing Loop for deletion: "); 365 DEBUG(L->dump()); 366 return deleteLoopIfDead(L, DT, SE, LI); 367 } 368