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/PostOrderIterator.h" 22 #include "llvm/ADT/SetVector.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Statistic.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/Analysis/AliasAnalysis.h" 28 #include "llvm/Analysis/CaptureTracking.h" 29 #include "llvm/Analysis/GlobalsModRef.h" 30 #include "llvm/Analysis/MemoryBuiltins.h" 31 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 32 #include "llvm/Analysis/MemoryLocation.h" 33 #include "llvm/Analysis/MemorySSA.h" 34 #include "llvm/Analysis/MemorySSAUpdater.h" 35 #include "llvm/Analysis/PostDominators.h" 36 #include "llvm/Analysis/TargetLibraryInfo.h" 37 #include "llvm/Analysis/ValueTracking.h" 38 #include "llvm/IR/Argument.h" 39 #include "llvm/IR/BasicBlock.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/PatternMatch.h" 55 #include "llvm/IR/Value.h" 56 #include "llvm/InitializePasses.h" 57 #include "llvm/Pass.h" 58 #include "llvm/Support/Casting.h" 59 #include "llvm/Support/CommandLine.h" 60 #include "llvm/Support/Debug.h" 61 #include "llvm/Support/DebugCounter.h" 62 #include "llvm/Support/ErrorHandling.h" 63 #include "llvm/Support/MathExtras.h" 64 #include "llvm/Support/raw_ostream.h" 65 #include "llvm/Transforms/Scalar.h" 66 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 67 #include "llvm/Transforms/Utils/Local.h" 68 #include <algorithm> 69 #include <cassert> 70 #include <cstddef> 71 #include <cstdint> 72 #include <iterator> 73 #include <map> 74 #include <utility> 75 76 using namespace llvm; 77 using namespace PatternMatch; 78 79 #define DEBUG_TYPE "dse" 80 81 STATISTIC(NumRemainingStores, "Number of stores remaining after DSE"); 82 STATISTIC(NumRedundantStores, "Number of redundant stores deleted"); 83 STATISTIC(NumFastStores, "Number of stores deleted"); 84 STATISTIC(NumFastOther, "Number of other instrs removed"); 85 STATISTIC(NumCompletePartials, "Number of stores dead by later partials"); 86 STATISTIC(NumModifiedStores, "Number of stores modified"); 87 STATISTIC(NumCFGChecks, "Number of stores modified"); 88 STATISTIC(NumCFGTries, "Number of stores modified"); 89 STATISTIC(NumCFGSuccess, "Number of stores modified"); 90 STATISTIC(NumDomMemDefChecks, 91 "Number iterations check for reads in getDomMemoryDef"); 92 93 DEBUG_COUNTER(MemorySSACounter, "dse-memoryssa", 94 "Controls which MemoryDefs are eliminated."); 95 96 static cl::opt<bool> 97 EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking", 98 cl::init(true), cl::Hidden, 99 cl::desc("Enable partial-overwrite tracking in DSE")); 100 101 static cl::opt<bool> 102 EnablePartialStoreMerging("enable-dse-partial-store-merging", 103 cl::init(true), cl::Hidden, 104 cl::desc("Enable partial store merging in DSE")); 105 106 static cl::opt<bool> 107 EnableMemorySSA("enable-dse-memoryssa", cl::init(false), cl::Hidden, 108 cl::desc("Use the new MemorySSA-backed DSE.")); 109 110 static cl::opt<unsigned> 111 MemorySSAScanLimit("dse-memoryssa-scanlimit", cl::init(150), cl::Hidden, 112 cl::desc("The number of memory instructions to scan for " 113 "dead store elimination (default = 100)")); 114 115 static cl::opt<unsigned> MemorySSADefsPerBlockLimit( 116 "dse-memoryssa-defs-per-block-limit", cl::init(5000), cl::Hidden, 117 cl::desc("The number of MemoryDefs we consider as candidates to eliminated " 118 "other stores per basic block (default = 5000)")); 119 120 static cl::opt<unsigned> MemorySSAPathCheckLimit( 121 "dse-memoryssa-path-check-limit", cl::init(50), cl::Hidden, 122 cl::desc("The maximum number of blocks to check when trying to prove that " 123 "all paths to an exit go through a killing block (default = 50)")); 124 125 //===----------------------------------------------------------------------===// 126 // Helper functions 127 //===----------------------------------------------------------------------===// 128 using OverlapIntervalsTy = std::map<int64_t, int64_t>; 129 using InstOverlapIntervalsTy = DenseMap<Instruction *, OverlapIntervalsTy>; 130 131 /// Delete this instruction. Before we do, go through and zero out all the 132 /// operands of this instruction. If any of them become dead, delete them and 133 /// the computation tree that feeds them. 134 /// If ValueSet is non-null, remove any deleted instructions from it as well. 135 static void 136 deleteDeadInstruction(Instruction *I, BasicBlock::iterator *BBI, 137 MemoryDependenceResults &MD, const TargetLibraryInfo &TLI, 138 InstOverlapIntervalsTy &IOL, 139 MapVector<Instruction *, bool> &ThrowableInst, 140 SmallSetVector<const Value *, 16> *ValueSet = nullptr) { 141 SmallVector<Instruction*, 32> NowDeadInsts; 142 143 NowDeadInsts.push_back(I); 144 --NumFastOther; 145 146 // Keeping the iterator straight is a pain, so we let this routine tell the 147 // caller what the next instruction is after we're done mucking about. 148 BasicBlock::iterator NewIter = *BBI; 149 150 // Before we touch this instruction, remove it from memdep! 151 do { 152 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 153 // Mark the DeadInst as dead in the list of throwable instructions. 154 auto It = ThrowableInst.find(DeadInst); 155 if (It != ThrowableInst.end()) 156 ThrowableInst[It->first] = false; 157 ++NumFastOther; 158 159 // Try to preserve debug information attached to the dead instruction. 160 salvageDebugInfo(*DeadInst); 161 salvageKnowledge(DeadInst); 162 163 // This instruction is dead, zap it, in stages. Start by removing it from 164 // MemDep, which needs to know the operands and needs it to be in the 165 // function. 166 MD.removeInstruction(DeadInst); 167 168 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) { 169 Value *Op = DeadInst->getOperand(op); 170 DeadInst->setOperand(op, nullptr); 171 172 // If this operand just became dead, add it to the NowDeadInsts list. 173 if (!Op->use_empty()) continue; 174 175 if (Instruction *OpI = dyn_cast<Instruction>(Op)) 176 if (isInstructionTriviallyDead(OpI, &TLI)) 177 NowDeadInsts.push_back(OpI); 178 } 179 180 if (ValueSet) ValueSet->remove(DeadInst); 181 IOL.erase(DeadInst); 182 183 if (NewIter == DeadInst->getIterator()) 184 NewIter = DeadInst->eraseFromParent(); 185 else 186 DeadInst->eraseFromParent(); 187 } while (!NowDeadInsts.empty()); 188 *BBI = NewIter; 189 // Pop dead entries from back of ThrowableInst till we find an alive entry. 190 while (!ThrowableInst.empty() && !ThrowableInst.back().second) 191 ThrowableInst.pop_back(); 192 } 193 194 /// Does this instruction write some memory? This only returns true for things 195 /// that we can analyze with other helpers below. 196 static bool hasAnalyzableMemoryWrite(Instruction *I, 197 const TargetLibraryInfo &TLI) { 198 if (isa<StoreInst>(I)) 199 return true; 200 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 201 switch (II->getIntrinsicID()) { 202 default: 203 return false; 204 case Intrinsic::memset: 205 case Intrinsic::memmove: 206 case Intrinsic::memcpy: 207 case Intrinsic::memcpy_element_unordered_atomic: 208 case Intrinsic::memmove_element_unordered_atomic: 209 case Intrinsic::memset_element_unordered_atomic: 210 case Intrinsic::init_trampoline: 211 case Intrinsic::lifetime_end: 212 return true; 213 } 214 } 215 if (auto *CB = dyn_cast<CallBase>(I)) { 216 LibFunc LF; 217 if (TLI.getLibFunc(*CB, LF) && TLI.has(LF)) { 218 switch (LF) { 219 case LibFunc_strcpy: 220 case LibFunc_strncpy: 221 case LibFunc_strcat: 222 case LibFunc_strncat: 223 return true; 224 default: 225 return false; 226 } 227 } 228 } 229 return false; 230 } 231 232 /// Return a Location stored to by the specified instruction. If isRemovable 233 /// returns true, this function and getLocForRead completely describe the memory 234 /// operations for this instruction. 235 static MemoryLocation getLocForWrite(Instruction *Inst) { 236 237 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 238 return MemoryLocation::get(SI); 239 240 if (auto *MI = dyn_cast<AnyMemIntrinsic>(Inst)) { 241 // memcpy/memmove/memset. 242 MemoryLocation Loc = MemoryLocation::getForDest(MI); 243 return Loc; 244 } 245 246 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 247 switch (II->getIntrinsicID()) { 248 default: 249 return MemoryLocation(); // Unhandled intrinsic. 250 case Intrinsic::init_trampoline: 251 return MemoryLocation(II->getArgOperand(0)); 252 case Intrinsic::lifetime_end: { 253 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(); 254 return MemoryLocation(II->getArgOperand(1), Len); 255 } 256 } 257 } 258 if (auto *CB = dyn_cast<CallBase>(Inst)) 259 // All the supported TLI functions so far happen to have dest as their 260 // first argument. 261 return MemoryLocation(CB->getArgOperand(0)); 262 return MemoryLocation(); 263 } 264 265 /// Return the location read by the specified "hasAnalyzableMemoryWrite" 266 /// instruction if any. 267 static MemoryLocation getLocForRead(Instruction *Inst, 268 const TargetLibraryInfo &TLI) { 269 assert(hasAnalyzableMemoryWrite(Inst, TLI) && "Unknown instruction case"); 270 271 // The only instructions that both read and write are the mem transfer 272 // instructions (memcpy/memmove). 273 if (auto *MTI = dyn_cast<AnyMemTransferInst>(Inst)) 274 return MemoryLocation::getForSource(MTI); 275 return MemoryLocation(); 276 } 277 278 /// If the value of this instruction and the memory it writes to is unused, may 279 /// we delete this instruction? 280 static bool isRemovable(Instruction *I) { 281 // Don't remove volatile/atomic stores. 282 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 283 return SI->isUnordered(); 284 285 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 286 switch (II->getIntrinsicID()) { 287 default: llvm_unreachable("doesn't pass 'hasAnalyzableMemoryWrite' predicate"); 288 case Intrinsic::lifetime_end: 289 // Never remove dead lifetime_end's, e.g. because it is followed by a 290 // free. 291 return false; 292 case Intrinsic::init_trampoline: 293 // Always safe to remove init_trampoline. 294 return true; 295 case Intrinsic::memset: 296 case Intrinsic::memmove: 297 case Intrinsic::memcpy: 298 // Don't remove volatile memory intrinsics. 299 return !cast<MemIntrinsic>(II)->isVolatile(); 300 case Intrinsic::memcpy_element_unordered_atomic: 301 case Intrinsic::memmove_element_unordered_atomic: 302 case Intrinsic::memset_element_unordered_atomic: 303 return true; 304 } 305 } 306 307 // note: only get here for calls with analyzable writes - i.e. libcalls 308 if (auto *CB = dyn_cast<CallBase>(I)) 309 return CB->use_empty(); 310 311 return false; 312 } 313 314 /// Returns true if the end of this instruction can be safely shortened in 315 /// length. 316 static bool isShortenableAtTheEnd(Instruction *I) { 317 // Don't shorten stores for now 318 if (isa<StoreInst>(I)) 319 return false; 320 321 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 322 switch (II->getIntrinsicID()) { 323 default: return false; 324 case Intrinsic::memset: 325 case Intrinsic::memcpy: 326 case Intrinsic::memcpy_element_unordered_atomic: 327 case Intrinsic::memset_element_unordered_atomic: 328 // Do shorten memory intrinsics. 329 // FIXME: Add memmove if it's also safe to transform. 330 return true; 331 } 332 } 333 334 // Don't shorten libcalls calls for now. 335 336 return false; 337 } 338 339 /// Returns true if the beginning of this instruction can be safely shortened 340 /// in length. 341 static bool isShortenableAtTheBeginning(Instruction *I) { 342 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be 343 // easily done by offsetting the source address. 344 return isa<AnyMemSetInst>(I); 345 } 346 347 /// Return the pointer that is being written to. 348 static Value *getStoredPointerOperand(Instruction *I) { 349 //TODO: factor this to reuse getLocForWrite 350 MemoryLocation Loc = getLocForWrite(I); 351 assert(Loc.Ptr && 352 "unable to find pointer written for analyzable instruction?"); 353 // TODO: most APIs don't expect const Value * 354 return const_cast<Value*>(Loc.Ptr); 355 } 356 357 static uint64_t getPointerSize(const Value *V, const DataLayout &DL, 358 const TargetLibraryInfo &TLI, 359 const Function *F) { 360 uint64_t Size; 361 ObjectSizeOpts Opts; 362 Opts.NullIsUnknownSize = NullPointerIsDefined(F); 363 364 if (getObjectSize(V, Size, DL, &TLI, Opts)) 365 return Size; 366 return MemoryLocation::UnknownSize; 367 } 368 369 namespace { 370 371 enum OverwriteResult { 372 OW_Begin, 373 OW_Complete, 374 OW_End, 375 OW_PartialEarlierWithFullLater, 376 OW_MaybePartial, 377 OW_Unknown 378 }; 379 380 } // end anonymous namespace 381 382 /// Return 'OW_Complete' if a store to the 'Later' location completely 383 /// overwrites a store to the 'Earlier' location. Return OW_MaybePartial 384 /// if \p Later does not completely overwrite \p Earlier, but they both 385 /// write to the same underlying object. In that case, use isPartialOverwrite to 386 /// check if \p Later partially overwrites \p Earlier. Returns 'OW_Unknown' if 387 /// nothing can be determined. 388 template <typename AATy> 389 static OverwriteResult 390 isOverwrite(const MemoryLocation &Later, const MemoryLocation &Earlier, 391 const DataLayout &DL, const TargetLibraryInfo &TLI, 392 int64_t &EarlierOff, int64_t &LaterOff, AATy &AA, 393 const Function *F) { 394 // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll 395 // get imprecise values here, though (except for unknown sizes). 396 if (!Later.Size.isPrecise() || !Earlier.Size.isPrecise()) 397 return OW_Unknown; 398 399 const uint64_t LaterSize = Later.Size.getValue(); 400 const uint64_t EarlierSize = Earlier.Size.getValue(); 401 402 const Value *P1 = Earlier.Ptr->stripPointerCasts(); 403 const Value *P2 = Later.Ptr->stripPointerCasts(); 404 405 // If the start pointers are the same, we just have to compare sizes to see if 406 // the later store was larger than the earlier store. 407 if (P1 == P2 || AA.isMustAlias(P1, P2)) { 408 // Make sure that the Later size is >= the Earlier size. 409 if (LaterSize >= EarlierSize) 410 return OW_Complete; 411 } 412 413 // Check to see if the later store is to the entire object (either a global, 414 // an alloca, or a byval/inalloca argument). If so, then it clearly 415 // overwrites any other store to the same object. 416 const Value *UO1 = getUnderlyingObject(P1), *UO2 = getUnderlyingObject(P2); 417 418 // If we can't resolve the same pointers to the same object, then we can't 419 // analyze them at all. 420 if (UO1 != UO2) 421 return OW_Unknown; 422 423 // If the "Later" store is to a recognizable object, get its size. 424 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI, F); 425 if (ObjectSize != MemoryLocation::UnknownSize) 426 if (ObjectSize == LaterSize && ObjectSize >= EarlierSize) 427 return OW_Complete; 428 429 // Okay, we have stores to two completely different pointers. Try to 430 // decompose the pointer into a "base + constant_offset" form. If the base 431 // pointers are equal, then we can reason about the two stores. 432 EarlierOff = 0; 433 LaterOff = 0; 434 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL); 435 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL); 436 437 // If the base pointers still differ, we have two completely different stores. 438 if (BP1 != BP2) 439 return OW_Unknown; 440 441 // The later store completely overlaps the earlier store if: 442 // 443 // 1. Both start at the same offset and the later one's size is greater than 444 // or equal to the earlier one's, or 445 // 446 // |--earlier--| 447 // |-- later --| 448 // 449 // 2. The earlier store has an offset greater than the later offset, but which 450 // still lies completely within the later store. 451 // 452 // |--earlier--| 453 // |----- later ------| 454 // 455 // We have to be careful here as *Off is signed while *.Size is unsigned. 456 if (EarlierOff >= LaterOff && 457 LaterSize >= EarlierSize && 458 uint64_t(EarlierOff - LaterOff) + EarlierSize <= LaterSize) 459 return OW_Complete; 460 461 // Later may overwrite earlier completely with other partial writes. 462 return OW_MaybePartial; 463 } 464 465 /// Return 'OW_Complete' if a store to the 'Later' location completely 466 /// overwrites a store to the 'Earlier' location, 'OW_End' if the end of the 467 /// 'Earlier' location is completely overwritten by 'Later', 'OW_Begin' if the 468 /// beginning of the 'Earlier' location is overwritten by 'Later'. 469 /// 'OW_PartialEarlierWithFullLater' means that an earlier (big) store was 470 /// overwritten by a latter (smaller) store which doesn't write outside the big 471 /// store's memory locations. Returns 'OW_Unknown' if nothing can be determined. 472 /// NOTE: This function must only be called if both \p Later and \p Earlier 473 /// write to the same underlying object with valid \p EarlierOff and \p 474 /// LaterOff. 475 static OverwriteResult isPartialOverwrite(const MemoryLocation &Later, 476 const MemoryLocation &Earlier, 477 int64_t EarlierOff, int64_t LaterOff, 478 Instruction *DepWrite, 479 InstOverlapIntervalsTy &IOL) { 480 const uint64_t LaterSize = Later.Size.getValue(); 481 const uint64_t EarlierSize = Earlier.Size.getValue(); 482 // We may now overlap, although the overlap is not complete. There might also 483 // be other incomplete overlaps, and together, they might cover the complete 484 // earlier write. 485 // Note: The correctness of this logic depends on the fact that this function 486 // is not even called providing DepWrite when there are any intervening reads. 487 if (EnablePartialOverwriteTracking && 488 LaterOff < int64_t(EarlierOff + EarlierSize) && 489 int64_t(LaterOff + LaterSize) >= EarlierOff) { 490 491 // Insert our part of the overlap into the map. 492 auto &IM = IOL[DepWrite]; 493 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: Earlier [" << EarlierOff 494 << ", " << int64_t(EarlierOff + EarlierSize) 495 << ") Later [" << LaterOff << ", " 496 << int64_t(LaterOff + LaterSize) << ")\n"); 497 498 // Make sure that we only insert non-overlapping intervals and combine 499 // adjacent intervals. The intervals are stored in the map with the ending 500 // offset as the key (in the half-open sense) and the starting offset as 501 // the value. 502 int64_t LaterIntStart = LaterOff, LaterIntEnd = LaterOff + LaterSize; 503 504 // Find any intervals ending at, or after, LaterIntStart which start 505 // before LaterIntEnd. 506 auto ILI = IM.lower_bound(LaterIntStart); 507 if (ILI != IM.end() && ILI->second <= LaterIntEnd) { 508 // This existing interval is overlapped with the current store somewhere 509 // in [LaterIntStart, LaterIntEnd]. Merge them by erasing the existing 510 // intervals and adjusting our start and end. 511 LaterIntStart = std::min(LaterIntStart, ILI->second); 512 LaterIntEnd = std::max(LaterIntEnd, ILI->first); 513 ILI = IM.erase(ILI); 514 515 // Continue erasing and adjusting our end in case other previous 516 // intervals are also overlapped with the current store. 517 // 518 // |--- ealier 1 ---| |--- ealier 2 ---| 519 // |------- later---------| 520 // 521 while (ILI != IM.end() && ILI->second <= LaterIntEnd) { 522 assert(ILI->second > LaterIntStart && "Unexpected interval"); 523 LaterIntEnd = std::max(LaterIntEnd, ILI->first); 524 ILI = IM.erase(ILI); 525 } 526 } 527 528 IM[LaterIntEnd] = LaterIntStart; 529 530 ILI = IM.begin(); 531 if (ILI->second <= EarlierOff && 532 ILI->first >= int64_t(EarlierOff + EarlierSize)) { 533 LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: Earlier [" 534 << EarlierOff << ", " 535 << int64_t(EarlierOff + EarlierSize) 536 << ") Composite Later [" << ILI->second << ", " 537 << ILI->first << ")\n"); 538 ++NumCompletePartials; 539 return OW_Complete; 540 } 541 } 542 543 // Check for an earlier store which writes to all the memory locations that 544 // the later store writes to. 545 if (EnablePartialStoreMerging && LaterOff >= EarlierOff && 546 int64_t(EarlierOff + EarlierSize) > LaterOff && 547 uint64_t(LaterOff - EarlierOff) + LaterSize <= EarlierSize) { 548 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite an earlier load [" 549 << EarlierOff << ", " 550 << int64_t(EarlierOff + EarlierSize) 551 << ") by a later store [" << LaterOff << ", " 552 << int64_t(LaterOff + LaterSize) << ")\n"); 553 // TODO: Maybe come up with a better name? 554 return OW_PartialEarlierWithFullLater; 555 } 556 557 // Another interesting case is if the later store overwrites the end of the 558 // earlier store. 559 // 560 // |--earlier--| 561 // |-- later --| 562 // 563 // In this case we may want to trim the size of earlier to avoid generating 564 // writes to addresses which will definitely be overwritten later 565 if (!EnablePartialOverwriteTracking && 566 (LaterOff > EarlierOff && LaterOff < int64_t(EarlierOff + EarlierSize) && 567 int64_t(LaterOff + LaterSize) >= int64_t(EarlierOff + EarlierSize))) 568 return OW_End; 569 570 // Finally, we also need to check if the later store overwrites the beginning 571 // of the earlier store. 572 // 573 // |--earlier--| 574 // |-- later --| 575 // 576 // In this case we may want to move the destination address and trim the size 577 // of earlier to avoid generating writes to addresses which will definitely 578 // be overwritten later. 579 if (!EnablePartialOverwriteTracking && 580 (LaterOff <= EarlierOff && int64_t(LaterOff + LaterSize) > EarlierOff)) { 581 assert(int64_t(LaterOff + LaterSize) < int64_t(EarlierOff + EarlierSize) && 582 "Expect to be handled as OW_Complete"); 583 return OW_Begin; 584 } 585 // Otherwise, they don't completely overlap. 586 return OW_Unknown; 587 } 588 589 /// If 'Inst' might be a self read (i.e. a noop copy of a 590 /// memory region into an identical pointer) then it doesn't actually make its 591 /// input dead in the traditional sense. Consider this case: 592 /// 593 /// memmove(A <- B) 594 /// memmove(A <- A) 595 /// 596 /// In this case, the second store to A does not make the first store to A dead. 597 /// The usual situation isn't an explicit A<-A store like this (which can be 598 /// trivially removed) but a case where two pointers may alias. 599 /// 600 /// This function detects when it is unsafe to remove a dependent instruction 601 /// because the DSE inducing instruction may be a self-read. 602 static bool isPossibleSelfRead(Instruction *Inst, 603 const MemoryLocation &InstStoreLoc, 604 Instruction *DepWrite, 605 const TargetLibraryInfo &TLI, 606 AliasAnalysis &AA) { 607 // Self reads can only happen for instructions that read memory. Get the 608 // location read. 609 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI); 610 if (!InstReadLoc.Ptr) 611 return false; // Not a reading instruction. 612 613 // If the read and written loc obviously don't alias, it isn't a read. 614 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) 615 return false; 616 617 if (isa<AnyMemCpyInst>(Inst)) { 618 // LLVM's memcpy overlap semantics are not fully fleshed out (see PR11763) 619 // but in practice memcpy(A <- B) either means that A and B are disjoint or 620 // are equal (i.e. there are not partial overlaps). Given that, if we have: 621 // 622 // memcpy/memmove(A <- B) // DepWrite 623 // memcpy(A <- B) // Inst 624 // 625 // with Inst reading/writing a >= size than DepWrite, we can reason as 626 // follows: 627 // 628 // - If A == B then both the copies are no-ops, so the DepWrite can be 629 // removed. 630 // - If A != B then A and B are disjoint locations in Inst. Since 631 // Inst.size >= DepWrite.size A and B are disjoint in DepWrite too. 632 // Therefore DepWrite can be removed. 633 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI); 634 635 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr)) 636 return false; 637 } 638 639 // If DepWrite doesn't read memory or if we can't prove it is a must alias, 640 // then it can't be considered dead. 641 return true; 642 } 643 644 /// Returns true if the memory which is accessed by the second instruction is not 645 /// modified between the first and the second instruction. 646 /// Precondition: Second instruction must be dominated by the first 647 /// instruction. 648 template <typename AATy> 649 static bool 650 memoryIsNotModifiedBetween(Instruction *FirstI, Instruction *SecondI, AATy &AA, 651 const DataLayout &DL, DominatorTree *DT) { 652 // Do a backwards scan through the CFG from SecondI to FirstI. Look for 653 // instructions which can modify the memory location accessed by SecondI. 654 // 655 // While doing the walk keep track of the address to check. It might be 656 // different in different basic blocks due to PHI translation. 657 using BlockAddressPair = std::pair<BasicBlock *, PHITransAddr>; 658 SmallVector<BlockAddressPair, 16> WorkList; 659 // Keep track of the address we visited each block with. Bail out if we 660 // visit a block with different addresses. 661 DenseMap<BasicBlock *, Value *> Visited; 662 663 BasicBlock::iterator FirstBBI(FirstI); 664 ++FirstBBI; 665 BasicBlock::iterator SecondBBI(SecondI); 666 BasicBlock *FirstBB = FirstI->getParent(); 667 BasicBlock *SecondBB = SecondI->getParent(); 668 MemoryLocation MemLoc = MemoryLocation::get(SecondI); 669 auto *MemLocPtr = const_cast<Value *>(MemLoc.Ptr); 670 671 // Start checking the SecondBB. 672 WorkList.push_back( 673 std::make_pair(SecondBB, PHITransAddr(MemLocPtr, DL, nullptr))); 674 bool isFirstBlock = true; 675 676 // Check all blocks going backward until we reach the FirstBB. 677 while (!WorkList.empty()) { 678 BlockAddressPair Current = WorkList.pop_back_val(); 679 BasicBlock *B = Current.first; 680 PHITransAddr &Addr = Current.second; 681 Value *Ptr = Addr.getAddr(); 682 683 // Ignore instructions before FirstI if this is the FirstBB. 684 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin()); 685 686 BasicBlock::iterator EI; 687 if (isFirstBlock) { 688 // Ignore instructions after SecondI if this is the first visit of SecondBB. 689 assert(B == SecondBB && "first block is not the store block"); 690 EI = SecondBBI; 691 isFirstBlock = false; 692 } else { 693 // It's not SecondBB or (in case of a loop) the second visit of SecondBB. 694 // In this case we also have to look at instructions after SecondI. 695 EI = B->end(); 696 } 697 for (; BI != EI; ++BI) { 698 Instruction *I = &*BI; 699 if (I->mayWriteToMemory() && I != SecondI) 700 if (isModSet(AA.getModRefInfo(I, MemLoc.getWithNewPtr(Ptr)))) 701 return false; 702 } 703 if (B != FirstBB) { 704 assert(B != &FirstBB->getParent()->getEntryBlock() && 705 "Should not hit the entry block because SI must be dominated by LI"); 706 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) { 707 PHITransAddr PredAddr = Addr; 708 if (PredAddr.NeedsPHITranslationFromBlock(B)) { 709 if (!PredAddr.IsPotentiallyPHITranslatable()) 710 return false; 711 if (PredAddr.PHITranslateValue(B, *PredI, DT, false)) 712 return false; 713 } 714 Value *TranslatedPtr = PredAddr.getAddr(); 715 auto Inserted = Visited.insert(std::make_pair(*PredI, TranslatedPtr)); 716 if (!Inserted.second) { 717 // We already visited this block before. If it was with a different 718 // address - bail out! 719 if (TranslatedPtr != Inserted.first->second) 720 return false; 721 // ... otherwise just skip it. 722 continue; 723 } 724 WorkList.push_back(std::make_pair(*PredI, PredAddr)); 725 } 726 } 727 } 728 return true; 729 } 730 731 /// Find all blocks that will unconditionally lead to the block BB and append 732 /// them to F. 733 static void findUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks, 734 BasicBlock *BB, DominatorTree *DT) { 735 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) { 736 BasicBlock *Pred = *I; 737 if (Pred == BB) continue; 738 Instruction *PredTI = Pred->getTerminator(); 739 if (PredTI->getNumSuccessors() != 1) 740 continue; 741 742 if (DT->isReachableFromEntry(Pred)) 743 Blocks.push_back(Pred); 744 } 745 } 746 747 /// Handle frees of entire structures whose dependency is a store 748 /// to a field of that structure. 749 static bool handleFree(CallInst *F, AliasAnalysis *AA, 750 MemoryDependenceResults *MD, DominatorTree *DT, 751 const TargetLibraryInfo *TLI, 752 InstOverlapIntervalsTy &IOL, 753 MapVector<Instruction *, bool> &ThrowableInst) { 754 bool MadeChange = false; 755 756 MemoryLocation Loc = MemoryLocation(F->getOperand(0)); 757 SmallVector<BasicBlock *, 16> Blocks; 758 Blocks.push_back(F->getParent()); 759 760 while (!Blocks.empty()) { 761 BasicBlock *BB = Blocks.pop_back_val(); 762 Instruction *InstPt = BB->getTerminator(); 763 if (BB == F->getParent()) InstPt = F; 764 765 MemDepResult Dep = 766 MD->getPointerDependencyFrom(Loc, false, InstPt->getIterator(), BB); 767 while (Dep.isDef() || Dep.isClobber()) { 768 Instruction *Dependency = Dep.getInst(); 769 if (!hasAnalyzableMemoryWrite(Dependency, *TLI) || 770 !isRemovable(Dependency)) 771 break; 772 773 Value *DepPointer = 774 getUnderlyingObject(getStoredPointerOperand(Dependency)); 775 776 // Check for aliasing. 777 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer)) 778 break; 779 780 LLVM_DEBUG( 781 dbgs() << "DSE: Dead Store to soon to be freed memory:\n DEAD: " 782 << *Dependency << '\n'); 783 784 // DCE instructions only used to calculate that store. 785 BasicBlock::iterator BBI(Dependency); 786 deleteDeadInstruction(Dependency, &BBI, *MD, *TLI, IOL, 787 ThrowableInst); 788 ++NumFastStores; 789 MadeChange = true; 790 791 // Inst's old Dependency is now deleted. Compute the next dependency, 792 // which may also be dead, as in 793 // s[0] = 0; 794 // s[1] = 0; // This has just been deleted. 795 // free(s); 796 Dep = MD->getPointerDependencyFrom(Loc, false, BBI, BB); 797 } 798 799 if (Dep.isNonLocal()) 800 findUnconditionalPreds(Blocks, BB, DT); 801 } 802 803 return MadeChange; 804 } 805 806 /// Check to see if the specified location may alias any of the stack objects in 807 /// the DeadStackObjects set. If so, they become live because the location is 808 /// being loaded. 809 static void removeAccessedObjects(const MemoryLocation &LoadedLoc, 810 SmallSetVector<const Value *, 16> &DeadStackObjects, 811 const DataLayout &DL, AliasAnalysis *AA, 812 const TargetLibraryInfo *TLI, 813 const Function *F) { 814 const Value *UnderlyingPointer = getUnderlyingObject(LoadedLoc.Ptr); 815 816 // A constant can't be in the dead pointer set. 817 if (isa<Constant>(UnderlyingPointer)) 818 return; 819 820 // If the kill pointer can be easily reduced to an alloca, don't bother doing 821 // extraneous AA queries. 822 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) { 823 DeadStackObjects.remove(UnderlyingPointer); 824 return; 825 } 826 827 // Remove objects that could alias LoadedLoc. 828 DeadStackObjects.remove_if([&](const Value *I) { 829 // See if the loaded location could alias the stack location. 830 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI, F)); 831 return !AA->isNoAlias(StackLoc, LoadedLoc); 832 }); 833 } 834 835 /// Remove dead stores to stack-allocated locations in the function end block. 836 /// Ex: 837 /// %A = alloca i32 838 /// ... 839 /// store i32 1, i32* %A 840 /// ret void 841 static bool handleEndBlock(BasicBlock &BB, AliasAnalysis *AA, 842 MemoryDependenceResults *MD, 843 const TargetLibraryInfo *TLI, 844 InstOverlapIntervalsTy &IOL, 845 MapVector<Instruction *, bool> &ThrowableInst) { 846 bool MadeChange = false; 847 848 // Keep track of all of the stack objects that are dead at the end of the 849 // function. 850 SmallSetVector<const Value*, 16> DeadStackObjects; 851 852 // Find all of the alloca'd pointers in the entry block. 853 BasicBlock &Entry = BB.getParent()->front(); 854 for (Instruction &I : Entry) { 855 if (isa<AllocaInst>(&I)) 856 DeadStackObjects.insert(&I); 857 858 // Okay, so these are dead heap objects, but if the pointer never escapes 859 // then it's leaked by this function anyways. 860 else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true)) 861 DeadStackObjects.insert(&I); 862 } 863 864 // Treat byval or inalloca arguments the same, stores to them are dead at the 865 // end of the function. 866 for (Argument &AI : BB.getParent()->args()) 867 if (AI.hasPassPointeeByValueCopyAttr()) 868 DeadStackObjects.insert(&AI); 869 870 const DataLayout &DL = BB.getModule()->getDataLayout(); 871 872 // Scan the basic block backwards 873 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){ 874 --BBI; 875 876 // If we find a store, check to see if it points into a dead stack value. 877 if (hasAnalyzableMemoryWrite(&*BBI, *TLI) && isRemovable(&*BBI)) { 878 // See through pointer-to-pointer bitcasts 879 SmallVector<const Value *, 4> Pointers; 880 getUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers); 881 882 // Stores to stack values are valid candidates for removal. 883 bool AllDead = true; 884 for (const Value *Pointer : Pointers) 885 if (!DeadStackObjects.count(Pointer)) { 886 AllDead = false; 887 break; 888 } 889 890 if (AllDead) { 891 Instruction *Dead = &*BBI; 892 893 LLVM_DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: " 894 << *Dead << "\n Objects: "; 895 for (SmallVectorImpl<const Value *>::iterator I = 896 Pointers.begin(), 897 E = Pointers.end(); 898 I != E; ++I) { 899 dbgs() << **I; 900 if (std::next(I) != E) 901 dbgs() << ", "; 902 } dbgs() 903 << '\n'); 904 905 // DCE instructions only used to calculate that store. 906 deleteDeadInstruction(Dead, &BBI, *MD, *TLI, IOL, ThrowableInst, 907 &DeadStackObjects); 908 ++NumFastStores; 909 MadeChange = true; 910 continue; 911 } 912 } 913 914 // Remove any dead non-memory-mutating instructions. 915 if (isInstructionTriviallyDead(&*BBI, TLI)) { 916 LLVM_DEBUG(dbgs() << "DSE: Removing trivially dead instruction:\n DEAD: " 917 << *&*BBI << '\n'); 918 deleteDeadInstruction(&*BBI, &BBI, *MD, *TLI, IOL, ThrowableInst, 919 &DeadStackObjects); 920 ++NumFastOther; 921 MadeChange = true; 922 continue; 923 } 924 925 if (isa<AllocaInst>(BBI)) { 926 // Remove allocas from the list of dead stack objects; there can't be 927 // any references before the definition. 928 DeadStackObjects.remove(&*BBI); 929 continue; 930 } 931 932 if (auto *Call = dyn_cast<CallBase>(&*BBI)) { 933 // Remove allocation function calls from the list of dead stack objects; 934 // there can't be any references before the definition. 935 if (isAllocLikeFn(&*BBI, TLI)) 936 DeadStackObjects.remove(&*BBI); 937 938 // If this call does not access memory, it can't be loading any of our 939 // pointers. 940 if (AA->doesNotAccessMemory(Call)) 941 continue; 942 943 // If the call might load from any of our allocas, then any store above 944 // the call is live. 945 DeadStackObjects.remove_if([&](const Value *I) { 946 // See if the call site touches the value. 947 return isRefSet(AA->getModRefInfo( 948 Call, I, getPointerSize(I, DL, *TLI, BB.getParent()))); 949 }); 950 951 // If all of the allocas were clobbered by the call then we're not going 952 // to find anything else to process. 953 if (DeadStackObjects.empty()) 954 break; 955 956 continue; 957 } 958 959 // We can remove the dead stores, irrespective of the fence and its ordering 960 // (release/acquire/seq_cst). Fences only constraints the ordering of 961 // already visible stores, it does not make a store visible to other 962 // threads. So, skipping over a fence does not change a store from being 963 // dead. 964 if (isa<FenceInst>(*BBI)) 965 continue; 966 967 MemoryLocation LoadedLoc; 968 969 // If we encounter a use of the pointer, it is no longer considered dead 970 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) { 971 if (!L->isUnordered()) // Be conservative with atomic/volatile load 972 break; 973 LoadedLoc = MemoryLocation::get(L); 974 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) { 975 LoadedLoc = MemoryLocation::get(V); 976 } else if (!BBI->mayReadFromMemory()) { 977 // Instruction doesn't read memory. Note that stores that weren't removed 978 // above will hit this case. 979 continue; 980 } else { 981 // Unknown inst; assume it clobbers everything. 982 break; 983 } 984 985 // Remove any allocas from the DeadPointer set that are loaded, as this 986 // makes any stores above the access live. 987 removeAccessedObjects(LoadedLoc, DeadStackObjects, DL, AA, TLI, BB.getParent()); 988 989 // If all of the allocas were clobbered by the access then we're not going 990 // to find anything else to process. 991 if (DeadStackObjects.empty()) 992 break; 993 } 994 995 return MadeChange; 996 } 997 998 static bool tryToShorten(Instruction *EarlierWrite, int64_t &EarlierOffset, 999 int64_t &EarlierSize, int64_t LaterOffset, 1000 int64_t LaterSize, bool IsOverwriteEnd) { 1001 // TODO: base this on the target vector size so that if the earlier 1002 // store was too small to get vector writes anyway then its likely 1003 // a good idea to shorten it 1004 // Power of 2 vector writes are probably always a bad idea to optimize 1005 // as any store/memset/memcpy is likely using vector instructions so 1006 // shortening it to not vector size is likely to be slower 1007 auto *EarlierIntrinsic = cast<AnyMemIntrinsic>(EarlierWrite); 1008 unsigned EarlierWriteAlign = EarlierIntrinsic->getDestAlignment(); 1009 if (!IsOverwriteEnd) 1010 LaterOffset = int64_t(LaterOffset + LaterSize); 1011 1012 if (!(isPowerOf2_64(LaterOffset) && EarlierWriteAlign <= LaterOffset) && 1013 !((EarlierWriteAlign != 0) && LaterOffset % EarlierWriteAlign == 0)) 1014 return false; 1015 1016 int64_t NewLength = IsOverwriteEnd 1017 ? LaterOffset - EarlierOffset 1018 : EarlierSize - (LaterOffset - EarlierOffset); 1019 1020 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(EarlierWrite)) { 1021 // When shortening an atomic memory intrinsic, the newly shortened 1022 // length must remain an integer multiple of the element size. 1023 const uint32_t ElementSize = AMI->getElementSizeInBytes(); 1024 if (0 != NewLength % ElementSize) 1025 return false; 1026 } 1027 1028 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW " 1029 << (IsOverwriteEnd ? "END" : "BEGIN") << ": " 1030 << *EarlierWrite << "\n KILLER (offset " << LaterOffset 1031 << ", " << EarlierSize << ")\n"); 1032 1033 Value *EarlierWriteLength = EarlierIntrinsic->getLength(); 1034 Value *TrimmedLength = 1035 ConstantInt::get(EarlierWriteLength->getType(), NewLength); 1036 EarlierIntrinsic->setLength(TrimmedLength); 1037 1038 EarlierSize = NewLength; 1039 if (!IsOverwriteEnd) { 1040 int64_t OffsetMoved = (LaterOffset - EarlierOffset); 1041 Value *Indices[1] = { 1042 ConstantInt::get(EarlierWriteLength->getType(), OffsetMoved)}; 1043 GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds( 1044 EarlierIntrinsic->getRawDest()->getType()->getPointerElementType(), 1045 EarlierIntrinsic->getRawDest(), Indices, "", EarlierWrite); 1046 NewDestGEP->setDebugLoc(EarlierIntrinsic->getDebugLoc()); 1047 EarlierIntrinsic->setDest(NewDestGEP); 1048 EarlierOffset = EarlierOffset + OffsetMoved; 1049 } 1050 return true; 1051 } 1052 1053 static bool tryToShortenEnd(Instruction *EarlierWrite, 1054 OverlapIntervalsTy &IntervalMap, 1055 int64_t &EarlierStart, int64_t &EarlierSize) { 1056 if (IntervalMap.empty() || !isShortenableAtTheEnd(EarlierWrite)) 1057 return false; 1058 1059 OverlapIntervalsTy::iterator OII = --IntervalMap.end(); 1060 int64_t LaterStart = OII->second; 1061 int64_t LaterSize = OII->first - LaterStart; 1062 1063 if (LaterStart > EarlierStart && LaterStart < EarlierStart + EarlierSize && 1064 LaterStart + LaterSize >= EarlierStart + EarlierSize) { 1065 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart, 1066 LaterSize, true)) { 1067 IntervalMap.erase(OII); 1068 return true; 1069 } 1070 } 1071 return false; 1072 } 1073 1074 static bool tryToShortenBegin(Instruction *EarlierWrite, 1075 OverlapIntervalsTy &IntervalMap, 1076 int64_t &EarlierStart, int64_t &EarlierSize) { 1077 if (IntervalMap.empty() || !isShortenableAtTheBeginning(EarlierWrite)) 1078 return false; 1079 1080 OverlapIntervalsTy::iterator OII = IntervalMap.begin(); 1081 int64_t LaterStart = OII->second; 1082 int64_t LaterSize = OII->first - LaterStart; 1083 1084 if (LaterStart <= EarlierStart && LaterStart + LaterSize > EarlierStart) { 1085 assert(LaterStart + LaterSize < EarlierStart + EarlierSize && 1086 "Should have been handled as OW_Complete"); 1087 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart, 1088 LaterSize, false)) { 1089 IntervalMap.erase(OII); 1090 return true; 1091 } 1092 } 1093 return false; 1094 } 1095 1096 static bool removePartiallyOverlappedStores(const DataLayout &DL, 1097 InstOverlapIntervalsTy &IOL) { 1098 bool Changed = false; 1099 for (auto OI : IOL) { 1100 Instruction *EarlierWrite = OI.first; 1101 MemoryLocation Loc = getLocForWrite(EarlierWrite); 1102 assert(isRemovable(EarlierWrite) && "Expect only removable instruction"); 1103 1104 const Value *Ptr = Loc.Ptr->stripPointerCasts(); 1105 int64_t EarlierStart = 0; 1106 int64_t EarlierSize = int64_t(Loc.Size.getValue()); 1107 GetPointerBaseWithConstantOffset(Ptr, EarlierStart, DL); 1108 OverlapIntervalsTy &IntervalMap = OI.second; 1109 Changed |= 1110 tryToShortenEnd(EarlierWrite, IntervalMap, EarlierStart, EarlierSize); 1111 if (IntervalMap.empty()) 1112 continue; 1113 Changed |= 1114 tryToShortenBegin(EarlierWrite, IntervalMap, EarlierStart, EarlierSize); 1115 } 1116 return Changed; 1117 } 1118 1119 static bool eliminateNoopStore(Instruction *Inst, BasicBlock::iterator &BBI, 1120 AliasAnalysis *AA, MemoryDependenceResults *MD, 1121 const DataLayout &DL, 1122 const TargetLibraryInfo *TLI, 1123 InstOverlapIntervalsTy &IOL, 1124 MapVector<Instruction *, bool> &ThrowableInst, 1125 DominatorTree *DT) { 1126 // Must be a store instruction. 1127 StoreInst *SI = dyn_cast<StoreInst>(Inst); 1128 if (!SI) 1129 return false; 1130 1131 // If we're storing the same value back to a pointer that we just loaded from, 1132 // then the store can be removed. 1133 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) { 1134 if (SI->getPointerOperand() == DepLoad->getPointerOperand() && 1135 isRemovable(SI) && 1136 memoryIsNotModifiedBetween(DepLoad, SI, *AA, DL, DT)) { 1137 1138 LLVM_DEBUG( 1139 dbgs() << "DSE: Remove Store Of Load from same pointer:\n LOAD: " 1140 << *DepLoad << "\n STORE: " << *SI << '\n'); 1141 1142 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, ThrowableInst); 1143 ++NumRedundantStores; 1144 return true; 1145 } 1146 } 1147 1148 // Remove null stores into the calloc'ed objects 1149 Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand()); 1150 if (StoredConstant && StoredConstant->isNullValue() && isRemovable(SI)) { 1151 Instruction *UnderlyingPointer = 1152 dyn_cast<Instruction>(getUnderlyingObject(SI->getPointerOperand())); 1153 1154 if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) && 1155 memoryIsNotModifiedBetween(UnderlyingPointer, SI, *AA, DL, DT)) { 1156 LLVM_DEBUG( 1157 dbgs() << "DSE: Remove null store to the calloc'ed object:\n DEAD: " 1158 << *Inst << "\n OBJECT: " << *UnderlyingPointer << '\n'); 1159 1160 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, ThrowableInst); 1161 ++NumRedundantStores; 1162 return true; 1163 } 1164 } 1165 return false; 1166 } 1167 1168 template <typename AATy> 1169 static Constant *tryToMergePartialOverlappingStores( 1170 StoreInst *Earlier, StoreInst *Later, int64_t InstWriteOffset, 1171 int64_t DepWriteOffset, const DataLayout &DL, AATy &AA, DominatorTree *DT) { 1172 1173 if (Earlier && isa<ConstantInt>(Earlier->getValueOperand()) && 1174 DL.typeSizeEqualsStoreSize(Earlier->getValueOperand()->getType()) && 1175 Later && isa<ConstantInt>(Later->getValueOperand()) && 1176 DL.typeSizeEqualsStoreSize(Later->getValueOperand()->getType()) && 1177 memoryIsNotModifiedBetween(Earlier, Later, AA, DL, DT)) { 1178 // If the store we find is: 1179 // a) partially overwritten by the store to 'Loc' 1180 // b) the later store is fully contained in the earlier one and 1181 // c) they both have a constant value 1182 // d) none of the two stores need padding 1183 // Merge the two stores, replacing the earlier store's value with a 1184 // merge of both values. 1185 // TODO: Deal with other constant types (vectors, etc), and probably 1186 // some mem intrinsics (if needed) 1187 1188 APInt EarlierValue = 1189 cast<ConstantInt>(Earlier->getValueOperand())->getValue(); 1190 APInt LaterValue = cast<ConstantInt>(Later->getValueOperand())->getValue(); 1191 unsigned LaterBits = LaterValue.getBitWidth(); 1192 assert(EarlierValue.getBitWidth() > LaterValue.getBitWidth()); 1193 LaterValue = LaterValue.zext(EarlierValue.getBitWidth()); 1194 1195 // Offset of the smaller store inside the larger store 1196 unsigned BitOffsetDiff = (InstWriteOffset - DepWriteOffset) * 8; 1197 unsigned LShiftAmount = DL.isBigEndian() ? EarlierValue.getBitWidth() - 1198 BitOffsetDiff - LaterBits 1199 : BitOffsetDiff; 1200 APInt Mask = APInt::getBitsSet(EarlierValue.getBitWidth(), LShiftAmount, 1201 LShiftAmount + LaterBits); 1202 // Clear the bits we'll be replacing, then OR with the smaller 1203 // store, shifted appropriately. 1204 APInt Merged = (EarlierValue & ~Mask) | (LaterValue << LShiftAmount); 1205 LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n Earlier: " << *Earlier 1206 << "\n Later: " << *Later 1207 << "\n Merged Value: " << Merged << '\n'); 1208 return ConstantInt::get(Earlier->getValueOperand()->getType(), Merged); 1209 } 1210 return nullptr; 1211 } 1212 1213 static bool eliminateDeadStores(BasicBlock &BB, AliasAnalysis *AA, 1214 MemoryDependenceResults *MD, DominatorTree *DT, 1215 const TargetLibraryInfo *TLI) { 1216 const DataLayout &DL = BB.getModule()->getDataLayout(); 1217 bool MadeChange = false; 1218 1219 MapVector<Instruction *, bool> ThrowableInst; 1220 1221 // A map of interval maps representing partially-overwritten value parts. 1222 InstOverlapIntervalsTy IOL; 1223 1224 // Do a top-down walk on the BB. 1225 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) { 1226 // Handle 'free' calls specially. 1227 if (CallInst *F = isFreeCall(&*BBI, TLI)) { 1228 MadeChange |= handleFree(F, AA, MD, DT, TLI, IOL, ThrowableInst); 1229 // Increment BBI after handleFree has potentially deleted instructions. 1230 // This ensures we maintain a valid iterator. 1231 ++BBI; 1232 continue; 1233 } 1234 1235 Instruction *Inst = &*BBI++; 1236 1237 if (Inst->mayThrow()) { 1238 ThrowableInst[Inst] = true; 1239 continue; 1240 } 1241 1242 // Check to see if Inst writes to memory. If not, continue. 1243 if (!hasAnalyzableMemoryWrite(Inst, *TLI)) 1244 continue; 1245 1246 // eliminateNoopStore will update in iterator, if necessary. 1247 if (eliminateNoopStore(Inst, BBI, AA, MD, DL, TLI, IOL, 1248 ThrowableInst, DT)) { 1249 MadeChange = true; 1250 continue; 1251 } 1252 1253 // If we find something that writes memory, get its memory dependence. 1254 MemDepResult InstDep = MD->getDependency(Inst); 1255 1256 // Ignore any store where we can't find a local dependence. 1257 // FIXME: cross-block DSE would be fun. :) 1258 if (!InstDep.isDef() && !InstDep.isClobber()) 1259 continue; 1260 1261 // Figure out what location is being stored to. 1262 MemoryLocation Loc = getLocForWrite(Inst); 1263 1264 // If we didn't get a useful location, fail. 1265 if (!Loc.Ptr) 1266 continue; 1267 1268 // Loop until we find a store we can eliminate or a load that 1269 // invalidates the analysis. Without an upper bound on the number of 1270 // instructions examined, this analysis can become very time-consuming. 1271 // However, the potential gain diminishes as we process more instructions 1272 // without eliminating any of them. Therefore, we limit the number of 1273 // instructions we look at. 1274 auto Limit = MD->getDefaultBlockScanLimit(); 1275 while (InstDep.isDef() || InstDep.isClobber()) { 1276 // Get the memory clobbered by the instruction we depend on. MemDep will 1277 // skip any instructions that 'Loc' clearly doesn't interact with. If we 1278 // end up depending on a may- or must-aliased load, then we can't optimize 1279 // away the store and we bail out. However, if we depend on something 1280 // that overwrites the memory location we *can* potentially optimize it. 1281 // 1282 // Find out what memory location the dependent instruction stores. 1283 Instruction *DepWrite = InstDep.getInst(); 1284 if (!hasAnalyzableMemoryWrite(DepWrite, *TLI)) 1285 break; 1286 MemoryLocation DepLoc = getLocForWrite(DepWrite); 1287 // If we didn't get a useful location, or if it isn't a size, bail out. 1288 if (!DepLoc.Ptr) 1289 break; 1290 1291 // Find the last throwable instruction not removed by call to 1292 // deleteDeadInstruction. 1293 Instruction *LastThrowing = nullptr; 1294 if (!ThrowableInst.empty()) 1295 LastThrowing = ThrowableInst.back().first; 1296 1297 // Make sure we don't look past a call which might throw. This is an 1298 // issue because MemoryDependenceAnalysis works in the wrong direction: 1299 // it finds instructions which dominate the current instruction, rather than 1300 // instructions which are post-dominated by the current instruction. 1301 // 1302 // If the underlying object is a non-escaping memory allocation, any store 1303 // to it is dead along the unwind edge. Otherwise, we need to preserve 1304 // the store. 1305 if (LastThrowing && DepWrite->comesBefore(LastThrowing)) { 1306 const Value *Underlying = getUnderlyingObject(DepLoc.Ptr); 1307 bool IsStoreDeadOnUnwind = isa<AllocaInst>(Underlying); 1308 if (!IsStoreDeadOnUnwind) { 1309 // We're looking for a call to an allocation function 1310 // where the allocation doesn't escape before the last 1311 // throwing instruction; PointerMayBeCaptured 1312 // reasonably fast approximation. 1313 IsStoreDeadOnUnwind = isAllocLikeFn(Underlying, TLI) && 1314 !PointerMayBeCaptured(Underlying, false, true); 1315 } 1316 if (!IsStoreDeadOnUnwind) 1317 break; 1318 } 1319 1320 // If we find a write that is a) removable (i.e., non-volatile), b) is 1321 // completely obliterated by the store to 'Loc', and c) which we know that 1322 // 'Inst' doesn't load from, then we can remove it. 1323 // Also try to merge two stores if a later one only touches memory written 1324 // to by the earlier one. 1325 if (isRemovable(DepWrite) && 1326 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) { 1327 int64_t InstWriteOffset, DepWriteOffset; 1328 OverwriteResult OR = isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, 1329 InstWriteOffset, *AA, BB.getParent()); 1330 if (OR == OW_MaybePartial) 1331 OR = isPartialOverwrite(Loc, DepLoc, DepWriteOffset, InstWriteOffset, 1332 DepWrite, IOL); 1333 1334 if (OR == OW_Complete) { 1335 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *DepWrite 1336 << "\n KILLER: " << *Inst << '\n'); 1337 1338 // Delete the store and now-dead instructions that feed it. 1339 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, 1340 ThrowableInst); 1341 ++NumFastStores; 1342 MadeChange = true; 1343 1344 // We erased DepWrite; start over. 1345 InstDep = MD->getDependency(Inst); 1346 continue; 1347 } else if ((OR == OW_End && isShortenableAtTheEnd(DepWrite)) || 1348 ((OR == OW_Begin && 1349 isShortenableAtTheBeginning(DepWrite)))) { 1350 assert(!EnablePartialOverwriteTracking && "Do not expect to perform " 1351 "when partial-overwrite " 1352 "tracking is enabled"); 1353 // The overwrite result is known, so these must be known, too. 1354 int64_t EarlierSize = DepLoc.Size.getValue(); 1355 int64_t LaterSize = Loc.Size.getValue(); 1356 bool IsOverwriteEnd = (OR == OW_End); 1357 MadeChange |= tryToShorten(DepWrite, DepWriteOffset, EarlierSize, 1358 InstWriteOffset, LaterSize, IsOverwriteEnd); 1359 } else if (EnablePartialStoreMerging && 1360 OR == OW_PartialEarlierWithFullLater) { 1361 auto *Earlier = dyn_cast<StoreInst>(DepWrite); 1362 auto *Later = dyn_cast<StoreInst>(Inst); 1363 if (Constant *C = tryToMergePartialOverlappingStores( 1364 Earlier, Later, InstWriteOffset, DepWriteOffset, DL, *AA, 1365 DT)) { 1366 auto *SI = new StoreInst( 1367 C, Earlier->getPointerOperand(), false, Earlier->getAlign(), 1368 Earlier->getOrdering(), Earlier->getSyncScopeID(), DepWrite); 1369 1370 unsigned MDToKeep[] = {LLVMContext::MD_dbg, LLVMContext::MD_tbaa, 1371 LLVMContext::MD_alias_scope, 1372 LLVMContext::MD_noalias, 1373 LLVMContext::MD_nontemporal}; 1374 SI->copyMetadata(*DepWrite, MDToKeep); 1375 ++NumModifiedStores; 1376 1377 // Delete the old stores and now-dead instructions that feed them. 1378 deleteDeadInstruction(Inst, &BBI, *MD, *TLI, IOL, 1379 ThrowableInst); 1380 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, 1381 ThrowableInst); 1382 MadeChange = true; 1383 1384 // We erased DepWrite and Inst (Loc); start over. 1385 break; 1386 } 1387 } 1388 } 1389 1390 // If this is a may-aliased store that is clobbering the store value, we 1391 // can keep searching past it for another must-aliased pointer that stores 1392 // to the same location. For example, in: 1393 // store -> P 1394 // store -> Q 1395 // store -> P 1396 // we can remove the first store to P even though we don't know if P and Q 1397 // alias. 1398 if (DepWrite == &BB.front()) break; 1399 1400 // Can't look past this instruction if it might read 'Loc'. 1401 if (isRefSet(AA->getModRefInfo(DepWrite, Loc))) 1402 break; 1403 1404 InstDep = MD->getPointerDependencyFrom(Loc, /*isLoad=*/ false, 1405 DepWrite->getIterator(), &BB, 1406 /*QueryInst=*/ nullptr, &Limit); 1407 } 1408 } 1409 1410 if (EnablePartialOverwriteTracking) 1411 MadeChange |= removePartiallyOverlappedStores(DL, IOL); 1412 1413 // If this block ends in a return, unwind, or unreachable, all allocas are 1414 // dead at its end, which means stores to them are also dead. 1415 if (BB.getTerminator()->getNumSuccessors() == 0) 1416 MadeChange |= handleEndBlock(BB, AA, MD, TLI, IOL, ThrowableInst); 1417 1418 return MadeChange; 1419 } 1420 1421 static bool eliminateDeadStores(Function &F, AliasAnalysis *AA, 1422 MemoryDependenceResults *MD, DominatorTree *DT, 1423 const TargetLibraryInfo *TLI) { 1424 bool MadeChange = false; 1425 for (BasicBlock &BB : F) 1426 // Only check non-dead blocks. Dead blocks may have strange pointer 1427 // cycles that will confuse alias analysis. 1428 if (DT->isReachableFromEntry(&BB)) 1429 MadeChange |= eliminateDeadStores(BB, AA, MD, DT, TLI); 1430 1431 return MadeChange; 1432 } 1433 1434 namespace { 1435 //============================================================================= 1436 // MemorySSA backed dead store elimination. 1437 // 1438 // The code below implements dead store elimination using MemorySSA. It uses 1439 // the following general approach: given a MemoryDef, walk upwards to find 1440 // clobbering MemoryDefs that may be killed by the starting def. Then check 1441 // that there are no uses that may read the location of the original MemoryDef 1442 // in between both MemoryDefs. A bit more concretely: 1443 // 1444 // For all MemoryDefs StartDef: 1445 // 1. Get the next dominating clobbering MemoryDef (DomAccess) by walking 1446 // upwards. 1447 // 2. Check that there are no reads between DomAccess and the StartDef by 1448 // checking all uses starting at DomAccess and walking until we see StartDef. 1449 // 3. For each found DomDef, check that: 1450 // 1. There are no barrier instructions between DomDef and StartDef (like 1451 // throws or stores with ordering constraints). 1452 // 2. StartDef is executed whenever DomDef is executed. 1453 // 3. StartDef completely overwrites DomDef. 1454 // 4. Erase DomDef from the function and MemorySSA. 1455 1456 // Returns true if \p M is an intrisnic that does not read or write memory. 1457 bool isNoopIntrinsic(MemoryUseOrDef *M) { 1458 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(M->getMemoryInst())) { 1459 switch (II->getIntrinsicID()) { 1460 case Intrinsic::lifetime_start: 1461 case Intrinsic::lifetime_end: 1462 case Intrinsic::invariant_end: 1463 case Intrinsic::launder_invariant_group: 1464 case Intrinsic::assume: 1465 return true; 1466 case Intrinsic::dbg_addr: 1467 case Intrinsic::dbg_declare: 1468 case Intrinsic::dbg_label: 1469 case Intrinsic::dbg_value: 1470 llvm_unreachable("Intrinsic should not be modeled in MemorySSA"); 1471 default: 1472 return false; 1473 } 1474 } 1475 return false; 1476 } 1477 1478 // Check if we can ignore \p D for DSE. 1479 bool canSkipDef(MemoryDef *D, bool DefVisibleToCaller) { 1480 Instruction *DI = D->getMemoryInst(); 1481 // Calls that only access inaccessible memory cannot read or write any memory 1482 // locations we consider for elimination. 1483 if (auto *CB = dyn_cast<CallBase>(DI)) 1484 if (CB->onlyAccessesInaccessibleMemory()) 1485 return true; 1486 1487 // We can eliminate stores to locations not visible to the caller across 1488 // throwing instructions. 1489 if (DI->mayThrow() && !DefVisibleToCaller) 1490 return true; 1491 1492 // We can remove the dead stores, irrespective of the fence and its ordering 1493 // (release/acquire/seq_cst). Fences only constraints the ordering of 1494 // already visible stores, it does not make a store visible to other 1495 // threads. So, skipping over a fence does not change a store from being 1496 // dead. 1497 if (isa<FenceInst>(DI)) 1498 return true; 1499 1500 // Skip intrinsics that do not really read or modify memory. 1501 if (isNoopIntrinsic(D)) 1502 return true; 1503 1504 return false; 1505 } 1506 1507 struct DSEState { 1508 Function &F; 1509 AliasAnalysis &AA; 1510 1511 /// The single BatchAA instance that is used to cache AA queries. It will 1512 /// not be invalidated over the whole run. This is safe, because: 1513 /// 1. Only memory writes are removed, so the alias cache for memory 1514 /// locations remains valid. 1515 /// 2. No new instructions are added (only instructions removed), so cached 1516 /// information for a deleted value cannot be accessed by a re-used new 1517 /// value pointer. 1518 BatchAAResults BatchAA; 1519 1520 MemorySSA &MSSA; 1521 DominatorTree &DT; 1522 PostDominatorTree &PDT; 1523 const TargetLibraryInfo &TLI; 1524 const DataLayout &DL; 1525 1526 // All MemoryDefs that potentially could kill other MemDefs. 1527 SmallVector<MemoryDef *, 64> MemDefs; 1528 // Any that should be skipped as they are already deleted 1529 SmallPtrSet<MemoryAccess *, 4> SkipStores; 1530 // Keep track of all of the objects that are invisible to the caller before 1531 // the function returns. 1532 // SmallPtrSet<const Value *, 16> InvisibleToCallerBeforeRet; 1533 DenseMap<const Value *, bool> InvisibleToCallerBeforeRet; 1534 // Keep track of all of the objects that are invisible to the caller after 1535 // the function returns. 1536 DenseMap<const Value *, bool> InvisibleToCallerAfterRet; 1537 // Keep track of blocks with throwing instructions not modeled in MemorySSA. 1538 SmallPtrSet<BasicBlock *, 16> ThrowingBlocks; 1539 // Post-order numbers for each basic block. Used to figure out if memory 1540 // accesses are executed before another access. 1541 DenseMap<BasicBlock *, unsigned> PostOrderNumbers; 1542 1543 /// Keep track of instructions (partly) overlapping with killing MemoryDefs per 1544 /// basic block. 1545 DenseMap<BasicBlock *, InstOverlapIntervalsTy> IOLs; 1546 1547 struct CheckCache { 1548 SmallPtrSet<MemoryAccess *, 16> KnownNoReads; 1549 SmallPtrSet<MemoryAccess *, 16> KnownReads; 1550 1551 bool isKnownNoRead(MemoryAccess *A) const { 1552 return KnownNoReads.find(A) != KnownNoReads.end(); 1553 } 1554 bool isKnownRead(MemoryAccess *A) const { 1555 return KnownReads.find(A) != KnownReads.end(); 1556 } 1557 }; 1558 1559 DSEState(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, DominatorTree &DT, 1560 PostDominatorTree &PDT, const TargetLibraryInfo &TLI) 1561 : F(F), AA(AA), BatchAA(AA), MSSA(MSSA), DT(DT), PDT(PDT), TLI(TLI), 1562 DL(F.getParent()->getDataLayout()) {} 1563 1564 static DSEState get(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, 1565 DominatorTree &DT, PostDominatorTree &PDT, 1566 const TargetLibraryInfo &TLI) { 1567 DSEState State(F, AA, MSSA, DT, PDT, TLI); 1568 // Collect blocks with throwing instructions not modeled in MemorySSA and 1569 // alloc-like objects. 1570 unsigned PO = 0; 1571 for (BasicBlock *BB : post_order(&F)) { 1572 State.PostOrderNumbers[BB] = PO++; 1573 for (Instruction &I : *BB) { 1574 MemoryAccess *MA = MSSA.getMemoryAccess(&I); 1575 if (I.mayThrow() && !MA) 1576 State.ThrowingBlocks.insert(I.getParent()); 1577 1578 auto *MD = dyn_cast_or_null<MemoryDef>(MA); 1579 if (MD && State.MemDefs.size() < MemorySSADefsPerBlockLimit && 1580 (State.getLocForWriteEx(&I) || State.isMemTerminatorInst(&I))) 1581 State.MemDefs.push_back(MD); 1582 } 1583 } 1584 1585 // Treat byval or inalloca arguments the same as Allocas, stores to them are 1586 // dead at the end of the function. 1587 for (Argument &AI : F.args()) 1588 if (AI.hasPassPointeeByValueCopyAttr()) { 1589 // For byval, the caller doesn't know the address of the allocation. 1590 if (AI.hasByValAttr()) 1591 State.InvisibleToCallerBeforeRet.insert({&AI, true}); 1592 State.InvisibleToCallerAfterRet.insert({&AI, true}); 1593 } 1594 1595 return State; 1596 } 1597 1598 bool isInvisibleToCallerAfterRet(const Value *V) { 1599 if (isa<AllocaInst>(V)) 1600 return true; 1601 auto I = InvisibleToCallerAfterRet.insert({V, false}); 1602 if (I.second) { 1603 if (!isInvisibleToCallerBeforeRet(V)) { 1604 I.first->second = false; 1605 } else { 1606 auto *Inst = dyn_cast<Instruction>(V); 1607 if (Inst && isAllocLikeFn(Inst, &TLI)) 1608 I.first->second = !PointerMayBeCaptured(V, true, false); 1609 } 1610 } 1611 return I.first->second; 1612 } 1613 1614 bool isInvisibleToCallerBeforeRet(const Value *V) { 1615 if (isa<AllocaInst>(V)) 1616 return true; 1617 auto I = InvisibleToCallerBeforeRet.insert({V, false}); 1618 if (I.second) { 1619 auto *Inst = dyn_cast<Instruction>(V); 1620 if (Inst && isAllocLikeFn(Inst, &TLI)) 1621 // NOTE: This could be made more precise by PointerMayBeCapturedBefore 1622 // with the killing MemoryDef. But we refrain from doing so for now to 1623 // limit compile-time and this does not cause any changes to the number 1624 // of stores removed on a large test set in practice. 1625 I.first->second = !PointerMayBeCaptured(V, false, true); 1626 } 1627 return I.first->second; 1628 } 1629 1630 Optional<MemoryLocation> getLocForWriteEx(Instruction *I) const { 1631 if (!I->mayWriteToMemory()) 1632 return None; 1633 1634 if (auto *MTI = dyn_cast<AnyMemIntrinsic>(I)) 1635 return {MemoryLocation::getForDest(MTI)}; 1636 1637 if (auto *CB = dyn_cast<CallBase>(I)) { 1638 LibFunc LF; 1639 if (TLI.getLibFunc(*CB, LF) && TLI.has(LF)) { 1640 switch (LF) { 1641 case LibFunc_strcpy: 1642 case LibFunc_strncpy: 1643 case LibFunc_strcat: 1644 case LibFunc_strncat: 1645 return {MemoryLocation(CB->getArgOperand(0))}; 1646 default: 1647 break; 1648 } 1649 } 1650 switch (CB->getIntrinsicID()) { 1651 case Intrinsic::init_trampoline: 1652 return {MemoryLocation(CB->getArgOperand(0))}; 1653 default: 1654 break; 1655 } 1656 return None; 1657 } 1658 1659 return MemoryLocation::getOrNone(I); 1660 } 1661 1662 /// Returns true if \p Use completely overwrites \p DefLoc. 1663 bool isCompleteOverwrite(MemoryLocation DefLoc, Instruction *UseInst) { 1664 // UseInst has a MemoryDef associated in MemorySSA. It's possible for a 1665 // MemoryDef to not write to memory, e.g. a volatile load is modeled as a 1666 // MemoryDef. 1667 if (!UseInst->mayWriteToMemory()) 1668 return false; 1669 1670 if (auto *CB = dyn_cast<CallBase>(UseInst)) 1671 if (CB->onlyAccessesInaccessibleMemory()) 1672 return false; 1673 1674 int64_t InstWriteOffset, DepWriteOffset; 1675 auto CC = getLocForWriteEx(UseInst); 1676 return CC && isOverwrite(*CC, DefLoc, DL, TLI, DepWriteOffset, 1677 InstWriteOffset, BatchAA, &F) == OW_Complete; 1678 } 1679 1680 /// Returns true if \p Def is not read before returning from the function. 1681 bool isWriteAtEndOfFunction(MemoryDef *Def) { 1682 LLVM_DEBUG(dbgs() << " Check if def " << *Def << " (" 1683 << *Def->getMemoryInst() 1684 << ") is at the end the function \n"); 1685 1686 auto MaybeLoc = getLocForWriteEx(Def->getMemoryInst()); 1687 if (!MaybeLoc) { 1688 LLVM_DEBUG(dbgs() << " ... could not get location for write.\n"); 1689 return false; 1690 } 1691 1692 SmallVector<MemoryAccess *, 4> WorkList; 1693 SmallPtrSet<MemoryAccess *, 8> Visited; 1694 auto PushMemUses = [&WorkList, &Visited](MemoryAccess *Acc) { 1695 if (!Visited.insert(Acc).second) 1696 return; 1697 for (Use &U : Acc->uses()) 1698 WorkList.push_back(cast<MemoryAccess>(U.getUser())); 1699 }; 1700 PushMemUses(Def); 1701 for (unsigned I = 0; I < WorkList.size(); I++) { 1702 if (WorkList.size() >= MemorySSAScanLimit) { 1703 LLVM_DEBUG(dbgs() << " ... hit exploration limit.\n"); 1704 return false; 1705 } 1706 1707 MemoryAccess *UseAccess = WorkList[I]; 1708 if (isa<MemoryPhi>(UseAccess)) { 1709 PushMemUses(UseAccess); 1710 continue; 1711 } 1712 1713 // TODO: Checking for aliasing is expensive. Consider reducing the amount 1714 // of times this is called and/or caching it. 1715 Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst(); 1716 if (isReadClobber(*MaybeLoc, UseInst)) { 1717 LLVM_DEBUG(dbgs() << " ... hit read clobber " << *UseInst << ".\n"); 1718 return false; 1719 } 1720 1721 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) 1722 PushMemUses(UseDef); 1723 } 1724 return true; 1725 } 1726 1727 /// If \p I is a memory terminator like llvm.lifetime.end or free, return a 1728 /// pair with the MemoryLocation terminated by \p I and a boolean flag 1729 /// indicating whether \p I is a free-like call. 1730 Optional<std::pair<MemoryLocation, bool>> 1731 getLocForTerminator(Instruction *I) const { 1732 uint64_t Len; 1733 Value *Ptr; 1734 if (match(I, m_Intrinsic<Intrinsic::lifetime_end>(m_ConstantInt(Len), 1735 m_Value(Ptr)))) 1736 return {std::make_pair(MemoryLocation(Ptr, Len), false)}; 1737 1738 if (auto *CB = dyn_cast<CallBase>(I)) { 1739 if (isFreeCall(I, &TLI)) 1740 return {std::make_pair(MemoryLocation(CB->getArgOperand(0)), true)}; 1741 } 1742 1743 return None; 1744 } 1745 1746 /// Returns true if \p I is a memory terminator instruction like 1747 /// llvm.lifetime.end or free. 1748 bool isMemTerminatorInst(Instruction *I) const { 1749 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I); 1750 return (II && II->getIntrinsicID() == Intrinsic::lifetime_end) || 1751 isFreeCall(I, &TLI); 1752 } 1753 1754 /// Returns true if \p MaybeTerm is a memory terminator for the same 1755 /// underlying object as \p DefLoc. 1756 bool isMemTerminator(MemoryLocation DefLoc, Instruction *MaybeTerm) { 1757 Optional<std::pair<MemoryLocation, bool>> MaybeTermLoc = 1758 getLocForTerminator(MaybeTerm); 1759 1760 if (!MaybeTermLoc) 1761 return false; 1762 1763 // If the terminator is a free-like call, all accesses to the underlying 1764 // object can be considered terminated. 1765 if (MaybeTermLoc->second) 1766 DefLoc = MemoryLocation(getUnderlyingObject(DefLoc.Ptr)); 1767 return BatchAA.isMustAlias(MaybeTermLoc->first, DefLoc); 1768 } 1769 1770 // Returns true if \p Use may read from \p DefLoc. 1771 bool isReadClobber(MemoryLocation DefLoc, Instruction *UseInst) { 1772 if (!UseInst->mayReadFromMemory()) 1773 return false; 1774 1775 if (auto *CB = dyn_cast<CallBase>(UseInst)) 1776 if (CB->onlyAccessesInaccessibleMemory()) 1777 return false; 1778 1779 // NOTE: For calls, the number of stores removed could be slightly improved 1780 // by using AA.callCapturesBefore(UseInst, DefLoc, &DT), but that showed to 1781 // be expensive compared to the benefits in practice. For now, avoid more 1782 // expensive analysis to limit compile-time. 1783 return isRefSet(BatchAA.getModRefInfo(UseInst, DefLoc)); 1784 } 1785 1786 // Find a MemoryDef writing to \p DefLoc and dominating \p Current, with no 1787 // read access between them or on any other path to a function exit block if 1788 // \p DefLoc is not accessible after the function returns. If there is no such 1789 // MemoryDef, return None. The returned value may not (completely) overwrite 1790 // \p DefLoc. Currently we bail out when we encounter an aliasing MemoryUse 1791 // (read). 1792 Optional<MemoryAccess *> 1793 getDomMemoryDef(MemoryDef *KillingDef, MemoryAccess *Current, 1794 MemoryLocation DefLoc, const Value *DefUO, CheckCache &Cache, 1795 unsigned &ScanLimit) { 1796 if (ScanLimit == 0) { 1797 LLVM_DEBUG(dbgs() << "\n ... hit scan limit\n"); 1798 return None; 1799 } 1800 1801 MemoryAccess *DomAccess; 1802 MemoryAccess *StartAccess = Current; 1803 bool StepAgain; 1804 LLVM_DEBUG(dbgs() << " trying to get dominating access for " << *Current 1805 << "\n"); 1806 // Find the next clobbering Mod access for DefLoc, starting at Current. 1807 do { 1808 StepAgain = false; 1809 // Reached TOP. 1810 if (MSSA.isLiveOnEntryDef(Current)) 1811 return None; 1812 1813 if (isa<MemoryPhi>(Current)) { 1814 DomAccess = Current; 1815 break; 1816 } 1817 MemoryUseOrDef *CurrentUD = cast<MemoryUseOrDef>(Current); 1818 // Look for access that clobber DefLoc. 1819 DomAccess = MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(CurrentUD, 1820 DefLoc); 1821 if (MSSA.isLiveOnEntryDef(DomAccess)) 1822 return None; 1823 1824 if (isa<MemoryPhi>(DomAccess)) 1825 break; 1826 1827 // Check if we can skip DomDef for DSE. 1828 MemoryDef *DomDef = dyn_cast<MemoryDef>(DomAccess); 1829 if (DomDef && canSkipDef(DomDef, !isInvisibleToCallerBeforeRet(DefUO))) { 1830 StepAgain = true; 1831 Current = DomDef->getDefiningAccess(); 1832 } 1833 1834 } while (StepAgain); 1835 1836 // Accesses to objects accessible after the function returns can only be 1837 // eliminated if the access is killed along all paths to the exit. Collect 1838 // the blocks with killing (=completely overwriting MemoryDefs) and check if 1839 // they cover all paths from DomAccess to any function exit. 1840 SmallPtrSet<Instruction *, 16> KillingDefs; 1841 KillingDefs.insert(KillingDef->getMemoryInst()); 1842 Instruction *DomMemInst = isa<MemoryDef>(DomAccess) 1843 ? cast<MemoryDef>(DomAccess)->getMemoryInst() 1844 : nullptr; 1845 LLVM_DEBUG({ 1846 dbgs() << " Checking for reads of " << *DomAccess; 1847 if (DomMemInst) 1848 dbgs() << " (" << *DomMemInst << ")\n"; 1849 else 1850 dbgs() << ")\n"; 1851 }); 1852 1853 SmallSetVector<MemoryAccess *, 32> WorkList; 1854 auto PushMemUses = [&WorkList](MemoryAccess *Acc) { 1855 for (Use &U : Acc->uses()) 1856 WorkList.insert(cast<MemoryAccess>(U.getUser())); 1857 }; 1858 PushMemUses(DomAccess); 1859 1860 // Optimistically collect all accesses for reads. If we do not find any 1861 // read clobbers, add them to the cache. 1862 SmallPtrSet<MemoryAccess *, 16> KnownNoReads; 1863 if (!DomMemInst || !DomMemInst->mayReadFromMemory()) 1864 KnownNoReads.insert(DomAccess); 1865 // Check if DomDef may be read. 1866 for (unsigned I = 0; I < WorkList.size(); I++) { 1867 MemoryAccess *UseAccess = WorkList[I]; 1868 1869 LLVM_DEBUG(dbgs() << " " << *UseAccess); 1870 // Bail out if the number of accesses to check exceeds the scan limit. 1871 if (ScanLimit < (WorkList.size() - I)) { 1872 LLVM_DEBUG(dbgs() << "\n ... hit scan limit\n"); 1873 return None; 1874 } 1875 --ScanLimit; 1876 NumDomMemDefChecks++; 1877 1878 // Check if we already visited this access. 1879 if (Cache.isKnownNoRead(UseAccess)) { 1880 LLVM_DEBUG(dbgs() << " ... skip, discovered that " << *UseAccess 1881 << " is safe earlier.\n"); 1882 continue; 1883 } 1884 if (Cache.isKnownRead(UseAccess)) { 1885 LLVM_DEBUG(dbgs() << " ... bail out, discovered that " << *UseAccess 1886 << " has a read-clobber earlier.\n"); 1887 return None; 1888 } 1889 KnownNoReads.insert(UseAccess); 1890 1891 if (isa<MemoryPhi>(UseAccess)) { 1892 if (any_of(KillingDefs, [this, UseAccess](Instruction *KI) { 1893 return DT.properlyDominates(KI->getParent(), 1894 UseAccess->getBlock()); 1895 })) { 1896 LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing block\n"); 1897 continue; 1898 } 1899 LLVM_DEBUG(dbgs() << "\n ... adding PHI uses\n"); 1900 PushMemUses(UseAccess); 1901 continue; 1902 } 1903 1904 Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst(); 1905 LLVM_DEBUG(dbgs() << " (" << *UseInst << ")\n"); 1906 1907 if (any_of(KillingDefs, [this, UseInst](Instruction *KI) { 1908 return DT.dominates(KI, UseInst); 1909 })) { 1910 LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing def\n"); 1911 continue; 1912 } 1913 1914 if (isNoopIntrinsic(cast<MemoryUseOrDef>(UseAccess))) { 1915 LLVM_DEBUG(dbgs() << " ... adding uses of intrinsic\n"); 1916 PushMemUses(UseAccess); 1917 continue; 1918 } 1919 1920 // A memory terminator kills all preceeding MemoryDefs and all succeeding 1921 // MemoryAccesses. We do not have to check it's users. 1922 if (isMemTerminator(DefLoc, UseInst)) 1923 continue; 1924 1925 // Uses which may read the original MemoryDef mean we cannot eliminate the 1926 // original MD. Stop walk. 1927 if (isReadClobber(DefLoc, UseInst)) { 1928 LLVM_DEBUG(dbgs() << " ... found read clobber\n"); 1929 Cache.KnownReads.insert(UseAccess); 1930 Cache.KnownReads.insert(StartAccess); 1931 Cache.KnownReads.insert(DomAccess); 1932 return None; 1933 } 1934 1935 // For the KillingDef and DomAccess we only have to check if it reads the 1936 // memory location. 1937 // TODO: It would probably be better to check for self-reads before 1938 // calling the function. 1939 if (KillingDef == UseAccess || DomAccess == UseAccess) { 1940 LLVM_DEBUG(dbgs() << " ... skipping killing def/dom access\n"); 1941 continue; 1942 } 1943 1944 // Check all uses for MemoryDefs, except for defs completely overwriting 1945 // the original location. Otherwise we have to check uses of *all* 1946 // MemoryDefs we discover, including non-aliasing ones. Otherwise we might 1947 // miss cases like the following 1948 // 1 = Def(LoE) ; <----- DomDef stores [0,1] 1949 // 2 = Def(1) ; (2, 1) = NoAlias, stores [2,3] 1950 // Use(2) ; MayAlias 2 *and* 1, loads [0, 3]. 1951 // (The Use points to the *first* Def it may alias) 1952 // 3 = Def(1) ; <---- Current (3, 2) = NoAlias, (3,1) = MayAlias, 1953 // stores [0,1] 1954 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) { 1955 if (isCompleteOverwrite(DefLoc, UseInst)) { 1956 if (!isInvisibleToCallerAfterRet(DefUO) && UseAccess != DomAccess) { 1957 BasicBlock *MaybeKillingBlock = UseInst->getParent(); 1958 if (PostOrderNumbers.find(MaybeKillingBlock)->second < 1959 PostOrderNumbers.find(DomAccess->getBlock())->second) { 1960 1961 LLVM_DEBUG(dbgs() 1962 << " ... found killing def " << *UseInst << "\n"); 1963 KillingDefs.insert(UseInst); 1964 } 1965 } 1966 } else 1967 PushMemUses(UseDef); 1968 } 1969 } 1970 1971 // For accesses to locations visible after the function returns, make sure 1972 // that the location is killed (=overwritten) along all paths from DomAccess 1973 // to the exit. 1974 if (!isInvisibleToCallerAfterRet(DefUO)) { 1975 SmallPtrSet<BasicBlock *, 16> KillingBlocks; 1976 for (Instruction *KD : KillingDefs) 1977 KillingBlocks.insert(KD->getParent()); 1978 assert(!KillingBlocks.empty() && 1979 "Expected at least a single killing block"); 1980 1981 // Find the common post-dominator of all killing blocks. 1982 BasicBlock *CommonPred = *KillingBlocks.begin(); 1983 for (auto I = std::next(KillingBlocks.begin()), E = KillingBlocks.end(); 1984 I != E; I++) { 1985 if (!CommonPred) 1986 break; 1987 CommonPred = PDT.findNearestCommonDominator(CommonPred, *I); 1988 } 1989 1990 // If CommonPred is in the set of killing blocks, just check if it 1991 // post-dominates DomAccess. 1992 if (KillingBlocks.count(CommonPred)) { 1993 if (PDT.dominates(CommonPred, DomAccess->getBlock())) 1994 return {DomAccess}; 1995 return None; 1996 } 1997 1998 // If the common post-dominator does not post-dominate DomAccess, there 1999 // is a path from DomAccess to an exit not going through a killing block. 2000 if (PDT.dominates(CommonPred, DomAccess->getBlock())) { 2001 SetVector<BasicBlock *> WorkList; 2002 2003 // DomAccess's post-order number provides an upper bound of the blocks 2004 // on a path starting at DomAccess. 2005 unsigned UpperBound = 2006 PostOrderNumbers.find(DomAccess->getBlock())->second; 2007 2008 // If CommonPred is null, there are multiple exits from the function. 2009 // They all have to be added to the worklist. 2010 if (CommonPred) 2011 WorkList.insert(CommonPred); 2012 else 2013 for (BasicBlock *R : PDT.roots()) 2014 WorkList.insert(R); 2015 2016 NumCFGTries++; 2017 // Check if all paths starting from an exit node go through one of the 2018 // killing blocks before reaching DomAccess. 2019 for (unsigned I = 0; I < WorkList.size(); I++) { 2020 NumCFGChecks++; 2021 BasicBlock *Current = WorkList[I]; 2022 if (KillingBlocks.count(Current)) 2023 continue; 2024 if (Current == DomAccess->getBlock()) 2025 return None; 2026 2027 // DomAccess is reachable from the entry, so we don't have to explore 2028 // unreachable blocks further. 2029 if (!DT.isReachableFromEntry(Current)) 2030 continue; 2031 2032 unsigned CPO = PostOrderNumbers.find(Current)->second; 2033 // Current block is not on a path starting at DomAccess. 2034 if (CPO > UpperBound) 2035 continue; 2036 for (BasicBlock *Pred : predecessors(Current)) 2037 WorkList.insert(Pred); 2038 2039 if (WorkList.size() >= MemorySSAPathCheckLimit) 2040 return None; 2041 } 2042 NumCFGSuccess++; 2043 return {DomAccess}; 2044 } 2045 return None; 2046 } 2047 2048 // No aliasing MemoryUses of DomAccess found, DomAccess is potentially dead. 2049 Cache.KnownNoReads.insert(KnownNoReads.begin(), KnownNoReads.end()); 2050 return {DomAccess}; 2051 } 2052 2053 // Delete dead memory defs 2054 void deleteDeadInstruction(Instruction *SI) { 2055 MemorySSAUpdater Updater(&MSSA); 2056 SmallVector<Instruction *, 32> NowDeadInsts; 2057 NowDeadInsts.push_back(SI); 2058 --NumFastOther; 2059 2060 while (!NowDeadInsts.empty()) { 2061 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 2062 ++NumFastOther; 2063 2064 // Try to preserve debug information attached to the dead instruction. 2065 salvageDebugInfo(*DeadInst); 2066 salvageKnowledge(DeadInst); 2067 2068 // Remove the Instruction from MSSA. 2069 if (MemoryAccess *MA = MSSA.getMemoryAccess(DeadInst)) { 2070 if (MemoryDef *MD = dyn_cast<MemoryDef>(MA)) { 2071 SkipStores.insert(MD); 2072 } 2073 Updater.removeMemoryAccess(MA); 2074 } 2075 2076 auto I = IOLs.find(DeadInst->getParent()); 2077 if (I != IOLs.end()) 2078 I->second.erase(DeadInst); 2079 // Remove its operands 2080 for (Use &O : DeadInst->operands()) 2081 if (Instruction *OpI = dyn_cast<Instruction>(O)) { 2082 O = nullptr; 2083 if (isInstructionTriviallyDead(OpI, &TLI)) 2084 NowDeadInsts.push_back(OpI); 2085 } 2086 2087 DeadInst->eraseFromParent(); 2088 } 2089 } 2090 2091 // Check for any extra throws between SI and NI that block DSE. This only 2092 // checks extra maythrows (those that aren't MemoryDef's). MemoryDef that may 2093 // throw are handled during the walk from one def to the next. 2094 bool mayThrowBetween(Instruction *SI, Instruction *NI, 2095 const Value *SILocUnd) { 2096 // First see if we can ignore it by using the fact that SI is an 2097 // alloca/alloca like object that is not visible to the caller during 2098 // execution of the function. 2099 if (SILocUnd && isInvisibleToCallerBeforeRet(SILocUnd)) 2100 return false; 2101 2102 if (SI->getParent() == NI->getParent()) 2103 return ThrowingBlocks.count(SI->getParent()); 2104 return !ThrowingBlocks.empty(); 2105 } 2106 2107 // Check if \p NI acts as a DSE barrier for \p SI. The following instructions 2108 // act as barriers: 2109 // * A memory instruction that may throw and \p SI accesses a non-stack 2110 // object. 2111 // * Atomic stores stronger that monotonic. 2112 bool isDSEBarrier(const Value *SILocUnd, Instruction *NI) { 2113 // If NI may throw it acts as a barrier, unless we are to an alloca/alloca 2114 // like object that does not escape. 2115 if (NI->mayThrow() && !isInvisibleToCallerBeforeRet(SILocUnd)) 2116 return true; 2117 2118 // If NI is an atomic load/store stronger than monotonic, do not try to 2119 // eliminate/reorder it. 2120 if (NI->isAtomic()) { 2121 if (auto *LI = dyn_cast<LoadInst>(NI)) 2122 return isStrongerThanMonotonic(LI->getOrdering()); 2123 if (auto *SI = dyn_cast<StoreInst>(NI)) 2124 return isStrongerThanMonotonic(SI->getOrdering()); 2125 if (auto *ARMW = dyn_cast<AtomicRMWInst>(NI)) 2126 return isStrongerThanMonotonic(ARMW->getOrdering()); 2127 if (auto *CmpXchg = dyn_cast<AtomicCmpXchgInst>(NI)) 2128 return isStrongerThanMonotonic(CmpXchg->getSuccessOrdering()) || 2129 isStrongerThanMonotonic(CmpXchg->getFailureOrdering()); 2130 llvm_unreachable("other instructions should be skipped in MemorySSA"); 2131 } 2132 return false; 2133 } 2134 2135 /// Eliminate writes to objects that are not visible in the caller and are not 2136 /// accessed before returning from the function. 2137 bool eliminateDeadWritesAtEndOfFunction() { 2138 bool MadeChange = false; 2139 LLVM_DEBUG( 2140 dbgs() 2141 << "Trying to eliminate MemoryDefs at the end of the function\n"); 2142 for (int I = MemDefs.size() - 1; I >= 0; I--) { 2143 MemoryDef *Def = MemDefs[I]; 2144 if (SkipStores.find(Def) != SkipStores.end() || 2145 !isRemovable(Def->getMemoryInst())) 2146 continue; 2147 2148 Instruction *DefI = Def->getMemoryInst(); 2149 SmallVector<const Value *, 4> Pointers; 2150 auto DefLoc = getLocForWriteEx(DefI); 2151 if (!DefLoc) 2152 continue; 2153 2154 // NOTE: Currently eliminating writes at the end of a function is limited 2155 // to MemoryDefs with a single underlying object, to save compile-time. In 2156 // practice it appears the case with multiple underlying objects is very 2157 // uncommon. If it turns out to be important, we can use 2158 // getUnderlyingObjects here instead. 2159 const Value *UO = getUnderlyingObject(DefLoc->Ptr); 2160 if (!UO || !isInvisibleToCallerAfterRet(UO)) 2161 continue; 2162 2163 if (isWriteAtEndOfFunction(Def)) { 2164 // See through pointer-to-pointer bitcasts 2165 LLVM_DEBUG(dbgs() << " ... MemoryDef is not accessed until the end " 2166 "of the function\n"); 2167 deleteDeadInstruction(DefI); 2168 ++NumFastStores; 2169 MadeChange = true; 2170 } 2171 } 2172 return MadeChange; 2173 } 2174 2175 /// \returns true if \p Def is a no-op store, either because it 2176 /// directly stores back a loaded value or stores zero to a calloced object. 2177 bool storeIsNoop(MemoryDef *Def, MemoryLocation DefLoc, const Value *DefUO) { 2178 StoreInst *Store = dyn_cast<StoreInst>(Def->getMemoryInst()); 2179 if (!Store) 2180 return false; 2181 2182 if (auto *LoadI = dyn_cast<LoadInst>(Store->getOperand(0))) { 2183 if (LoadI->getPointerOperand() == Store->getOperand(1)) { 2184 auto *LoadAccess = MSSA.getMemoryAccess(LoadI)->getDefiningAccess(); 2185 // If both accesses share the same defining access, no instructions 2186 // between them can modify the memory location. 2187 return LoadAccess == Def->getDefiningAccess(); 2188 } 2189 } 2190 2191 Constant *StoredConstant = dyn_cast<Constant>(Store->getOperand(0)); 2192 if (StoredConstant && StoredConstant->isNullValue()) { 2193 auto *DefUOInst = dyn_cast<Instruction>(DefUO); 2194 if (DefUOInst && isCallocLikeFn(DefUOInst, &TLI)) { 2195 auto *UnderlyingDef = cast<MemoryDef>(MSSA.getMemoryAccess(DefUOInst)); 2196 // If UnderlyingDef is the clobbering access of Def, no instructions 2197 // between them can modify the memory location. 2198 auto *ClobberDef = 2199 MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(Def); 2200 return UnderlyingDef == ClobberDef; 2201 } 2202 } 2203 return false; 2204 } 2205 }; 2206 2207 bool eliminateDeadStoresMemorySSA(Function &F, AliasAnalysis &AA, 2208 MemorySSA &MSSA, DominatorTree &DT, 2209 PostDominatorTree &PDT, 2210 const TargetLibraryInfo &TLI) { 2211 bool MadeChange = false; 2212 2213 DSEState State = DSEState::get(F, AA, MSSA, DT, PDT, TLI); 2214 // For each store: 2215 for (unsigned I = 0; I < State.MemDefs.size(); I++) { 2216 MemoryDef *KillingDef = State.MemDefs[I]; 2217 if (State.SkipStores.count(KillingDef)) 2218 continue; 2219 Instruction *SI = KillingDef->getMemoryInst(); 2220 2221 auto MaybeSILoc = State.getLocForWriteEx(SI); 2222 if (State.isMemTerminatorInst(SI)) 2223 MaybeSILoc = State.getLocForTerminator(SI).map( 2224 [](const std::pair<MemoryLocation, bool> &P) { return P.first; }); 2225 else 2226 MaybeSILoc = State.getLocForWriteEx(SI); 2227 2228 if (!MaybeSILoc) { 2229 LLVM_DEBUG(dbgs() << "Failed to find analyzable write location for " 2230 << *SI << "\n"); 2231 continue; 2232 } 2233 MemoryLocation SILoc = *MaybeSILoc; 2234 assert(SILoc.Ptr && "SILoc should not be null"); 2235 const Value *SILocUnd = getUnderlyingObject(SILoc.Ptr); 2236 2237 // Check if the store is a no-op. 2238 if (isRemovable(SI) && State.storeIsNoop(KillingDef, SILoc, SILocUnd)) { 2239 LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n DEAD: " << *SI << '\n'); 2240 State.deleteDeadInstruction(SI); 2241 NumRedundantStores++; 2242 MadeChange = true; 2243 continue; 2244 } 2245 2246 MemoryAccess *Current = KillingDef; 2247 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs killed by " 2248 << *KillingDef << " (" << *SI << ")\n"); 2249 2250 unsigned ScanLimit = MemorySSAScanLimit; 2251 // Worklist of MemoryAccesses that may be killed by KillingDef. 2252 SetVector<MemoryAccess *> ToCheck; 2253 ToCheck.insert(KillingDef->getDefiningAccess()); 2254 2255 DSEState::CheckCache Cache; 2256 // Check if MemoryAccesses in the worklist are killed by KillingDef. 2257 for (unsigned I = 0; I < ToCheck.size(); I++) { 2258 Current = ToCheck[I]; 2259 if (State.SkipStores.count(Current)) 2260 continue; 2261 2262 Optional<MemoryAccess *> Next = State.getDomMemoryDef( 2263 KillingDef, Current, SILoc, SILocUnd, Cache, ScanLimit); 2264 2265 if (!Next) { 2266 LLVM_DEBUG(dbgs() << " finished walk\n"); 2267 continue; 2268 } 2269 2270 MemoryAccess *DomAccess = *Next; 2271 LLVM_DEBUG(dbgs() << " Checking if we can kill " << *DomAccess); 2272 if (isa<MemoryPhi>(DomAccess)) { 2273 LLVM_DEBUG(dbgs() << "\n ... adding incoming values to worklist\n"); 2274 for (Value *V : cast<MemoryPhi>(DomAccess)->incoming_values()) { 2275 MemoryAccess *IncomingAccess = cast<MemoryAccess>(V); 2276 BasicBlock *IncomingBlock = IncomingAccess->getBlock(); 2277 BasicBlock *PhiBlock = DomAccess->getBlock(); 2278 2279 // We only consider incoming MemoryAccesses that come before the 2280 // MemoryPhi. Otherwise we could discover candidates that do not 2281 // strictly dominate our starting def. 2282 if (State.PostOrderNumbers[IncomingBlock] > 2283 State.PostOrderNumbers[PhiBlock]) 2284 ToCheck.insert(IncomingAccess); 2285 } 2286 continue; 2287 } 2288 MemoryDef *NextDef = dyn_cast<MemoryDef>(DomAccess); 2289 Instruction *NI = NextDef->getMemoryInst(); 2290 LLVM_DEBUG(dbgs() << " (" << *NI << ")\n"); 2291 2292 // Before we try to remove anything, check for any extra throwing 2293 // instructions that block us from DSEing 2294 if (State.mayThrowBetween(SI, NI, SILocUnd)) { 2295 LLVM_DEBUG(dbgs() << " ... skip, may throw!\n"); 2296 break; 2297 } 2298 2299 // Check for anything that looks like it will be a barrier to further 2300 // removal 2301 if (State.isDSEBarrier(SILocUnd, NI)) { 2302 LLVM_DEBUG(dbgs() << " ... skip, barrier\n"); 2303 continue; 2304 } 2305 2306 ToCheck.insert(NextDef->getDefiningAccess()); 2307 2308 if (!hasAnalyzableMemoryWrite(NI, TLI)) { 2309 LLVM_DEBUG(dbgs() << " ... skip, cannot analyze def\n"); 2310 continue; 2311 } 2312 2313 if (!isRemovable(NI)) { 2314 LLVM_DEBUG(dbgs() << " ... skip, cannot remove def\n"); 2315 continue; 2316 } 2317 2318 if (!DebugCounter::shouldExecute(MemorySSACounter)) 2319 continue; 2320 2321 MemoryLocation NILoc = *State.getLocForWriteEx(NI); 2322 2323 if (State.isMemTerminatorInst(SI)) { 2324 const Value *NIUnd = getUnderlyingObject(NILoc.Ptr); 2325 if (!SILocUnd || SILocUnd != NIUnd) 2326 continue; 2327 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *NI 2328 << "\n KILLER: " << *SI << '\n'); 2329 State.deleteDeadInstruction(NI); 2330 ++NumFastStores; 2331 MadeChange = true; 2332 } else { 2333 // Check if NI overwrites SI. 2334 int64_t InstWriteOffset, DepWriteOffset; 2335 OverwriteResult OR = 2336 isOverwrite(SILoc, NILoc, State.DL, TLI, DepWriteOffset, 2337 InstWriteOffset, State.BatchAA, &F); 2338 if (OR == OW_MaybePartial) { 2339 auto Iter = State.IOLs.insert( 2340 std::make_pair<BasicBlock *, InstOverlapIntervalsTy>( 2341 NI->getParent(), InstOverlapIntervalsTy())); 2342 auto &IOL = Iter.first->second; 2343 OR = isPartialOverwrite(SILoc, NILoc, DepWriteOffset, InstWriteOffset, 2344 NI, IOL); 2345 } 2346 2347 if (EnablePartialStoreMerging && OR == OW_PartialEarlierWithFullLater) { 2348 auto *Earlier = dyn_cast<StoreInst>(NI); 2349 auto *Later = dyn_cast<StoreInst>(SI); 2350 // We are re-using tryToMergePartialOverlappingStores, which requires 2351 // Earlier to domiante Later. 2352 // TODO: implement tryToMergeParialOverlappingStores using MemorySSA. 2353 if (Earlier && Later && DT.dominates(Earlier, Later)) { 2354 if (Constant *Merged = tryToMergePartialOverlappingStores( 2355 Earlier, Later, InstWriteOffset, DepWriteOffset, State.DL, 2356 State.BatchAA, &DT)) { 2357 2358 // Update stored value of earlier store to merged constant. 2359 Earlier->setOperand(0, Merged); 2360 ++NumModifiedStores; 2361 MadeChange = true; 2362 2363 // Remove later store and remove any outstanding overlap intervals 2364 // for the updated store. 2365 State.deleteDeadInstruction(Later); 2366 auto I = State.IOLs.find(Earlier->getParent()); 2367 if (I != State.IOLs.end()) 2368 I->second.erase(Earlier); 2369 break; 2370 } 2371 } 2372 } 2373 2374 if (OR == OW_Complete) { 2375 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *NI 2376 << "\n KILLER: " << *SI << '\n'); 2377 State.deleteDeadInstruction(NI); 2378 ++NumFastStores; 2379 MadeChange = true; 2380 } 2381 } 2382 } 2383 } 2384 2385 if (EnablePartialOverwriteTracking) 2386 for (auto &KV : State.IOLs) 2387 MadeChange |= removePartiallyOverlappedStores(State.DL, KV.second); 2388 2389 MadeChange |= State.eliminateDeadWritesAtEndOfFunction(); 2390 return MadeChange; 2391 } 2392 } // end anonymous namespace 2393 2394 //===----------------------------------------------------------------------===// 2395 // DSE Pass 2396 //===----------------------------------------------------------------------===// 2397 PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) { 2398 AliasAnalysis &AA = AM.getResult<AAManager>(F); 2399 const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(F); 2400 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 2401 2402 bool Changed = false; 2403 if (EnableMemorySSA) { 2404 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); 2405 PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F); 2406 2407 Changed = eliminateDeadStoresMemorySSA(F, AA, MSSA, DT, PDT, TLI); 2408 } else { 2409 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F); 2410 2411 Changed = eliminateDeadStores(F, &AA, &MD, &DT, &TLI); 2412 } 2413 2414 #ifdef LLVM_ENABLE_STATS 2415 if (AreStatisticsEnabled()) 2416 for (auto &I : instructions(F)) 2417 NumRemainingStores += isa<StoreInst>(&I); 2418 #endif 2419 2420 if (!Changed) 2421 return PreservedAnalyses::all(); 2422 2423 PreservedAnalyses PA; 2424 PA.preserveSet<CFGAnalyses>(); 2425 PA.preserve<GlobalsAA>(); 2426 if (EnableMemorySSA) 2427 PA.preserve<MemorySSAAnalysis>(); 2428 else 2429 PA.preserve<MemoryDependenceAnalysis>(); 2430 return PA; 2431 } 2432 2433 namespace { 2434 2435 /// A legacy pass for the legacy pass manager that wraps \c DSEPass. 2436 class DSELegacyPass : public FunctionPass { 2437 public: 2438 static char ID; // Pass identification, replacement for typeid 2439 2440 DSELegacyPass() : FunctionPass(ID) { 2441 initializeDSELegacyPassPass(*PassRegistry::getPassRegistry()); 2442 } 2443 2444 bool runOnFunction(Function &F) override { 2445 if (skipFunction(F)) 2446 return false; 2447 2448 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 2449 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2450 const TargetLibraryInfo &TLI = 2451 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 2452 2453 bool Changed = false; 2454 if (EnableMemorySSA) { 2455 MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); 2456 PostDominatorTree &PDT = 2457 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 2458 2459 Changed = eliminateDeadStoresMemorySSA(F, AA, MSSA, DT, PDT, TLI); 2460 } else { 2461 MemoryDependenceResults &MD = 2462 getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); 2463 2464 Changed = eliminateDeadStores(F, &AA, &MD, &DT, &TLI); 2465 } 2466 2467 #ifdef LLVM_ENABLE_STATS 2468 if (AreStatisticsEnabled()) 2469 for (auto &I : instructions(F)) 2470 NumRemainingStores += isa<StoreInst>(&I); 2471 #endif 2472 2473 return Changed; 2474 } 2475 2476 void getAnalysisUsage(AnalysisUsage &AU) const override { 2477 AU.setPreservesCFG(); 2478 AU.addRequired<AAResultsWrapperPass>(); 2479 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2480 AU.addPreserved<GlobalsAAWrapperPass>(); 2481 AU.addRequired<DominatorTreeWrapperPass>(); 2482 AU.addPreserved<DominatorTreeWrapperPass>(); 2483 2484 if (EnableMemorySSA) { 2485 AU.addRequired<PostDominatorTreeWrapperPass>(); 2486 AU.addRequired<MemorySSAWrapperPass>(); 2487 AU.addPreserved<PostDominatorTreeWrapperPass>(); 2488 AU.addPreserved<MemorySSAWrapperPass>(); 2489 } else { 2490 AU.addRequired<MemoryDependenceWrapperPass>(); 2491 AU.addPreserved<MemoryDependenceWrapperPass>(); 2492 } 2493 } 2494 }; 2495 2496 } // end anonymous namespace 2497 2498 char DSELegacyPass::ID = 0; 2499 2500 INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false, 2501 false) 2502 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2503 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 2504 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 2505 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 2506 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 2507 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 2508 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2509 INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false, 2510 false) 2511 2512 FunctionPass *llvm::createDeadStoreEliminationPass() { 2513 return new DSELegacyPass(); 2514 } 2515