1 //===- ADCE.cpp - Code to perform dead code elimination -------------------===// 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 Aggressive Dead Code Elimination pass. This pass 11 // optimistically assumes that all instructions are dead until proven otherwise, 12 // allowing it to eliminate dead computations that other DCE passes do not 13 // catch, particularly involving loop computations. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Transforms/Scalar/ADCE.h" 18 19 #include "llvm/ADT/DepthFirstIterator.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/GlobalsModRef.h" 24 #include "llvm/IR/BasicBlock.h" 25 #include "llvm/IR/CFG.h" 26 #include "llvm/IR/DebugInfoMetadata.h" 27 #include "llvm/IR/InstIterator.h" 28 #include "llvm/IR/Instructions.h" 29 #include "llvm/IR/IntrinsicInst.h" 30 #include "llvm/Pass.h" 31 #include "llvm/ProfileData/InstrProf.h" 32 #include "llvm/Transforms/Scalar.h" 33 using namespace llvm; 34 35 #define DEBUG_TYPE "adce" 36 37 STATISTIC(NumRemoved, "Number of instructions removed"); 38 39 // This is a tempoary option until we change the interface 40 // to this pass based on optimization level. 41 static cl::opt<bool> RemoveControlFlowFlag("adce-remove-control-flow", 42 cl::init(false), cl::Hidden); 43 44 namespace { 45 /// Information about Instructions 46 struct InstInfoType { 47 /// True if the associated instruction is live. 48 bool Live = false; 49 /// Quick access to information for block containing associated Instruction. 50 struct BlockInfoType *Block = nullptr; 51 }; 52 53 /// Information about basic blocks relevant to dead code elimination. 54 struct BlockInfoType { 55 /// True when this block contains a live instructions. 56 bool Live = false; 57 /// True when this block ends in an unconditional branch. 58 bool UnconditionalBranch = false; 59 60 /// Quick access to the LiveInfo for the terminator, 61 /// holds the value &InstInfo[Terminator] 62 InstInfoType *TerminatorLiveInfo = nullptr; 63 64 bool terminatorIsLive() const { return TerminatorLiveInfo->Live; } 65 66 /// Corresponding BasicBlock. 67 BasicBlock *BB = nullptr; 68 69 /// Cache of BB->getTerminator() 70 TerminatorInst *Terminator = nullptr; 71 }; 72 73 class AggressiveDeadCodeElimination { 74 Function &F; 75 76 /// Mapping of blocks to associated information, an element in BlockInfoVec. 77 DenseMap<BasicBlock *, BlockInfoType> BlockInfo; 78 bool isLive(BasicBlock *BB) { return BlockInfo[BB].Live; } 79 80 /// Mapping of instructions to associated information. 81 DenseMap<Instruction *, InstInfoType> InstInfo; 82 bool isLive(Instruction *I) { return InstInfo[I].Live; } 83 84 /// Instructions known to be live where we need to mark 85 /// reaching definitions as live. 86 SmallVector<Instruction *, 128> Worklist; 87 /// Debug info scopes around a live instruction. 88 SmallPtrSet<const Metadata *, 32> AliveScopes; 89 90 /// Set of blocks with not known to have live terminators. 91 SmallPtrSet<BasicBlock *, 16> BlocksWithDeadTerminators; 92 93 /// The set of blocks which we have determined are live in the 94 /// most recent iteration of propagating liveness. 95 SmallPtrSet<BasicBlock *, 16> NewLiveBlocks; 96 97 /// Set up auxiliary data structures for Instructions and BasicBlocks and 98 /// initialize the Worklist to the set of must-be-live Instruscions. 99 void initialize(); 100 /// Return true for operations which are always treated as live. 101 bool isAlwaysLive(Instruction &I); 102 /// Return true for instrumentation instructions for value profiling. 103 bool isInstrumentsConstant(Instruction &I); 104 105 /// Propagate liveness to reaching definitions. 106 void markLiveInstructions(); 107 /// Mark an instruction as live. 108 void markLive(Instruction *I); 109 110 /// Record the Debug Scopes which surround live debug information. 111 void collectLiveScopes(const DILocalScope &LS); 112 void collectLiveScopes(const DILocation &DL); 113 114 /// Analyze dead branches to find those whose branches are the sources 115 /// of control dependences impacting a live block. Those branches are 116 /// marked live. 117 void markLiveBranchesFromControlDependences(); 118 119 /// Remove instructions not marked live, return if any any instruction 120 /// was removed. 121 bool removeDeadInstructions(); 122 123 public: 124 AggressiveDeadCodeElimination(Function &F) : F(F) {} 125 bool performDeadCodeElimination(); 126 }; 127 } 128 129 bool AggressiveDeadCodeElimination::performDeadCodeElimination() { 130 initialize(); 131 markLiveInstructions(); 132 return removeDeadInstructions(); 133 } 134 135 static bool isUnconditionalBranch(TerminatorInst *Term) { 136 auto BR = dyn_cast<BranchInst>(Term); 137 return BR && BR->isUnconditional(); 138 } 139 140 void AggressiveDeadCodeElimination::initialize() { 141 142 auto NumBlocks = F.size(); 143 144 // We will have an entry in the map for each block so we grow the 145 // structure to twice that size to keep the load factor low in the hash table. 146 BlockInfo.reserve(NumBlocks); 147 size_t NumInsts = 0; 148 149 // Iterate over blocks and initialize BlockInfoVec entries, count 150 // instructions to size the InstInfo hash table. 151 for (auto &BB : F) { 152 NumInsts += BB.size(); 153 auto &Info = BlockInfo[&BB]; 154 Info.BB = &BB; 155 Info.Terminator = BB.getTerminator(); 156 Info.UnconditionalBranch = isUnconditionalBranch(Info.Terminator); 157 } 158 159 // Initialize instruction map and set pointers to block info. 160 InstInfo.reserve(NumInsts); 161 for (auto &BBInfo : BlockInfo) 162 for (Instruction &I : *BBInfo.second.BB) 163 InstInfo[&I].Block = &BBInfo.second; 164 165 // Since BlockInfoVec holds pointers into InstInfo and vice-versa, we may not 166 // add any more elements to either after this point. 167 for (auto &BBInfo : BlockInfo) 168 BBInfo.second.TerminatorLiveInfo = &InstInfo[BBInfo.second.Terminator]; 169 170 // Collect the set of "root" instructions that are known live. 171 for (Instruction &I : instructions(F)) 172 if (isAlwaysLive(I)) 173 markLive(&I); 174 175 if (!RemoveControlFlowFlag) 176 return; 177 178 // This is temporary: will update with post order traveral to 179 // find loop bottoms 180 SmallPtrSet<BasicBlock *, 16> Seen; 181 for (auto &BB : F) { 182 Seen.insert(&BB); 183 TerminatorInst *Term = BB.getTerminator(); 184 if (isLive(Term)) 185 continue; 186 187 for (auto Succ : successors(&BB)) 188 if (Seen.count(Succ)) { 189 // back edge.... 190 markLive(Term); 191 break; 192 } 193 } 194 // end temporary handling of loops 195 196 // Treat the entry block as always live 197 auto *BB = &F.getEntryBlock(); 198 auto &EntryInfo = BlockInfo[BB]; 199 EntryInfo.Live = true; 200 if (EntryInfo.UnconditionalBranch) 201 markLive(EntryInfo.Terminator); 202 203 // Build initial collection of blocks with dead terminators 204 for (auto &BBInfo : BlockInfo) 205 if (!BBInfo.second.terminatorIsLive()) 206 BlocksWithDeadTerminators.insert(BBInfo.second.BB); 207 } 208 209 bool AggressiveDeadCodeElimination::isAlwaysLive(Instruction &I) { 210 // TODO -- use llvm::isInstructionTriviallyDead 211 if (I.isEHPad() || I.mayHaveSideEffects()) { 212 // Skip any value profile instrumentation calls if they are 213 // instrumenting constants. 214 if (isInstrumentsConstant(I)) 215 return false; 216 return true; 217 } 218 if (!isa<TerminatorInst>(I)) 219 return false; 220 if (RemoveControlFlowFlag && (isa<BranchInst>(I) || isa<SwitchInst>(I))) 221 return false; 222 return true; 223 } 224 225 // Check if this instruction is a runtime call for value profiling and 226 // if it's instrumenting a constant. 227 bool AggressiveDeadCodeElimination::isInstrumentsConstant(Instruction &I) { 228 // TODO -- move this test into llvm::isInstructionTriviallyDead 229 if (CallInst *CI = dyn_cast<CallInst>(&I)) 230 if (Function *Callee = CI->getCalledFunction()) 231 if (Callee->getName().equals(getInstrProfValueProfFuncName())) 232 if (isa<Constant>(CI->getArgOperand(0))) 233 return true; 234 return false; 235 } 236 237 void AggressiveDeadCodeElimination::markLiveInstructions() { 238 239 // Propagate liveness backwards to operands. 240 do { 241 // Worklist holds newly discovered live instructions 242 // where we need to mark the inputs as live. 243 while (!Worklist.empty()) { 244 Instruction *LiveInst = Worklist.pop_back_val(); 245 246 // Collect the live debug info scopes attached to this instruction. 247 if (const DILocation *DL = LiveInst->getDebugLoc()) 248 collectLiveScopes(*DL); 249 250 DEBUG(dbgs() << "work live: "; LiveInst->dump();); 251 for (Use &OI : LiveInst->operands()) 252 if (Instruction *Inst = dyn_cast<Instruction>(OI)) 253 markLive(Inst); 254 } 255 markLiveBranchesFromControlDependences(); 256 // TODO -- handle PhiNodes 257 } while (!Worklist.empty()); 258 259 // temporary until control dependences are implemented 260 assert(BlocksWithDeadTerminators.empty()); 261 } 262 263 void AggressiveDeadCodeElimination::markLive(Instruction *I) { 264 265 auto &Info = InstInfo[I]; 266 if (Info.Live) 267 return; 268 269 DEBUG(dbgs() << "mark live: "; I->dump()); 270 Info.Live = true; 271 Worklist.push_back(I); 272 273 // Mark the containing block live 274 auto &BBInfo = *Info.Block; 275 if (BBInfo.Terminator == I) 276 BlocksWithDeadTerminators.erase(BBInfo.BB); 277 if (BBInfo.Live) 278 return; 279 280 DEBUG(dbgs() << "mark block live: " << BBInfo.BB->getName() << '\n'); 281 BBInfo.Live = true; 282 NewLiveBlocks.insert(BBInfo.BB); 283 284 // Mark unconditional branches at the end of live 285 // blocks as live since there is no work to do for them later 286 if (BBInfo.UnconditionalBranch && I != BBInfo.Terminator) 287 markLive(BBInfo.Terminator); 288 } 289 290 void AggressiveDeadCodeElimination::collectLiveScopes(const DILocalScope &LS) { 291 if (!AliveScopes.insert(&LS).second) 292 return; 293 294 if (isa<DISubprogram>(LS)) 295 return; 296 297 // Tail-recurse through the scope chain. 298 collectLiveScopes(cast<DILocalScope>(*LS.getScope())); 299 } 300 301 void AggressiveDeadCodeElimination::collectLiveScopes(const DILocation &DL) { 302 // Even though DILocations are not scopes, shove them into AliveScopes so we 303 // don't revisit them. 304 if (!AliveScopes.insert(&DL).second) 305 return; 306 307 // Collect live scopes from the scope chain. 308 collectLiveScopes(*DL.getScope()); 309 310 // Tail-recurse through the inlined-at chain. 311 if (const DILocation *IA = DL.getInlinedAt()) 312 collectLiveScopes(*IA); 313 } 314 315 void AggressiveDeadCodeElimination::markLiveBranchesFromControlDependences() { 316 317 // This is a place holder, mark all read operations live 318 // The next patch will replace this with using iterated dominance 319 // frontier to compute branches that need to be live because they 320 // control live blocks with live operations 321 SmallVector<TerminatorInst *, 16> DeadTerminators; 322 for (auto *BB : BlocksWithDeadTerminators) 323 DeadTerminators.push_back(BB->getTerminator()); 324 for (auto I : DeadTerminators) 325 markLive(I); 326 NewLiveBlocks.clear(); 327 } 328 329 bool AggressiveDeadCodeElimination::removeDeadInstructions() { 330 331 // The inverse of the live set is the dead set. These are those instructions 332 // which have no side effects and do not influence the control flow or return 333 // value of the function, and may therefore be deleted safely. 334 // NOTE: We reuse the Worklist vector here for memory efficiency. 335 for (Instruction &I : instructions(F)) { 336 // Check if the instruction is alive. 337 if (isLive(&I)) 338 continue; 339 340 assert(!I.isTerminator() && "NYI: Removing Control Flow"); 341 342 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) { 343 // Check if the scope of this variable location is alive. 344 if (AliveScopes.count(DII->getDebugLoc()->getScope())) 345 continue; 346 347 // Fallthrough and drop the intrinsic. 348 DEBUG({ 349 // If intrinsic is pointing at a live SSA value, there may be an 350 // earlier optimization bug: if we know the location of the variable, 351 // why isn't the scope of the location alive? 352 if (Value *V = DII->getVariableLocation()) 353 if (Instruction *II = dyn_cast<Instruction>(V)) 354 if (isLive(II)) 355 dbgs() << "Dropping debug info for " << *DII << "\n"; 356 }); 357 } 358 359 // Prepare to delete. 360 Worklist.push_back(&I); 361 I.dropAllReferences(); 362 } 363 364 for (Instruction *&I : Worklist) { 365 ++NumRemoved; 366 I->eraseFromParent(); 367 } 368 369 return !Worklist.empty(); 370 } 371 372 PreservedAnalyses ADCEPass::run(Function &F, FunctionAnalysisManager &) { 373 if (!AggressiveDeadCodeElimination(F).performDeadCodeElimination()) 374 return PreservedAnalyses::all(); 375 376 // FIXME: This should also 'preserve the CFG'. 377 auto PA = PreservedAnalyses(); 378 PA.preserve<GlobalsAA>(); 379 return PA; 380 } 381 382 namespace { 383 struct ADCELegacyPass : public FunctionPass { 384 static char ID; // Pass identification, replacement for typeid 385 ADCELegacyPass() : FunctionPass(ID) { 386 initializeADCELegacyPassPass(*PassRegistry::getPassRegistry()); 387 } 388 389 bool runOnFunction(Function &F) override { 390 if (skipFunction(F)) 391 return false; 392 return AggressiveDeadCodeElimination(F).performDeadCodeElimination(); 393 } 394 395 void getAnalysisUsage(AnalysisUsage &AU) const override { 396 AU.setPreservesCFG(); 397 AU.addPreserved<GlobalsAAWrapperPass>(); 398 } 399 }; 400 } 401 402 char ADCELegacyPass::ID = 0; 403 INITIALIZE_PASS(ADCELegacyPass, "adce", "Aggressive Dead Code Elimination", 404 false, false) 405 406 FunctionPass *llvm::createAggressiveDCEPass() { return new ADCELegacyPass(); } 407