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