1 //===- DeadStoreElimination.cpp - Fast Dead Store 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 a trivial dead store elimination that only considers 11 // basic-block local redundant stores. 12 // 13 // FIXME: This should eventually be extended to be a post-dominator tree 14 // traversal. Doing so would be pretty trivial. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #define DEBUG_TYPE "dse" 19 #include "llvm/Transforms/Scalar.h" 20 #include "llvm/Constants.h" 21 #include "llvm/Function.h" 22 #include "llvm/Instructions.h" 23 #include "llvm/IntrinsicInst.h" 24 #include "llvm/Pass.h" 25 #include "llvm/ADT/SmallPtrSet.h" 26 #include "llvm/ADT/Statistic.h" 27 #include "llvm/Analysis/AliasAnalysis.h" 28 #include "llvm/Analysis/Dominators.h" 29 #include "llvm/Analysis/MemoryBuiltins.h" 30 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 31 #include "llvm/Target/TargetData.h" 32 #include "llvm/Transforms/Utils/Local.h" 33 using namespace llvm; 34 35 STATISTIC(NumFastStores, "Number of stores deleted"); 36 STATISTIC(NumFastOther , "Number of other instrs removed"); 37 38 namespace { 39 struct DSE : public FunctionPass { 40 TargetData *TD; 41 42 static char ID; // Pass identification, replacement for typeid 43 DSE() : FunctionPass(&ID) {} 44 45 virtual bool runOnFunction(Function &F) { 46 bool Changed = false; 47 48 DominatorTree &DT = getAnalysis<DominatorTree>(); 49 50 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) 51 // Only check non-dead blocks. Dead blocks may have strange pointer 52 // cycles that will confuse alias analysis. 53 if (DT.isReachableFromEntry(I)) 54 Changed |= runOnBasicBlock(*I); 55 return Changed; 56 } 57 58 bool runOnBasicBlock(BasicBlock &BB); 59 bool handleFreeWithNonTrivialDependency(const CallInst *F, 60 MemDepResult Dep); 61 bool handleEndBlock(BasicBlock &BB); 62 bool RemoveUndeadPointers(Value *Ptr, uint64_t killPointerSize, 63 BasicBlock::iterator &BBI, 64 SmallPtrSet<Value*, 64> &deadPointers); 65 void DeleteDeadInstruction(Instruction *I, 66 SmallPtrSet<Value*, 64> *deadPointers = 0); 67 68 69 // getAnalysisUsage - We require post dominance frontiers (aka Control 70 // Dependence Graph) 71 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 72 AU.setPreservesCFG(); 73 AU.addRequired<DominatorTree>(); 74 AU.addRequired<AliasAnalysis>(); 75 AU.addRequired<MemoryDependenceAnalysis>(); 76 AU.addPreserved<DominatorTree>(); 77 AU.addPreserved<MemoryDependenceAnalysis>(); 78 } 79 80 unsigned getPointerSize(Value *V) const; 81 }; 82 } 83 84 char DSE::ID = 0; 85 static RegisterPass<DSE> X("dse", "Dead Store Elimination"); 86 87 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); } 88 89 /// doesClobberMemory - Does this instruction clobber (write without reading) 90 /// some memory? 91 static bool doesClobberMemory(Instruction *I) { 92 if (isa<StoreInst>(I)) 93 return true; 94 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 95 switch (II->getIntrinsicID()) { 96 default: 97 return false; 98 case Intrinsic::memset: 99 case Intrinsic::memmove: 100 case Intrinsic::memcpy: 101 case Intrinsic::init_trampoline: 102 case Intrinsic::lifetime_end: 103 return true; 104 } 105 } 106 return false; 107 } 108 109 /// isElidable - If the value of this instruction and the memory it writes to is 110 /// unused, may we delete this instrtction? 111 static bool isElidable(Instruction *I) { 112 assert(doesClobberMemory(I)); 113 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 114 return II->getIntrinsicID() != Intrinsic::lifetime_end; 115 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 116 return !SI->isVolatile(); 117 return true; 118 } 119 120 /// getPointerOperand - Return the pointer that is being clobbered. 121 static Value *getPointerOperand(Instruction *I) { 122 assert(doesClobberMemory(I)); 123 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 124 return SI->getPointerOperand(); 125 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) 126 return MI->getArgOperand(0); 127 128 IntrinsicInst *II = cast<IntrinsicInst>(I); 129 switch (II->getIntrinsicID()) { 130 default: assert(false && "Unexpected intrinsic!"); 131 case Intrinsic::init_trampoline: 132 return II->getArgOperand(0); 133 case Intrinsic::lifetime_end: 134 return II->getArgOperand(1); 135 } 136 } 137 138 /// getStoreSize - Return the length in bytes of the write by the clobbering 139 /// instruction. If variable or unknown, returns -1. 140 static unsigned getStoreSize(Instruction *I, const TargetData *TD) { 141 assert(doesClobberMemory(I)); 142 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 143 if (!TD) return -1u; 144 return TD->getTypeStoreSize(SI->getOperand(0)->getType()); 145 } 146 147 Value *Len; 148 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) { 149 Len = MI->getLength(); 150 } else { 151 IntrinsicInst *II = cast<IntrinsicInst>(I); 152 switch (II->getIntrinsicID()) { 153 default: assert(false && "Unexpected intrinsic!"); 154 case Intrinsic::init_trampoline: 155 return -1u; 156 case Intrinsic::lifetime_end: 157 Len = II->getArgOperand(0); 158 break; 159 } 160 } 161 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len)) 162 if (!LenCI->isAllOnesValue()) 163 return LenCI->getZExtValue(); 164 return -1u; 165 } 166 167 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is 168 /// greater than or equal to the store in I2. This returns false if we don't 169 /// know. 170 /// 171 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2, 172 const TargetData *TD) { 173 const Type *I1Ty = getPointerOperand(I1)->getType(); 174 const Type *I2Ty = getPointerOperand(I2)->getType(); 175 176 // Exactly the same type, must have exactly the same size. 177 if (I1Ty == I2Ty) return true; 178 179 int I1Size = getStoreSize(I1, TD); 180 int I2Size = getStoreSize(I2, TD); 181 182 return I1Size != -1 && I2Size != -1 && I1Size >= I2Size; 183 } 184 185 bool DSE::runOnBasicBlock(BasicBlock &BB) { 186 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>(); 187 TD = getAnalysisIfAvailable<TargetData>(); 188 189 bool MadeChange = false; 190 191 // Do a top-down walk on the BB. 192 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) { 193 Instruction *Inst = BBI++; 194 195 // If we find a store or a free, get its memory dependence. 196 if (!doesClobberMemory(Inst) && !isFreeCall(Inst)) 197 continue; 198 199 MemDepResult InstDep = MD.getDependency(Inst); 200 201 // Ignore non-local stores. 202 // FIXME: cross-block DSE would be fun. :) 203 if (InstDep.isNonLocal()) continue; 204 205 // Handle frees whose dependencies are non-trivial. 206 if (const CallInst *F = isFreeCall(Inst)) { 207 MadeChange |= handleFreeWithNonTrivialDependency(F, InstDep); 208 continue; 209 } 210 211 // If not a definite must-alias dependency, ignore it. 212 if (!InstDep.isDef()) 213 continue; 214 215 // If this is a store-store dependence, then the previous store is dead so 216 // long as this store is at least as big as it. 217 if (doesClobberMemory(InstDep.getInst())) { 218 Instruction *DepStore = InstDep.getInst(); 219 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) && 220 isElidable(DepStore)) { 221 // Delete the store and now-dead instructions that feed it. 222 DeleteDeadInstruction(DepStore); 223 ++NumFastStores; 224 MadeChange = true; 225 226 // DeleteDeadInstruction can delete the current instruction in loop 227 // cases, reset BBI. 228 BBI = Inst; 229 if (BBI != BB.begin()) 230 --BBI; 231 continue; 232 } 233 } 234 235 if (!isElidable(Inst)) 236 continue; 237 238 // If we're storing the same value back to a pointer that we just 239 // loaded from, then the store can be removed. 240 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 241 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) { 242 if (SI->getPointerOperand() == DepLoad->getPointerOperand() && 243 SI->getOperand(0) == DepLoad) { 244 // DeleteDeadInstruction can delete the current instruction. Save BBI 245 // in case we need it. 246 WeakVH NextInst(BBI); 247 248 DeleteDeadInstruction(SI); 249 250 if (NextInst == 0) // Next instruction deleted. 251 BBI = BB.begin(); 252 else if (BBI != BB.begin()) // Revisit this instruction if possible. 253 --BBI; 254 ++NumFastStores; 255 MadeChange = true; 256 continue; 257 } 258 } 259 } 260 261 // If this is a lifetime end marker, we can throw away the store. 262 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) { 263 if (II->getIntrinsicID() == Intrinsic::lifetime_end) { 264 // Delete the store and now-dead instructions that feed it. 265 // DeleteDeadInstruction can delete the current instruction. Save BBI 266 // in case we need it. 267 WeakVH NextInst(BBI); 268 269 DeleteDeadInstruction(Inst); 270 271 if (NextInst == 0) // Next instruction deleted. 272 BBI = BB.begin(); 273 else if (BBI != BB.begin()) // Revisit this instruction if possible. 274 --BBI; 275 ++NumFastStores; 276 MadeChange = true; 277 continue; 278 } 279 } 280 } 281 282 // If this block ends in a return, unwind, or unreachable, all allocas are 283 // dead at its end, which means stores to them are also dead. 284 if (BB.getTerminator()->getNumSuccessors() == 0) 285 MadeChange |= handleEndBlock(BB); 286 287 return MadeChange; 288 } 289 290 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose 291 /// dependency is a store to a field of that structure. 292 bool DSE::handleFreeWithNonTrivialDependency(const CallInst *F, 293 MemDepResult Dep) { 294 AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 295 296 Instruction *Dependency = Dep.getInst(); 297 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency)) 298 return false; 299 300 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject(); 301 302 // Check for aliasing. 303 if (AA.alias(F->getArgOperand(0), 1, DepPointer, 1) != 304 AliasAnalysis::MustAlias) 305 return false; 306 307 // DCE instructions only used to calculate that store 308 DeleteDeadInstruction(Dependency); 309 ++NumFastStores; 310 return true; 311 } 312 313 /// handleEndBlock - Remove dead stores to stack-allocated locations in the 314 /// function end block. Ex: 315 /// %A = alloca i32 316 /// ... 317 /// store i32 1, i32* %A 318 /// ret void 319 bool DSE::handleEndBlock(BasicBlock &BB) { 320 AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 321 322 bool MadeChange = false; 323 324 // Pointers alloca'd in this function are dead in the end block 325 SmallPtrSet<Value*, 64> deadPointers; 326 327 // Find all of the alloca'd pointers in the entry block. 328 BasicBlock *Entry = BB.getParent()->begin(); 329 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) 330 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) 331 deadPointers.insert(AI); 332 333 // Treat byval arguments the same, stores to them are dead at the end of the 334 // function. 335 for (Function::arg_iterator AI = BB.getParent()->arg_begin(), 336 AE = BB.getParent()->arg_end(); AI != AE; ++AI) 337 if (AI->hasByValAttr()) 338 deadPointers.insert(AI); 339 340 // Scan the basic block backwards 341 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){ 342 --BBI; 343 344 // If we find a store whose pointer is dead. 345 if (doesClobberMemory(BBI)) { 346 if (isElidable(BBI)) { 347 // See through pointer-to-pointer bitcasts 348 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject(); 349 350 // Alloca'd pointers or byval arguments (which are functionally like 351 // alloca's) are valid candidates for removal. 352 if (deadPointers.count(pointerOperand)) { 353 // DCE instructions only used to calculate that store. 354 Instruction *Dead = BBI; 355 ++BBI; 356 DeleteDeadInstruction(Dead, &deadPointers); 357 ++NumFastStores; 358 MadeChange = true; 359 continue; 360 } 361 } 362 363 // Because a memcpy or memmove is also a load, we can't skip it if we 364 // didn't remove it. 365 if (!isa<MemTransferInst>(BBI)) 366 continue; 367 } 368 369 Value *killPointer = 0; 370 uint64_t killPointerSize = ~0UL; 371 372 // If we encounter a use of the pointer, it is no longer considered dead 373 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) { 374 // However, if this load is unused and not volatile, we can go ahead and 375 // remove it, and not have to worry about it making our pointer undead! 376 if (L->use_empty() && !L->isVolatile()) { 377 ++BBI; 378 DeleteDeadInstruction(L, &deadPointers); 379 ++NumFastOther; 380 MadeChange = true; 381 continue; 382 } 383 384 killPointer = L->getPointerOperand(); 385 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) { 386 killPointer = V->getOperand(0); 387 } else if (isa<MemTransferInst>(BBI) && 388 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) { 389 killPointer = cast<MemTransferInst>(BBI)->getSource(); 390 killPointerSize = cast<ConstantInt>( 391 cast<MemTransferInst>(BBI)->getLength())->getZExtValue(); 392 } else if (AllocaInst *A = dyn_cast<AllocaInst>(BBI)) { 393 deadPointers.erase(A); 394 395 // Dead alloca's can be DCE'd when we reach them 396 if (A->use_empty()) { 397 ++BBI; 398 DeleteDeadInstruction(A, &deadPointers); 399 ++NumFastOther; 400 MadeChange = true; 401 } 402 403 continue; 404 } else if (CallSite::get(BBI).getInstruction() != 0) { 405 // If this call does not access memory, it can't 406 // be undeadifying any of our pointers. 407 CallSite CS = CallSite::get(BBI); 408 if (AA.doesNotAccessMemory(CS)) 409 continue; 410 411 unsigned modRef = 0; 412 unsigned other = 0; 413 414 // Remove any pointers made undead by the call from the dead set 415 std::vector<Value*> dead; 416 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(), 417 E = deadPointers.end(); I != E; ++I) { 418 // HACK: if we detect that our AA is imprecise, it's not 419 // worth it to scan the rest of the deadPointers set. Just 420 // assume that the AA will return ModRef for everything, and 421 // go ahead and bail. 422 if (modRef >= 16 && other == 0) { 423 deadPointers.clear(); 424 return MadeChange; 425 } 426 427 // See if the call site touches it 428 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, 429 getPointerSize(*I)); 430 431 if (A == AliasAnalysis::ModRef) 432 ++modRef; 433 else 434 ++other; 435 436 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref) 437 dead.push_back(*I); 438 } 439 440 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end(); 441 I != E; ++I) 442 deadPointers.erase(*I); 443 444 continue; 445 } else if (isInstructionTriviallyDead(BBI)) { 446 // For any non-memory-affecting non-terminators, DCE them as we reach them 447 Instruction *Inst = BBI; 448 ++BBI; 449 DeleteDeadInstruction(Inst, &deadPointers); 450 ++NumFastOther; 451 MadeChange = true; 452 continue; 453 } 454 455 if (!killPointer) 456 continue; 457 458 killPointer = killPointer->getUnderlyingObject(); 459 460 // Deal with undead pointers 461 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI, 462 deadPointers); 463 } 464 465 return MadeChange; 466 } 467 468 /// RemoveUndeadPointers - check for uses of a pointer that make it 469 /// undead when scanning for dead stores to alloca's. 470 bool DSE::RemoveUndeadPointers(Value *killPointer, uint64_t killPointerSize, 471 BasicBlock::iterator &BBI, 472 SmallPtrSet<Value*, 64> &deadPointers) { 473 AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 474 475 // If the kill pointer can be easily reduced to an alloca, 476 // don't bother doing extraneous AA queries. 477 if (deadPointers.count(killPointer)) { 478 deadPointers.erase(killPointer); 479 return false; 480 } 481 482 // A global can't be in the dead pointer set. 483 if (isa<GlobalValue>(killPointer)) 484 return false; 485 486 bool MadeChange = false; 487 488 SmallVector<Value*, 16> undead; 489 490 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(), 491 E = deadPointers.end(); I != E; ++I) { 492 // See if this pointer could alias it 493 AliasAnalysis::AliasResult A = AA.alias(*I, getPointerSize(*I), 494 killPointer, killPointerSize); 495 496 // If it must-alias and a store, we can delete it 497 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) { 498 StoreInst *S = cast<StoreInst>(BBI); 499 500 // Remove it! 501 ++BBI; 502 DeleteDeadInstruction(S, &deadPointers); 503 ++NumFastStores; 504 MadeChange = true; 505 506 continue; 507 508 // Otherwise, it is undead 509 } else if (A != AliasAnalysis::NoAlias) 510 undead.push_back(*I); 511 } 512 513 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end(); 514 I != E; ++I) 515 deadPointers.erase(*I); 516 517 return MadeChange; 518 } 519 520 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through 521 /// and zero out all the operands of this instruction. If any of them become 522 /// dead, delete them and the computation tree that feeds them. 523 /// 524 /// If ValueSet is non-null, remove any deleted instructions from it as well. 525 /// 526 void DSE::DeleteDeadInstruction(Instruction *I, 527 SmallPtrSet<Value*, 64> *ValueSet) { 528 SmallVector<Instruction*, 32> NowDeadInsts; 529 530 NowDeadInsts.push_back(I); 531 --NumFastOther; 532 533 // Before we touch this instruction, remove it from memdep! 534 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>(); 535 do { 536 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 537 538 ++NumFastOther; 539 540 // This instruction is dead, zap it, in stages. Start by removing it from 541 // MemDep, which needs to know the operands and needs it to be in the 542 // function. 543 MDA.removeInstruction(DeadInst); 544 545 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) { 546 Value *Op = DeadInst->getOperand(op); 547 DeadInst->setOperand(op, 0); 548 549 // If this operand just became dead, add it to the NowDeadInsts list. 550 if (!Op->use_empty()) continue; 551 552 if (Instruction *OpI = dyn_cast<Instruction>(Op)) 553 if (isInstructionTriviallyDead(OpI)) 554 NowDeadInsts.push_back(OpI); 555 } 556 557 DeadInst->eraseFromParent(); 558 559 if (ValueSet) ValueSet->erase(DeadInst); 560 } while (!NowDeadInsts.empty()); 561 } 562 563 unsigned DSE::getPointerSize(Value *V) const { 564 if (TD) { 565 if (AllocaInst *A = dyn_cast<AllocaInst>(V)) { 566 // Get size information for the alloca 567 if (ConstantInt *C = dyn_cast<ConstantInt>(A->getArraySize())) 568 return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType()); 569 } else { 570 assert(isa<Argument>(V) && "Expected AllocaInst or Argument!"); 571 const PointerType *PT = cast<PointerType>(V->getType()); 572 return TD->getTypeAllocSize(PT->getElementType()); 573 } 574 } 575 return ~0U; 576 } 577