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/MemorySSA.h" 33 #include "llvm/Analysis/MemorySSAUpdater.h" 34 #include "llvm/Analysis/PostDominators.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/Analysis/ValueTracking.h" 37 #include "llvm/IR/Argument.h" 38 #include "llvm/IR/BasicBlock.h" 39 #include "llvm/IR/CallSite.h" 40 #include "llvm/IR/Constant.h" 41 #include "llvm/IR/Constants.h" 42 #include "llvm/IR/DataLayout.h" 43 #include "llvm/IR/Dominators.h" 44 #include "llvm/IR/Function.h" 45 #include "llvm/IR/InstIterator.h" 46 #include "llvm/IR/InstrTypes.h" 47 #include "llvm/IR/Instruction.h" 48 #include "llvm/IR/Instructions.h" 49 #include "llvm/IR/IntrinsicInst.h" 50 #include "llvm/IR/Intrinsics.h" 51 #include "llvm/IR/LLVMContext.h" 52 #include "llvm/IR/Module.h" 53 #include "llvm/IR/PassManager.h" 54 #include "llvm/IR/Value.h" 55 #include "llvm/InitializePasses.h" 56 #include "llvm/Pass.h" 57 #include "llvm/Support/Casting.h" 58 #include "llvm/Support/CommandLine.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/DebugCounter.h" 61 #include "llvm/Support/ErrorHandling.h" 62 #include "llvm/Support/MathExtras.h" 63 #include "llvm/Support/raw_ostream.h" 64 #include "llvm/Transforms/Scalar.h" 65 #include "llvm/Transforms/Utils/Local.h" 66 #include <algorithm> 67 #include <cassert> 68 #include <cstddef> 69 #include <cstdint> 70 #include <iterator> 71 #include <map> 72 #include <utility> 73 74 using namespace llvm; 75 76 #define DEBUG_TYPE "dse" 77 78 STATISTIC(NumRedundantStores, "Number of redundant stores deleted"); 79 STATISTIC(NumFastStores, "Number of stores deleted"); 80 STATISTIC(NumFastOther, "Number of other instrs removed"); 81 STATISTIC(NumCompletePartials, "Number of stores dead by later partials"); 82 STATISTIC(NumModifiedStores, "Number of stores modified"); 83 84 DEBUG_COUNTER(MemorySSACounter, "dse-memoryssa", 85 "Controls which MemoryDefs are eliminated."); 86 87 static cl::opt<bool> 88 EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking", 89 cl::init(true), cl::Hidden, 90 cl::desc("Enable partial-overwrite tracking in DSE")); 91 92 static cl::opt<bool> 93 EnablePartialStoreMerging("enable-dse-partial-store-merging", 94 cl::init(true), cl::Hidden, 95 cl::desc("Enable partial store merging in DSE")); 96 97 static cl::opt<bool> 98 EnableMemorySSA("enable-dse-memoryssa", cl::init(false), cl::Hidden, 99 cl::desc("Use the new MemorySSA-backed DSE.")); 100 101 static cl::opt<unsigned> 102 MemorySSAScanLimit("dse-memoryssa-scanlimit", cl::init(100), cl::Hidden, 103 cl::desc("The number of memory instructions to scan for " 104 "dead store elimination (default = 100)")); 105 106 static cl::opt<unsigned> MemorySSADefsPerBlockLimit( 107 "dse-memoryssa-defs-per-block-limit", cl::init(5000), cl::Hidden, 108 cl::desc("The number of MemoryDefs we consider as candidates to eliminated " 109 "other stores per basic block (default = 5000)")); 110 111 //===----------------------------------------------------------------------===// 112 // Helper functions 113 //===----------------------------------------------------------------------===// 114 using OverlapIntervalsTy = std::map<int64_t, int64_t>; 115 using InstOverlapIntervalsTy = DenseMap<Instruction *, OverlapIntervalsTy>; 116 117 /// Delete this instruction. Before we do, go through and zero out all the 118 /// operands of this instruction. If any of them become dead, delete them and 119 /// the computation tree that feeds them. 120 /// If ValueSet is non-null, remove any deleted instructions from it as well. 121 static void 122 deleteDeadInstruction(Instruction *I, BasicBlock::iterator *BBI, 123 MemoryDependenceResults &MD, const TargetLibraryInfo &TLI, 124 InstOverlapIntervalsTy &IOL, 125 MapVector<Instruction *, bool> &ThrowableInst, 126 SmallSetVector<const Value *, 16> *ValueSet = nullptr) { 127 SmallVector<Instruction*, 32> NowDeadInsts; 128 129 NowDeadInsts.push_back(I); 130 --NumFastOther; 131 132 // Keeping the iterator straight is a pain, so we let this routine tell the 133 // caller what the next instruction is after we're done mucking about. 134 BasicBlock::iterator NewIter = *BBI; 135 136 // Before we touch this instruction, remove it from memdep! 137 do { 138 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 139 // Mark the DeadInst as dead in the list of throwable instructions. 140 auto It = ThrowableInst.find(DeadInst); 141 if (It != ThrowableInst.end()) 142 ThrowableInst[It->first] = false; 143 ++NumFastOther; 144 145 // Try to preserve debug information attached to the dead instruction. 146 salvageDebugInfo(*DeadInst); 147 148 // This instruction is dead, zap it, in stages. Start by removing it from 149 // MemDep, which needs to know the operands and needs it to be in the 150 // function. 151 MD.removeInstruction(DeadInst); 152 153 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) { 154 Value *Op = DeadInst->getOperand(op); 155 DeadInst->setOperand(op, nullptr); 156 157 // If this operand just became dead, add it to the NowDeadInsts list. 158 if (!Op->use_empty()) continue; 159 160 if (Instruction *OpI = dyn_cast<Instruction>(Op)) 161 if (isInstructionTriviallyDead(OpI, &TLI)) 162 NowDeadInsts.push_back(OpI); 163 } 164 165 if (ValueSet) ValueSet->remove(DeadInst); 166 IOL.erase(DeadInst); 167 168 if (NewIter == DeadInst->getIterator()) 169 NewIter = DeadInst->eraseFromParent(); 170 else 171 DeadInst->eraseFromParent(); 172 } while (!NowDeadInsts.empty()); 173 *BBI = NewIter; 174 // Pop dead entries from back of ThrowableInst till we find an alive entry. 175 while (!ThrowableInst.empty() && !ThrowableInst.back().second) 176 ThrowableInst.pop_back(); 177 } 178 179 /// Does this instruction write some memory? This only returns true for things 180 /// that we can analyze with other helpers below. 181 static bool hasAnalyzableMemoryWrite(Instruction *I, 182 const TargetLibraryInfo &TLI) { 183 if (isa<StoreInst>(I)) 184 return true; 185 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 186 switch (II->getIntrinsicID()) { 187 default: 188 return false; 189 case Intrinsic::memset: 190 case Intrinsic::memmove: 191 case Intrinsic::memcpy: 192 case Intrinsic::memcpy_element_unordered_atomic: 193 case Intrinsic::memmove_element_unordered_atomic: 194 case Intrinsic::memset_element_unordered_atomic: 195 case Intrinsic::init_trampoline: 196 case Intrinsic::lifetime_end: 197 return true; 198 } 199 } 200 if (auto CS = CallSite(I)) { 201 if (Function *F = CS.getCalledFunction()) { 202 LibFunc LF; 203 if (TLI.getLibFunc(*F, LF) && TLI.has(LF)) { 204 switch (LF) { 205 case LibFunc_strcpy: 206 case LibFunc_strncpy: 207 case LibFunc_strcat: 208 case LibFunc_strncat: 209 return true; 210 default: 211 return false; 212 } 213 } 214 } 215 } 216 return false; 217 } 218 219 /// Return a Location stored to by the specified instruction. If isRemovable 220 /// returns true, this function and getLocForRead completely describe the memory 221 /// operations for this instruction. 222 static MemoryLocation getLocForWrite(Instruction *Inst) { 223 224 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 225 return MemoryLocation::get(SI); 226 227 if (auto *MI = dyn_cast<AnyMemIntrinsic>(Inst)) { 228 // memcpy/memmove/memset. 229 MemoryLocation Loc = MemoryLocation::getForDest(MI); 230 return Loc; 231 } 232 233 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 234 switch (II->getIntrinsicID()) { 235 default: 236 return MemoryLocation(); // Unhandled intrinsic. 237 case Intrinsic::init_trampoline: 238 return MemoryLocation(II->getArgOperand(0)); 239 case Intrinsic::lifetime_end: { 240 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(); 241 return MemoryLocation(II->getArgOperand(1), Len); 242 } 243 } 244 } 245 if (auto CS = CallSite(Inst)) 246 // All the supported TLI functions so far happen to have dest as their 247 // first argument. 248 return MemoryLocation(CS.getArgument(0)); 249 return MemoryLocation(); 250 } 251 252 /// Return the location read by the specified "hasAnalyzableMemoryWrite" 253 /// instruction if any. 254 static MemoryLocation getLocForRead(Instruction *Inst, 255 const TargetLibraryInfo &TLI) { 256 assert(hasAnalyzableMemoryWrite(Inst, TLI) && "Unknown instruction case"); 257 258 // The only instructions that both read and write are the mem transfer 259 // instructions (memcpy/memmove). 260 if (auto *MTI = dyn_cast<AnyMemTransferInst>(Inst)) 261 return MemoryLocation::getForSource(MTI); 262 return MemoryLocation(); 263 } 264 265 /// If the value of this instruction and the memory it writes to is unused, may 266 /// we delete this instruction? 267 static bool isRemovable(Instruction *I) { 268 // Don't remove volatile/atomic stores. 269 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 270 return SI->isUnordered(); 271 272 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 273 switch (II->getIntrinsicID()) { 274 default: llvm_unreachable("doesn't pass 'hasAnalyzableMemoryWrite' predicate"); 275 case Intrinsic::lifetime_end: 276 // Never remove dead lifetime_end's, e.g. because it is followed by a 277 // free. 278 return false; 279 case Intrinsic::init_trampoline: 280 // Always safe to remove init_trampoline. 281 return true; 282 case Intrinsic::memset: 283 case Intrinsic::memmove: 284 case Intrinsic::memcpy: 285 // Don't remove volatile memory intrinsics. 286 return !cast<MemIntrinsic>(II)->isVolatile(); 287 case Intrinsic::memcpy_element_unordered_atomic: 288 case Intrinsic::memmove_element_unordered_atomic: 289 case Intrinsic::memset_element_unordered_atomic: 290 return true; 291 } 292 } 293 294 // note: only get here for calls with analyzable writes - i.e. libcalls 295 if (auto CS = CallSite(I)) 296 return CS.getInstruction()->use_empty(); 297 298 return false; 299 } 300 301 /// Returns true if the end of this instruction can be safely shortened in 302 /// length. 303 static bool isShortenableAtTheEnd(Instruction *I) { 304 // Don't shorten stores for now 305 if (isa<StoreInst>(I)) 306 return false; 307 308 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 309 switch (II->getIntrinsicID()) { 310 default: return false; 311 case Intrinsic::memset: 312 case Intrinsic::memcpy: 313 case Intrinsic::memcpy_element_unordered_atomic: 314 case Intrinsic::memset_element_unordered_atomic: 315 // Do shorten memory intrinsics. 316 // FIXME: Add memmove if it's also safe to transform. 317 return true; 318 } 319 } 320 321 // Don't shorten libcalls calls for now. 322 323 return false; 324 } 325 326 /// Returns true if the beginning of this instruction can be safely shortened 327 /// in length. 328 static bool isShortenableAtTheBeginning(Instruction *I) { 329 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be 330 // easily done by offsetting the source address. 331 return isa<AnyMemSetInst>(I); 332 } 333 334 /// Return the pointer that is being written to. 335 static Value *getStoredPointerOperand(Instruction *I) { 336 //TODO: factor this to reuse getLocForWrite 337 MemoryLocation Loc = getLocForWrite(I); 338 assert(Loc.Ptr && 339 "unable to find pointer written for analyzable instruction?"); 340 // TODO: most APIs don't expect const Value * 341 return const_cast<Value*>(Loc.Ptr); 342 } 343 344 static uint64_t getPointerSize(const Value *V, const DataLayout &DL, 345 const TargetLibraryInfo &TLI, 346 const Function *F) { 347 uint64_t Size; 348 ObjectSizeOpts Opts; 349 Opts.NullIsUnknownSize = NullPointerIsDefined(F); 350 351 if (getObjectSize(V, Size, DL, &TLI, Opts)) 352 return Size; 353 return MemoryLocation::UnknownSize; 354 } 355 356 namespace { 357 358 enum OverwriteResult { 359 OW_Begin, 360 OW_Complete, 361 OW_End, 362 OW_PartialEarlierWithFullLater, 363 OW_Unknown 364 }; 365 366 } // end anonymous namespace 367 368 /// Return 'OW_Complete' if a store to the 'Later' location completely 369 /// overwrites a store to the 'Earlier' location, 'OW_End' if the end of the 370 /// 'Earlier' location is completely overwritten by 'Later', 'OW_Begin' if the 371 /// beginning of the 'Earlier' location is overwritten by 'Later'. 372 /// 'OW_PartialEarlierWithFullLater' means that an earlier (big) store was 373 /// overwritten by a latter (smaller) store which doesn't write outside the big 374 /// store's memory locations. Returns 'OW_Unknown' if nothing can be determined. 375 static OverwriteResult isOverwrite(const MemoryLocation &Later, 376 const MemoryLocation &Earlier, 377 const DataLayout &DL, 378 const TargetLibraryInfo &TLI, 379 int64_t &EarlierOff, int64_t &LaterOff, 380 Instruction *DepWrite, 381 InstOverlapIntervalsTy &IOL, 382 AliasAnalysis &AA, 383 const Function *F) { 384 // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll 385 // get imprecise values here, though (except for unknown sizes). 386 if (!Later.Size.isPrecise() || !Earlier.Size.isPrecise()) 387 return OW_Unknown; 388 389 const uint64_t LaterSize = Later.Size.getValue(); 390 const uint64_t EarlierSize = Earlier.Size.getValue(); 391 392 const Value *P1 = Earlier.Ptr->stripPointerCasts(); 393 const Value *P2 = Later.Ptr->stripPointerCasts(); 394 395 // If the start pointers are the same, we just have to compare sizes to see if 396 // the later store was larger than the earlier store. 397 if (P1 == P2 || AA.isMustAlias(P1, P2)) { 398 // Make sure that the Later size is >= the Earlier size. 399 if (LaterSize >= EarlierSize) 400 return OW_Complete; 401 } 402 403 // Check to see if the later store is to the entire object (either a global, 404 // an alloca, or a byval/inalloca argument). If so, then it clearly 405 // overwrites any other store to the same object. 406 const Value *UO1 = GetUnderlyingObject(P1, DL), 407 *UO2 = GetUnderlyingObject(P2, DL); 408 409 // If we can't resolve the same pointers to the same object, then we can't 410 // analyze them at all. 411 if (UO1 != UO2) 412 return OW_Unknown; 413 414 // If the "Later" store is to a recognizable object, get its size. 415 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI, F); 416 if (ObjectSize != MemoryLocation::UnknownSize) 417 if (ObjectSize == LaterSize && ObjectSize >= EarlierSize) 418 return OW_Complete; 419 420 // Okay, we have stores to two completely different pointers. Try to 421 // decompose the pointer into a "base + constant_offset" form. If the base 422 // pointers are equal, then we can reason about the two stores. 423 EarlierOff = 0; 424 LaterOff = 0; 425 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL); 426 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL); 427 428 // If the base pointers still differ, we have two completely different stores. 429 if (BP1 != BP2) 430 return OW_Unknown; 431 432 // The later store completely overlaps the earlier store if: 433 // 434 // 1. Both start at the same offset and the later one's size is greater than 435 // or equal to the earlier one's, or 436 // 437 // |--earlier--| 438 // |-- later --| 439 // 440 // 2. The earlier store has an offset greater than the later offset, but which 441 // still lies completely within the later store. 442 // 443 // |--earlier--| 444 // |----- later ------| 445 // 446 // We have to be careful here as *Off is signed while *.Size is unsigned. 447 if (EarlierOff >= LaterOff && 448 LaterSize >= EarlierSize && 449 uint64_t(EarlierOff - LaterOff) + EarlierSize <= LaterSize) 450 return OW_Complete; 451 452 // We may now overlap, although the overlap is not complete. There might also 453 // be other incomplete overlaps, and together, they might cover the complete 454 // earlier write. 455 // Note: The correctness of this logic depends on the fact that this function 456 // is not even called providing DepWrite when there are any intervening reads. 457 if (EnablePartialOverwriteTracking && 458 LaterOff < int64_t(EarlierOff + EarlierSize) && 459 int64_t(LaterOff + LaterSize) >= EarlierOff) { 460 461 // Insert our part of the overlap into the map. 462 auto &IM = IOL[DepWrite]; 463 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: Earlier [" << EarlierOff 464 << ", " << int64_t(EarlierOff + EarlierSize) 465 << ") Later [" << LaterOff << ", " 466 << int64_t(LaterOff + LaterSize) << ")\n"); 467 468 // Make sure that we only insert non-overlapping intervals and combine 469 // adjacent intervals. The intervals are stored in the map with the ending 470 // offset as the key (in the half-open sense) and the starting offset as 471 // the value. 472 int64_t LaterIntStart = LaterOff, LaterIntEnd = LaterOff + LaterSize; 473 474 // Find any intervals ending at, or after, LaterIntStart which start 475 // before LaterIntEnd. 476 auto ILI = IM.lower_bound(LaterIntStart); 477 if (ILI != IM.end() && ILI->second <= LaterIntEnd) { 478 // This existing interval is overlapped with the current store somewhere 479 // in [LaterIntStart, LaterIntEnd]. Merge them by erasing the existing 480 // intervals and adjusting our start and end. 481 LaterIntStart = std::min(LaterIntStart, ILI->second); 482 LaterIntEnd = std::max(LaterIntEnd, ILI->first); 483 ILI = IM.erase(ILI); 484 485 // Continue erasing and adjusting our end in case other previous 486 // intervals are also overlapped with the current store. 487 // 488 // |--- ealier 1 ---| |--- ealier 2 ---| 489 // |------- later---------| 490 // 491 while (ILI != IM.end() && ILI->second <= LaterIntEnd) { 492 assert(ILI->second > LaterIntStart && "Unexpected interval"); 493 LaterIntEnd = std::max(LaterIntEnd, ILI->first); 494 ILI = IM.erase(ILI); 495 } 496 } 497 498 IM[LaterIntEnd] = LaterIntStart; 499 500 ILI = IM.begin(); 501 if (ILI->second <= EarlierOff && 502 ILI->first >= int64_t(EarlierOff + EarlierSize)) { 503 LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: Earlier [" 504 << EarlierOff << ", " 505 << int64_t(EarlierOff + EarlierSize) 506 << ") Composite Later [" << ILI->second << ", " 507 << ILI->first << ")\n"); 508 ++NumCompletePartials; 509 return OW_Complete; 510 } 511 } 512 513 // Check for an earlier store which writes to all the memory locations that 514 // the later store writes to. 515 if (EnablePartialStoreMerging && LaterOff >= EarlierOff && 516 int64_t(EarlierOff + EarlierSize) > LaterOff && 517 uint64_t(LaterOff - EarlierOff) + LaterSize <= EarlierSize) { 518 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite an earlier load [" 519 << EarlierOff << ", " 520 << int64_t(EarlierOff + EarlierSize) 521 << ") by a later store [" << LaterOff << ", " 522 << int64_t(LaterOff + LaterSize) << ")\n"); 523 // TODO: Maybe come up with a better name? 524 return OW_PartialEarlierWithFullLater; 525 } 526 527 // Another interesting case is if the later store overwrites the end of the 528 // earlier store. 529 // 530 // |--earlier--| 531 // |-- later --| 532 // 533 // In this case we may want to trim the size of earlier to avoid generating 534 // writes to addresses which will definitely be overwritten later 535 if (!EnablePartialOverwriteTracking && 536 (LaterOff > EarlierOff && LaterOff < int64_t(EarlierOff + EarlierSize) && 537 int64_t(LaterOff + LaterSize) >= int64_t(EarlierOff + EarlierSize))) 538 return OW_End; 539 540 // Finally, we also need to check if the later store overwrites the beginning 541 // of the earlier store. 542 // 543 // |--earlier--| 544 // |-- later --| 545 // 546 // In this case we may want to move the destination address and trim the size 547 // of earlier to avoid generating writes to addresses which will definitely 548 // be overwritten later. 549 if (!EnablePartialOverwriteTracking && 550 (LaterOff <= EarlierOff && int64_t(LaterOff + LaterSize) > EarlierOff)) { 551 assert(int64_t(LaterOff + LaterSize) < int64_t(EarlierOff + EarlierSize) && 552 "Expect to be handled as OW_Complete"); 553 return OW_Begin; 554 } 555 // Otherwise, they don't completely overlap. 556 return OW_Unknown; 557 } 558 559 /// If 'Inst' might be a self read (i.e. a noop copy of a 560 /// memory region into an identical pointer) then it doesn't actually make its 561 /// input dead in the traditional sense. Consider this case: 562 /// 563 /// memmove(A <- B) 564 /// memmove(A <- A) 565 /// 566 /// In this case, the second store to A does not make the first store to A dead. 567 /// The usual situation isn't an explicit A<-A store like this (which can be 568 /// trivially removed) but a case where two pointers may alias. 569 /// 570 /// This function detects when it is unsafe to remove a dependent instruction 571 /// because the DSE inducing instruction may be a self-read. 572 static bool isPossibleSelfRead(Instruction *Inst, 573 const MemoryLocation &InstStoreLoc, 574 Instruction *DepWrite, 575 const TargetLibraryInfo &TLI, 576 AliasAnalysis &AA) { 577 // Self reads can only happen for instructions that read memory. Get the 578 // location read. 579 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI); 580 if (!InstReadLoc.Ptr) 581 return false; // Not a reading instruction. 582 583 // If the read and written loc obviously don't alias, it isn't a read. 584 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) 585 return false; 586 587 if (isa<AnyMemCpyInst>(Inst)) { 588 // LLVM's memcpy overlap semantics are not fully fleshed out (see PR11763) 589 // but in practice memcpy(A <- B) either means that A and B are disjoint or 590 // are equal (i.e. there are not partial overlaps). Given that, if we have: 591 // 592 // memcpy/memmove(A <- B) // DepWrite 593 // memcpy(A <- B) // Inst 594 // 595 // with Inst reading/writing a >= size than DepWrite, we can reason as 596 // follows: 597 // 598 // - If A == B then both the copies are no-ops, so the DepWrite can be 599 // removed. 600 // - If A != B then A and B are disjoint locations in Inst. Since 601 // Inst.size >= DepWrite.size A and B are disjoint in DepWrite too. 602 // Therefore DepWrite can be removed. 603 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI); 604 605 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr)) 606 return false; 607 } 608 609 // If DepWrite doesn't read memory or if we can't prove it is a must alias, 610 // then it can't be considered dead. 611 return true; 612 } 613 614 /// Returns true if the memory which is accessed by the second instruction is not 615 /// modified between the first and the second instruction. 616 /// Precondition: Second instruction must be dominated by the first 617 /// instruction. 618 static bool memoryIsNotModifiedBetween(Instruction *FirstI, 619 Instruction *SecondI, 620 AliasAnalysis *AA) { 621 SmallVector<BasicBlock *, 16> WorkList; 622 SmallPtrSet<BasicBlock *, 8> Visited; 623 BasicBlock::iterator FirstBBI(FirstI); 624 ++FirstBBI; 625 BasicBlock::iterator SecondBBI(SecondI); 626 BasicBlock *FirstBB = FirstI->getParent(); 627 BasicBlock *SecondBB = SecondI->getParent(); 628 MemoryLocation MemLoc = MemoryLocation::get(SecondI); 629 630 // Start checking the SecondBB. 631 WorkList.push_back(SecondBB); 632 bool isFirstBlock = true; 633 634 // Check all blocks going backward until we reach the FirstBB. 635 while (!WorkList.empty()) { 636 BasicBlock *B = WorkList.pop_back_val(); 637 638 // Ignore instructions before FirstI if this is the FirstBB. 639 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin()); 640 641 BasicBlock::iterator EI; 642 if (isFirstBlock) { 643 // Ignore instructions after SecondI if this is the first visit of SecondBB. 644 assert(B == SecondBB && "first block is not the store block"); 645 EI = SecondBBI; 646 isFirstBlock = false; 647 } else { 648 // It's not SecondBB or (in case of a loop) the second visit of SecondBB. 649 // In this case we also have to look at instructions after SecondI. 650 EI = B->end(); 651 } 652 for (; BI != EI; ++BI) { 653 Instruction *I = &*BI; 654 if (I->mayWriteToMemory() && I != SecondI) 655 if (isModSet(AA->getModRefInfo(I, MemLoc))) 656 return false; 657 } 658 if (B != FirstBB) { 659 assert(B != &FirstBB->getParent()->getEntryBlock() && 660 "Should not hit the entry block because SI must be dominated by LI"); 661 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) { 662 if (!Visited.insert(*PredI).second) 663 continue; 664 WorkList.push_back(*PredI); 665 } 666 } 667 } 668 return true; 669 } 670 671 /// Find all blocks that will unconditionally lead to the block BB and append 672 /// them to F. 673 static void findUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks, 674 BasicBlock *BB, DominatorTree *DT) { 675 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) { 676 BasicBlock *Pred = *I; 677 if (Pred == BB) continue; 678 Instruction *PredTI = Pred->getTerminator(); 679 if (PredTI->getNumSuccessors() != 1) 680 continue; 681 682 if (DT->isReachableFromEntry(Pred)) 683 Blocks.push_back(Pred); 684 } 685 } 686 687 /// Handle frees of entire structures whose dependency is a store 688 /// to a field of that structure. 689 static bool handleFree(CallInst *F, AliasAnalysis *AA, 690 MemoryDependenceResults *MD, DominatorTree *DT, 691 const TargetLibraryInfo *TLI, 692 InstOverlapIntervalsTy &IOL, 693 MapVector<Instruction *, bool> &ThrowableInst) { 694 bool MadeChange = false; 695 696 MemoryLocation Loc = MemoryLocation(F->getOperand(0)); 697 SmallVector<BasicBlock *, 16> Blocks; 698 Blocks.push_back(F->getParent()); 699 const DataLayout &DL = F->getModule()->getDataLayout(); 700 701 while (!Blocks.empty()) { 702 BasicBlock *BB = Blocks.pop_back_val(); 703 Instruction *InstPt = BB->getTerminator(); 704 if (BB == F->getParent()) InstPt = F; 705 706 MemDepResult Dep = 707 MD->getPointerDependencyFrom(Loc, false, InstPt->getIterator(), BB); 708 while (Dep.isDef() || Dep.isClobber()) { 709 Instruction *Dependency = Dep.getInst(); 710 if (!hasAnalyzableMemoryWrite(Dependency, *TLI) || 711 !isRemovable(Dependency)) 712 break; 713 714 Value *DepPointer = 715 GetUnderlyingObject(getStoredPointerOperand(Dependency), DL); 716 717 // Check for aliasing. 718 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer)) 719 break; 720 721 LLVM_DEBUG( 722 dbgs() << "DSE: Dead Store to soon to be freed memory:\n DEAD: " 723 << *Dependency << '\n'); 724 725 // DCE instructions only used to calculate that store. 726 BasicBlock::iterator BBI(Dependency); 727 deleteDeadInstruction(Dependency, &BBI, *MD, *TLI, IOL, 728 ThrowableInst); 729 ++NumFastStores; 730 MadeChange = true; 731 732 // Inst's old Dependency is now deleted. Compute the next dependency, 733 // which may also be dead, as in 734 // s[0] = 0; 735 // s[1] = 0; // This has just been deleted. 736 // free(s); 737 Dep = MD->getPointerDependencyFrom(Loc, false, BBI, BB); 738 } 739 740 if (Dep.isNonLocal()) 741 findUnconditionalPreds(Blocks, BB, DT); 742 } 743 744 return MadeChange; 745 } 746 747 /// Check to see if the specified location may alias any of the stack objects in 748 /// the DeadStackObjects set. If so, they become live because the location is 749 /// being loaded. 750 static void removeAccessedObjects(const MemoryLocation &LoadedLoc, 751 SmallSetVector<const Value *, 16> &DeadStackObjects, 752 const DataLayout &DL, AliasAnalysis *AA, 753 const TargetLibraryInfo *TLI, 754 const Function *F) { 755 const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL); 756 757 // A constant can't be in the dead pointer set. 758 if (isa<Constant>(UnderlyingPointer)) 759 return; 760 761 // If the kill pointer can be easily reduced to an alloca, don't bother doing 762 // extraneous AA queries. 763 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) { 764 DeadStackObjects.remove(UnderlyingPointer); 765 return; 766 } 767 768 // Remove objects that could alias LoadedLoc. 769 DeadStackObjects.remove_if([&](const Value *I) { 770 // See if the loaded location could alias the stack location. 771 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI, F)); 772 return !AA->isNoAlias(StackLoc, LoadedLoc); 773 }); 774 } 775 776 /// Remove dead stores to stack-allocated locations in the function end block. 777 /// Ex: 778 /// %A = alloca i32 779 /// ... 780 /// store i32 1, i32* %A 781 /// ret void 782 static bool handleEndBlock(BasicBlock &BB, AliasAnalysis *AA, 783 MemoryDependenceResults *MD, 784 const TargetLibraryInfo *TLI, 785 InstOverlapIntervalsTy &IOL, 786 MapVector<Instruction *, bool> &ThrowableInst) { 787 bool MadeChange = false; 788 789 // Keep track of all of the stack objects that are dead at the end of the 790 // function. 791 SmallSetVector<const Value*, 16> DeadStackObjects; 792 793 // Find all of the alloca'd pointers in the entry block. 794 BasicBlock &Entry = BB.getParent()->front(); 795 for (Instruction &I : Entry) { 796 if (isa<AllocaInst>(&I)) 797 DeadStackObjects.insert(&I); 798 799 // Okay, so these are dead heap objects, but if the pointer never escapes 800 // then it's leaked by this function anyways. 801 else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true)) 802 DeadStackObjects.insert(&I); 803 } 804 805 // Treat byval or inalloca arguments the same, stores to them are dead at the 806 // end of the function. 807 for (Argument &AI : BB.getParent()->args()) 808 if (AI.hasByValOrInAllocaAttr()) 809 DeadStackObjects.insert(&AI); 810 811 const DataLayout &DL = BB.getModule()->getDataLayout(); 812 813 // Scan the basic block backwards 814 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){ 815 --BBI; 816 817 // If we find a store, check to see if it points into a dead stack value. 818 if (hasAnalyzableMemoryWrite(&*BBI, *TLI) && isRemovable(&*BBI)) { 819 // See through pointer-to-pointer bitcasts 820 SmallVector<const Value *, 4> Pointers; 821 GetUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers, DL); 822 823 // Stores to stack values are valid candidates for removal. 824 bool AllDead = true; 825 for (const Value *Pointer : Pointers) 826 if (!DeadStackObjects.count(Pointer)) { 827 AllDead = false; 828 break; 829 } 830 831 if (AllDead) { 832 Instruction *Dead = &*BBI; 833 834 LLVM_DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: " 835 << *Dead << "\n Objects: "; 836 for (SmallVectorImpl<const Value *>::iterator I = 837 Pointers.begin(), 838 E = Pointers.end(); 839 I != E; ++I) { 840 dbgs() << **I; 841 if (std::next(I) != E) 842 dbgs() << ", "; 843 } dbgs() 844 << '\n'); 845 846 // DCE instructions only used to calculate that store. 847 deleteDeadInstruction(Dead, &BBI, *MD, *TLI, IOL, ThrowableInst, 848 &DeadStackObjects); 849 ++NumFastStores; 850 MadeChange = true; 851 continue; 852 } 853 } 854 855 // Remove any dead non-memory-mutating instructions. 856 if (isInstructionTriviallyDead(&*BBI, TLI)) { 857 LLVM_DEBUG(dbgs() << "DSE: Removing trivially dead instruction:\n DEAD: " 858 << *&*BBI << '\n'); 859 deleteDeadInstruction(&*BBI, &BBI, *MD, *TLI, IOL, ThrowableInst, 860 &DeadStackObjects); 861 ++NumFastOther; 862 MadeChange = true; 863 continue; 864 } 865 866 if (isa<AllocaInst>(BBI)) { 867 // Remove allocas from the list of dead stack objects; there can't be 868 // any references before the definition. 869 DeadStackObjects.remove(&*BBI); 870 continue; 871 } 872 873 if (auto *Call = dyn_cast<CallBase>(&*BBI)) { 874 // Remove allocation function calls from the list of dead stack objects; 875 // there can't be any references before the definition. 876 if (isAllocLikeFn(&*BBI, TLI)) 877 DeadStackObjects.remove(&*BBI); 878 879 // If this call does not access memory, it can't be loading any of our 880 // pointers. 881 if (AA->doesNotAccessMemory(Call)) 882 continue; 883 884 // If the call might load from any of our allocas, then any store above 885 // the call is live. 886 DeadStackObjects.remove_if([&](const Value *I) { 887 // See if the call site touches the value. 888 return isRefSet(AA->getModRefInfo( 889 Call, I, getPointerSize(I, DL, *TLI, BB.getParent()))); 890 }); 891 892 // If all of the allocas were clobbered by the call then we're not going 893 // to find anything else to process. 894 if (DeadStackObjects.empty()) 895 break; 896 897 continue; 898 } 899 900 // We can remove the dead stores, irrespective of the fence and its ordering 901 // (release/acquire/seq_cst). Fences only constraints the ordering of 902 // already visible stores, it does not make a store visible to other 903 // threads. So, skipping over a fence does not change a store from being 904 // dead. 905 if (isa<FenceInst>(*BBI)) 906 continue; 907 908 MemoryLocation LoadedLoc; 909 910 // If we encounter a use of the pointer, it is no longer considered dead 911 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) { 912 if (!L->isUnordered()) // Be conservative with atomic/volatile load 913 break; 914 LoadedLoc = MemoryLocation::get(L); 915 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) { 916 LoadedLoc = MemoryLocation::get(V); 917 } else if (!BBI->mayReadFromMemory()) { 918 // Instruction doesn't read memory. Note that stores that weren't removed 919 // above will hit this case. 920 continue; 921 } else { 922 // Unknown inst; assume it clobbers everything. 923 break; 924 } 925 926 // Remove any allocas from the DeadPointer set that are loaded, as this 927 // makes any stores above the access live. 928 removeAccessedObjects(LoadedLoc, DeadStackObjects, DL, AA, TLI, BB.getParent()); 929 930 // If all of the allocas were clobbered by the access then we're not going 931 // to find anything else to process. 932 if (DeadStackObjects.empty()) 933 break; 934 } 935 936 return MadeChange; 937 } 938 939 static bool tryToShorten(Instruction *EarlierWrite, int64_t &EarlierOffset, 940 int64_t &EarlierSize, int64_t LaterOffset, 941 int64_t LaterSize, bool IsOverwriteEnd) { 942 // TODO: base this on the target vector size so that if the earlier 943 // store was too small to get vector writes anyway then its likely 944 // a good idea to shorten it 945 // Power of 2 vector writes are probably always a bad idea to optimize 946 // as any store/memset/memcpy is likely using vector instructions so 947 // shortening it to not vector size is likely to be slower 948 auto *EarlierIntrinsic = cast<AnyMemIntrinsic>(EarlierWrite); 949 unsigned EarlierWriteAlign = EarlierIntrinsic->getDestAlignment(); 950 if (!IsOverwriteEnd) 951 LaterOffset = int64_t(LaterOffset + LaterSize); 952 953 if (!(isPowerOf2_64(LaterOffset) && EarlierWriteAlign <= LaterOffset) && 954 !((EarlierWriteAlign != 0) && LaterOffset % EarlierWriteAlign == 0)) 955 return false; 956 957 int64_t NewLength = IsOverwriteEnd 958 ? LaterOffset - EarlierOffset 959 : EarlierSize - (LaterOffset - EarlierOffset); 960 961 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(EarlierWrite)) { 962 // When shortening an atomic memory intrinsic, the newly shortened 963 // length must remain an integer multiple of the element size. 964 const uint32_t ElementSize = AMI->getElementSizeInBytes(); 965 if (0 != NewLength % ElementSize) 966 return false; 967 } 968 969 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW " 970 << (IsOverwriteEnd ? "END" : "BEGIN") << ": " 971 << *EarlierWrite << "\n KILLER (offset " << LaterOffset 972 << ", " << EarlierSize << ")\n"); 973 974 Value *EarlierWriteLength = EarlierIntrinsic->getLength(); 975 Value *TrimmedLength = 976 ConstantInt::get(EarlierWriteLength->getType(), NewLength); 977 EarlierIntrinsic->setLength(TrimmedLength); 978 979 EarlierSize = NewLength; 980 if (!IsOverwriteEnd) { 981 int64_t OffsetMoved = (LaterOffset - EarlierOffset); 982 Value *Indices[1] = { 983 ConstantInt::get(EarlierWriteLength->getType(), OffsetMoved)}; 984 GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds( 985 EarlierIntrinsic->getRawDest()->getType()->getPointerElementType(), 986 EarlierIntrinsic->getRawDest(), Indices, "", EarlierWrite); 987 NewDestGEP->setDebugLoc(EarlierIntrinsic->getDebugLoc()); 988 EarlierIntrinsic->setDest(NewDestGEP); 989 EarlierOffset = EarlierOffset + OffsetMoved; 990 } 991 return true; 992 } 993 994 static bool tryToShortenEnd(Instruction *EarlierWrite, 995 OverlapIntervalsTy &IntervalMap, 996 int64_t &EarlierStart, int64_t &EarlierSize) { 997 if (IntervalMap.empty() || !isShortenableAtTheEnd(EarlierWrite)) 998 return false; 999 1000 OverlapIntervalsTy::iterator OII = --IntervalMap.end(); 1001 int64_t LaterStart = OII->second; 1002 int64_t LaterSize = OII->first - LaterStart; 1003 1004 if (LaterStart > EarlierStart && LaterStart < EarlierStart + EarlierSize && 1005 LaterStart + LaterSize >= EarlierStart + EarlierSize) { 1006 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart, 1007 LaterSize, true)) { 1008 IntervalMap.erase(OII); 1009 return true; 1010 } 1011 } 1012 return false; 1013 } 1014 1015 static bool tryToShortenBegin(Instruction *EarlierWrite, 1016 OverlapIntervalsTy &IntervalMap, 1017 int64_t &EarlierStart, int64_t &EarlierSize) { 1018 if (IntervalMap.empty() || !isShortenableAtTheBeginning(EarlierWrite)) 1019 return false; 1020 1021 OverlapIntervalsTy::iterator OII = IntervalMap.begin(); 1022 int64_t LaterStart = OII->second; 1023 int64_t LaterSize = OII->first - LaterStart; 1024 1025 if (LaterStart <= EarlierStart && LaterStart + LaterSize > EarlierStart) { 1026 assert(LaterStart + LaterSize < EarlierStart + EarlierSize && 1027 "Should have been handled as OW_Complete"); 1028 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart, 1029 LaterSize, false)) { 1030 IntervalMap.erase(OII); 1031 return true; 1032 } 1033 } 1034 return false; 1035 } 1036 1037 static bool removePartiallyOverlappedStores(AliasAnalysis *AA, 1038 const DataLayout &DL, 1039 InstOverlapIntervalsTy &IOL) { 1040 bool Changed = false; 1041 for (auto OI : IOL) { 1042 Instruction *EarlierWrite = OI.first; 1043 MemoryLocation Loc = getLocForWrite(EarlierWrite); 1044 assert(isRemovable(EarlierWrite) && "Expect only removable instruction"); 1045 1046 const Value *Ptr = Loc.Ptr->stripPointerCasts(); 1047 int64_t EarlierStart = 0; 1048 int64_t EarlierSize = int64_t(Loc.Size.getValue()); 1049 GetPointerBaseWithConstantOffset(Ptr, EarlierStart, DL); 1050 OverlapIntervalsTy &IntervalMap = OI.second; 1051 Changed |= 1052 tryToShortenEnd(EarlierWrite, IntervalMap, EarlierStart, EarlierSize); 1053 if (IntervalMap.empty()) 1054 continue; 1055 Changed |= 1056 tryToShortenBegin(EarlierWrite, IntervalMap, EarlierStart, EarlierSize); 1057 } 1058 return Changed; 1059 } 1060 1061 static bool eliminateNoopStore(Instruction *Inst, BasicBlock::iterator &BBI, 1062 AliasAnalysis *AA, MemoryDependenceResults *MD, 1063 const DataLayout &DL, 1064 const TargetLibraryInfo *TLI, 1065 InstOverlapIntervalsTy &IOL, 1066 MapVector<Instruction *, bool> &ThrowableInst) { 1067 // Must be a store instruction. 1068 StoreInst *SI = dyn_cast<StoreInst>(Inst); 1069 if (!SI) 1070 return false; 1071 1072 // If we're storing the same value back to a pointer that we just loaded from, 1073 // then the store can be removed. 1074 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) { 1075 if (SI->getPointerOperand() == DepLoad->getPointerOperand() && 1076 isRemovable(SI) && memoryIsNotModifiedBetween(DepLoad, SI, AA)) { 1077 1078 LLVM_DEBUG( 1079 dbgs() << "DSE: Remove Store Of Load from same pointer:\n LOAD: " 1080 << *DepLoad << "\n STORE: " << *SI << '\n'); 1081 1082 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, ThrowableInst); 1083 ++NumRedundantStores; 1084 return true; 1085 } 1086 } 1087 1088 // Remove null stores into the calloc'ed objects 1089 Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand()); 1090 if (StoredConstant && StoredConstant->isNullValue() && isRemovable(SI)) { 1091 Instruction *UnderlyingPointer = 1092 dyn_cast<Instruction>(GetUnderlyingObject(SI->getPointerOperand(), DL)); 1093 1094 if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) && 1095 memoryIsNotModifiedBetween(UnderlyingPointer, SI, AA)) { 1096 LLVM_DEBUG( 1097 dbgs() << "DSE: Remove null store to the calloc'ed object:\n DEAD: " 1098 << *Inst << "\n OBJECT: " << *UnderlyingPointer << '\n'); 1099 1100 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, ThrowableInst); 1101 ++NumRedundantStores; 1102 return true; 1103 } 1104 } 1105 return false; 1106 } 1107 1108 static bool eliminateDeadStores(BasicBlock &BB, AliasAnalysis *AA, 1109 MemoryDependenceResults *MD, DominatorTree *DT, 1110 const TargetLibraryInfo *TLI) { 1111 const DataLayout &DL = BB.getModule()->getDataLayout(); 1112 bool MadeChange = false; 1113 1114 MapVector<Instruction *, bool> ThrowableInst; 1115 1116 // A map of interval maps representing partially-overwritten value parts. 1117 InstOverlapIntervalsTy IOL; 1118 1119 // Do a top-down walk on the BB. 1120 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) { 1121 // Handle 'free' calls specially. 1122 if (CallInst *F = isFreeCall(&*BBI, TLI)) { 1123 MadeChange |= handleFree(F, AA, MD, DT, TLI, IOL, ThrowableInst); 1124 // Increment BBI after handleFree has potentially deleted instructions. 1125 // This ensures we maintain a valid iterator. 1126 ++BBI; 1127 continue; 1128 } 1129 1130 Instruction *Inst = &*BBI++; 1131 1132 if (Inst->mayThrow()) { 1133 ThrowableInst[Inst] = true; 1134 continue; 1135 } 1136 1137 // Check to see if Inst writes to memory. If not, continue. 1138 if (!hasAnalyzableMemoryWrite(Inst, *TLI)) 1139 continue; 1140 1141 // eliminateNoopStore will update in iterator, if necessary. 1142 if (eliminateNoopStore(Inst, BBI, AA, MD, DL, TLI, IOL, 1143 ThrowableInst)) { 1144 MadeChange = true; 1145 continue; 1146 } 1147 1148 // If we find something that writes memory, get its memory dependence. 1149 MemDepResult InstDep = MD->getDependency(Inst); 1150 1151 // Ignore any store where we can't find a local dependence. 1152 // FIXME: cross-block DSE would be fun. :) 1153 if (!InstDep.isDef() && !InstDep.isClobber()) 1154 continue; 1155 1156 // Figure out what location is being stored to. 1157 MemoryLocation Loc = getLocForWrite(Inst); 1158 1159 // If we didn't get a useful location, fail. 1160 if (!Loc.Ptr) 1161 continue; 1162 1163 // Loop until we find a store we can eliminate or a load that 1164 // invalidates the analysis. Without an upper bound on the number of 1165 // instructions examined, this analysis can become very time-consuming. 1166 // However, the potential gain diminishes as we process more instructions 1167 // without eliminating any of them. Therefore, we limit the number of 1168 // instructions we look at. 1169 auto Limit = MD->getDefaultBlockScanLimit(); 1170 while (InstDep.isDef() || InstDep.isClobber()) { 1171 // Get the memory clobbered by the instruction we depend on. MemDep will 1172 // skip any instructions that 'Loc' clearly doesn't interact with. If we 1173 // end up depending on a may- or must-aliased load, then we can't optimize 1174 // away the store and we bail out. However, if we depend on something 1175 // that overwrites the memory location we *can* potentially optimize it. 1176 // 1177 // Find out what memory location the dependent instruction stores. 1178 Instruction *DepWrite = InstDep.getInst(); 1179 if (!hasAnalyzableMemoryWrite(DepWrite, *TLI)) 1180 break; 1181 MemoryLocation DepLoc = getLocForWrite(DepWrite); 1182 // If we didn't get a useful location, or if it isn't a size, bail out. 1183 if (!DepLoc.Ptr) 1184 break; 1185 1186 // Find the last throwable instruction not removed by call to 1187 // deleteDeadInstruction. 1188 Instruction *LastThrowing = nullptr; 1189 if (!ThrowableInst.empty()) 1190 LastThrowing = ThrowableInst.back().first; 1191 1192 // Make sure we don't look past a call which might throw. This is an 1193 // issue because MemoryDependenceAnalysis works in the wrong direction: 1194 // it finds instructions which dominate the current instruction, rather than 1195 // instructions which are post-dominated by the current instruction. 1196 // 1197 // If the underlying object is a non-escaping memory allocation, any store 1198 // to it is dead along the unwind edge. Otherwise, we need to preserve 1199 // the store. 1200 if (LastThrowing && DepWrite->comesBefore(LastThrowing)) { 1201 const Value* Underlying = GetUnderlyingObject(DepLoc.Ptr, DL); 1202 bool IsStoreDeadOnUnwind = isa<AllocaInst>(Underlying); 1203 if (!IsStoreDeadOnUnwind) { 1204 // We're looking for a call to an allocation function 1205 // where the allocation doesn't escape before the last 1206 // throwing instruction; PointerMayBeCaptured 1207 // reasonably fast approximation. 1208 IsStoreDeadOnUnwind = isAllocLikeFn(Underlying, TLI) && 1209 !PointerMayBeCaptured(Underlying, false, true); 1210 } 1211 if (!IsStoreDeadOnUnwind) 1212 break; 1213 } 1214 1215 // If we find a write that is a) removable (i.e., non-volatile), b) is 1216 // completely obliterated by the store to 'Loc', and c) which we know that 1217 // 'Inst' doesn't load from, then we can remove it. 1218 // Also try to merge two stores if a later one only touches memory written 1219 // to by the earlier one. 1220 if (isRemovable(DepWrite) && 1221 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) { 1222 int64_t InstWriteOffset, DepWriteOffset; 1223 OverwriteResult OR = isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, 1224 InstWriteOffset, DepWrite, IOL, *AA, 1225 BB.getParent()); 1226 if (OR == OW_Complete) { 1227 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *DepWrite 1228 << "\n KILLER: " << *Inst << '\n'); 1229 1230 // Delete the store and now-dead instructions that feed it. 1231 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, 1232 ThrowableInst); 1233 ++NumFastStores; 1234 MadeChange = true; 1235 1236 // We erased DepWrite; start over. 1237 InstDep = MD->getDependency(Inst); 1238 continue; 1239 } else if ((OR == OW_End && isShortenableAtTheEnd(DepWrite)) || 1240 ((OR == OW_Begin && 1241 isShortenableAtTheBeginning(DepWrite)))) { 1242 assert(!EnablePartialOverwriteTracking && "Do not expect to perform " 1243 "when partial-overwrite " 1244 "tracking is enabled"); 1245 // The overwrite result is known, so these must be known, too. 1246 int64_t EarlierSize = DepLoc.Size.getValue(); 1247 int64_t LaterSize = Loc.Size.getValue(); 1248 bool IsOverwriteEnd = (OR == OW_End); 1249 MadeChange |= tryToShorten(DepWrite, DepWriteOffset, EarlierSize, 1250 InstWriteOffset, LaterSize, IsOverwriteEnd); 1251 } else if (EnablePartialStoreMerging && 1252 OR == OW_PartialEarlierWithFullLater) { 1253 auto *Earlier = dyn_cast<StoreInst>(DepWrite); 1254 auto *Later = dyn_cast<StoreInst>(Inst); 1255 if (Earlier && isa<ConstantInt>(Earlier->getValueOperand()) && 1256 DL.typeSizeEqualsStoreSize( 1257 Earlier->getValueOperand()->getType()) && 1258 Later && isa<ConstantInt>(Later->getValueOperand()) && 1259 DL.typeSizeEqualsStoreSize( 1260 Later->getValueOperand()->getType()) && 1261 memoryIsNotModifiedBetween(Earlier, Later, AA)) { 1262 // If the store we find is: 1263 // a) partially overwritten by the store to 'Loc' 1264 // b) the later store is fully contained in the earlier one and 1265 // c) they both have a constant value 1266 // d) none of the two stores need padding 1267 // Merge the two stores, replacing the earlier store's value with a 1268 // merge of both values. 1269 // TODO: Deal with other constant types (vectors, etc), and probably 1270 // some mem intrinsics (if needed) 1271 1272 APInt EarlierValue = 1273 cast<ConstantInt>(Earlier->getValueOperand())->getValue(); 1274 APInt LaterValue = 1275 cast<ConstantInt>(Later->getValueOperand())->getValue(); 1276 unsigned LaterBits = LaterValue.getBitWidth(); 1277 assert(EarlierValue.getBitWidth() > LaterValue.getBitWidth()); 1278 LaterValue = LaterValue.zext(EarlierValue.getBitWidth()); 1279 1280 // Offset of the smaller store inside the larger store 1281 unsigned BitOffsetDiff = (InstWriteOffset - DepWriteOffset) * 8; 1282 unsigned LShiftAmount = 1283 DL.isBigEndian() 1284 ? EarlierValue.getBitWidth() - BitOffsetDiff - LaterBits 1285 : BitOffsetDiff; 1286 APInt Mask = 1287 APInt::getBitsSet(EarlierValue.getBitWidth(), LShiftAmount, 1288 LShiftAmount + LaterBits); 1289 // Clear the bits we'll be replacing, then OR with the smaller 1290 // store, shifted appropriately. 1291 APInt Merged = 1292 (EarlierValue & ~Mask) | (LaterValue << LShiftAmount); 1293 LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n Earlier: " << *DepWrite 1294 << "\n Later: " << *Inst 1295 << "\n Merged Value: " << Merged << '\n'); 1296 1297 auto *SI = new StoreInst( 1298 ConstantInt::get(Earlier->getValueOperand()->getType(), Merged), 1299 Earlier->getPointerOperand(), false, 1300 MaybeAlign(Earlier->getAlignment()), Earlier->getOrdering(), 1301 Earlier->getSyncScopeID(), DepWrite); 1302 1303 unsigned MDToKeep[] = {LLVMContext::MD_dbg, LLVMContext::MD_tbaa, 1304 LLVMContext::MD_alias_scope, 1305 LLVMContext::MD_noalias, 1306 LLVMContext::MD_nontemporal}; 1307 SI->copyMetadata(*DepWrite, MDToKeep); 1308 ++NumModifiedStores; 1309 1310 // Delete the old stores and now-dead instructions that feed them. 1311 deleteDeadInstruction(Inst, &BBI, *MD, *TLI, IOL, 1312 ThrowableInst); 1313 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, 1314 ThrowableInst); 1315 MadeChange = true; 1316 1317 // We erased DepWrite and Inst (Loc); start over. 1318 break; 1319 } 1320 } 1321 } 1322 1323 // If this is a may-aliased store that is clobbering the store value, we 1324 // can keep searching past it for another must-aliased pointer that stores 1325 // to the same location. For example, in: 1326 // store -> P 1327 // store -> Q 1328 // store -> P 1329 // we can remove the first store to P even though we don't know if P and Q 1330 // alias. 1331 if (DepWrite == &BB.front()) break; 1332 1333 // Can't look past this instruction if it might read 'Loc'. 1334 if (isRefSet(AA->getModRefInfo(DepWrite, Loc))) 1335 break; 1336 1337 InstDep = MD->getPointerDependencyFrom(Loc, /*isLoad=*/ false, 1338 DepWrite->getIterator(), &BB, 1339 /*QueryInst=*/ nullptr, &Limit); 1340 } 1341 } 1342 1343 if (EnablePartialOverwriteTracking) 1344 MadeChange |= removePartiallyOverlappedStores(AA, DL, IOL); 1345 1346 // If this block ends in a return, unwind, or unreachable, all allocas are 1347 // dead at its end, which means stores to them are also dead. 1348 if (BB.getTerminator()->getNumSuccessors() == 0) 1349 MadeChange |= handleEndBlock(BB, AA, MD, TLI, IOL, ThrowableInst); 1350 1351 return MadeChange; 1352 } 1353 1354 static bool eliminateDeadStores(Function &F, AliasAnalysis *AA, 1355 MemoryDependenceResults *MD, DominatorTree *DT, 1356 const TargetLibraryInfo *TLI) { 1357 bool MadeChange = false; 1358 for (BasicBlock &BB : F) 1359 // Only check non-dead blocks. Dead blocks may have strange pointer 1360 // cycles that will confuse alias analysis. 1361 if (DT->isReachableFromEntry(&BB)) 1362 MadeChange |= eliminateDeadStores(BB, AA, MD, DT, TLI); 1363 1364 return MadeChange; 1365 } 1366 1367 namespace { 1368 //============================================================================= 1369 // MemorySSA backed dead store elimination. 1370 // 1371 // The code below implements dead store elimination using MemorySSA. It uses 1372 // the following general approach: given a MemoryDef, walk upwards to find 1373 // clobbering MemoryDefs that may be killed by the starting def. Then check 1374 // that there are no uses that may read the location of the original MemoryDef 1375 // in between both MemoryDefs. A bit more concretely: 1376 // 1377 // For all MemoryDefs StartDef: 1378 // 1. Get the next dominating clobbering MemoryDef (DomAccess) by walking 1379 // upwards. 1380 // 2. Check that there are no reads between DomAccess and the StartDef by 1381 // checking all uses starting at DomAccess and walking until we see StartDef. 1382 // 3. For each found DomDef, check that: 1383 // 1. There are no barrier instructions between DomDef and StartDef (like 1384 // throws or stores with ordering constraints). 1385 // 2. StartDef is executed whenever DomDef is executed. 1386 // 3. StartDef completely overwrites DomDef. 1387 // 4. Erase DomDef from the function and MemorySSA. 1388 1389 // Returns true if \p M is an intrisnic that does not read or write memory. 1390 bool isNoopIntrinsic(MemoryUseOrDef *M) { 1391 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(M->getMemoryInst())) { 1392 switch (II->getIntrinsicID()) { 1393 case Intrinsic::lifetime_start: 1394 case Intrinsic::lifetime_end: 1395 case Intrinsic::invariant_end: 1396 case Intrinsic::launder_invariant_group: 1397 case Intrinsic::assume: 1398 return true; 1399 case Intrinsic::dbg_addr: 1400 case Intrinsic::dbg_declare: 1401 case Intrinsic::dbg_label: 1402 case Intrinsic::dbg_value: 1403 llvm_unreachable("Intrinsic should not be modeled in MemorySSA"); 1404 default: 1405 return false; 1406 } 1407 } 1408 return false; 1409 } 1410 1411 // Check if we can ignore \p D for DSE. 1412 bool canSkipDef(MemoryDef *D, bool DefVisibleToCaller) { 1413 Instruction *DI = D->getMemoryInst(); 1414 // Calls that only access inaccessible memory cannot read or write any memory 1415 // locations we consider for elimination. 1416 if (auto CS = CallSite(DI)) 1417 if (CS.onlyAccessesInaccessibleMemory()) 1418 return true; 1419 1420 // We can eliminate stores to locations not visible to the caller across 1421 // throwing instructions. 1422 if (DI->mayThrow() && !DefVisibleToCaller) 1423 return true; 1424 1425 // We can remove the dead stores, irrespective of the fence and its ordering 1426 // (release/acquire/seq_cst). Fences only constraints the ordering of 1427 // already visible stores, it does not make a store visible to other 1428 // threads. So, skipping over a fence does not change a store from being 1429 // dead. 1430 if (isa<FenceInst>(DI)) 1431 return true; 1432 1433 // Skip intrinsics that do not really read or modify memory. 1434 if (isNoopIntrinsic(D)) 1435 return true; 1436 1437 return false; 1438 } 1439 1440 struct DSEState { 1441 Function &F; 1442 AliasAnalysis &AA; 1443 MemorySSA &MSSA; 1444 DominatorTree &DT; 1445 PostDominatorTree &PDT; 1446 const TargetLibraryInfo &TLI; 1447 1448 // All MemoryDefs that potentially could kill other MemDefs. 1449 SmallVector<MemoryDef *, 64> MemDefs; 1450 // Any that should be skipped as they are already deleted 1451 SmallPtrSet<MemoryAccess *, 4> SkipStores; 1452 // Keep track of all of the objects that are invisible to the caller until the 1453 // function returns. 1454 SmallPtrSet<const Value *, 16> InvisibleToCaller; 1455 // Keep track of blocks with throwing instructions not modeled in MemorySSA. 1456 SmallPtrSet<BasicBlock *, 16> ThrowingBlocks; 1457 1458 /// Keep track of instructions (partly) overlapping with killing MemoryDefs per 1459 /// basic block. 1460 DenseMap<BasicBlock *, InstOverlapIntervalsTy> IOLs; 1461 1462 DSEState(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, DominatorTree &DT, 1463 PostDominatorTree &PDT, const TargetLibraryInfo &TLI) 1464 : F(F), AA(AA), MSSA(MSSA), DT(DT), PDT(PDT), TLI(TLI) {} 1465 1466 static DSEState get(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, 1467 DominatorTree &DT, PostDominatorTree &PDT, 1468 const TargetLibraryInfo &TLI) { 1469 DSEState State(F, AA, MSSA, DT, PDT, TLI); 1470 // Collect blocks with throwing instructions not modeled in MemorySSA and 1471 // alloc-like objects. 1472 for (Instruction &I : instructions(F)) { 1473 if (I.mayThrow() && !MSSA.getMemoryAccess(&I)) 1474 State.ThrowingBlocks.insert(I.getParent()); 1475 1476 auto *MD = dyn_cast_or_null<MemoryDef>(MSSA.getMemoryAccess(&I)); 1477 if (MD && State.MemDefs.size() < MemorySSADefsPerBlockLimit && 1478 hasAnalyzableMemoryWrite(&I, TLI) && isRemovable(&I)) 1479 State.MemDefs.push_back(MD); 1480 1481 // Track alloca and alloca-like objects. Here we care about objects not 1482 // visible to the caller during function execution. Alloca objects are 1483 // invalid in the caller, for alloca-like objects we ensure that they are 1484 // not captured throughout the function. 1485 if (isa<AllocaInst>(&I) || 1486 (isAllocLikeFn(&I, &TLI) && !PointerMayBeCaptured(&I, false, true))) 1487 State.InvisibleToCaller.insert(&I); 1488 } 1489 // Treat byval or inalloca arguments the same as Allocas, stores to them are 1490 // dead at the end of the function. 1491 for (Argument &AI : F.args()) 1492 if (AI.hasByValOrInAllocaAttr()) 1493 State.InvisibleToCaller.insert(&AI); 1494 return State; 1495 } 1496 1497 Optional<MemoryLocation> getLocForWriteEx(Instruction *I) const { 1498 if (!I->mayWriteToMemory()) 1499 return None; 1500 1501 if (auto *MTI = dyn_cast<AnyMemIntrinsic>(I)) 1502 return {MemoryLocation::getForDest(MTI)}; 1503 1504 if (auto CS = CallSite(I)) { 1505 if (Function *F = CS.getCalledFunction()) { 1506 StringRef FnName = F->getName(); 1507 if (TLI.has(LibFunc_strcpy) && FnName == TLI.getName(LibFunc_strcpy)) 1508 return {MemoryLocation(CS.getArgument(0))}; 1509 if (TLI.has(LibFunc_strncpy) && FnName == TLI.getName(LibFunc_strncpy)) 1510 return {MemoryLocation(CS.getArgument(0))}; 1511 if (TLI.has(LibFunc_strcat) && FnName == TLI.getName(LibFunc_strcat)) 1512 return {MemoryLocation(CS.getArgument(0))}; 1513 if (TLI.has(LibFunc_strncat) && FnName == TLI.getName(LibFunc_strncat)) 1514 return {MemoryLocation(CS.getArgument(0))}; 1515 } 1516 return None; 1517 } 1518 1519 return MemoryLocation::getOrNone(I); 1520 } 1521 1522 /// Returns true if \p Use completely overwrites \p DefLoc. 1523 bool isCompleteOverwrite(MemoryLocation DefLoc, Instruction *UseInst) const { 1524 // UseInst has a MemoryDef associated in MemorySSA. It's possible for a 1525 // MemoryDef to not write to memory, e.g. a volatile load is modeled as a 1526 // MemoryDef. 1527 if (!UseInst->mayWriteToMemory()) 1528 return false; 1529 1530 if (auto CS = CallSite(UseInst)) 1531 if (CS.onlyAccessesInaccessibleMemory()) 1532 return false; 1533 1534 ModRefInfo MR = AA.getModRefInfo(UseInst, DefLoc); 1535 // If necessary, perform additional analysis. 1536 if (isModSet(MR)) 1537 MR = AA.callCapturesBefore(UseInst, DefLoc, &DT); 1538 1539 Optional<MemoryLocation> UseLoc = getLocForWriteEx(UseInst); 1540 return isModSet(MR) && isMustSet(MR) && 1541 UseLoc->Size.getValue() >= DefLoc.Size.getValue(); 1542 } 1543 1544 /// Returns true if \p Use may read from \p DefLoc. 1545 bool isReadClobber(MemoryLocation DefLoc, Instruction *UseInst) const { 1546 if (!UseInst->mayReadFromMemory()) 1547 return false; 1548 1549 if (auto CS = CallSite(UseInst)) 1550 if (CS.onlyAccessesInaccessibleMemory()) 1551 return false; 1552 1553 ModRefInfo MR = AA.getModRefInfo(UseInst, DefLoc); 1554 // If necessary, perform additional analysis. 1555 if (isRefSet(MR)) 1556 MR = AA.callCapturesBefore(UseInst, DefLoc, &DT); 1557 return isRefSet(MR); 1558 } 1559 1560 // Find a MemoryDef writing to \p DefLoc and dominating \p Current, with no 1561 // read access in between or return None otherwise. The returned value may not 1562 // (completely) overwrite \p DefLoc. Currently we bail out when we encounter 1563 // any of the following 1564 // * An aliasing MemoryUse (read). 1565 // * A MemoryPHI. 1566 Optional<MemoryAccess *> getDomMemoryDef(MemoryDef *KillingDef, 1567 MemoryAccess *Current, 1568 MemoryLocation DefLoc, 1569 bool DefVisibleToCaller, 1570 int &ScanLimit) const { 1571 MemoryDef *DomDef; 1572 MemoryAccess *StartDef = Current; 1573 bool StepAgain; 1574 LLVM_DEBUG(dbgs() << " trying to get dominating access for " << *Current 1575 << "\n"); 1576 // Find the next clobbering Mod access for DefLoc, starting at Current. 1577 do { 1578 StepAgain = false; 1579 // Reached TOP. 1580 if (MSSA.isLiveOnEntryDef(Current)) 1581 return None; 1582 1583 MemoryUseOrDef *CurrentUD = dyn_cast<MemoryUseOrDef>(Current); 1584 if (!CurrentUD) 1585 return None; 1586 1587 // Look for access that clobber DefLoc. 1588 MemoryAccess *DomAccess = 1589 MSSA.getSkipSelfWalker()->getClobberingMemoryAccess( 1590 CurrentUD->getDefiningAccess(), DefLoc); 1591 DomDef = dyn_cast<MemoryDef>(DomAccess); 1592 if (!DomDef || MSSA.isLiveOnEntryDef(DomDef)) 1593 return None; 1594 1595 // Check if we can skip DomDef for DSE. We also require the KillingDef 1596 // execute whenever DomDef executes and use post-dominance to ensure that. 1597 if (canSkipDef(DomDef, DefVisibleToCaller) || 1598 !PDT.dominates(KillingDef->getBlock(), DomDef->getBlock())) { 1599 StepAgain = true; 1600 Current = DomDef; 1601 } 1602 1603 } while (StepAgain); 1604 1605 LLVM_DEBUG(dbgs() << " Checking for reads of " << *DomDef << " (" 1606 << *DomDef->getMemoryInst() << ")\n"); 1607 1608 SmallSetVector<MemoryAccess *, 32> WorkList; 1609 auto PushMemUses = [&WorkList](MemoryAccess *Acc) { 1610 for (Use &U : Acc->uses()) 1611 WorkList.insert(cast<MemoryAccess>(U.getUser())); 1612 }; 1613 PushMemUses(DomDef); 1614 1615 // Check if DomDef may be read. 1616 for (unsigned I = 0; I < WorkList.size(); I++) { 1617 MemoryAccess *UseAccess = WorkList[I]; 1618 1619 LLVM_DEBUG(dbgs() << " Checking use " << *UseAccess); 1620 if (--ScanLimit == 0) { 1621 LLVM_DEBUG(dbgs() << " ... hit scan limit\n"); 1622 return None; 1623 } 1624 1625 // Bail out on MemoryPhis for now. 1626 if (isa<MemoryPhi>(UseAccess)) { 1627 LLVM_DEBUG(dbgs() << " ... hit MemoryPhi\n"); 1628 return None; 1629 } 1630 1631 Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst(); 1632 LLVM_DEBUG(dbgs() << " (" << *UseInst << ")\n"); 1633 1634 if (isNoopIntrinsic(cast<MemoryUseOrDef>(UseAccess))) { 1635 PushMemUses(UseAccess); 1636 continue; 1637 } 1638 1639 // Uses which may read the original MemoryDef mean we cannot eliminate the 1640 // original MD. Stop walk. 1641 if (isReadClobber(DefLoc, UseInst)) { 1642 LLVM_DEBUG(dbgs() << " ... found read clobber\n"); 1643 return None; 1644 } 1645 1646 if (StartDef == UseAccess) 1647 continue; 1648 1649 // Check all uses for MemoryDefs, except for defs completely overwriting 1650 // the original location. Otherwise we have to check uses of *all* 1651 // MemoryDefs we discover, including non-aliasing ones. Otherwise we might 1652 // miss cases like the following 1653 // 1 = Def(LoE) ; <----- DomDef stores [0,1] 1654 // 2 = Def(1) ; (2, 1) = NoAlias, stores [2,3] 1655 // Use(2) ; MayAlias 2 *and* 1, loads [0, 3]. 1656 // (The Use points to the *first* Def it may alias) 1657 // 3 = Def(1) ; <---- Current (3, 2) = NoAlias, (3,1) = MayAlias, 1658 // stores [0,1] 1659 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) { 1660 if (!isCompleteOverwrite(DefLoc, UseInst)) 1661 PushMemUses(UseDef); 1662 } 1663 } 1664 1665 // No aliasing MemoryUses of DomDef found, DomDef is potentially dead. 1666 return {DomDef}; 1667 } 1668 1669 // Delete dead memory defs 1670 void deleteDeadInstruction(Instruction *SI) { 1671 MemorySSAUpdater Updater(&MSSA); 1672 SmallVector<Instruction *, 32> NowDeadInsts; 1673 NowDeadInsts.push_back(SI); 1674 --NumFastOther; 1675 1676 while (!NowDeadInsts.empty()) { 1677 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 1678 ++NumFastOther; 1679 1680 // Try to preserve debug information attached to the dead instruction. 1681 salvageDebugInfo(*DeadInst); 1682 1683 // Remove the Instruction from MSSA. 1684 if (MemoryAccess *MA = MSSA.getMemoryAccess(DeadInst)) { 1685 if (MemoryDef *MD = dyn_cast<MemoryDef>(MA)) { 1686 SkipStores.insert(MD); 1687 } 1688 Updater.removeMemoryAccess(MA); 1689 } 1690 1691 auto I = IOLs.find(DeadInst->getParent()); 1692 if (I != IOLs.end()) 1693 I->second.erase(DeadInst); 1694 // Remove its operands 1695 for (Use &O : DeadInst->operands()) 1696 if (Instruction *OpI = dyn_cast<Instruction>(O)) { 1697 O = nullptr; 1698 if (isInstructionTriviallyDead(OpI, &TLI)) 1699 NowDeadInsts.push_back(OpI); 1700 } 1701 1702 DeadInst->eraseFromParent(); 1703 } 1704 } 1705 1706 // Check for any extra throws between SI and NI that block DSE. This only 1707 // checks extra maythrows (those that aren't MemoryDef's). MemoryDef that may 1708 // throw are handled during the walk from one def to the next. 1709 bool mayThrowBetween(Instruction *SI, Instruction *NI, 1710 const Value *SILocUnd) const { 1711 // First see if we can ignore it by using the fact that SI is an 1712 // alloca/alloca like object that is not visible to the caller during 1713 // execution of the function. 1714 if (SILocUnd && InvisibleToCaller.count(SILocUnd)) 1715 return false; 1716 1717 if (SI->getParent() == NI->getParent()) 1718 return ThrowingBlocks.find(SI->getParent()) != ThrowingBlocks.end(); 1719 return !ThrowingBlocks.empty(); 1720 } 1721 1722 // Check if \p NI acts as a DSE barrier for \p SI. The following instructions 1723 // act as barriers: 1724 // * A memory instruction that may throw and \p SI accesses a non-stack 1725 // object. 1726 // * Atomic stores stronger that monotonic. 1727 bool isDSEBarrier(Instruction *SI, MemoryLocation &SILoc, 1728 const Value *SILocUnd, Instruction *NI, 1729 MemoryLocation &NILoc) const { 1730 // If NI may throw it acts as a barrier, unless we are to an alloca/alloca 1731 // like object that does not escape. 1732 if (NI->mayThrow() && !InvisibleToCaller.count(SILocUnd)) 1733 return true; 1734 1735 if (NI->isAtomic()) { 1736 if (auto *NSI = dyn_cast<StoreInst>(NI)) { 1737 if (isStrongerThanMonotonic(NSI->getOrdering())) 1738 return true; 1739 } else 1740 llvm_unreachable( 1741 "Other instructions should be modeled/skipped in MemorySSA"); 1742 } 1743 1744 return false; 1745 } 1746 }; 1747 1748 bool eliminateDeadStoresMemorySSA(Function &F, AliasAnalysis &AA, 1749 MemorySSA &MSSA, DominatorTree &DT, 1750 PostDominatorTree &PDT, 1751 const TargetLibraryInfo &TLI) { 1752 const DataLayout &DL = F.getParent()->getDataLayout(); 1753 bool MadeChange = false; 1754 1755 DSEState State = DSEState::get(F, AA, MSSA, DT, PDT, TLI); 1756 // For each store: 1757 for (unsigned I = 0; I < State.MemDefs.size(); I++) { 1758 MemoryDef *Current = State.MemDefs[I]; 1759 if (State.SkipStores.count(Current)) 1760 continue; 1761 Instruction *SI = cast<MemoryDef>(Current)->getMemoryInst(); 1762 auto MaybeSILoc = State.getLocForWriteEx(SI); 1763 if (!MaybeSILoc) { 1764 LLVM_DEBUG(dbgs() << "Failed to find analyzable write location for " 1765 << *SI << "\n"); 1766 continue; 1767 } 1768 MemoryLocation SILoc = *MaybeSILoc; 1769 assert(SILoc.Ptr && "SILoc should not be null"); 1770 const Value *SILocUnd = GetUnderlyingObject(SILoc.Ptr, DL); 1771 Instruction *DefObj = 1772 const_cast<Instruction *>(dyn_cast<Instruction>(SILocUnd)); 1773 bool DefVisibleToCaller = !State.InvisibleToCaller.count(SILocUnd); 1774 if (DefObj && ((isAllocLikeFn(DefObj, &TLI) && 1775 !PointerMayBeCapturedBefore(DefObj, false, true, SI, &DT)))) 1776 DefVisibleToCaller = false; 1777 1778 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs killed by " << *SI 1779 << "\n"); 1780 1781 int ScanLimit = MemorySSAScanLimit; 1782 MemoryDef *StartDef = Current; 1783 // Walk MemorySSA upward to find MemoryDefs that might be killed by SI. 1784 while (Optional<MemoryAccess *> Next = State.getDomMemoryDef( 1785 StartDef, Current, SILoc, DefVisibleToCaller, ScanLimit)) { 1786 MemoryAccess *DomAccess = *Next; 1787 LLVM_DEBUG(dbgs() << " Checking if we can kill " << *DomAccess << "\n"); 1788 MemoryDef *NextDef = dyn_cast<MemoryDef>(DomAccess); 1789 Instruction *NI = NextDef->getMemoryInst(); 1790 LLVM_DEBUG(dbgs() << " def " << *NI << "\n"); 1791 1792 if (!hasAnalyzableMemoryWrite(NI, TLI)) 1793 break; 1794 1795 if (!isRemovable(NI)) { 1796 LLVM_DEBUG(dbgs() << " skip, cannot remove def\n"); 1797 continue; 1798 } 1799 1800 MemoryLocation NILoc = *State.getLocForWriteEx(NI); 1801 // Check for anything that looks like it will be a barrier to further 1802 // removal 1803 if (State.isDSEBarrier(SI, SILoc, SILocUnd, NI, NILoc)) { 1804 LLVM_DEBUG(dbgs() << " stop, barrier\n"); 1805 break; 1806 } 1807 1808 // Before we try to remove anything, check for any extra throwing 1809 // instructions that block us from DSEing 1810 if (State.mayThrowBetween(SI, NI, SILocUnd)) { 1811 LLVM_DEBUG(dbgs() << " stop, may throw!\n"); 1812 break; 1813 } 1814 1815 if (!DebugCounter::shouldExecute(MemorySSACounter)) 1816 break; 1817 1818 // Check if NI overwrites SI. 1819 int64_t InstWriteOffset, DepWriteOffset; 1820 auto Iter = State.IOLs.insert( 1821 std::make_pair<BasicBlock *, InstOverlapIntervalsTy>( 1822 NI->getParent(), InstOverlapIntervalsTy())); 1823 auto &IOL = Iter.first->second; 1824 OverwriteResult OR = isOverwrite(SILoc, NILoc, DL, TLI, DepWriteOffset, 1825 InstWriteOffset, NI, IOL, AA, &F); 1826 1827 if (OR == OW_Complete) { 1828 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *NI 1829 << "\n KILLER: " << *SI << '\n'); 1830 State.deleteDeadInstruction(NI); 1831 ++NumFastStores; 1832 MadeChange = true; 1833 } else 1834 Current = NextDef; 1835 } 1836 } 1837 1838 if (EnablePartialOverwriteTracking) 1839 for (auto &KV : State.IOLs) 1840 MadeChange |= removePartiallyOverlappedStores(&AA, DL, KV.second); 1841 1842 return MadeChange; 1843 } 1844 } // end anonymous namespace 1845 1846 //===----------------------------------------------------------------------===// 1847 // DSE Pass 1848 //===----------------------------------------------------------------------===// 1849 PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) { 1850 AliasAnalysis &AA = AM.getResult<AAManager>(F); 1851 const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1852 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 1853 1854 if (EnableMemorySSA) { 1855 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); 1856 PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F); 1857 1858 if (!eliminateDeadStoresMemorySSA(F, AA, MSSA, DT, PDT, TLI)) 1859 return PreservedAnalyses::all(); 1860 } else { 1861 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F); 1862 1863 if (!eliminateDeadStores(F, &AA, &MD, &DT, &TLI)) 1864 return PreservedAnalyses::all(); 1865 } 1866 1867 PreservedAnalyses PA; 1868 PA.preserveSet<CFGAnalyses>(); 1869 PA.preserve<GlobalsAA>(); 1870 if (EnableMemorySSA) 1871 PA.preserve<MemorySSAAnalysis>(); 1872 else 1873 PA.preserve<MemoryDependenceAnalysis>(); 1874 return PA; 1875 } 1876 1877 namespace { 1878 1879 /// A legacy pass for the legacy pass manager that wraps \c DSEPass. 1880 class DSELegacyPass : public FunctionPass { 1881 public: 1882 static char ID; // Pass identification, replacement for typeid 1883 1884 DSELegacyPass() : FunctionPass(ID) { 1885 initializeDSELegacyPassPass(*PassRegistry::getPassRegistry()); 1886 } 1887 1888 bool runOnFunction(Function &F) override { 1889 if (skipFunction(F)) 1890 return false; 1891 1892 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 1893 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1894 const TargetLibraryInfo &TLI = 1895 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 1896 1897 if (EnableMemorySSA) { 1898 MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); 1899 PostDominatorTree &PDT = 1900 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 1901 1902 return eliminateDeadStoresMemorySSA(F, AA, MSSA, DT, PDT, TLI); 1903 } else { 1904 MemoryDependenceResults &MD = 1905 getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); 1906 1907 return eliminateDeadStores(F, &AA, &MD, &DT, &TLI); 1908 } 1909 } 1910 1911 void getAnalysisUsage(AnalysisUsage &AU) const override { 1912 AU.setPreservesCFG(); 1913 AU.addRequired<AAResultsWrapperPass>(); 1914 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1915 AU.addPreserved<GlobalsAAWrapperPass>(); 1916 AU.addRequired<DominatorTreeWrapperPass>(); 1917 AU.addPreserved<DominatorTreeWrapperPass>(); 1918 1919 if (EnableMemorySSA) { 1920 AU.addRequired<PostDominatorTreeWrapperPass>(); 1921 AU.addRequired<MemorySSAWrapperPass>(); 1922 AU.addPreserved<PostDominatorTreeWrapperPass>(); 1923 AU.addPreserved<MemorySSAWrapperPass>(); 1924 } else { 1925 AU.addRequired<MemoryDependenceWrapperPass>(); 1926 AU.addPreserved<MemoryDependenceWrapperPass>(); 1927 } 1928 } 1929 }; 1930 1931 } // end anonymous namespace 1932 1933 char DSELegacyPass::ID = 0; 1934 1935 INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false, 1936 false) 1937 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1938 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 1939 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1940 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 1941 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 1942 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 1943 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1944 INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false, 1945 false) 1946 1947 FunctionPass *llvm::createDeadStoreEliminationPass() { 1948 return new DSELegacyPass(); 1949 } 1950