1 //===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Dead Loop Deletion Pass. This pass is responsible 10 // for eliminating loops with non-infinite computable trip counts that have no 11 // side effects or volatile instructions, and do not contribute to the 12 // computation of the function's return value. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/Transforms/Scalar/LoopDeletion.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/Analysis/GlobalsModRef.h" 20 #include "llvm/Analysis/LoopPass.h" 21 #include "llvm/Analysis/MemorySSA.h" 22 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 23 #include "llvm/IR/Dominators.h" 24 #include "llvm/IR/PatternMatch.h" 25 #include "llvm/InitializePasses.h" 26 #include "llvm/Transforms/Scalar.h" 27 #include "llvm/Transforms/Scalar/LoopPassManager.h" 28 #include "llvm/Transforms/Utils/LoopUtils.h" 29 using namespace llvm; 30 31 #define DEBUG_TYPE "loop-delete" 32 33 STATISTIC(NumDeleted, "Number of loops deleted"); 34 35 enum class LoopDeletionResult { 36 Unmodified, 37 Modified, 38 Deleted, 39 }; 40 41 /// Determines if a loop is dead. 42 /// 43 /// This assumes that we've already checked for unique exit and exiting blocks, 44 /// and that the code is in LCSSA form. 45 static bool isLoopDead(Loop *L, ScalarEvolution &SE, 46 SmallVectorImpl<BasicBlock *> &ExitingBlocks, 47 BasicBlock *ExitBlock, bool &Changed, 48 BasicBlock *Preheader) { 49 // Make sure that all PHI entries coming from the loop are loop invariant. 50 // Because the code is in LCSSA form, any values used outside of the loop 51 // must pass through a PHI in the exit block, meaning that this check is 52 // sufficient to guarantee that no loop-variant values are used outside 53 // of the loop. 54 bool AllEntriesInvariant = true; 55 bool AllOutgoingValuesSame = true; 56 for (PHINode &P : ExitBlock->phis()) { 57 Value *incoming = P.getIncomingValueForBlock(ExitingBlocks[0]); 58 59 // Make sure all exiting blocks produce the same incoming value for the exit 60 // block. If there are different incoming values for different exiting 61 // blocks, then it is impossible to statically determine which value should 62 // be used. 63 AllOutgoingValuesSame = 64 all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) { 65 return incoming == P.getIncomingValueForBlock(BB); 66 }); 67 68 if (!AllOutgoingValuesSame) 69 break; 70 71 if (Instruction *I = dyn_cast<Instruction>(incoming)) 72 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) { 73 AllEntriesInvariant = false; 74 break; 75 } 76 } 77 78 if (Changed) 79 SE.forgetLoopDispositions(L); 80 81 if (!AllEntriesInvariant || !AllOutgoingValuesSame) 82 return false; 83 84 // Make sure that no instructions in the block have potential side-effects. 85 // This includes instructions that could write to memory, and loads that are 86 // marked volatile. 87 for (auto &I : L->blocks()) 88 if (any_of(*I, [](Instruction &I) { 89 return I.mayHaveSideEffects() && !I.isDroppable(); 90 })) 91 return false; 92 return true; 93 } 94 95 /// This function returns true if there is no viable path from the 96 /// entry block to the header of \p L. Right now, it only does 97 /// a local search to save compile time. 98 static bool isLoopNeverExecuted(Loop *L) { 99 using namespace PatternMatch; 100 101 auto *Preheader = L->getLoopPreheader(); 102 // TODO: We can relax this constraint, since we just need a loop 103 // predecessor. 104 assert(Preheader && "Needs preheader!"); 105 106 if (Preheader == &Preheader->getParent()->getEntryBlock()) 107 return false; 108 // All predecessors of the preheader should have a constant conditional 109 // branch, with the loop's preheader as not-taken. 110 for (auto *Pred: predecessors(Preheader)) { 111 BasicBlock *Taken, *NotTaken; 112 ConstantInt *Cond; 113 if (!match(Pred->getTerminator(), 114 m_Br(m_ConstantInt(Cond), Taken, NotTaken))) 115 return false; 116 if (!Cond->getZExtValue()) 117 std::swap(Taken, NotTaken); 118 if (Taken == Preheader) 119 return false; 120 } 121 assert(!pred_empty(Preheader) && 122 "Preheader should have predecessors at this point!"); 123 // All the predecessors have the loop preheader as not-taken target. 124 return true; 125 } 126 127 /// Remove a loop if it is dead. 128 /// 129 /// A loop is considered dead if it does not impact the observable behavior of 130 /// the program other than finite running time. This never removes a loop that 131 /// might be infinite (unless it is never executed), as doing so could change 132 /// the halting/non-halting nature of a program. 133 /// 134 /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in 135 /// order to make various safety checks work. 136 /// 137 /// \returns true if any changes were made. This may mutate the loop even if it 138 /// is unable to delete it due to hoisting trivially loop invariant 139 /// instructions out of the loop. 140 static LoopDeletionResult deleteLoopIfDead(Loop *L, DominatorTree &DT, 141 ScalarEvolution &SE, LoopInfo &LI, 142 MemorySSA *MSSA, 143 OptimizationRemarkEmitter &ORE) { 144 assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); 145 146 // We can only remove the loop if there is a preheader that we can branch from 147 // after removing it. Also, if LoopSimplify form is not available, stay out 148 // of trouble. 149 BasicBlock *Preheader = L->getLoopPreheader(); 150 if (!Preheader || !L->hasDedicatedExits()) { 151 LLVM_DEBUG( 152 dbgs() 153 << "Deletion requires Loop with preheader and dedicated exits.\n"); 154 return LoopDeletionResult::Unmodified; 155 } 156 // We can't remove loops that contain subloops. If the subloops were dead, 157 // they would already have been removed in earlier executions of this pass. 158 if (L->begin() != L->end()) { 159 LLVM_DEBUG(dbgs() << "Loop contains subloops.\n"); 160 return LoopDeletionResult::Unmodified; 161 } 162 163 164 BasicBlock *ExitBlock = L->getUniqueExitBlock(); 165 166 if (ExitBlock && isLoopNeverExecuted(L)) { 167 LLVM_DEBUG(dbgs() << "Loop is proven to never execute, delete it!"); 168 // Set incoming value to undef for phi nodes in the exit block. 169 for (PHINode &P : ExitBlock->phis()) { 170 std::fill(P.incoming_values().begin(), P.incoming_values().end(), 171 UndefValue::get(P.getType())); 172 } 173 ORE.emit([&]() { 174 return OptimizationRemark(DEBUG_TYPE, "NeverExecutes", L->getStartLoc(), 175 L->getHeader()) 176 << "Loop deleted because it never executes"; 177 }); 178 deleteDeadLoop(L, &DT, &SE, &LI, MSSA); 179 ++NumDeleted; 180 return LoopDeletionResult::Deleted; 181 } 182 183 // The remaining checks below are for a loop being dead because all statements 184 // in the loop are invariant. 185 SmallVector<BasicBlock *, 4> ExitingBlocks; 186 L->getExitingBlocks(ExitingBlocks); 187 188 // We require that the loop only have a single exit block. Otherwise, we'd 189 // be in the situation of needing to be able to solve statically which exit 190 // block will be branched to, or trying to preserve the branching logic in 191 // a loop invariant manner. 192 if (!ExitBlock) { 193 LLVM_DEBUG(dbgs() << "Deletion requires single exit block\n"); 194 return LoopDeletionResult::Unmodified; 195 } 196 // Finally, we have to check that the loop really is dead. 197 bool Changed = false; 198 if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) { 199 LLVM_DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n"); 200 return Changed ? LoopDeletionResult::Modified 201 : LoopDeletionResult::Unmodified; 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.getConstantMaxBackedgeTakenCount(L); 207 if (isa<SCEVCouldNotCompute>(S)) { 208 LLVM_DEBUG(dbgs() << "Could not compute SCEV MaxBackedgeTakenCount.\n"); 209 return Changed ? LoopDeletionResult::Modified 210 : LoopDeletionResult::Unmodified; 211 } 212 213 LLVM_DEBUG(dbgs() << "Loop is invariant, delete it!"); 214 ORE.emit([&]() { 215 return OptimizationRemark(DEBUG_TYPE, "Invariant", L->getStartLoc(), 216 L->getHeader()) 217 << "Loop deleted because it is invariant"; 218 }); 219 deleteDeadLoop(L, &DT, &SE, &LI, MSSA); 220 ++NumDeleted; 221 222 return LoopDeletionResult::Deleted; 223 } 224 225 PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM, 226 LoopStandardAnalysisResults &AR, 227 LPMUpdater &Updater) { 228 229 LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: "); 230 LLVM_DEBUG(L.dump()); 231 std::string LoopName = std::string(L.getName()); 232 // For the new PM, we can't use OptimizationRemarkEmitter as an analysis 233 // pass. Function analyses need to be preserved across loop transformations 234 // but ORE cannot be preserved (see comment before the pass definition). 235 OptimizationRemarkEmitter ORE(L.getHeader()->getParent()); 236 auto Result = deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, AR.MSSA, ORE); 237 if (Result == LoopDeletionResult::Unmodified) 238 return PreservedAnalyses::all(); 239 240 if (Result == LoopDeletionResult::Deleted) 241 Updater.markLoopAsDeleted(L, LoopName); 242 243 auto PA = getLoopPassPreservedAnalyses(); 244 if (AR.MSSA) 245 PA.preserve<MemorySSAAnalysis>(); 246 return PA; 247 } 248 249 namespace { 250 class LoopDeletionLegacyPass : public LoopPass { 251 public: 252 static char ID; // Pass ID, replacement for typeid 253 LoopDeletionLegacyPass() : LoopPass(ID) { 254 initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry()); 255 } 256 257 // Possibly eliminate loop L if it is dead. 258 bool runOnLoop(Loop *L, LPPassManager &) override; 259 260 void getAnalysisUsage(AnalysisUsage &AU) const override { 261 AU.addPreserved<MemorySSAWrapperPass>(); 262 getLoopAnalysisUsage(AU); 263 } 264 }; 265 } 266 267 char LoopDeletionLegacyPass::ID = 0; 268 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion", 269 "Delete dead loops", false, false) 270 INITIALIZE_PASS_DEPENDENCY(LoopPass) 271 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion", 272 "Delete dead loops", false, false) 273 274 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); } 275 276 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) { 277 if (skipLoop(L)) 278 return false; 279 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 280 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 281 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 282 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>(); 283 MemorySSA *MSSA = nullptr; 284 if (MSSAAnalysis) 285 MSSA = &MSSAAnalysis->getMSSA(); 286 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis 287 // pass. Function analyses need to be preserved across loop transformations 288 // but ORE cannot be preserved (see comment before the pass definition). 289 OptimizationRemarkEmitter ORE(L->getHeader()->getParent()); 290 291 LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: "); 292 LLVM_DEBUG(L->dump()); 293 294 LoopDeletionResult Result = deleteLoopIfDead(L, DT, SE, LI, MSSA, ORE); 295 296 if (Result == LoopDeletionResult::Deleted) 297 LPM.markLoopAsDeleted(*L); 298 299 return Result != LoopDeletionResult::Unmodified; 300 } 301