1 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===// 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 a trivial dead store elimination that only considers 10 // basic-block local redundant stores. 11 // 12 // FIXME: This should eventually be extended to be a post-dominator tree 13 // traversal. Doing so would be pretty trivial. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Transforms/Scalar/DeadStoreElimination.h" 18 #include "llvm/ADT/APInt.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/MapVector.h" 21 #include "llvm/ADT/SetVector.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/CaptureTracking.h" 28 #include "llvm/Analysis/GlobalsModRef.h" 29 #include "llvm/Analysis/MemoryBuiltins.h" 30 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 31 #include "llvm/Analysis/MemoryLocation.h" 32 #include "llvm/Analysis/OrderedBasicBlock.h" 33 #include "llvm/Analysis/TargetLibraryInfo.h" 34 #include "llvm/Analysis/ValueTracking.h" 35 #include "llvm/IR/Argument.h" 36 #include "llvm/IR/BasicBlock.h" 37 #include "llvm/IR/CallSite.h" 38 #include "llvm/IR/Constant.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/DataLayout.h" 41 #include "llvm/IR/Dominators.h" 42 #include "llvm/IR/Function.h" 43 #include "llvm/IR/InstrTypes.h" 44 #include "llvm/IR/Instruction.h" 45 #include "llvm/IR/Instructions.h" 46 #include "llvm/IR/IntrinsicInst.h" 47 #include "llvm/IR/Intrinsics.h" 48 #include "llvm/IR/LLVMContext.h" 49 #include "llvm/IR/Module.h" 50 #include "llvm/IR/PassManager.h" 51 #include "llvm/IR/Value.h" 52 #include "llvm/InitializePasses.h" 53 #include "llvm/Pass.h" 54 #include "llvm/Support/Casting.h" 55 #include "llvm/Support/CommandLine.h" 56 #include "llvm/Support/Debug.h" 57 #include "llvm/Support/ErrorHandling.h" 58 #include "llvm/Support/MathExtras.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include "llvm/Transforms/Scalar.h" 61 #include "llvm/Transforms/Utils/Local.h" 62 #include <algorithm> 63 #include <cassert> 64 #include <cstddef> 65 #include <cstdint> 66 #include <iterator> 67 #include <map> 68 #include <utility> 69 70 using namespace llvm; 71 72 #define DEBUG_TYPE "dse" 73 74 STATISTIC(NumRedundantStores, "Number of redundant stores deleted"); 75 STATISTIC(NumFastStores, "Number of stores deleted"); 76 STATISTIC(NumFastOther, "Number of other instrs removed"); 77 STATISTIC(NumCompletePartials, "Number of stores dead by later partials"); 78 STATISTIC(NumModifiedStores, "Number of stores modified"); 79 80 static cl::opt<bool> 81 EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking", 82 cl::init(true), cl::Hidden, 83 cl::desc("Enable partial-overwrite tracking in DSE")); 84 85 static cl::opt<bool> 86 EnablePartialStoreMerging("enable-dse-partial-store-merging", 87 cl::init(true), cl::Hidden, 88 cl::desc("Enable partial store merging in DSE")); 89 90 // Temporary dummy option for tests. 91 static cl::opt<bool> 92 EnableMemorySSA("enable-dse-memoryssa", cl::init(false), cl::Hidden, 93 cl::desc("Use the new MemorySSA-backed DSE.")); 94 95 //===----------------------------------------------------------------------===// 96 // Helper functions 97 //===----------------------------------------------------------------------===// 98 using OverlapIntervalsTy = std::map<int64_t, int64_t>; 99 using InstOverlapIntervalsTy = DenseMap<Instruction *, OverlapIntervalsTy>; 100 101 /// Delete this instruction. Before we do, go through and zero out all the 102 /// operands of this instruction. If any of them become dead, delete them and 103 /// the computation tree that feeds them. 104 /// If ValueSet is non-null, remove any deleted instructions from it as well. 105 static void 106 deleteDeadInstruction(Instruction *I, BasicBlock::iterator *BBI, 107 MemoryDependenceResults &MD, const TargetLibraryInfo &TLI, 108 InstOverlapIntervalsTy &IOL, OrderedBasicBlock &OBB, 109 MapVector<Instruction *, bool> &ThrowableInst, 110 SmallSetVector<const Value *, 16> *ValueSet = nullptr) { 111 SmallVector<Instruction*, 32> NowDeadInsts; 112 113 NowDeadInsts.push_back(I); 114 --NumFastOther; 115 116 // Keeping the iterator straight is a pain, so we let this routine tell the 117 // caller what the next instruction is after we're done mucking about. 118 BasicBlock::iterator NewIter = *BBI; 119 120 // Before we touch this instruction, remove it from memdep! 121 do { 122 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 123 // Mark the DeadInst as dead in the list of throwable instructions. 124 auto It = ThrowableInst.find(DeadInst); 125 if (It != ThrowableInst.end()) 126 ThrowableInst[It->first] = false; 127 ++NumFastOther; 128 129 // Try to preserve debug information attached to the dead instruction. 130 salvageDebugInfo(*DeadInst); 131 132 // This instruction is dead, zap it, in stages. Start by removing it from 133 // MemDep, which needs to know the operands and needs it to be in the 134 // function. 135 MD.removeInstruction(DeadInst); 136 137 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) { 138 Value *Op = DeadInst->getOperand(op); 139 DeadInst->setOperand(op, nullptr); 140 141 // If this operand just became dead, add it to the NowDeadInsts list. 142 if (!Op->use_empty()) continue; 143 144 if (Instruction *OpI = dyn_cast<Instruction>(Op)) 145 if (isInstructionTriviallyDead(OpI, &TLI)) 146 NowDeadInsts.push_back(OpI); 147 } 148 149 if (ValueSet) ValueSet->remove(DeadInst); 150 IOL.erase(DeadInst); 151 OBB.eraseInstruction(DeadInst); 152 153 if (NewIter == DeadInst->getIterator()) 154 NewIter = DeadInst->eraseFromParent(); 155 else 156 DeadInst->eraseFromParent(); 157 } while (!NowDeadInsts.empty()); 158 *BBI = NewIter; 159 // Pop dead entries from back of ThrowableInst till we find an alive entry. 160 while (!ThrowableInst.empty() && !ThrowableInst.back().second) 161 ThrowableInst.pop_back(); 162 } 163 164 /// Does this instruction write some memory? This only returns true for things 165 /// that we can analyze with other helpers below. 166 static bool hasAnalyzableMemoryWrite(Instruction *I, 167 const TargetLibraryInfo &TLI) { 168 if (isa<StoreInst>(I)) 169 return true; 170 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 171 switch (II->getIntrinsicID()) { 172 default: 173 return false; 174 case Intrinsic::memset: 175 case Intrinsic::memmove: 176 case Intrinsic::memcpy: 177 case Intrinsic::memcpy_element_unordered_atomic: 178 case Intrinsic::memmove_element_unordered_atomic: 179 case Intrinsic::memset_element_unordered_atomic: 180 case Intrinsic::init_trampoline: 181 case Intrinsic::lifetime_end: 182 return true; 183 } 184 } 185 if (auto CS = CallSite(I)) { 186 if (Function *F = CS.getCalledFunction()) { 187 LibFunc LF; 188 if (TLI.getLibFunc(*F, LF) && TLI.has(LF)) { 189 switch (LF) { 190 case LibFunc_strcpy: 191 case LibFunc_strncpy: 192 case LibFunc_strcat: 193 case LibFunc_strncat: 194 return true; 195 default: 196 return false; 197 } 198 } 199 } 200 } 201 return false; 202 } 203 204 /// Return a Location stored to by the specified instruction. If isRemovable 205 /// returns true, this function and getLocForRead completely describe the memory 206 /// operations for this instruction. 207 static MemoryLocation getLocForWrite(Instruction *Inst) { 208 209 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 210 return MemoryLocation::get(SI); 211 212 if (auto *MI = dyn_cast<AnyMemIntrinsic>(Inst)) { 213 // memcpy/memmove/memset. 214 MemoryLocation Loc = MemoryLocation::getForDest(MI); 215 return Loc; 216 } 217 218 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 219 switch (II->getIntrinsicID()) { 220 default: 221 return MemoryLocation(); // Unhandled intrinsic. 222 case Intrinsic::init_trampoline: 223 return MemoryLocation(II->getArgOperand(0)); 224 case Intrinsic::lifetime_end: { 225 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(); 226 return MemoryLocation(II->getArgOperand(1), Len); 227 } 228 } 229 } 230 if (auto CS = CallSite(Inst)) 231 // All the supported TLI functions so far happen to have dest as their 232 // first argument. 233 return MemoryLocation(CS.getArgument(0)); 234 return MemoryLocation(); 235 } 236 237 /// Return the location read by the specified "hasAnalyzableMemoryWrite" 238 /// instruction if any. 239 static MemoryLocation getLocForRead(Instruction *Inst, 240 const TargetLibraryInfo &TLI) { 241 assert(hasAnalyzableMemoryWrite(Inst, TLI) && "Unknown instruction case"); 242 243 // The only instructions that both read and write are the mem transfer 244 // instructions (memcpy/memmove). 245 if (auto *MTI = dyn_cast<AnyMemTransferInst>(Inst)) 246 return MemoryLocation::getForSource(MTI); 247 return MemoryLocation(); 248 } 249 250 /// If the value of this instruction and the memory it writes to is unused, may 251 /// we delete this instruction? 252 static bool isRemovable(Instruction *I) { 253 // Don't remove volatile/atomic stores. 254 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 255 return SI->isUnordered(); 256 257 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 258 switch (II->getIntrinsicID()) { 259 default: llvm_unreachable("doesn't pass 'hasAnalyzableMemoryWrite' predicate"); 260 case Intrinsic::lifetime_end: 261 // Never remove dead lifetime_end's, e.g. because it is followed by a 262 // free. 263 return false; 264 case Intrinsic::init_trampoline: 265 // Always safe to remove init_trampoline. 266 return true; 267 case Intrinsic::memset: 268 case Intrinsic::memmove: 269 case Intrinsic::memcpy: 270 // Don't remove volatile memory intrinsics. 271 return !cast<MemIntrinsic>(II)->isVolatile(); 272 case Intrinsic::memcpy_element_unordered_atomic: 273 case Intrinsic::memmove_element_unordered_atomic: 274 case Intrinsic::memset_element_unordered_atomic: 275 return true; 276 } 277 } 278 279 // note: only get here for calls with analyzable writes - i.e. libcalls 280 if (auto CS = CallSite(I)) 281 return CS.getInstruction()->use_empty(); 282 283 return false; 284 } 285 286 /// Returns true if the end of this instruction can be safely shortened in 287 /// length. 288 static bool isShortenableAtTheEnd(Instruction *I) { 289 // Don't shorten stores for now 290 if (isa<StoreInst>(I)) 291 return false; 292 293 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 294 switch (II->getIntrinsicID()) { 295 default: return false; 296 case Intrinsic::memset: 297 case Intrinsic::memcpy: 298 case Intrinsic::memcpy_element_unordered_atomic: 299 case Intrinsic::memset_element_unordered_atomic: 300 // Do shorten memory intrinsics. 301 // FIXME: Add memmove if it's also safe to transform. 302 return true; 303 } 304 } 305 306 // Don't shorten libcalls calls for now. 307 308 return false; 309 } 310 311 /// Returns true if the beginning of this instruction can be safely shortened 312 /// in length. 313 static bool isShortenableAtTheBeginning(Instruction *I) { 314 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be 315 // easily done by offsetting the source address. 316 return isa<AnyMemSetInst>(I); 317 } 318 319 /// Return the pointer that is being written to. 320 static Value *getStoredPointerOperand(Instruction *I) { 321 //TODO: factor this to reuse getLocForWrite 322 MemoryLocation Loc = getLocForWrite(I); 323 assert(Loc.Ptr && 324 "unable to find pointer written for analyzable instruction?"); 325 // TODO: most APIs don't expect const Value * 326 return const_cast<Value*>(Loc.Ptr); 327 } 328 329 static uint64_t getPointerSize(const Value *V, const DataLayout &DL, 330 const TargetLibraryInfo &TLI, 331 const Function *F) { 332 uint64_t Size; 333 ObjectSizeOpts Opts; 334 Opts.NullIsUnknownSize = NullPointerIsDefined(F); 335 336 if (getObjectSize(V, Size, DL, &TLI, Opts)) 337 return Size; 338 return MemoryLocation::UnknownSize; 339 } 340 341 namespace { 342 343 enum OverwriteResult { 344 OW_Begin, 345 OW_Complete, 346 OW_End, 347 OW_PartialEarlierWithFullLater, 348 OW_Unknown 349 }; 350 351 } // end anonymous namespace 352 353 /// Return 'OW_Complete' if a store to the 'Later' location completely 354 /// overwrites a store to the 'Earlier' location, 'OW_End' if the end of the 355 /// 'Earlier' location is completely overwritten by 'Later', 'OW_Begin' if the 356 /// beginning of the 'Earlier' location is overwritten by 'Later'. 357 /// 'OW_PartialEarlierWithFullLater' means that an earlier (big) store was 358 /// overwritten by a latter (smaller) store which doesn't write outside the big 359 /// store's memory locations. Returns 'OW_Unknown' if nothing can be determined. 360 static OverwriteResult isOverwrite(const MemoryLocation &Later, 361 const MemoryLocation &Earlier, 362 const DataLayout &DL, 363 const TargetLibraryInfo &TLI, 364 int64_t &EarlierOff, int64_t &LaterOff, 365 Instruction *DepWrite, 366 InstOverlapIntervalsTy &IOL, 367 AliasAnalysis &AA, 368 const Function *F) { 369 // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll 370 // get imprecise values here, though (except for unknown sizes). 371 if (!Later.Size.isPrecise() || !Earlier.Size.isPrecise()) 372 return OW_Unknown; 373 374 const uint64_t LaterSize = Later.Size.getValue(); 375 const uint64_t EarlierSize = Earlier.Size.getValue(); 376 377 const Value *P1 = Earlier.Ptr->stripPointerCasts(); 378 const Value *P2 = Later.Ptr->stripPointerCasts(); 379 380 // If the start pointers are the same, we just have to compare sizes to see if 381 // the later store was larger than the earlier store. 382 if (P1 == P2 || AA.isMustAlias(P1, P2)) { 383 // Make sure that the Later size is >= the Earlier size. 384 if (LaterSize >= EarlierSize) 385 return OW_Complete; 386 } 387 388 // Check to see if the later store is to the entire object (either a global, 389 // an alloca, or a byval/inalloca argument). If so, then it clearly 390 // overwrites any other store to the same object. 391 const Value *UO1 = GetUnderlyingObject(P1, DL), 392 *UO2 = GetUnderlyingObject(P2, DL); 393 394 // If we can't resolve the same pointers to the same object, then we can't 395 // analyze them at all. 396 if (UO1 != UO2) 397 return OW_Unknown; 398 399 // If the "Later" store is to a recognizable object, get its size. 400 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI, F); 401 if (ObjectSize != MemoryLocation::UnknownSize) 402 if (ObjectSize == LaterSize && ObjectSize >= EarlierSize) 403 return OW_Complete; 404 405 // Okay, we have stores to two completely different pointers. Try to 406 // decompose the pointer into a "base + constant_offset" form. If the base 407 // pointers are equal, then we can reason about the two stores. 408 EarlierOff = 0; 409 LaterOff = 0; 410 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL); 411 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL); 412 413 // If the base pointers still differ, we have two completely different stores. 414 if (BP1 != BP2) 415 return OW_Unknown; 416 417 // The later store completely overlaps the earlier store if: 418 // 419 // 1. Both start at the same offset and the later one's size is greater than 420 // or equal to the earlier one's, or 421 // 422 // |--earlier--| 423 // |-- later --| 424 // 425 // 2. The earlier store has an offset greater than the later offset, but which 426 // still lies completely within the later store. 427 // 428 // |--earlier--| 429 // |----- later ------| 430 // 431 // We have to be careful here as *Off is signed while *.Size is unsigned. 432 if (EarlierOff >= LaterOff && 433 LaterSize >= EarlierSize && 434 uint64_t(EarlierOff - LaterOff) + EarlierSize <= LaterSize) 435 return OW_Complete; 436 437 // We may now overlap, although the overlap is not complete. There might also 438 // be other incomplete overlaps, and together, they might cover the complete 439 // earlier write. 440 // Note: The correctness of this logic depends on the fact that this function 441 // is not even called providing DepWrite when there are any intervening reads. 442 if (EnablePartialOverwriteTracking && 443 LaterOff < int64_t(EarlierOff + EarlierSize) && 444 int64_t(LaterOff + LaterSize) >= EarlierOff) { 445 446 // Insert our part of the overlap into the map. 447 auto &IM = IOL[DepWrite]; 448 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: Earlier [" << EarlierOff 449 << ", " << int64_t(EarlierOff + EarlierSize) 450 << ") Later [" << LaterOff << ", " 451 << int64_t(LaterOff + LaterSize) << ")\n"); 452 453 // Make sure that we only insert non-overlapping intervals and combine 454 // adjacent intervals. The intervals are stored in the map with the ending 455 // offset as the key (in the half-open sense) and the starting offset as 456 // the value. 457 int64_t LaterIntStart = LaterOff, LaterIntEnd = LaterOff + LaterSize; 458 459 // Find any intervals ending at, or after, LaterIntStart which start 460 // before LaterIntEnd. 461 auto ILI = IM.lower_bound(LaterIntStart); 462 if (ILI != IM.end() && ILI->second <= LaterIntEnd) { 463 // This existing interval is overlapped with the current store somewhere 464 // in [LaterIntStart, LaterIntEnd]. Merge them by erasing the existing 465 // intervals and adjusting our start and end. 466 LaterIntStart = std::min(LaterIntStart, ILI->second); 467 LaterIntEnd = std::max(LaterIntEnd, ILI->first); 468 ILI = IM.erase(ILI); 469 470 // Continue erasing and adjusting our end in case other previous 471 // intervals are also overlapped with the current store. 472 // 473 // |--- ealier 1 ---| |--- ealier 2 ---| 474 // |------- later---------| 475 // 476 while (ILI != IM.end() && ILI->second <= LaterIntEnd) { 477 assert(ILI->second > LaterIntStart && "Unexpected interval"); 478 LaterIntEnd = std::max(LaterIntEnd, ILI->first); 479 ILI = IM.erase(ILI); 480 } 481 } 482 483 IM[LaterIntEnd] = LaterIntStart; 484 485 ILI = IM.begin(); 486 if (ILI->second <= EarlierOff && 487 ILI->first >= int64_t(EarlierOff + EarlierSize)) { 488 LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: Earlier [" 489 << EarlierOff << ", " 490 << int64_t(EarlierOff + EarlierSize) 491 << ") Composite Later [" << ILI->second << ", " 492 << ILI->first << ")\n"); 493 ++NumCompletePartials; 494 return OW_Complete; 495 } 496 } 497 498 // Check for an earlier store which writes to all the memory locations that 499 // the later store writes to. 500 if (EnablePartialStoreMerging && LaterOff >= EarlierOff && 501 int64_t(EarlierOff + EarlierSize) > LaterOff && 502 uint64_t(LaterOff - EarlierOff) + LaterSize <= EarlierSize) { 503 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite an earlier load [" 504 << EarlierOff << ", " 505 << int64_t(EarlierOff + EarlierSize) 506 << ") by a later store [" << LaterOff << ", " 507 << int64_t(LaterOff + LaterSize) << ")\n"); 508 // TODO: Maybe come up with a better name? 509 return OW_PartialEarlierWithFullLater; 510 } 511 512 // Another interesting case is if the later store overwrites the end of the 513 // earlier store. 514 // 515 // |--earlier--| 516 // |-- later --| 517 // 518 // In this case we may want to trim the size of earlier to avoid generating 519 // writes to addresses which will definitely be overwritten later 520 if (!EnablePartialOverwriteTracking && 521 (LaterOff > EarlierOff && LaterOff < int64_t(EarlierOff + EarlierSize) && 522 int64_t(LaterOff + LaterSize) >= int64_t(EarlierOff + EarlierSize))) 523 return OW_End; 524 525 // Finally, we also need to check if the later store overwrites the beginning 526 // of the earlier store. 527 // 528 // |--earlier--| 529 // |-- later --| 530 // 531 // In this case we may want to move the destination address and trim the size 532 // of earlier to avoid generating writes to addresses which will definitely 533 // be overwritten later. 534 if (!EnablePartialOverwriteTracking && 535 (LaterOff <= EarlierOff && int64_t(LaterOff + LaterSize) > EarlierOff)) { 536 assert(int64_t(LaterOff + LaterSize) < int64_t(EarlierOff + EarlierSize) && 537 "Expect to be handled as OW_Complete"); 538 return OW_Begin; 539 } 540 // Otherwise, they don't completely overlap. 541 return OW_Unknown; 542 } 543 544 /// If 'Inst' might be a self read (i.e. a noop copy of a 545 /// memory region into an identical pointer) then it doesn't actually make its 546 /// input dead in the traditional sense. Consider this case: 547 /// 548 /// memmove(A <- B) 549 /// memmove(A <- A) 550 /// 551 /// In this case, the second store to A does not make the first store to A dead. 552 /// The usual situation isn't an explicit A<-A store like this (which can be 553 /// trivially removed) but a case where two pointers may alias. 554 /// 555 /// This function detects when it is unsafe to remove a dependent instruction 556 /// because the DSE inducing instruction may be a self-read. 557 static bool isPossibleSelfRead(Instruction *Inst, 558 const MemoryLocation &InstStoreLoc, 559 Instruction *DepWrite, 560 const TargetLibraryInfo &TLI, 561 AliasAnalysis &AA) { 562 // Self reads can only happen for instructions that read memory. Get the 563 // location read. 564 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI); 565 if (!InstReadLoc.Ptr) 566 return false; // Not a reading instruction. 567 568 // If the read and written loc obviously don't alias, it isn't a read. 569 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) 570 return false; 571 572 if (isa<AnyMemCpyInst>(Inst)) { 573 // LLVM's memcpy overlap semantics are not fully fleshed out (see PR11763) 574 // but in practice memcpy(A <- B) either means that A and B are disjoint or 575 // are equal (i.e. there are not partial overlaps). Given that, if we have: 576 // 577 // memcpy/memmove(A <- B) // DepWrite 578 // memcpy(A <- B) // Inst 579 // 580 // with Inst reading/writing a >= size than DepWrite, we can reason as 581 // follows: 582 // 583 // - If A == B then both the copies are no-ops, so the DepWrite can be 584 // removed. 585 // - If A != B then A and B are disjoint locations in Inst. Since 586 // Inst.size >= DepWrite.size A and B are disjoint in DepWrite too. 587 // Therefore DepWrite can be removed. 588 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI); 589 590 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr)) 591 return false; 592 } 593 594 // If DepWrite doesn't read memory or if we can't prove it is a must alias, 595 // then it can't be considered dead. 596 return true; 597 } 598 599 /// Returns true if the memory which is accessed by the second instruction is not 600 /// modified between the first and the second instruction. 601 /// Precondition: Second instruction must be dominated by the first 602 /// instruction. 603 static bool memoryIsNotModifiedBetween(Instruction *FirstI, 604 Instruction *SecondI, 605 AliasAnalysis *AA) { 606 SmallVector<BasicBlock *, 16> WorkList; 607 SmallPtrSet<BasicBlock *, 8> Visited; 608 BasicBlock::iterator FirstBBI(FirstI); 609 ++FirstBBI; 610 BasicBlock::iterator SecondBBI(SecondI); 611 BasicBlock *FirstBB = FirstI->getParent(); 612 BasicBlock *SecondBB = SecondI->getParent(); 613 MemoryLocation MemLoc = MemoryLocation::get(SecondI); 614 615 // Start checking the SecondBB. 616 WorkList.push_back(SecondBB); 617 bool isFirstBlock = true; 618 619 // Check all blocks going backward until we reach the FirstBB. 620 while (!WorkList.empty()) { 621 BasicBlock *B = WorkList.pop_back_val(); 622 623 // Ignore instructions before FirstI if this is the FirstBB. 624 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin()); 625 626 BasicBlock::iterator EI; 627 if (isFirstBlock) { 628 // Ignore instructions after SecondI if this is the first visit of SecondBB. 629 assert(B == SecondBB && "first block is not the store block"); 630 EI = SecondBBI; 631 isFirstBlock = false; 632 } else { 633 // It's not SecondBB or (in case of a loop) the second visit of SecondBB. 634 // In this case we also have to look at instructions after SecondI. 635 EI = B->end(); 636 } 637 for (; BI != EI; ++BI) { 638 Instruction *I = &*BI; 639 if (I->mayWriteToMemory() && I != SecondI) 640 if (isModSet(AA->getModRefInfo(I, MemLoc))) 641 return false; 642 } 643 if (B != FirstBB) { 644 assert(B != &FirstBB->getParent()->getEntryBlock() && 645 "Should not hit the entry block because SI must be dominated by LI"); 646 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) { 647 if (!Visited.insert(*PredI).second) 648 continue; 649 WorkList.push_back(*PredI); 650 } 651 } 652 } 653 return true; 654 } 655 656 /// Find all blocks that will unconditionally lead to the block BB and append 657 /// them to F. 658 static void findUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks, 659 BasicBlock *BB, DominatorTree *DT) { 660 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) { 661 BasicBlock *Pred = *I; 662 if (Pred == BB) continue; 663 Instruction *PredTI = Pred->getTerminator(); 664 if (PredTI->getNumSuccessors() != 1) 665 continue; 666 667 if (DT->isReachableFromEntry(Pred)) 668 Blocks.push_back(Pred); 669 } 670 } 671 672 /// Handle frees of entire structures whose dependency is a store 673 /// to a field of that structure. 674 static bool handleFree(CallInst *F, AliasAnalysis *AA, 675 MemoryDependenceResults *MD, DominatorTree *DT, 676 const TargetLibraryInfo *TLI, 677 InstOverlapIntervalsTy &IOL, OrderedBasicBlock &OBB, 678 MapVector<Instruction *, bool> &ThrowableInst) { 679 bool MadeChange = false; 680 681 MemoryLocation Loc = MemoryLocation(F->getOperand(0)); 682 SmallVector<BasicBlock *, 16> Blocks; 683 Blocks.push_back(F->getParent()); 684 const DataLayout &DL = F->getModule()->getDataLayout(); 685 686 while (!Blocks.empty()) { 687 BasicBlock *BB = Blocks.pop_back_val(); 688 Instruction *InstPt = BB->getTerminator(); 689 if (BB == F->getParent()) InstPt = F; 690 691 MemDepResult Dep = 692 MD->getPointerDependencyFrom(Loc, false, InstPt->getIterator(), BB); 693 while (Dep.isDef() || Dep.isClobber()) { 694 Instruction *Dependency = Dep.getInst(); 695 if (!hasAnalyzableMemoryWrite(Dependency, *TLI) || 696 !isRemovable(Dependency)) 697 break; 698 699 Value *DepPointer = 700 GetUnderlyingObject(getStoredPointerOperand(Dependency), DL); 701 702 // Check for aliasing. 703 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer)) 704 break; 705 706 LLVM_DEBUG( 707 dbgs() << "DSE: Dead Store to soon to be freed memory:\n DEAD: " 708 << *Dependency << '\n'); 709 710 // DCE instructions only used to calculate that store. 711 BasicBlock::iterator BBI(Dependency); 712 deleteDeadInstruction(Dependency, &BBI, *MD, *TLI, IOL, OBB, 713 ThrowableInst); 714 ++NumFastStores; 715 MadeChange = true; 716 717 // Inst's old Dependency is now deleted. Compute the next dependency, 718 // which may also be dead, as in 719 // s[0] = 0; 720 // s[1] = 0; // This has just been deleted. 721 // free(s); 722 Dep = MD->getPointerDependencyFrom(Loc, false, BBI, BB); 723 } 724 725 if (Dep.isNonLocal()) 726 findUnconditionalPreds(Blocks, BB, DT); 727 } 728 729 return MadeChange; 730 } 731 732 /// Check to see if the specified location may alias any of the stack objects in 733 /// the DeadStackObjects set. If so, they become live because the location is 734 /// being loaded. 735 static void removeAccessedObjects(const MemoryLocation &LoadedLoc, 736 SmallSetVector<const Value *, 16> &DeadStackObjects, 737 const DataLayout &DL, AliasAnalysis *AA, 738 const TargetLibraryInfo *TLI, 739 const Function *F) { 740 const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL); 741 742 // A constant can't be in the dead pointer set. 743 if (isa<Constant>(UnderlyingPointer)) 744 return; 745 746 // If the kill pointer can be easily reduced to an alloca, don't bother doing 747 // extraneous AA queries. 748 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) { 749 DeadStackObjects.remove(UnderlyingPointer); 750 return; 751 } 752 753 // Remove objects that could alias LoadedLoc. 754 DeadStackObjects.remove_if([&](const Value *I) { 755 // See if the loaded location could alias the stack location. 756 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI, F)); 757 return !AA->isNoAlias(StackLoc, LoadedLoc); 758 }); 759 } 760 761 /// Remove dead stores to stack-allocated locations in the function end block. 762 /// Ex: 763 /// %A = alloca i32 764 /// ... 765 /// store i32 1, i32* %A 766 /// ret void 767 static bool handleEndBlock(BasicBlock &BB, AliasAnalysis *AA, 768 MemoryDependenceResults *MD, 769 const TargetLibraryInfo *TLI, 770 InstOverlapIntervalsTy &IOL, OrderedBasicBlock &OBB, 771 MapVector<Instruction *, bool> &ThrowableInst) { 772 bool MadeChange = false; 773 774 // Keep track of all of the stack objects that are dead at the end of the 775 // function. 776 SmallSetVector<const Value*, 16> DeadStackObjects; 777 778 // Find all of the alloca'd pointers in the entry block. 779 BasicBlock &Entry = BB.getParent()->front(); 780 for (Instruction &I : Entry) { 781 if (isa<AllocaInst>(&I)) 782 DeadStackObjects.insert(&I); 783 784 // Okay, so these are dead heap objects, but if the pointer never escapes 785 // then it's leaked by this function anyways. 786 else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true)) 787 DeadStackObjects.insert(&I); 788 } 789 790 // Treat byval or inalloca arguments the same, stores to them are dead at the 791 // end of the function. 792 for (Argument &AI : BB.getParent()->args()) 793 if (AI.hasByValOrInAllocaAttr()) 794 DeadStackObjects.insert(&AI); 795 796 const DataLayout &DL = BB.getModule()->getDataLayout(); 797 798 // Scan the basic block backwards 799 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){ 800 --BBI; 801 802 // If we find a store, check to see if it points into a dead stack value. 803 if (hasAnalyzableMemoryWrite(&*BBI, *TLI) && isRemovable(&*BBI)) { 804 // See through pointer-to-pointer bitcasts 805 SmallVector<const Value *, 4> Pointers; 806 GetUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers, DL); 807 808 // Stores to stack values are valid candidates for removal. 809 bool AllDead = true; 810 for (const Value *Pointer : Pointers) 811 if (!DeadStackObjects.count(Pointer)) { 812 AllDead = false; 813 break; 814 } 815 816 if (AllDead) { 817 Instruction *Dead = &*BBI; 818 819 LLVM_DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: " 820 << *Dead << "\n Objects: "; 821 for (SmallVectorImpl<const Value *>::iterator I = 822 Pointers.begin(), 823 E = Pointers.end(); 824 I != E; ++I) { 825 dbgs() << **I; 826 if (std::next(I) != E) 827 dbgs() << ", "; 828 } dbgs() 829 << '\n'); 830 831 // DCE instructions only used to calculate that store. 832 deleteDeadInstruction(Dead, &BBI, *MD, *TLI, IOL, OBB, ThrowableInst, 833 &DeadStackObjects); 834 ++NumFastStores; 835 MadeChange = true; 836 continue; 837 } 838 } 839 840 // Remove any dead non-memory-mutating instructions. 841 if (isInstructionTriviallyDead(&*BBI, TLI)) { 842 LLVM_DEBUG(dbgs() << "DSE: Removing trivially dead instruction:\n DEAD: " 843 << *&*BBI << '\n'); 844 deleteDeadInstruction(&*BBI, &BBI, *MD, *TLI, IOL, OBB, ThrowableInst, 845 &DeadStackObjects); 846 ++NumFastOther; 847 MadeChange = true; 848 continue; 849 } 850 851 if (isa<AllocaInst>(BBI)) { 852 // Remove allocas from the list of dead stack objects; there can't be 853 // any references before the definition. 854 DeadStackObjects.remove(&*BBI); 855 continue; 856 } 857 858 if (auto *Call = dyn_cast<CallBase>(&*BBI)) { 859 // Remove allocation function calls from the list of dead stack objects; 860 // there can't be any references before the definition. 861 if (isAllocLikeFn(&*BBI, TLI)) 862 DeadStackObjects.remove(&*BBI); 863 864 // If this call does not access memory, it can't be loading any of our 865 // pointers. 866 if (AA->doesNotAccessMemory(Call)) 867 continue; 868 869 // If the call might load from any of our allocas, then any store above 870 // the call is live. 871 DeadStackObjects.remove_if([&](const Value *I) { 872 // See if the call site touches the value. 873 return isRefSet(AA->getModRefInfo( 874 Call, I, getPointerSize(I, DL, *TLI, BB.getParent()))); 875 }); 876 877 // If all of the allocas were clobbered by the call then we're not going 878 // to find anything else to process. 879 if (DeadStackObjects.empty()) 880 break; 881 882 continue; 883 } 884 885 // We can remove the dead stores, irrespective of the fence and its ordering 886 // (release/acquire/seq_cst). Fences only constraints the ordering of 887 // already visible stores, it does not make a store visible to other 888 // threads. So, skipping over a fence does not change a store from being 889 // dead. 890 if (isa<FenceInst>(*BBI)) 891 continue; 892 893 MemoryLocation LoadedLoc; 894 895 // If we encounter a use of the pointer, it is no longer considered dead 896 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) { 897 if (!L->isUnordered()) // Be conservative with atomic/volatile load 898 break; 899 LoadedLoc = MemoryLocation::get(L); 900 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) { 901 LoadedLoc = MemoryLocation::get(V); 902 } else if (!BBI->mayReadFromMemory()) { 903 // Instruction doesn't read memory. Note that stores that weren't removed 904 // above will hit this case. 905 continue; 906 } else { 907 // Unknown inst; assume it clobbers everything. 908 break; 909 } 910 911 // Remove any allocas from the DeadPointer set that are loaded, as this 912 // makes any stores above the access live. 913 removeAccessedObjects(LoadedLoc, DeadStackObjects, DL, AA, TLI, BB.getParent()); 914 915 // If all of the allocas were clobbered by the access then we're not going 916 // to find anything else to process. 917 if (DeadStackObjects.empty()) 918 break; 919 } 920 921 return MadeChange; 922 } 923 924 static bool tryToShorten(Instruction *EarlierWrite, int64_t &EarlierOffset, 925 int64_t &EarlierSize, int64_t LaterOffset, 926 int64_t LaterSize, bool IsOverwriteEnd) { 927 // TODO: base this on the target vector size so that if the earlier 928 // store was too small to get vector writes anyway then its likely 929 // a good idea to shorten it 930 // Power of 2 vector writes are probably always a bad idea to optimize 931 // as any store/memset/memcpy is likely using vector instructions so 932 // shortening it to not vector size is likely to be slower 933 auto *EarlierIntrinsic = cast<AnyMemIntrinsic>(EarlierWrite); 934 unsigned EarlierWriteAlign = EarlierIntrinsic->getDestAlignment(); 935 if (!IsOverwriteEnd) 936 LaterOffset = int64_t(LaterOffset + LaterSize); 937 938 if (!(isPowerOf2_64(LaterOffset) && EarlierWriteAlign <= LaterOffset) && 939 !((EarlierWriteAlign != 0) && LaterOffset % EarlierWriteAlign == 0)) 940 return false; 941 942 int64_t NewLength = IsOverwriteEnd 943 ? LaterOffset - EarlierOffset 944 : EarlierSize - (LaterOffset - EarlierOffset); 945 946 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(EarlierWrite)) { 947 // When shortening an atomic memory intrinsic, the newly shortened 948 // length must remain an integer multiple of the element size. 949 const uint32_t ElementSize = AMI->getElementSizeInBytes(); 950 if (0 != NewLength % ElementSize) 951 return false; 952 } 953 954 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW " 955 << (IsOverwriteEnd ? "END" : "BEGIN") << ": " 956 << *EarlierWrite << "\n KILLER (offset " << LaterOffset 957 << ", " << EarlierSize << ")\n"); 958 959 Value *EarlierWriteLength = EarlierIntrinsic->getLength(); 960 Value *TrimmedLength = 961 ConstantInt::get(EarlierWriteLength->getType(), NewLength); 962 EarlierIntrinsic->setLength(TrimmedLength); 963 964 EarlierSize = NewLength; 965 if (!IsOverwriteEnd) { 966 int64_t OffsetMoved = (LaterOffset - EarlierOffset); 967 Value *Indices[1] = { 968 ConstantInt::get(EarlierWriteLength->getType(), OffsetMoved)}; 969 GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds( 970 EarlierIntrinsic->getRawDest()->getType()->getPointerElementType(), 971 EarlierIntrinsic->getRawDest(), Indices, "", EarlierWrite); 972 NewDestGEP->setDebugLoc(EarlierIntrinsic->getDebugLoc()); 973 EarlierIntrinsic->setDest(NewDestGEP); 974 EarlierOffset = EarlierOffset + OffsetMoved; 975 } 976 return true; 977 } 978 979 static bool tryToShortenEnd(Instruction *EarlierWrite, 980 OverlapIntervalsTy &IntervalMap, 981 int64_t &EarlierStart, int64_t &EarlierSize) { 982 if (IntervalMap.empty() || !isShortenableAtTheEnd(EarlierWrite)) 983 return false; 984 985 OverlapIntervalsTy::iterator OII = --IntervalMap.end(); 986 int64_t LaterStart = OII->second; 987 int64_t LaterSize = OII->first - LaterStart; 988 989 if (LaterStart > EarlierStart && LaterStart < EarlierStart + EarlierSize && 990 LaterStart + LaterSize >= EarlierStart + EarlierSize) { 991 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart, 992 LaterSize, true)) { 993 IntervalMap.erase(OII); 994 return true; 995 } 996 } 997 return false; 998 } 999 1000 static bool tryToShortenBegin(Instruction *EarlierWrite, 1001 OverlapIntervalsTy &IntervalMap, 1002 int64_t &EarlierStart, int64_t &EarlierSize) { 1003 if (IntervalMap.empty() || !isShortenableAtTheBeginning(EarlierWrite)) 1004 return false; 1005 1006 OverlapIntervalsTy::iterator OII = IntervalMap.begin(); 1007 int64_t LaterStart = OII->second; 1008 int64_t LaterSize = OII->first - LaterStart; 1009 1010 if (LaterStart <= EarlierStart && LaterStart + LaterSize > EarlierStart) { 1011 assert(LaterStart + LaterSize < EarlierStart + EarlierSize && 1012 "Should have been handled as OW_Complete"); 1013 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart, 1014 LaterSize, false)) { 1015 IntervalMap.erase(OII); 1016 return true; 1017 } 1018 } 1019 return false; 1020 } 1021 1022 static bool removePartiallyOverlappedStores(AliasAnalysis *AA, 1023 const DataLayout &DL, 1024 InstOverlapIntervalsTy &IOL) { 1025 bool Changed = false; 1026 for (auto OI : IOL) { 1027 Instruction *EarlierWrite = OI.first; 1028 MemoryLocation Loc = getLocForWrite(EarlierWrite); 1029 assert(isRemovable(EarlierWrite) && "Expect only removable instruction"); 1030 1031 const Value *Ptr = Loc.Ptr->stripPointerCasts(); 1032 int64_t EarlierStart = 0; 1033 int64_t EarlierSize = int64_t(Loc.Size.getValue()); 1034 GetPointerBaseWithConstantOffset(Ptr, EarlierStart, DL); 1035 OverlapIntervalsTy &IntervalMap = OI.second; 1036 Changed |= 1037 tryToShortenEnd(EarlierWrite, IntervalMap, EarlierStart, EarlierSize); 1038 if (IntervalMap.empty()) 1039 continue; 1040 Changed |= 1041 tryToShortenBegin(EarlierWrite, IntervalMap, EarlierStart, EarlierSize); 1042 } 1043 return Changed; 1044 } 1045 1046 static bool eliminateNoopStore(Instruction *Inst, BasicBlock::iterator &BBI, 1047 AliasAnalysis *AA, MemoryDependenceResults *MD, 1048 const DataLayout &DL, 1049 const TargetLibraryInfo *TLI, 1050 InstOverlapIntervalsTy &IOL, 1051 OrderedBasicBlock &OBB, 1052 MapVector<Instruction *, bool> &ThrowableInst) { 1053 // Must be a store instruction. 1054 StoreInst *SI = dyn_cast<StoreInst>(Inst); 1055 if (!SI) 1056 return false; 1057 1058 // If we're storing the same value back to a pointer that we just loaded from, 1059 // then the store can be removed. 1060 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) { 1061 if (SI->getPointerOperand() == DepLoad->getPointerOperand() && 1062 isRemovable(SI) && memoryIsNotModifiedBetween(DepLoad, SI, AA)) { 1063 1064 LLVM_DEBUG( 1065 dbgs() << "DSE: Remove Store Of Load from same pointer:\n LOAD: " 1066 << *DepLoad << "\n STORE: " << *SI << '\n'); 1067 1068 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, OBB, ThrowableInst); 1069 ++NumRedundantStores; 1070 return true; 1071 } 1072 } 1073 1074 // Remove null stores into the calloc'ed objects 1075 Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand()); 1076 if (StoredConstant && StoredConstant->isNullValue() && isRemovable(SI)) { 1077 Instruction *UnderlyingPointer = 1078 dyn_cast<Instruction>(GetUnderlyingObject(SI->getPointerOperand(), DL)); 1079 1080 if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) && 1081 memoryIsNotModifiedBetween(UnderlyingPointer, SI, AA)) { 1082 LLVM_DEBUG( 1083 dbgs() << "DSE: Remove null store to the calloc'ed object:\n DEAD: " 1084 << *Inst << "\n OBJECT: " << *UnderlyingPointer << '\n'); 1085 1086 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, OBB, ThrowableInst); 1087 ++NumRedundantStores; 1088 return true; 1089 } 1090 } 1091 return false; 1092 } 1093 1094 static bool eliminateDeadStores(BasicBlock &BB, AliasAnalysis *AA, 1095 MemoryDependenceResults *MD, DominatorTree *DT, 1096 const TargetLibraryInfo *TLI) { 1097 const DataLayout &DL = BB.getModule()->getDataLayout(); 1098 bool MadeChange = false; 1099 1100 OrderedBasicBlock OBB(&BB); 1101 MapVector<Instruction *, bool> ThrowableInst; 1102 1103 // A map of interval maps representing partially-overwritten value parts. 1104 InstOverlapIntervalsTy IOL; 1105 1106 // Do a top-down walk on the BB. 1107 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) { 1108 // Handle 'free' calls specially. 1109 if (CallInst *F = isFreeCall(&*BBI, TLI)) { 1110 MadeChange |= handleFree(F, AA, MD, DT, TLI, IOL, OBB, ThrowableInst); 1111 // Increment BBI after handleFree has potentially deleted instructions. 1112 // This ensures we maintain a valid iterator. 1113 ++BBI; 1114 continue; 1115 } 1116 1117 Instruction *Inst = &*BBI++; 1118 1119 if (Inst->mayThrow()) { 1120 ThrowableInst[Inst] = true; 1121 continue; 1122 } 1123 1124 // Check to see if Inst writes to memory. If not, continue. 1125 if (!hasAnalyzableMemoryWrite(Inst, *TLI)) 1126 continue; 1127 1128 // eliminateNoopStore will update in iterator, if necessary. 1129 if (eliminateNoopStore(Inst, BBI, AA, MD, DL, TLI, IOL, OBB, 1130 ThrowableInst)) { 1131 MadeChange = true; 1132 continue; 1133 } 1134 1135 // If we find something that writes memory, get its memory dependence. 1136 MemDepResult InstDep = MD->getDependency(Inst, &OBB); 1137 1138 // Ignore any store where we can't find a local dependence. 1139 // FIXME: cross-block DSE would be fun. :) 1140 if (!InstDep.isDef() && !InstDep.isClobber()) 1141 continue; 1142 1143 // Figure out what location is being stored to. 1144 MemoryLocation Loc = getLocForWrite(Inst); 1145 1146 // If we didn't get a useful location, fail. 1147 if (!Loc.Ptr) 1148 continue; 1149 1150 // Loop until we find a store we can eliminate or a load that 1151 // invalidates the analysis. Without an upper bound on the number of 1152 // instructions examined, this analysis can become very time-consuming. 1153 // However, the potential gain diminishes as we process more instructions 1154 // without eliminating any of them. Therefore, we limit the number of 1155 // instructions we look at. 1156 auto Limit = MD->getDefaultBlockScanLimit(); 1157 while (InstDep.isDef() || InstDep.isClobber()) { 1158 // Get the memory clobbered by the instruction we depend on. MemDep will 1159 // skip any instructions that 'Loc' clearly doesn't interact with. If we 1160 // end up depending on a may- or must-aliased load, then we can't optimize 1161 // away the store and we bail out. However, if we depend on something 1162 // that overwrites the memory location we *can* potentially optimize it. 1163 // 1164 // Find out what memory location the dependent instruction stores. 1165 Instruction *DepWrite = InstDep.getInst(); 1166 if (!hasAnalyzableMemoryWrite(DepWrite, *TLI)) 1167 break; 1168 MemoryLocation DepLoc = getLocForWrite(DepWrite); 1169 // If we didn't get a useful location, or if it isn't a size, bail out. 1170 if (!DepLoc.Ptr) 1171 break; 1172 1173 // Find the last throwable instruction not removed by call to 1174 // deleteDeadInstruction. 1175 Instruction *LastThrowing = nullptr; 1176 if (!ThrowableInst.empty()) 1177 LastThrowing = ThrowableInst.back().first; 1178 1179 // Make sure we don't look past a call which might throw. This is an 1180 // issue because MemoryDependenceAnalysis works in the wrong direction: 1181 // it finds instructions which dominate the current instruction, rather than 1182 // instructions which are post-dominated by the current instruction. 1183 // 1184 // If the underlying object is a non-escaping memory allocation, any store 1185 // to it is dead along the unwind edge. Otherwise, we need to preserve 1186 // the store. 1187 if (LastThrowing && OBB.dominates(DepWrite, LastThrowing)) { 1188 const Value* Underlying = GetUnderlyingObject(DepLoc.Ptr, DL); 1189 bool IsStoreDeadOnUnwind = isa<AllocaInst>(Underlying); 1190 if (!IsStoreDeadOnUnwind) { 1191 // We're looking for a call to an allocation function 1192 // where the allocation doesn't escape before the last 1193 // throwing instruction; PointerMayBeCaptured 1194 // reasonably fast approximation. 1195 IsStoreDeadOnUnwind = isAllocLikeFn(Underlying, TLI) && 1196 !PointerMayBeCaptured(Underlying, false, true); 1197 } 1198 if (!IsStoreDeadOnUnwind) 1199 break; 1200 } 1201 1202 // If we find a write that is a) removable (i.e., non-volatile), b) is 1203 // completely obliterated by the store to 'Loc', and c) which we know that 1204 // 'Inst' doesn't load from, then we can remove it. 1205 // Also try to merge two stores if a later one only touches memory written 1206 // to by the earlier one. 1207 if (isRemovable(DepWrite) && 1208 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) { 1209 int64_t InstWriteOffset, DepWriteOffset; 1210 OverwriteResult OR = isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, 1211 InstWriteOffset, DepWrite, IOL, *AA, 1212 BB.getParent()); 1213 if (OR == OW_Complete) { 1214 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *DepWrite 1215 << "\n KILLER: " << *Inst << '\n'); 1216 1217 // Delete the store and now-dead instructions that feed it. 1218 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, OBB, 1219 ThrowableInst); 1220 ++NumFastStores; 1221 MadeChange = true; 1222 1223 // We erased DepWrite; start over. 1224 InstDep = MD->getDependency(Inst, &OBB); 1225 continue; 1226 } else if ((OR == OW_End && isShortenableAtTheEnd(DepWrite)) || 1227 ((OR == OW_Begin && 1228 isShortenableAtTheBeginning(DepWrite)))) { 1229 assert(!EnablePartialOverwriteTracking && "Do not expect to perform " 1230 "when partial-overwrite " 1231 "tracking is enabled"); 1232 // The overwrite result is known, so these must be known, too. 1233 int64_t EarlierSize = DepLoc.Size.getValue(); 1234 int64_t LaterSize = Loc.Size.getValue(); 1235 bool IsOverwriteEnd = (OR == OW_End); 1236 MadeChange |= tryToShorten(DepWrite, DepWriteOffset, EarlierSize, 1237 InstWriteOffset, LaterSize, IsOverwriteEnd); 1238 } else if (EnablePartialStoreMerging && 1239 OR == OW_PartialEarlierWithFullLater) { 1240 auto *Earlier = dyn_cast<StoreInst>(DepWrite); 1241 auto *Later = dyn_cast<StoreInst>(Inst); 1242 if (Earlier && isa<ConstantInt>(Earlier->getValueOperand()) && 1243 DL.typeSizeEqualsStoreSize( 1244 Earlier->getValueOperand()->getType()) && 1245 Later && isa<ConstantInt>(Later->getValueOperand()) && 1246 DL.typeSizeEqualsStoreSize( 1247 Later->getValueOperand()->getType()) && 1248 memoryIsNotModifiedBetween(Earlier, Later, AA)) { 1249 // If the store we find is: 1250 // a) partially overwritten by the store to 'Loc' 1251 // b) the later store is fully contained in the earlier one and 1252 // c) they both have a constant value 1253 // d) none of the two stores need padding 1254 // Merge the two stores, replacing the earlier store's value with a 1255 // merge of both values. 1256 // TODO: Deal with other constant types (vectors, etc), and probably 1257 // some mem intrinsics (if needed) 1258 1259 APInt EarlierValue = 1260 cast<ConstantInt>(Earlier->getValueOperand())->getValue(); 1261 APInt LaterValue = 1262 cast<ConstantInt>(Later->getValueOperand())->getValue(); 1263 unsigned LaterBits = LaterValue.getBitWidth(); 1264 assert(EarlierValue.getBitWidth() > LaterValue.getBitWidth()); 1265 LaterValue = LaterValue.zext(EarlierValue.getBitWidth()); 1266 1267 // Offset of the smaller store inside the larger store 1268 unsigned BitOffsetDiff = (InstWriteOffset - DepWriteOffset) * 8; 1269 unsigned LShiftAmount = 1270 DL.isBigEndian() 1271 ? EarlierValue.getBitWidth() - BitOffsetDiff - LaterBits 1272 : BitOffsetDiff; 1273 APInt Mask = 1274 APInt::getBitsSet(EarlierValue.getBitWidth(), LShiftAmount, 1275 LShiftAmount + LaterBits); 1276 // Clear the bits we'll be replacing, then OR with the smaller 1277 // store, shifted appropriately. 1278 APInt Merged = 1279 (EarlierValue & ~Mask) | (LaterValue << LShiftAmount); 1280 LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n Earlier: " << *DepWrite 1281 << "\n Later: " << *Inst 1282 << "\n Merged Value: " << Merged << '\n'); 1283 1284 auto *SI = new StoreInst( 1285 ConstantInt::get(Earlier->getValueOperand()->getType(), Merged), 1286 Earlier->getPointerOperand(), false, 1287 MaybeAlign(Earlier->getAlignment()), Earlier->getOrdering(), 1288 Earlier->getSyncScopeID(), DepWrite); 1289 1290 unsigned MDToKeep[] = {LLVMContext::MD_dbg, LLVMContext::MD_tbaa, 1291 LLVMContext::MD_alias_scope, 1292 LLVMContext::MD_noalias, 1293 LLVMContext::MD_nontemporal}; 1294 SI->copyMetadata(*DepWrite, MDToKeep); 1295 ++NumModifiedStores; 1296 1297 // Remove earlier, wider, store 1298 OBB.replaceInstruction(DepWrite, SI); 1299 1300 // Delete the old stores and now-dead instructions that feed them. 1301 deleteDeadInstruction(Inst, &BBI, *MD, *TLI, IOL, OBB, 1302 ThrowableInst); 1303 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, OBB, 1304 ThrowableInst); 1305 MadeChange = true; 1306 1307 // We erased DepWrite and Inst (Loc); start over. 1308 break; 1309 } 1310 } 1311 } 1312 1313 // If this is a may-aliased store that is clobbering the store value, we 1314 // can keep searching past it for another must-aliased pointer that stores 1315 // to the same location. For example, in: 1316 // store -> P 1317 // store -> Q 1318 // store -> P 1319 // we can remove the first store to P even though we don't know if P and Q 1320 // alias. 1321 if (DepWrite == &BB.front()) break; 1322 1323 // Can't look past this instruction if it might read 'Loc'. 1324 if (isRefSet(AA->getModRefInfo(DepWrite, Loc))) 1325 break; 1326 1327 InstDep = MD->getPointerDependencyFrom(Loc, /*isLoad=*/ false, 1328 DepWrite->getIterator(), &BB, 1329 /*QueryInst=*/ nullptr, &Limit); 1330 } 1331 } 1332 1333 if (EnablePartialOverwriteTracking) 1334 MadeChange |= removePartiallyOverlappedStores(AA, DL, IOL); 1335 1336 // If this block ends in a return, unwind, or unreachable, all allocas are 1337 // dead at its end, which means stores to them are also dead. 1338 if (BB.getTerminator()->getNumSuccessors() == 0) 1339 MadeChange |= handleEndBlock(BB, AA, MD, TLI, IOL, OBB, ThrowableInst); 1340 1341 return MadeChange; 1342 } 1343 1344 static bool eliminateDeadStores(Function &F, AliasAnalysis *AA, 1345 MemoryDependenceResults *MD, DominatorTree *DT, 1346 const TargetLibraryInfo *TLI) { 1347 bool MadeChange = false; 1348 for (BasicBlock &BB : F) 1349 // Only check non-dead blocks. Dead blocks may have strange pointer 1350 // cycles that will confuse alias analysis. 1351 if (DT->isReachableFromEntry(&BB)) 1352 MadeChange |= eliminateDeadStores(BB, AA, MD, DT, TLI); 1353 1354 return MadeChange; 1355 } 1356 1357 //===----------------------------------------------------------------------===// 1358 // DSE Pass 1359 //===----------------------------------------------------------------------===// 1360 PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) { 1361 AliasAnalysis *AA = &AM.getResult<AAManager>(F); 1362 DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F); 1363 MemoryDependenceResults *MD = &AM.getResult<MemoryDependenceAnalysis>(F); 1364 const TargetLibraryInfo *TLI = &AM.getResult<TargetLibraryAnalysis>(F); 1365 1366 if (!eliminateDeadStores(F, AA, MD, DT, TLI)) 1367 return PreservedAnalyses::all(); 1368 1369 PreservedAnalyses PA; 1370 PA.preserveSet<CFGAnalyses>(); 1371 PA.preserve<GlobalsAA>(); 1372 PA.preserve<MemoryDependenceAnalysis>(); 1373 return PA; 1374 } 1375 1376 namespace { 1377 1378 /// A legacy pass for the legacy pass manager that wraps \c DSEPass. 1379 class DSELegacyPass : public FunctionPass { 1380 public: 1381 static char ID; // Pass identification, replacement for typeid 1382 1383 DSELegacyPass() : FunctionPass(ID) { 1384 initializeDSELegacyPassPass(*PassRegistry::getPassRegistry()); 1385 } 1386 1387 bool runOnFunction(Function &F) override { 1388 if (skipFunction(F)) 1389 return false; 1390 1391 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1392 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 1393 MemoryDependenceResults *MD = 1394 &getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); 1395 const TargetLibraryInfo *TLI = 1396 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 1397 1398 return eliminateDeadStores(F, AA, MD, DT, TLI); 1399 } 1400 1401 void getAnalysisUsage(AnalysisUsage &AU) const override { 1402 AU.setPreservesCFG(); 1403 AU.addRequired<DominatorTreeWrapperPass>(); 1404 AU.addRequired<AAResultsWrapperPass>(); 1405 AU.addRequired<MemoryDependenceWrapperPass>(); 1406 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1407 AU.addPreserved<DominatorTreeWrapperPass>(); 1408 AU.addPreserved<GlobalsAAWrapperPass>(); 1409 AU.addPreserved<MemoryDependenceWrapperPass>(); 1410 } 1411 }; 1412 1413 } // end anonymous namespace 1414 1415 char DSELegacyPass::ID = 0; 1416 1417 INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false, 1418 false) 1419 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1420 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1421 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 1422 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 1423 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1424 INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false, 1425 false) 1426 1427 FunctionPass *llvm::createDeadStoreEliminationPass() { 1428 return new DSELegacyPass(); 1429 } 1430