1 //===- DeadStoreElimination.cpp - MemorySSA Backed 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 // The code below implements dead store elimination using MemorySSA. It uses 10 // the following general approach: given a MemoryDef, walk upwards to find 11 // clobbering MemoryDefs that may be killed by the starting def. Then check 12 // that there are no uses that may read the location of the original MemoryDef 13 // in between both MemoryDefs. A bit more concretely: 14 // 15 // For all MemoryDefs StartDef: 16 // 1. Get the next dominating clobbering MemoryDef (EarlierAccess) by walking 17 // upwards. 18 // 2. Check that there are no reads between EarlierAccess and the StartDef by 19 // checking all uses starting at EarlierAccess and walking until we see 20 // StartDef. 21 // 3. For each found CurrentDef, check that: 22 // 1. There are no barrier instructions between CurrentDef and StartDef (like 23 // throws or stores with ordering constraints). 24 // 2. StartDef is executed whenever CurrentDef is executed. 25 // 3. StartDef completely overwrites CurrentDef. 26 // 4. Erase CurrentDef from the function and MemorySSA. 27 // 28 //===----------------------------------------------------------------------===// 29 30 #include "llvm/Transforms/Scalar/DeadStoreElimination.h" 31 #include "llvm/ADT/APInt.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/MapVector.h" 34 #include "llvm/ADT/PostOrderIterator.h" 35 #include "llvm/ADT/SetVector.h" 36 #include "llvm/ADT/SmallPtrSet.h" 37 #include "llvm/ADT/SmallVector.h" 38 #include "llvm/ADT/Statistic.h" 39 #include "llvm/ADT/StringRef.h" 40 #include "llvm/Analysis/AliasAnalysis.h" 41 #include "llvm/Analysis/CaptureTracking.h" 42 #include "llvm/Analysis/GlobalsModRef.h" 43 #include "llvm/Analysis/LoopInfo.h" 44 #include "llvm/Analysis/MemoryBuiltins.h" 45 #include "llvm/Analysis/MemoryLocation.h" 46 #include "llvm/Analysis/MemorySSA.h" 47 #include "llvm/Analysis/MemorySSAUpdater.h" 48 #include "llvm/Analysis/MustExecute.h" 49 #include "llvm/Analysis/PostDominators.h" 50 #include "llvm/Analysis/TargetLibraryInfo.h" 51 #include "llvm/Analysis/ValueTracking.h" 52 #include "llvm/IR/Argument.h" 53 #include "llvm/IR/BasicBlock.h" 54 #include "llvm/IR/Constant.h" 55 #include "llvm/IR/Constants.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/Dominators.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/InstIterator.h" 60 #include "llvm/IR/InstrTypes.h" 61 #include "llvm/IR/Instruction.h" 62 #include "llvm/IR/Instructions.h" 63 #include "llvm/IR/IntrinsicInst.h" 64 #include "llvm/IR/Intrinsics.h" 65 #include "llvm/IR/LLVMContext.h" 66 #include "llvm/IR/Module.h" 67 #include "llvm/IR/PassManager.h" 68 #include "llvm/IR/PatternMatch.h" 69 #include "llvm/IR/Value.h" 70 #include "llvm/InitializePasses.h" 71 #include "llvm/Pass.h" 72 #include "llvm/Support/Casting.h" 73 #include "llvm/Support/CommandLine.h" 74 #include "llvm/Support/Debug.h" 75 #include "llvm/Support/DebugCounter.h" 76 #include "llvm/Support/ErrorHandling.h" 77 #include "llvm/Support/MathExtras.h" 78 #include "llvm/Support/raw_ostream.h" 79 #include "llvm/Transforms/Scalar.h" 80 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 81 #include "llvm/Transforms/Utils/Local.h" 82 #include <algorithm> 83 #include <cassert> 84 #include <cstddef> 85 #include <cstdint> 86 #include <iterator> 87 #include <map> 88 #include <utility> 89 90 using namespace llvm; 91 using namespace PatternMatch; 92 93 #define DEBUG_TYPE "dse" 94 95 STATISTIC(NumRemainingStores, "Number of stores remaining after DSE"); 96 STATISTIC(NumRedundantStores, "Number of redundant stores deleted"); 97 STATISTIC(NumFastStores, "Number of stores deleted"); 98 STATISTIC(NumFastOther, "Number of other instrs removed"); 99 STATISTIC(NumCompletePartials, "Number of stores dead by later partials"); 100 STATISTIC(NumModifiedStores, "Number of stores modified"); 101 STATISTIC(NumCFGChecks, "Number of stores modified"); 102 STATISTIC(NumCFGTries, "Number of stores modified"); 103 STATISTIC(NumCFGSuccess, "Number of stores modified"); 104 STATISTIC(NumGetDomMemoryDefPassed, 105 "Number of times a valid candidate is returned from getDomMemoryDef"); 106 STATISTIC(NumDomMemDefChecks, 107 "Number iterations check for reads in getDomMemoryDef"); 108 109 DEBUG_COUNTER(MemorySSACounter, "dse-memoryssa", 110 "Controls which MemoryDefs are eliminated."); 111 112 static cl::opt<bool> 113 EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking", 114 cl::init(true), cl::Hidden, 115 cl::desc("Enable partial-overwrite tracking in DSE")); 116 117 static cl::opt<bool> 118 EnablePartialStoreMerging("enable-dse-partial-store-merging", 119 cl::init(true), cl::Hidden, 120 cl::desc("Enable partial store merging in DSE")); 121 122 static cl::opt<unsigned> 123 MemorySSAScanLimit("dse-memoryssa-scanlimit", cl::init(150), cl::Hidden, 124 cl::desc("The number of memory instructions to scan for " 125 "dead store elimination (default = 100)")); 126 static cl::opt<unsigned> MemorySSAUpwardsStepLimit( 127 "dse-memoryssa-walklimit", cl::init(90), cl::Hidden, 128 cl::desc("The maximum number of steps while walking upwards to find " 129 "MemoryDefs that may be killed (default = 90)")); 130 131 static cl::opt<unsigned> MemorySSAPartialStoreLimit( 132 "dse-memoryssa-partial-store-limit", cl::init(5), cl::Hidden, 133 cl::desc("The maximum number candidates that only partially overwrite the " 134 "killing MemoryDef to consider" 135 " (default = 5)")); 136 137 static cl::opt<unsigned> MemorySSADefsPerBlockLimit( 138 "dse-memoryssa-defs-per-block-limit", cl::init(5000), cl::Hidden, 139 cl::desc("The number of MemoryDefs we consider as candidates to eliminated " 140 "other stores per basic block (default = 5000)")); 141 142 static cl::opt<unsigned> MemorySSASameBBStepCost( 143 "dse-memoryssa-samebb-cost", cl::init(1), cl::Hidden, 144 cl::desc( 145 "The cost of a step in the same basic block as the killing MemoryDef" 146 "(default = 1)")); 147 148 static cl::opt<unsigned> 149 MemorySSAOtherBBStepCost("dse-memoryssa-otherbb-cost", cl::init(5), 150 cl::Hidden, 151 cl::desc("The cost of a step in a different basic " 152 "block than the killing MemoryDef" 153 "(default = 5)")); 154 155 static cl::opt<unsigned> MemorySSAPathCheckLimit( 156 "dse-memoryssa-path-check-limit", cl::init(50), cl::Hidden, 157 cl::desc("The maximum number of blocks to check when trying to prove that " 158 "all paths to an exit go through a killing block (default = 50)")); 159 160 //===----------------------------------------------------------------------===// 161 // Helper functions 162 //===----------------------------------------------------------------------===// 163 using OverlapIntervalsTy = std::map<int64_t, int64_t>; 164 using InstOverlapIntervalsTy = DenseMap<Instruction *, OverlapIntervalsTy>; 165 166 /// Does this instruction write some memory? This only returns true for things 167 /// that we can analyze with other helpers below. 168 static bool hasAnalyzableMemoryWrite(Instruction *I, 169 const TargetLibraryInfo &TLI) { 170 if (isa<StoreInst>(I)) 171 return true; 172 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 173 switch (II->getIntrinsicID()) { 174 default: 175 return false; 176 case Intrinsic::memset: 177 case Intrinsic::memmove: 178 case Intrinsic::memcpy: 179 case Intrinsic::memcpy_inline: 180 case Intrinsic::memcpy_element_unordered_atomic: 181 case Intrinsic::memmove_element_unordered_atomic: 182 case Intrinsic::memset_element_unordered_atomic: 183 case Intrinsic::init_trampoline: 184 case Intrinsic::lifetime_end: 185 case Intrinsic::masked_store: 186 return true; 187 } 188 } 189 if (auto *CB = dyn_cast<CallBase>(I)) { 190 LibFunc LF; 191 if (TLI.getLibFunc(*CB, LF) && TLI.has(LF)) { 192 switch (LF) { 193 case LibFunc_strcpy: 194 case LibFunc_strncpy: 195 case LibFunc_strcat: 196 case LibFunc_strncat: 197 return true; 198 default: 199 return false; 200 } 201 } 202 } 203 return false; 204 } 205 206 /// Return a Location stored to by the specified instruction. If isRemovable 207 /// returns true, this function and getLocForRead completely describe the memory 208 /// operations for this instruction. 209 static MemoryLocation getLocForWrite(Instruction *Inst, 210 const TargetLibraryInfo &TLI) { 211 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 212 return MemoryLocation::get(SI); 213 214 // memcpy/memmove/memset. 215 if (auto *MI = dyn_cast<AnyMemIntrinsic>(Inst)) 216 return MemoryLocation::getForDest(MI); 217 218 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 219 switch (II->getIntrinsicID()) { 220 default: 221 return MemoryLocation(); // Unhandled intrinsic. 222 case Intrinsic::init_trampoline: 223 return MemoryLocation::getAfter(II->getArgOperand(0)); 224 case Intrinsic::masked_store: 225 return MemoryLocation::getForArgument(II, 1, TLI); 226 case Intrinsic::lifetime_end: { 227 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(); 228 return MemoryLocation(II->getArgOperand(1), Len); 229 } 230 } 231 } 232 if (auto *CB = dyn_cast<CallBase>(Inst)) 233 // All the supported TLI functions so far happen to have dest as their 234 // first argument. 235 return MemoryLocation::getAfter(CB->getArgOperand(0)); 236 return MemoryLocation(); 237 } 238 239 /// If the value of this instruction and the memory it writes to is unused, may 240 /// we delete this instruction? 241 static bool isRemovable(Instruction *I) { 242 // Don't remove volatile/atomic stores. 243 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 244 return SI->isUnordered(); 245 246 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 247 switch (II->getIntrinsicID()) { 248 default: llvm_unreachable("doesn't pass 'hasAnalyzableMemoryWrite' predicate"); 249 case Intrinsic::lifetime_end: 250 // Never remove dead lifetime_end's, e.g. because it is followed by a 251 // free. 252 return false; 253 case Intrinsic::init_trampoline: 254 // Always safe to remove init_trampoline. 255 return true; 256 case Intrinsic::memset: 257 case Intrinsic::memmove: 258 case Intrinsic::memcpy: 259 case Intrinsic::memcpy_inline: 260 // Don't remove volatile memory intrinsics. 261 return !cast<MemIntrinsic>(II)->isVolatile(); 262 case Intrinsic::memcpy_element_unordered_atomic: 263 case Intrinsic::memmove_element_unordered_atomic: 264 case Intrinsic::memset_element_unordered_atomic: 265 case Intrinsic::masked_store: 266 return true; 267 } 268 } 269 270 // note: only get here for calls with analyzable writes - i.e. libcalls 271 if (auto *CB = dyn_cast<CallBase>(I)) 272 return CB->use_empty(); 273 274 return false; 275 } 276 277 /// Returns true if the end of this instruction can be safely shortened in 278 /// length. 279 static bool isShortenableAtTheEnd(Instruction *I) { 280 // Don't shorten stores for now 281 if (isa<StoreInst>(I)) 282 return false; 283 284 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 285 switch (II->getIntrinsicID()) { 286 default: return false; 287 case Intrinsic::memset: 288 case Intrinsic::memcpy: 289 case Intrinsic::memcpy_element_unordered_atomic: 290 case Intrinsic::memset_element_unordered_atomic: 291 // Do shorten memory intrinsics. 292 // FIXME: Add memmove if it's also safe to transform. 293 return true; 294 } 295 } 296 297 // Don't shorten libcalls calls for now. 298 299 return false; 300 } 301 302 /// Returns true if the beginning of this instruction can be safely shortened 303 /// in length. 304 static bool isShortenableAtTheBeginning(Instruction *I) { 305 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be 306 // easily done by offsetting the source address. 307 return isa<AnyMemSetInst>(I); 308 } 309 310 static uint64_t getPointerSize(const Value *V, const DataLayout &DL, 311 const TargetLibraryInfo &TLI, 312 const Function *F) { 313 uint64_t Size; 314 ObjectSizeOpts Opts; 315 Opts.NullIsUnknownSize = NullPointerIsDefined(F); 316 317 if (getObjectSize(V, Size, DL, &TLI, Opts)) 318 return Size; 319 return MemoryLocation::UnknownSize; 320 } 321 322 namespace { 323 324 enum OverwriteResult { 325 OW_Begin, 326 OW_Complete, 327 OW_End, 328 OW_PartialEarlierWithFullLater, 329 OW_MaybePartial, 330 OW_Unknown 331 }; 332 333 } // end anonymous namespace 334 335 /// Check if two instruction are masked stores that completely 336 /// overwrite one another. More specifically, \p Later has to 337 /// overwrite \p Earlier. 338 static OverwriteResult isMaskedStoreOverwrite(const Instruction *Later, 339 const Instruction *Earlier, 340 BatchAAResults &AA) { 341 const auto *IIL = dyn_cast<IntrinsicInst>(Later); 342 const auto *IIE = dyn_cast<IntrinsicInst>(Earlier); 343 if (IIL == nullptr || IIE == nullptr) 344 return OW_Unknown; 345 if (IIL->getIntrinsicID() != Intrinsic::masked_store || 346 IIE->getIntrinsicID() != Intrinsic::masked_store) 347 return OW_Unknown; 348 // Pointers. 349 Value *LP = IIL->getArgOperand(1)->stripPointerCasts(); 350 Value *EP = IIE->getArgOperand(1)->stripPointerCasts(); 351 if (LP != EP && !AA.isMustAlias(LP, EP)) 352 return OW_Unknown; 353 // Masks. 354 // TODO: check that Later's mask is a superset of the Earlier's mask. 355 if (IIL->getArgOperand(3) != IIE->getArgOperand(3)) 356 return OW_Unknown; 357 return OW_Complete; 358 } 359 360 /// Return 'OW_Complete' if a store to the 'Later' location completely 361 /// overwrites a store to the 'Earlier' location, 'OW_End' if the end of the 362 /// 'Earlier' location is completely overwritten by 'Later', 'OW_Begin' if the 363 /// beginning of the 'Earlier' location is overwritten by 'Later'. 364 /// 'OW_PartialEarlierWithFullLater' means that an earlier (big) store was 365 /// overwritten by a latter (smaller) store which doesn't write outside the big 366 /// store's memory locations. Returns 'OW_Unknown' if nothing can be determined. 367 /// NOTE: This function must only be called if both \p Later and \p Earlier 368 /// write to the same underlying object with valid \p EarlierOff and \p 369 /// LaterOff. 370 static OverwriteResult isPartialOverwrite(const MemoryLocation &Later, 371 const MemoryLocation &Earlier, 372 int64_t EarlierOff, int64_t LaterOff, 373 Instruction *DepWrite, 374 InstOverlapIntervalsTy &IOL) { 375 const uint64_t LaterSize = Later.Size.getValue(); 376 const uint64_t EarlierSize = Earlier.Size.getValue(); 377 // We may now overlap, although the overlap is not complete. There might also 378 // be other incomplete overlaps, and together, they might cover the complete 379 // earlier write. 380 // Note: The correctness of this logic depends on the fact that this function 381 // is not even called providing DepWrite when there are any intervening reads. 382 if (EnablePartialOverwriteTracking && 383 LaterOff < int64_t(EarlierOff + EarlierSize) && 384 int64_t(LaterOff + LaterSize) >= EarlierOff) { 385 386 // Insert our part of the overlap into the map. 387 auto &IM = IOL[DepWrite]; 388 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: Earlier [" << EarlierOff 389 << ", " << int64_t(EarlierOff + EarlierSize) 390 << ") Later [" << LaterOff << ", " 391 << int64_t(LaterOff + LaterSize) << ")\n"); 392 393 // Make sure that we only insert non-overlapping intervals and combine 394 // adjacent intervals. The intervals are stored in the map with the ending 395 // offset as the key (in the half-open sense) and the starting offset as 396 // the value. 397 int64_t LaterIntStart = LaterOff, LaterIntEnd = LaterOff + LaterSize; 398 399 // Find any intervals ending at, or after, LaterIntStart which start 400 // before LaterIntEnd. 401 auto ILI = IM.lower_bound(LaterIntStart); 402 if (ILI != IM.end() && ILI->second <= LaterIntEnd) { 403 // This existing interval is overlapped with the current store somewhere 404 // in [LaterIntStart, LaterIntEnd]. Merge them by erasing the existing 405 // intervals and adjusting our start and end. 406 LaterIntStart = std::min(LaterIntStart, ILI->second); 407 LaterIntEnd = std::max(LaterIntEnd, ILI->first); 408 ILI = IM.erase(ILI); 409 410 // Continue erasing and adjusting our end in case other previous 411 // intervals are also overlapped with the current store. 412 // 413 // |--- ealier 1 ---| |--- ealier 2 ---| 414 // |------- later---------| 415 // 416 while (ILI != IM.end() && ILI->second <= LaterIntEnd) { 417 assert(ILI->second > LaterIntStart && "Unexpected interval"); 418 LaterIntEnd = std::max(LaterIntEnd, ILI->first); 419 ILI = IM.erase(ILI); 420 } 421 } 422 423 IM[LaterIntEnd] = LaterIntStart; 424 425 ILI = IM.begin(); 426 if (ILI->second <= EarlierOff && 427 ILI->first >= int64_t(EarlierOff + EarlierSize)) { 428 LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: Earlier [" 429 << EarlierOff << ", " 430 << int64_t(EarlierOff + EarlierSize) 431 << ") Composite Later [" << ILI->second << ", " 432 << ILI->first << ")\n"); 433 ++NumCompletePartials; 434 return OW_Complete; 435 } 436 } 437 438 // Check for an earlier store which writes to all the memory locations that 439 // the later store writes to. 440 if (EnablePartialStoreMerging && LaterOff >= EarlierOff && 441 int64_t(EarlierOff + EarlierSize) > LaterOff && 442 uint64_t(LaterOff - EarlierOff) + LaterSize <= EarlierSize) { 443 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite an earlier load [" 444 << EarlierOff << ", " 445 << int64_t(EarlierOff + EarlierSize) 446 << ") by a later store [" << LaterOff << ", " 447 << int64_t(LaterOff + LaterSize) << ")\n"); 448 // TODO: Maybe come up with a better name? 449 return OW_PartialEarlierWithFullLater; 450 } 451 452 // Another interesting case is if the later store overwrites the end of the 453 // earlier store. 454 // 455 // |--earlier--| 456 // |-- later --| 457 // 458 // In this case we may want to trim the size of earlier to avoid generating 459 // writes to addresses which will definitely be overwritten later 460 if (!EnablePartialOverwriteTracking && 461 (LaterOff > EarlierOff && LaterOff < int64_t(EarlierOff + EarlierSize) && 462 int64_t(LaterOff + LaterSize) >= int64_t(EarlierOff + EarlierSize))) 463 return OW_End; 464 465 // Finally, we also need to check if the later store overwrites the beginning 466 // of the earlier store. 467 // 468 // |--earlier--| 469 // |-- later --| 470 // 471 // In this case we may want to move the destination address and trim the size 472 // of earlier to avoid generating writes to addresses which will definitely 473 // be overwritten later. 474 if (!EnablePartialOverwriteTracking && 475 (LaterOff <= EarlierOff && int64_t(LaterOff + LaterSize) > EarlierOff)) { 476 assert(int64_t(LaterOff + LaterSize) < int64_t(EarlierOff + EarlierSize) && 477 "Expect to be handled as OW_Complete"); 478 return OW_Begin; 479 } 480 // Otherwise, they don't completely overlap. 481 return OW_Unknown; 482 } 483 484 /// Returns true if the memory which is accessed by the second instruction is not 485 /// modified between the first and the second instruction. 486 /// Precondition: Second instruction must be dominated by the first 487 /// instruction. 488 static bool 489 memoryIsNotModifiedBetween(Instruction *FirstI, Instruction *SecondI, 490 BatchAAResults &AA, const DataLayout &DL, 491 DominatorTree *DT) { 492 // Do a backwards scan through the CFG from SecondI to FirstI. Look for 493 // instructions which can modify the memory location accessed by SecondI. 494 // 495 // While doing the walk keep track of the address to check. It might be 496 // different in different basic blocks due to PHI translation. 497 using BlockAddressPair = std::pair<BasicBlock *, PHITransAddr>; 498 SmallVector<BlockAddressPair, 16> WorkList; 499 // Keep track of the address we visited each block with. Bail out if we 500 // visit a block with different addresses. 501 DenseMap<BasicBlock *, Value *> Visited; 502 503 BasicBlock::iterator FirstBBI(FirstI); 504 ++FirstBBI; 505 BasicBlock::iterator SecondBBI(SecondI); 506 BasicBlock *FirstBB = FirstI->getParent(); 507 BasicBlock *SecondBB = SecondI->getParent(); 508 MemoryLocation MemLoc = MemoryLocation::get(SecondI); 509 auto *MemLocPtr = const_cast<Value *>(MemLoc.Ptr); 510 511 // Start checking the SecondBB. 512 WorkList.push_back( 513 std::make_pair(SecondBB, PHITransAddr(MemLocPtr, DL, nullptr))); 514 bool isFirstBlock = true; 515 516 // Check all blocks going backward until we reach the FirstBB. 517 while (!WorkList.empty()) { 518 BlockAddressPair Current = WorkList.pop_back_val(); 519 BasicBlock *B = Current.first; 520 PHITransAddr &Addr = Current.second; 521 Value *Ptr = Addr.getAddr(); 522 523 // Ignore instructions before FirstI if this is the FirstBB. 524 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin()); 525 526 BasicBlock::iterator EI; 527 if (isFirstBlock) { 528 // Ignore instructions after SecondI if this is the first visit of SecondBB. 529 assert(B == SecondBB && "first block is not the store block"); 530 EI = SecondBBI; 531 isFirstBlock = false; 532 } else { 533 // It's not SecondBB or (in case of a loop) the second visit of SecondBB. 534 // In this case we also have to look at instructions after SecondI. 535 EI = B->end(); 536 } 537 for (; BI != EI; ++BI) { 538 Instruction *I = &*BI; 539 if (I->mayWriteToMemory() && I != SecondI) 540 if (isModSet(AA.getModRefInfo(I, MemLoc.getWithNewPtr(Ptr)))) 541 return false; 542 } 543 if (B != FirstBB) { 544 assert(B != &FirstBB->getParent()->getEntryBlock() && 545 "Should not hit the entry block because SI must be dominated by LI"); 546 for (BasicBlock *Pred : predecessors(B)) { 547 PHITransAddr PredAddr = Addr; 548 if (PredAddr.NeedsPHITranslationFromBlock(B)) { 549 if (!PredAddr.IsPotentiallyPHITranslatable()) 550 return false; 551 if (PredAddr.PHITranslateValue(B, Pred, DT, false)) 552 return false; 553 } 554 Value *TranslatedPtr = PredAddr.getAddr(); 555 auto Inserted = Visited.insert(std::make_pair(Pred, TranslatedPtr)); 556 if (!Inserted.second) { 557 // We already visited this block before. If it was with a different 558 // address - bail out! 559 if (TranslatedPtr != Inserted.first->second) 560 return false; 561 // ... otherwise just skip it. 562 continue; 563 } 564 WorkList.push_back(std::make_pair(Pred, PredAddr)); 565 } 566 } 567 } 568 return true; 569 } 570 571 static bool tryToShorten(Instruction *EarlierWrite, int64_t &EarlierStart, 572 uint64_t &EarlierSize, int64_t LaterStart, 573 uint64_t LaterSize, bool IsOverwriteEnd) { 574 auto *EarlierIntrinsic = cast<AnyMemIntrinsic>(EarlierWrite); 575 Align PrefAlign = EarlierIntrinsic->getDestAlign().valueOrOne(); 576 577 // We assume that memet/memcpy operates in chunks of the "largest" native 578 // type size and aligned on the same value. That means optimal start and size 579 // of memset/memcpy should be modulo of preferred alignment of that type. That 580 // is it there is no any sense in trying to reduce store size any further 581 // since any "extra" stores comes for free anyway. 582 // On the other hand, maximum alignment we can achieve is limited by alignment 583 // of initial store. 584 585 // TODO: Limit maximum alignment by preferred (or abi?) alignment of the 586 // "largest" native type. 587 // Note: What is the proper way to get that value? 588 // Should TargetTransformInfo::getRegisterBitWidth be used or anything else? 589 // PrefAlign = std::min(DL.getPrefTypeAlign(LargestType), PrefAlign); 590 591 int64_t ToRemoveStart = 0; 592 uint64_t ToRemoveSize = 0; 593 // Compute start and size of the region to remove. Make sure 'PrefAlign' is 594 // maintained on the remaining store. 595 if (IsOverwriteEnd) { 596 // Calculate required adjustment for 'LaterStart'in order to keep remaining 597 // store size aligned on 'PerfAlign'. 598 uint64_t Off = 599 offsetToAlignment(uint64_t(LaterStart - EarlierStart), PrefAlign); 600 ToRemoveStart = LaterStart + Off; 601 if (EarlierSize <= uint64_t(ToRemoveStart - EarlierStart)) 602 return false; 603 ToRemoveSize = EarlierSize - uint64_t(ToRemoveStart - EarlierStart); 604 } else { 605 ToRemoveStart = EarlierStart; 606 assert(LaterSize >= uint64_t(EarlierStart - LaterStart) && 607 "Not overlapping accesses?"); 608 ToRemoveSize = LaterSize - uint64_t(EarlierStart - LaterStart); 609 // Calculate required adjustment for 'ToRemoveSize'in order to keep 610 // start of the remaining store aligned on 'PerfAlign'. 611 uint64_t Off = offsetToAlignment(ToRemoveSize, PrefAlign); 612 if (Off != 0) { 613 if (ToRemoveSize <= (PrefAlign.value() - Off)) 614 return false; 615 ToRemoveSize -= PrefAlign.value() - Off; 616 } 617 assert(isAligned(PrefAlign, ToRemoveSize) && 618 "Should preserve selected alignment"); 619 } 620 621 assert(ToRemoveSize > 0 && "Shouldn't reach here if nothing to remove"); 622 assert(EarlierSize > ToRemoveSize && "Can't remove more than original size"); 623 624 uint64_t NewSize = EarlierSize - ToRemoveSize; 625 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(EarlierWrite)) { 626 // When shortening an atomic memory intrinsic, the newly shortened 627 // length must remain an integer multiple of the element size. 628 const uint32_t ElementSize = AMI->getElementSizeInBytes(); 629 if (0 != NewSize % ElementSize) 630 return false; 631 } 632 633 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW " 634 << (IsOverwriteEnd ? "END" : "BEGIN") << ": " 635 << *EarlierWrite << "\n KILLER [" << ToRemoveStart << ", " 636 << int64_t(ToRemoveStart + ToRemoveSize) << ")\n"); 637 638 Value *EarlierWriteLength = EarlierIntrinsic->getLength(); 639 Value *TrimmedLength = 640 ConstantInt::get(EarlierWriteLength->getType(), NewSize); 641 EarlierIntrinsic->setLength(TrimmedLength); 642 EarlierIntrinsic->setDestAlignment(PrefAlign); 643 644 if (!IsOverwriteEnd) { 645 Value *Indices[1] = { 646 ConstantInt::get(EarlierWriteLength->getType(), ToRemoveSize)}; 647 GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds( 648 EarlierIntrinsic->getRawDest()->getType()->getPointerElementType(), 649 EarlierIntrinsic->getRawDest(), Indices, "", EarlierWrite); 650 NewDestGEP->setDebugLoc(EarlierIntrinsic->getDebugLoc()); 651 EarlierIntrinsic->setDest(NewDestGEP); 652 } 653 654 // Finally update start and size of earlier access. 655 if (!IsOverwriteEnd) 656 EarlierStart += ToRemoveSize; 657 EarlierSize = NewSize; 658 659 return true; 660 } 661 662 static bool tryToShortenEnd(Instruction *EarlierWrite, 663 OverlapIntervalsTy &IntervalMap, 664 int64_t &EarlierStart, uint64_t &EarlierSize) { 665 if (IntervalMap.empty() || !isShortenableAtTheEnd(EarlierWrite)) 666 return false; 667 668 OverlapIntervalsTy::iterator OII = --IntervalMap.end(); 669 int64_t LaterStart = OII->second; 670 uint64_t LaterSize = OII->first - LaterStart; 671 672 assert(OII->first - LaterStart >= 0 && "Size expected to be positive"); 673 674 if (LaterStart > EarlierStart && 675 // Note: "LaterStart - EarlierStart" is known to be positive due to 676 // preceding check. 677 (uint64_t)(LaterStart - EarlierStart) < EarlierSize && 678 // Note: "EarlierSize - (uint64_t)(LaterStart - EarlierStart)" is known to 679 // be non negative due to preceding checks. 680 LaterSize >= EarlierSize - (uint64_t)(LaterStart - EarlierStart)) { 681 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart, 682 LaterSize, true)) { 683 IntervalMap.erase(OII); 684 return true; 685 } 686 } 687 return false; 688 } 689 690 static bool tryToShortenBegin(Instruction *EarlierWrite, 691 OverlapIntervalsTy &IntervalMap, 692 int64_t &EarlierStart, uint64_t &EarlierSize) { 693 if (IntervalMap.empty() || !isShortenableAtTheBeginning(EarlierWrite)) 694 return false; 695 696 OverlapIntervalsTy::iterator OII = IntervalMap.begin(); 697 int64_t LaterStart = OII->second; 698 uint64_t LaterSize = OII->first - LaterStart; 699 700 assert(OII->first - LaterStart >= 0 && "Size expected to be positive"); 701 702 if (LaterStart <= EarlierStart && 703 // Note: "EarlierStart - LaterStart" is known to be non negative due to 704 // preceding check. 705 LaterSize > (uint64_t)(EarlierStart - LaterStart)) { 706 // Note: "LaterSize - (uint64_t)(EarlierStart - LaterStart)" is known to be 707 // positive due to preceding checks. 708 assert(LaterSize - (uint64_t)(EarlierStart - LaterStart) < EarlierSize && 709 "Should have been handled as OW_Complete"); 710 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart, 711 LaterSize, false)) { 712 IntervalMap.erase(OII); 713 return true; 714 } 715 } 716 return false; 717 } 718 719 static bool removePartiallyOverlappedStores(const DataLayout &DL, 720 InstOverlapIntervalsTy &IOL, 721 const TargetLibraryInfo &TLI) { 722 bool Changed = false; 723 for (auto OI : IOL) { 724 Instruction *EarlierWrite = OI.first; 725 MemoryLocation Loc = getLocForWrite(EarlierWrite, TLI); 726 assert(isRemovable(EarlierWrite) && "Expect only removable instruction"); 727 728 const Value *Ptr = Loc.Ptr->stripPointerCasts(); 729 int64_t EarlierStart = 0; 730 uint64_t EarlierSize = Loc.Size.getValue(); 731 GetPointerBaseWithConstantOffset(Ptr, EarlierStart, DL); 732 OverlapIntervalsTy &IntervalMap = OI.second; 733 Changed |= 734 tryToShortenEnd(EarlierWrite, IntervalMap, EarlierStart, EarlierSize); 735 if (IntervalMap.empty()) 736 continue; 737 Changed |= 738 tryToShortenBegin(EarlierWrite, IntervalMap, EarlierStart, EarlierSize); 739 } 740 return Changed; 741 } 742 743 static Constant *tryToMergePartialOverlappingStores( 744 StoreInst *Earlier, StoreInst *Later, int64_t InstWriteOffset, 745 int64_t DepWriteOffset, const DataLayout &DL, BatchAAResults &AA, 746 DominatorTree *DT) { 747 748 if (Earlier && isa<ConstantInt>(Earlier->getValueOperand()) && 749 DL.typeSizeEqualsStoreSize(Earlier->getValueOperand()->getType()) && 750 Later && isa<ConstantInt>(Later->getValueOperand()) && 751 DL.typeSizeEqualsStoreSize(Later->getValueOperand()->getType()) && 752 memoryIsNotModifiedBetween(Earlier, Later, AA, DL, DT)) { 753 // If the store we find is: 754 // a) partially overwritten by the store to 'Loc' 755 // b) the later store is fully contained in the earlier one and 756 // c) they both have a constant value 757 // d) none of the two stores need padding 758 // Merge the two stores, replacing the earlier store's value with a 759 // merge of both values. 760 // TODO: Deal with other constant types (vectors, etc), and probably 761 // some mem intrinsics (if needed) 762 763 APInt EarlierValue = 764 cast<ConstantInt>(Earlier->getValueOperand())->getValue(); 765 APInt LaterValue = cast<ConstantInt>(Later->getValueOperand())->getValue(); 766 unsigned LaterBits = LaterValue.getBitWidth(); 767 assert(EarlierValue.getBitWidth() > LaterValue.getBitWidth()); 768 LaterValue = LaterValue.zext(EarlierValue.getBitWidth()); 769 770 // Offset of the smaller store inside the larger store 771 unsigned BitOffsetDiff = (InstWriteOffset - DepWriteOffset) * 8; 772 unsigned LShiftAmount = DL.isBigEndian() ? EarlierValue.getBitWidth() - 773 BitOffsetDiff - LaterBits 774 : BitOffsetDiff; 775 APInt Mask = APInt::getBitsSet(EarlierValue.getBitWidth(), LShiftAmount, 776 LShiftAmount + LaterBits); 777 // Clear the bits we'll be replacing, then OR with the smaller 778 // store, shifted appropriately. 779 APInt Merged = (EarlierValue & ~Mask) | (LaterValue << LShiftAmount); 780 LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n Earlier: " << *Earlier 781 << "\n Later: " << *Later 782 << "\n Merged Value: " << Merged << '\n'); 783 return ConstantInt::get(Earlier->getValueOperand()->getType(), Merged); 784 } 785 return nullptr; 786 } 787 788 namespace { 789 // Returns true if \p I is an intrisnic that does not read or write memory. 790 bool isNoopIntrinsic(Instruction *I) { 791 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 792 switch (II->getIntrinsicID()) { 793 case Intrinsic::lifetime_start: 794 case Intrinsic::lifetime_end: 795 case Intrinsic::invariant_end: 796 case Intrinsic::launder_invariant_group: 797 case Intrinsic::assume: 798 return true; 799 case Intrinsic::dbg_addr: 800 case Intrinsic::dbg_declare: 801 case Intrinsic::dbg_label: 802 case Intrinsic::dbg_value: 803 llvm_unreachable("Intrinsic should not be modeled in MemorySSA"); 804 default: 805 return false; 806 } 807 } 808 return false; 809 } 810 811 // Check if we can ignore \p D for DSE. 812 bool canSkipDef(MemoryDef *D, bool DefVisibleToCaller) { 813 Instruction *DI = D->getMemoryInst(); 814 // Calls that only access inaccessible memory cannot read or write any memory 815 // locations we consider for elimination. 816 if (auto *CB = dyn_cast<CallBase>(DI)) 817 if (CB->onlyAccessesInaccessibleMemory()) 818 return true; 819 820 // We can eliminate stores to locations not visible to the caller across 821 // throwing instructions. 822 if (DI->mayThrow() && !DefVisibleToCaller) 823 return true; 824 825 // We can remove the dead stores, irrespective of the fence and its ordering 826 // (release/acquire/seq_cst). Fences only constraints the ordering of 827 // already visible stores, it does not make a store visible to other 828 // threads. So, skipping over a fence does not change a store from being 829 // dead. 830 if (isa<FenceInst>(DI)) 831 return true; 832 833 // Skip intrinsics that do not really read or modify memory. 834 if (isNoopIntrinsic(D->getMemoryInst())) 835 return true; 836 837 return false; 838 } 839 840 struct DSEState { 841 Function &F; 842 AliasAnalysis &AA; 843 844 /// The single BatchAA instance that is used to cache AA queries. It will 845 /// not be invalidated over the whole run. This is safe, because: 846 /// 1. Only memory writes are removed, so the alias cache for memory 847 /// locations remains valid. 848 /// 2. No new instructions are added (only instructions removed), so cached 849 /// information for a deleted value cannot be accessed by a re-used new 850 /// value pointer. 851 BatchAAResults BatchAA; 852 853 MemorySSA &MSSA; 854 DominatorTree &DT; 855 PostDominatorTree &PDT; 856 const TargetLibraryInfo &TLI; 857 const DataLayout &DL; 858 const LoopInfo &LI; 859 860 // Whether the function contains any irreducible control flow, useful for 861 // being accurately able to detect loops. 862 bool ContainsIrreducibleLoops; 863 864 // All MemoryDefs that potentially could kill other MemDefs. 865 SmallVector<MemoryDef *, 64> MemDefs; 866 // Any that should be skipped as they are already deleted 867 SmallPtrSet<MemoryAccess *, 4> SkipStores; 868 // Keep track of all of the objects that are invisible to the caller before 869 // the function returns. 870 // SmallPtrSet<const Value *, 16> InvisibleToCallerBeforeRet; 871 DenseMap<const Value *, bool> InvisibleToCallerBeforeRet; 872 // Keep track of all of the objects that are invisible to the caller after 873 // the function returns. 874 DenseMap<const Value *, bool> InvisibleToCallerAfterRet; 875 // Keep track of blocks with throwing instructions not modeled in MemorySSA. 876 SmallPtrSet<BasicBlock *, 16> ThrowingBlocks; 877 // Post-order numbers for each basic block. Used to figure out if memory 878 // accesses are executed before another access. 879 DenseMap<BasicBlock *, unsigned> PostOrderNumbers; 880 881 /// Keep track of instructions (partly) overlapping with killing MemoryDefs per 882 /// basic block. 883 DenseMap<BasicBlock *, InstOverlapIntervalsTy> IOLs; 884 885 DSEState(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, DominatorTree &DT, 886 PostDominatorTree &PDT, const TargetLibraryInfo &TLI, 887 const LoopInfo &LI) 888 : F(F), AA(AA), BatchAA(AA), MSSA(MSSA), DT(DT), PDT(PDT), TLI(TLI), 889 DL(F.getParent()->getDataLayout()), LI(LI) {} 890 891 static DSEState get(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, 892 DominatorTree &DT, PostDominatorTree &PDT, 893 const TargetLibraryInfo &TLI, const LoopInfo &LI) { 894 DSEState State(F, AA, MSSA, DT, PDT, TLI, LI); 895 // Collect blocks with throwing instructions not modeled in MemorySSA and 896 // alloc-like objects. 897 unsigned PO = 0; 898 for (BasicBlock *BB : post_order(&F)) { 899 State.PostOrderNumbers[BB] = PO++; 900 for (Instruction &I : *BB) { 901 MemoryAccess *MA = MSSA.getMemoryAccess(&I); 902 if (I.mayThrow() && !MA) 903 State.ThrowingBlocks.insert(I.getParent()); 904 905 auto *MD = dyn_cast_or_null<MemoryDef>(MA); 906 if (MD && State.MemDefs.size() < MemorySSADefsPerBlockLimit && 907 (State.getLocForWriteEx(&I) || State.isMemTerminatorInst(&I))) 908 State.MemDefs.push_back(MD); 909 } 910 } 911 912 // Treat byval or inalloca arguments the same as Allocas, stores to them are 913 // dead at the end of the function. 914 for (Argument &AI : F.args()) 915 if (AI.hasPassPointeeByValueCopyAttr()) { 916 // For byval, the caller doesn't know the address of the allocation. 917 if (AI.hasByValAttr()) 918 State.InvisibleToCallerBeforeRet.insert({&AI, true}); 919 State.InvisibleToCallerAfterRet.insert({&AI, true}); 920 } 921 922 // Collect whether there is any irreducible control flow in the function. 923 State.ContainsIrreducibleLoops = mayContainIrreducibleControl(F, &LI); 924 925 return State; 926 } 927 928 /// Return 'OW_Complete' if a store to the 'Later' location (by \p LaterI 929 /// instruction) completely overwrites a store to the 'Earlier' location. 930 /// (by \p EarlierI instruction). 931 /// Return OW_MaybePartial if \p Later does not completely overwrite 932 /// \p Earlier, but they both write to the same underlying object. In that 933 /// case, use isPartialOverwrite to check if \p Later partially overwrites 934 /// \p Earlier. Returns 'OW_Unknown' if nothing can be determined. 935 OverwriteResult 936 isOverwrite(const Instruction *LaterI, const Instruction *EarlierI, 937 const MemoryLocation &Later, const MemoryLocation &Earlier, 938 int64_t &EarlierOff, int64_t &LaterOff) { 939 // AliasAnalysis does not always account for loops. Limit overwrite checks 940 // to dependencies for which we can guarantee they are independant of any 941 // loops they are in. 942 if (!isGuaranteedLoopIndependent(EarlierI, LaterI, Earlier)) 943 return OW_Unknown; 944 945 // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll 946 // get imprecise values here, though (except for unknown sizes). 947 if (!Later.Size.isPrecise() || !Earlier.Size.isPrecise()) { 948 // In case no constant size is known, try to an IR values for the number 949 // of bytes written and check if they match. 950 const auto *LaterMemI = dyn_cast<MemIntrinsic>(LaterI); 951 const auto *EarlierMemI = dyn_cast<MemIntrinsic>(EarlierI); 952 if (LaterMemI && EarlierMemI) { 953 const Value *LaterV = LaterMemI->getLength(); 954 const Value *EarlierV = EarlierMemI->getLength(); 955 if (LaterV == EarlierV && BatchAA.isMustAlias(Earlier, Later)) 956 return OW_Complete; 957 } 958 959 // Masked stores have imprecise locations, but we can reason about them 960 // to some extent. 961 return isMaskedStoreOverwrite(LaterI, EarlierI, BatchAA); 962 } 963 964 const uint64_t LaterSize = Later.Size.getValue(); 965 const uint64_t EarlierSize = Earlier.Size.getValue(); 966 967 // Query the alias information 968 AliasResult AAR = BatchAA.alias(Later, Earlier); 969 970 // If the start pointers are the same, we just have to compare sizes to see if 971 // the later store was larger than the earlier store. 972 if (AAR == AliasResult::MustAlias) { 973 // Make sure that the Later size is >= the Earlier size. 974 if (LaterSize >= EarlierSize) 975 return OW_Complete; 976 } 977 978 // If we hit a partial alias we may have a full overwrite 979 if (AAR == AliasResult::PartialAlias && AAR.hasOffset()) { 980 int32_t Off = AAR.getOffset(); 981 if (Off >= 0 && (uint64_t)Off + EarlierSize <= LaterSize) 982 return OW_Complete; 983 } 984 985 // Check to see if the later store is to the entire object (either a global, 986 // an alloca, or a byval/inalloca argument). If so, then it clearly 987 // overwrites any other store to the same object. 988 const Value *P1 = Earlier.Ptr->stripPointerCasts(); 989 const Value *P2 = Later.Ptr->stripPointerCasts(); 990 const Value *UO1 = getUnderlyingObject(P1), *UO2 = getUnderlyingObject(P2); 991 992 // If we can't resolve the same pointers to the same object, then we can't 993 // analyze them at all. 994 if (UO1 != UO2) 995 return OW_Unknown; 996 997 // If the "Later" store is to a recognizable object, get its size. 998 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI, &F); 999 if (ObjectSize != MemoryLocation::UnknownSize) 1000 if (ObjectSize == LaterSize && ObjectSize >= EarlierSize) 1001 return OW_Complete; 1002 1003 // Okay, we have stores to two completely different pointers. Try to 1004 // decompose the pointer into a "base + constant_offset" form. If the base 1005 // pointers are equal, then we can reason about the two stores. 1006 EarlierOff = 0; 1007 LaterOff = 0; 1008 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL); 1009 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL); 1010 1011 // If the base pointers still differ, we have two completely different stores. 1012 if (BP1 != BP2) 1013 return OW_Unknown; 1014 1015 // The later access completely overlaps the earlier store if and only if 1016 // both start and end of the earlier one is "inside" the later one: 1017 // |<->|--earlier--|<->| 1018 // |-------later-------| 1019 // Accesses may overlap if and only if start of one of them is "inside" 1020 // another one: 1021 // |<->|--earlier--|<----->| 1022 // |-------later-------| 1023 // OR 1024 // |----- earlier -----| 1025 // |<->|---later---|<----->| 1026 // 1027 // We have to be careful here as *Off is signed while *.Size is unsigned. 1028 1029 // Check if the earlier access starts "not before" the later one. 1030 if (EarlierOff >= LaterOff) { 1031 // If the earlier access ends "not after" the later access then the earlier 1032 // one is completely overwritten by the later one. 1033 if (uint64_t(EarlierOff - LaterOff) + EarlierSize <= LaterSize) 1034 return OW_Complete; 1035 // If start of the earlier access is "before" end of the later access then 1036 // accesses overlap. 1037 else if ((uint64_t)(EarlierOff - LaterOff) < LaterSize) 1038 return OW_MaybePartial; 1039 } 1040 // If start of the later access is "before" end of the earlier access then 1041 // accesses overlap. 1042 else if ((uint64_t)(LaterOff - EarlierOff) < EarlierSize) { 1043 return OW_MaybePartial; 1044 } 1045 1046 // Can reach here only if accesses are known not to overlap. There is no 1047 // dedicated code to indicate no overlap so signal "unknown". 1048 return OW_Unknown; 1049 } 1050 1051 bool isInvisibleToCallerAfterRet(const Value *V) { 1052 if (isa<AllocaInst>(V)) 1053 return true; 1054 auto I = InvisibleToCallerAfterRet.insert({V, false}); 1055 if (I.second) { 1056 if (!isInvisibleToCallerBeforeRet(V)) { 1057 I.first->second = false; 1058 } else { 1059 auto *Inst = dyn_cast<Instruction>(V); 1060 if (Inst && isAllocLikeFn(Inst, &TLI)) 1061 I.first->second = !PointerMayBeCaptured(V, true, false); 1062 } 1063 } 1064 return I.first->second; 1065 } 1066 1067 bool isInvisibleToCallerBeforeRet(const Value *V) { 1068 if (isa<AllocaInst>(V)) 1069 return true; 1070 auto I = InvisibleToCallerBeforeRet.insert({V, false}); 1071 if (I.second) { 1072 auto *Inst = dyn_cast<Instruction>(V); 1073 if (Inst && isAllocLikeFn(Inst, &TLI)) 1074 // NOTE: This could be made more precise by PointerMayBeCapturedBefore 1075 // with the killing MemoryDef. But we refrain from doing so for now to 1076 // limit compile-time and this does not cause any changes to the number 1077 // of stores removed on a large test set in practice. 1078 I.first->second = !PointerMayBeCaptured(V, false, true); 1079 } 1080 return I.first->second; 1081 } 1082 1083 Optional<MemoryLocation> getLocForWriteEx(Instruction *I) const { 1084 if (!I->mayWriteToMemory()) 1085 return None; 1086 1087 if (auto *MTI = dyn_cast<AnyMemIntrinsic>(I)) 1088 return {MemoryLocation::getForDest(MTI)}; 1089 1090 if (auto *CB = dyn_cast<CallBase>(I)) { 1091 // If the functions may write to memory we do not know about, bail out. 1092 if (!CB->onlyAccessesArgMemory() && 1093 !CB->onlyAccessesInaccessibleMemOrArgMem()) 1094 return None; 1095 1096 LibFunc LF; 1097 if (TLI.getLibFunc(*CB, LF) && TLI.has(LF)) { 1098 switch (LF) { 1099 case LibFunc_strcpy: 1100 case LibFunc_strncpy: 1101 case LibFunc_strcat: 1102 case LibFunc_strncat: 1103 return {MemoryLocation::getAfter(CB->getArgOperand(0))}; 1104 default: 1105 break; 1106 } 1107 } 1108 switch (CB->getIntrinsicID()) { 1109 case Intrinsic::init_trampoline: 1110 return {MemoryLocation::getAfter(CB->getArgOperand(0))}; 1111 case Intrinsic::masked_store: 1112 return {MemoryLocation::getForArgument(CB, 1, TLI)}; 1113 default: 1114 break; 1115 } 1116 return None; 1117 } 1118 1119 return MemoryLocation::getOrNone(I); 1120 } 1121 1122 /// Returns true if \p UseInst completely overwrites \p DefLoc 1123 /// (stored by \p DefInst). 1124 bool isCompleteOverwrite(const MemoryLocation &DefLoc, Instruction *DefInst, 1125 Instruction *UseInst) { 1126 // UseInst has a MemoryDef associated in MemorySSA. It's possible for a 1127 // MemoryDef to not write to memory, e.g. a volatile load is modeled as a 1128 // MemoryDef. 1129 if (!UseInst->mayWriteToMemory()) 1130 return false; 1131 1132 if (auto *CB = dyn_cast<CallBase>(UseInst)) 1133 if (CB->onlyAccessesInaccessibleMemory()) 1134 return false; 1135 1136 int64_t InstWriteOffset, DepWriteOffset; 1137 if (auto CC = getLocForWriteEx(UseInst)) 1138 return isOverwrite(UseInst, DefInst, *CC, DefLoc, DepWriteOffset, 1139 InstWriteOffset) == OW_Complete; 1140 return false; 1141 } 1142 1143 /// Returns true if \p Def is not read before returning from the function. 1144 bool isWriteAtEndOfFunction(MemoryDef *Def) { 1145 LLVM_DEBUG(dbgs() << " Check if def " << *Def << " (" 1146 << *Def->getMemoryInst() 1147 << ") is at the end the function \n"); 1148 1149 auto MaybeLoc = getLocForWriteEx(Def->getMemoryInst()); 1150 if (!MaybeLoc) { 1151 LLVM_DEBUG(dbgs() << " ... could not get location for write.\n"); 1152 return false; 1153 } 1154 1155 SmallVector<MemoryAccess *, 4> WorkList; 1156 SmallPtrSet<MemoryAccess *, 8> Visited; 1157 auto PushMemUses = [&WorkList, &Visited](MemoryAccess *Acc) { 1158 if (!Visited.insert(Acc).second) 1159 return; 1160 for (Use &U : Acc->uses()) 1161 WorkList.push_back(cast<MemoryAccess>(U.getUser())); 1162 }; 1163 PushMemUses(Def); 1164 for (unsigned I = 0; I < WorkList.size(); I++) { 1165 if (WorkList.size() >= MemorySSAScanLimit) { 1166 LLVM_DEBUG(dbgs() << " ... hit exploration limit.\n"); 1167 return false; 1168 } 1169 1170 MemoryAccess *UseAccess = WorkList[I]; 1171 // Simply adding the users of MemoryPhi to the worklist is not enough, 1172 // because we might miss read clobbers in different iterations of a loop, 1173 // for example. 1174 // TODO: Add support for phi translation to handle the loop case. 1175 if (isa<MemoryPhi>(UseAccess)) 1176 return false; 1177 1178 // TODO: Checking for aliasing is expensive. Consider reducing the amount 1179 // of times this is called and/or caching it. 1180 Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst(); 1181 if (isReadClobber(*MaybeLoc, UseInst)) { 1182 LLVM_DEBUG(dbgs() << " ... hit read clobber " << *UseInst << ".\n"); 1183 return false; 1184 } 1185 1186 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) 1187 PushMemUses(UseDef); 1188 } 1189 return true; 1190 } 1191 1192 /// If \p I is a memory terminator like llvm.lifetime.end or free, return a 1193 /// pair with the MemoryLocation terminated by \p I and a boolean flag 1194 /// indicating whether \p I is a free-like call. 1195 Optional<std::pair<MemoryLocation, bool>> 1196 getLocForTerminator(Instruction *I) const { 1197 uint64_t Len; 1198 Value *Ptr; 1199 if (match(I, m_Intrinsic<Intrinsic::lifetime_end>(m_ConstantInt(Len), 1200 m_Value(Ptr)))) 1201 return {std::make_pair(MemoryLocation(Ptr, Len), false)}; 1202 1203 if (auto *CB = dyn_cast<CallBase>(I)) { 1204 if (isFreeCall(I, &TLI)) 1205 return {std::make_pair(MemoryLocation::getAfter(CB->getArgOperand(0)), 1206 true)}; 1207 } 1208 1209 return None; 1210 } 1211 1212 /// Returns true if \p I is a memory terminator instruction like 1213 /// llvm.lifetime.end or free. 1214 bool isMemTerminatorInst(Instruction *I) const { 1215 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I); 1216 return (II && II->getIntrinsicID() == Intrinsic::lifetime_end) || 1217 isFreeCall(I, &TLI); 1218 } 1219 1220 /// Returns true if \p MaybeTerm is a memory terminator for \p Loc from 1221 /// instruction \p AccessI. 1222 bool isMemTerminator(const MemoryLocation &Loc, Instruction *AccessI, 1223 Instruction *MaybeTerm) { 1224 Optional<std::pair<MemoryLocation, bool>> MaybeTermLoc = 1225 getLocForTerminator(MaybeTerm); 1226 1227 if (!MaybeTermLoc) 1228 return false; 1229 1230 // If the terminator is a free-like call, all accesses to the underlying 1231 // object can be considered terminated. 1232 if (getUnderlyingObject(Loc.Ptr) != 1233 getUnderlyingObject(MaybeTermLoc->first.Ptr)) 1234 return false; 1235 1236 auto TermLoc = MaybeTermLoc->first; 1237 if (MaybeTermLoc->second) { 1238 const Value *LocUO = getUnderlyingObject(Loc.Ptr); 1239 return BatchAA.isMustAlias(TermLoc.Ptr, LocUO); 1240 } 1241 int64_t InstWriteOffset, DepWriteOffset; 1242 return isOverwrite(MaybeTerm, AccessI, TermLoc, Loc, DepWriteOffset, 1243 InstWriteOffset) == OW_Complete; 1244 } 1245 1246 // Returns true if \p Use may read from \p DefLoc. 1247 bool isReadClobber(const MemoryLocation &DefLoc, Instruction *UseInst) { 1248 if (isNoopIntrinsic(UseInst)) 1249 return false; 1250 1251 // Monotonic or weaker atomic stores can be re-ordered and do not need to be 1252 // treated as read clobber. 1253 if (auto SI = dyn_cast<StoreInst>(UseInst)) 1254 return isStrongerThan(SI->getOrdering(), AtomicOrdering::Monotonic); 1255 1256 if (!UseInst->mayReadFromMemory()) 1257 return false; 1258 1259 if (auto *CB = dyn_cast<CallBase>(UseInst)) 1260 if (CB->onlyAccessesInaccessibleMemory()) 1261 return false; 1262 1263 // NOTE: For calls, the number of stores removed could be slightly improved 1264 // by using AA.callCapturesBefore(UseInst, DefLoc, &DT), but that showed to 1265 // be expensive compared to the benefits in practice. For now, avoid more 1266 // expensive analysis to limit compile-time. 1267 return isRefSet(BatchAA.getModRefInfo(UseInst, DefLoc)); 1268 } 1269 1270 /// Returns true if a dependency between \p Current and \p KillingDef is 1271 /// guaranteed to be loop invariant for the loops that they are in. Either 1272 /// because they are known to be in the same block, in the same loop level or 1273 /// by guaranteeing that \p CurrentLoc only references a single MemoryLocation 1274 /// during execution of the containing function. 1275 bool isGuaranteedLoopIndependent(const Instruction *Current, 1276 const Instruction *KillingDef, 1277 const MemoryLocation &CurrentLoc) { 1278 // If the dependency is within the same block or loop level (being careful 1279 // of irreducible loops), we know that AA will return a valid result for the 1280 // memory dependency. (Both at the function level, outside of any loop, 1281 // would also be valid but we currently disable that to limit compile time). 1282 if (Current->getParent() == KillingDef->getParent()) 1283 return true; 1284 const Loop *CurrentLI = LI.getLoopFor(Current->getParent()); 1285 if (!ContainsIrreducibleLoops && CurrentLI && 1286 CurrentLI == LI.getLoopFor(KillingDef->getParent())) 1287 return true; 1288 // Otherwise check the memory location is invariant to any loops. 1289 return isGuaranteedLoopInvariant(CurrentLoc.Ptr); 1290 } 1291 1292 /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible 1293 /// loop. In particular, this guarantees that it only references a single 1294 /// MemoryLocation during execution of the containing function. 1295 bool isGuaranteedLoopInvariant(const Value *Ptr) { 1296 auto IsGuaranteedLoopInvariantBase = [this](const Value *Ptr) { 1297 Ptr = Ptr->stripPointerCasts(); 1298 if (auto *I = dyn_cast<Instruction>(Ptr)) { 1299 if (isa<AllocaInst>(Ptr)) 1300 return true; 1301 1302 if (isAllocLikeFn(I, &TLI)) 1303 return true; 1304 1305 return false; 1306 } 1307 return true; 1308 }; 1309 1310 Ptr = Ptr->stripPointerCasts(); 1311 if (auto *I = dyn_cast<Instruction>(Ptr)) { 1312 if (I->getParent()->isEntryBlock()) 1313 return true; 1314 } 1315 if (auto *GEP = dyn_cast<GEPOperator>(Ptr)) { 1316 return IsGuaranteedLoopInvariantBase(GEP->getPointerOperand()) && 1317 GEP->hasAllConstantIndices(); 1318 } 1319 return IsGuaranteedLoopInvariantBase(Ptr); 1320 } 1321 1322 // Find a MemoryDef writing to \p DefLoc and dominating \p StartAccess, with 1323 // no read access between them or on any other path to a function exit block 1324 // if \p DefLoc is not accessible after the function returns. If there is no 1325 // such MemoryDef, return None. The returned value may not (completely) 1326 // overwrite \p DefLoc. Currently we bail out when we encounter an aliasing 1327 // MemoryUse (read). 1328 Optional<MemoryAccess *> 1329 getDomMemoryDef(MemoryDef *KillingDef, MemoryAccess *StartAccess, 1330 const MemoryLocation &DefLoc, const Value *DefUO, 1331 unsigned &ScanLimit, unsigned &WalkerStepLimit, 1332 bool IsMemTerm, unsigned &PartialLimit) { 1333 if (ScanLimit == 0 || WalkerStepLimit == 0) { 1334 LLVM_DEBUG(dbgs() << "\n ... hit scan limit\n"); 1335 return None; 1336 } 1337 1338 MemoryAccess *Current = StartAccess; 1339 Instruction *KillingI = KillingDef->getMemoryInst(); 1340 bool StepAgain; 1341 LLVM_DEBUG(dbgs() << " trying to get dominating access\n"); 1342 1343 // Find the next clobbering Mod access for DefLoc, starting at StartAccess. 1344 Optional<MemoryLocation> CurrentLoc; 1345 do { 1346 StepAgain = false; 1347 LLVM_DEBUG({ 1348 dbgs() << " visiting " << *Current; 1349 if (!MSSA.isLiveOnEntryDef(Current) && isa<MemoryUseOrDef>(Current)) 1350 dbgs() << " (" << *cast<MemoryUseOrDef>(Current)->getMemoryInst() 1351 << ")"; 1352 dbgs() << "\n"; 1353 }); 1354 1355 // Reached TOP. 1356 if (MSSA.isLiveOnEntryDef(Current)) { 1357 LLVM_DEBUG(dbgs() << " ... found LiveOnEntryDef\n"); 1358 return None; 1359 } 1360 1361 // Cost of a step. Accesses in the same block are more likely to be valid 1362 // candidates for elimination, hence consider them cheaper. 1363 unsigned StepCost = KillingDef->getBlock() == Current->getBlock() 1364 ? MemorySSASameBBStepCost 1365 : MemorySSAOtherBBStepCost; 1366 if (WalkerStepLimit <= StepCost) { 1367 LLVM_DEBUG(dbgs() << " ... hit walker step limit\n"); 1368 return None; 1369 } 1370 WalkerStepLimit -= StepCost; 1371 1372 // Return for MemoryPhis. They cannot be eliminated directly and the 1373 // caller is responsible for traversing them. 1374 if (isa<MemoryPhi>(Current)) { 1375 LLVM_DEBUG(dbgs() << " ... found MemoryPhi\n"); 1376 return Current; 1377 } 1378 1379 // Below, check if CurrentDef is a valid candidate to be eliminated by 1380 // KillingDef. If it is not, check the next candidate. 1381 MemoryDef *CurrentDef = cast<MemoryDef>(Current); 1382 Instruction *CurrentI = CurrentDef->getMemoryInst(); 1383 1384 if (canSkipDef(CurrentDef, !isInvisibleToCallerBeforeRet(DefUO))) { 1385 StepAgain = true; 1386 Current = CurrentDef->getDefiningAccess(); 1387 continue; 1388 } 1389 1390 // Before we try to remove anything, check for any extra throwing 1391 // instructions that block us from DSEing 1392 if (mayThrowBetween(KillingI, CurrentI, DefUO)) { 1393 LLVM_DEBUG(dbgs() << " ... skip, may throw!\n"); 1394 return None; 1395 } 1396 1397 // Check for anything that looks like it will be a barrier to further 1398 // removal 1399 if (isDSEBarrier(DefUO, CurrentI)) { 1400 LLVM_DEBUG(dbgs() << " ... skip, barrier\n"); 1401 return None; 1402 } 1403 1404 // If Current is known to be on path that reads DefLoc or is a read 1405 // clobber, bail out, as the path is not profitable. We skip this check 1406 // for intrinsic calls, because the code knows how to handle memcpy 1407 // intrinsics. 1408 if (!isa<IntrinsicInst>(CurrentI) && isReadClobber(DefLoc, CurrentI)) 1409 return None; 1410 1411 // Quick check if there are direct uses that are read-clobbers. 1412 if (any_of(Current->uses(), [this, &DefLoc, StartAccess](Use &U) { 1413 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(U.getUser())) 1414 return !MSSA.dominates(StartAccess, UseOrDef) && 1415 isReadClobber(DefLoc, UseOrDef->getMemoryInst()); 1416 return false; 1417 })) { 1418 LLVM_DEBUG(dbgs() << " ... found a read clobber\n"); 1419 return None; 1420 } 1421 1422 // If Current cannot be analyzed or is not removable, check the next 1423 // candidate. 1424 if (!hasAnalyzableMemoryWrite(CurrentI, TLI) || !isRemovable(CurrentI)) { 1425 StepAgain = true; 1426 Current = CurrentDef->getDefiningAccess(); 1427 continue; 1428 } 1429 1430 // If Current does not have an analyzable write location, skip it 1431 CurrentLoc = getLocForWriteEx(CurrentI); 1432 if (!CurrentLoc) { 1433 StepAgain = true; 1434 Current = CurrentDef->getDefiningAccess(); 1435 continue; 1436 } 1437 1438 // AliasAnalysis does not account for loops. Limit elimination to 1439 // candidates for which we can guarantee they always store to the same 1440 // memory location and not located in different loops. 1441 if (!isGuaranteedLoopIndependent(CurrentI, KillingI, *CurrentLoc)) { 1442 LLVM_DEBUG(dbgs() << " ... not guaranteed loop independent\n"); 1443 StepAgain = true; 1444 Current = CurrentDef->getDefiningAccess(); 1445 WalkerStepLimit -= 1; 1446 continue; 1447 } 1448 1449 if (IsMemTerm) { 1450 // If the killing def is a memory terminator (e.g. lifetime.end), check 1451 // the next candidate if the current Current does not write the same 1452 // underlying object as the terminator. 1453 if (!isMemTerminator(*CurrentLoc, CurrentI, KillingI)) { 1454 StepAgain = true; 1455 Current = CurrentDef->getDefiningAccess(); 1456 } 1457 continue; 1458 } else { 1459 int64_t InstWriteOffset, DepWriteOffset; 1460 auto OR = isOverwrite(KillingI, CurrentI, DefLoc, *CurrentLoc, 1461 DepWriteOffset, InstWriteOffset); 1462 // If Current does not write to the same object as KillingDef, check 1463 // the next candidate. 1464 if (OR == OW_Unknown) { 1465 StepAgain = true; 1466 Current = CurrentDef->getDefiningAccess(); 1467 } else if (OR == OW_MaybePartial) { 1468 // If KillingDef only partially overwrites Current, check the next 1469 // candidate if the partial step limit is exceeded. This aggressively 1470 // limits the number of candidates for partial store elimination, 1471 // which are less likely to be removable in the end. 1472 if (PartialLimit <= 1) { 1473 StepAgain = true; 1474 Current = CurrentDef->getDefiningAccess(); 1475 WalkerStepLimit -= 1; 1476 continue; 1477 } 1478 PartialLimit -= 1; 1479 } 1480 } 1481 } while (StepAgain); 1482 1483 // Accesses to objects accessible after the function returns can only be 1484 // eliminated if the access is killed along all paths to the exit. Collect 1485 // the blocks with killing (=completely overwriting MemoryDefs) and check if 1486 // they cover all paths from EarlierAccess to any function exit. 1487 SmallPtrSet<Instruction *, 16> KillingDefs; 1488 KillingDefs.insert(KillingDef->getMemoryInst()); 1489 MemoryAccess *EarlierAccess = Current; 1490 Instruction *EarlierMemInst = 1491 cast<MemoryDef>(EarlierAccess)->getMemoryInst(); 1492 LLVM_DEBUG(dbgs() << " Checking for reads of " << *EarlierAccess << " (" 1493 << *EarlierMemInst << ")\n"); 1494 1495 SmallSetVector<MemoryAccess *, 32> WorkList; 1496 auto PushMemUses = [&WorkList](MemoryAccess *Acc) { 1497 for (Use &U : Acc->uses()) 1498 WorkList.insert(cast<MemoryAccess>(U.getUser())); 1499 }; 1500 PushMemUses(EarlierAccess); 1501 1502 // Optimistically collect all accesses for reads. If we do not find any 1503 // read clobbers, add them to the cache. 1504 SmallPtrSet<MemoryAccess *, 16> KnownNoReads; 1505 if (!EarlierMemInst->mayReadFromMemory()) 1506 KnownNoReads.insert(EarlierAccess); 1507 // Check if EarlierDef may be read. 1508 for (unsigned I = 0; I < WorkList.size(); I++) { 1509 MemoryAccess *UseAccess = WorkList[I]; 1510 1511 LLVM_DEBUG(dbgs() << " " << *UseAccess); 1512 // Bail out if the number of accesses to check exceeds the scan limit. 1513 if (ScanLimit < (WorkList.size() - I)) { 1514 LLVM_DEBUG(dbgs() << "\n ... hit scan limit\n"); 1515 return None; 1516 } 1517 --ScanLimit; 1518 NumDomMemDefChecks++; 1519 KnownNoReads.insert(UseAccess); 1520 1521 if (isa<MemoryPhi>(UseAccess)) { 1522 if (any_of(KillingDefs, [this, UseAccess](Instruction *KI) { 1523 return DT.properlyDominates(KI->getParent(), 1524 UseAccess->getBlock()); 1525 })) { 1526 LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing block\n"); 1527 continue; 1528 } 1529 LLVM_DEBUG(dbgs() << "\n ... adding PHI uses\n"); 1530 PushMemUses(UseAccess); 1531 continue; 1532 } 1533 1534 Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst(); 1535 LLVM_DEBUG(dbgs() << " (" << *UseInst << ")\n"); 1536 1537 if (any_of(KillingDefs, [this, UseInst](Instruction *KI) { 1538 return DT.dominates(KI, UseInst); 1539 })) { 1540 LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing def\n"); 1541 continue; 1542 } 1543 1544 // A memory terminator kills all preceeding MemoryDefs and all succeeding 1545 // MemoryAccesses. We do not have to check it's users. 1546 if (isMemTerminator(*CurrentLoc, EarlierMemInst, UseInst)) { 1547 LLVM_DEBUG( 1548 dbgs() 1549 << " ... skipping, memterminator invalidates following accesses\n"); 1550 continue; 1551 } 1552 1553 if (isNoopIntrinsic(cast<MemoryUseOrDef>(UseAccess)->getMemoryInst())) { 1554 LLVM_DEBUG(dbgs() << " ... adding uses of intrinsic\n"); 1555 PushMemUses(UseAccess); 1556 continue; 1557 } 1558 1559 if (UseInst->mayThrow() && !isInvisibleToCallerBeforeRet(DefUO)) { 1560 LLVM_DEBUG(dbgs() << " ... found throwing instruction\n"); 1561 return None; 1562 } 1563 1564 // Uses which may read the original MemoryDef mean we cannot eliminate the 1565 // original MD. Stop walk. 1566 if (isReadClobber(*CurrentLoc, UseInst)) { 1567 LLVM_DEBUG(dbgs() << " ... found read clobber\n"); 1568 return None; 1569 } 1570 1571 // If this worklist walks back to the original memory access (and the 1572 // pointer is not guarenteed loop invariant) then we cannot assume that a 1573 // store kills itself. 1574 if (EarlierAccess == UseAccess && 1575 !isGuaranteedLoopInvariant(CurrentLoc->Ptr)) { 1576 LLVM_DEBUG(dbgs() << " ... found not loop invariant self access\n"); 1577 return None; 1578 } 1579 // Otherwise, for the KillingDef and EarlierAccess we only have to check 1580 // if it reads the memory location. 1581 // TODO: It would probably be better to check for self-reads before 1582 // calling the function. 1583 if (KillingDef == UseAccess || EarlierAccess == UseAccess) { 1584 LLVM_DEBUG(dbgs() << " ... skipping killing def/dom access\n"); 1585 continue; 1586 } 1587 1588 // Check all uses for MemoryDefs, except for defs completely overwriting 1589 // the original location. Otherwise we have to check uses of *all* 1590 // MemoryDefs we discover, including non-aliasing ones. Otherwise we might 1591 // miss cases like the following 1592 // 1 = Def(LoE) ; <----- EarlierDef stores [0,1] 1593 // 2 = Def(1) ; (2, 1) = NoAlias, stores [2,3] 1594 // Use(2) ; MayAlias 2 *and* 1, loads [0, 3]. 1595 // (The Use points to the *first* Def it may alias) 1596 // 3 = Def(1) ; <---- Current (3, 2) = NoAlias, (3,1) = MayAlias, 1597 // stores [0,1] 1598 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) { 1599 if (isCompleteOverwrite(*CurrentLoc, EarlierMemInst, UseInst)) { 1600 BasicBlock *MaybeKillingBlock = UseInst->getParent(); 1601 if (PostOrderNumbers.find(MaybeKillingBlock)->second < 1602 PostOrderNumbers.find(EarlierAccess->getBlock())->second) { 1603 if (!isInvisibleToCallerAfterRet(DefUO)) { 1604 LLVM_DEBUG(dbgs() 1605 << " ... found killing def " << *UseInst << "\n"); 1606 KillingDefs.insert(UseInst); 1607 } 1608 } else { 1609 LLVM_DEBUG(dbgs() 1610 << " ... found preceeding def " << *UseInst << "\n"); 1611 return None; 1612 } 1613 } else 1614 PushMemUses(UseDef); 1615 } 1616 } 1617 1618 // For accesses to locations visible after the function returns, make sure 1619 // that the location is killed (=overwritten) along all paths from 1620 // EarlierAccess to the exit. 1621 if (!isInvisibleToCallerAfterRet(DefUO)) { 1622 SmallPtrSet<BasicBlock *, 16> KillingBlocks; 1623 for (Instruction *KD : KillingDefs) 1624 KillingBlocks.insert(KD->getParent()); 1625 assert(!KillingBlocks.empty() && 1626 "Expected at least a single killing block"); 1627 1628 // Find the common post-dominator of all killing blocks. 1629 BasicBlock *CommonPred = *KillingBlocks.begin(); 1630 for (auto I = std::next(KillingBlocks.begin()), E = KillingBlocks.end(); 1631 I != E; I++) { 1632 if (!CommonPred) 1633 break; 1634 CommonPred = PDT.findNearestCommonDominator(CommonPred, *I); 1635 } 1636 1637 // If CommonPred is in the set of killing blocks, just check if it 1638 // post-dominates EarlierAccess. 1639 if (KillingBlocks.count(CommonPred)) { 1640 if (PDT.dominates(CommonPred, EarlierAccess->getBlock())) 1641 return {EarlierAccess}; 1642 return None; 1643 } 1644 1645 // If the common post-dominator does not post-dominate EarlierAccess, 1646 // there is a path from EarlierAccess to an exit not going through a 1647 // killing block. 1648 if (PDT.dominates(CommonPred, EarlierAccess->getBlock())) { 1649 SetVector<BasicBlock *> WorkList; 1650 1651 // If CommonPred is null, there are multiple exits from the function. 1652 // They all have to be added to the worklist. 1653 if (CommonPred) 1654 WorkList.insert(CommonPred); 1655 else 1656 for (BasicBlock *R : PDT.roots()) 1657 WorkList.insert(R); 1658 1659 NumCFGTries++; 1660 // Check if all paths starting from an exit node go through one of the 1661 // killing blocks before reaching EarlierAccess. 1662 for (unsigned I = 0; I < WorkList.size(); I++) { 1663 NumCFGChecks++; 1664 BasicBlock *Current = WorkList[I]; 1665 if (KillingBlocks.count(Current)) 1666 continue; 1667 if (Current == EarlierAccess->getBlock()) 1668 return None; 1669 1670 // EarlierAccess is reachable from the entry, so we don't have to 1671 // explore unreachable blocks further. 1672 if (!DT.isReachableFromEntry(Current)) 1673 continue; 1674 1675 for (BasicBlock *Pred : predecessors(Current)) 1676 WorkList.insert(Pred); 1677 1678 if (WorkList.size() >= MemorySSAPathCheckLimit) 1679 return None; 1680 } 1681 NumCFGSuccess++; 1682 return {EarlierAccess}; 1683 } 1684 return None; 1685 } 1686 1687 // No aliasing MemoryUses of EarlierAccess found, EarlierAccess is 1688 // potentially dead. 1689 return {EarlierAccess}; 1690 } 1691 1692 // Delete dead memory defs 1693 void deleteDeadInstruction(Instruction *SI) { 1694 MemorySSAUpdater Updater(&MSSA); 1695 SmallVector<Instruction *, 32> NowDeadInsts; 1696 NowDeadInsts.push_back(SI); 1697 --NumFastOther; 1698 1699 while (!NowDeadInsts.empty()) { 1700 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 1701 ++NumFastOther; 1702 1703 // Try to preserve debug information attached to the dead instruction. 1704 salvageDebugInfo(*DeadInst); 1705 salvageKnowledge(DeadInst); 1706 1707 // Remove the Instruction from MSSA. 1708 if (MemoryAccess *MA = MSSA.getMemoryAccess(DeadInst)) { 1709 if (MemoryDef *MD = dyn_cast<MemoryDef>(MA)) { 1710 SkipStores.insert(MD); 1711 } 1712 Updater.removeMemoryAccess(MA); 1713 } 1714 1715 auto I = IOLs.find(DeadInst->getParent()); 1716 if (I != IOLs.end()) 1717 I->second.erase(DeadInst); 1718 // Remove its operands 1719 for (Use &O : DeadInst->operands()) 1720 if (Instruction *OpI = dyn_cast<Instruction>(O)) { 1721 O = nullptr; 1722 if (isInstructionTriviallyDead(OpI, &TLI)) 1723 NowDeadInsts.push_back(OpI); 1724 } 1725 1726 DeadInst->eraseFromParent(); 1727 } 1728 } 1729 1730 // Check for any extra throws between SI and NI that block DSE. This only 1731 // checks extra maythrows (those that aren't MemoryDef's). MemoryDef that may 1732 // throw are handled during the walk from one def to the next. 1733 bool mayThrowBetween(Instruction *SI, Instruction *NI, 1734 const Value *SILocUnd) { 1735 // First see if we can ignore it by using the fact that SI is an 1736 // alloca/alloca like object that is not visible to the caller during 1737 // execution of the function. 1738 if (SILocUnd && isInvisibleToCallerBeforeRet(SILocUnd)) 1739 return false; 1740 1741 if (SI->getParent() == NI->getParent()) 1742 return ThrowingBlocks.count(SI->getParent()); 1743 return !ThrowingBlocks.empty(); 1744 } 1745 1746 // Check if \p NI acts as a DSE barrier for \p SI. The following instructions 1747 // act as barriers: 1748 // * A memory instruction that may throw and \p SI accesses a non-stack 1749 // object. 1750 // * Atomic stores stronger that monotonic. 1751 bool isDSEBarrier(const Value *SILocUnd, Instruction *NI) { 1752 // If NI may throw it acts as a barrier, unless we are to an alloca/alloca 1753 // like object that does not escape. 1754 if (NI->mayThrow() && !isInvisibleToCallerBeforeRet(SILocUnd)) 1755 return true; 1756 1757 // If NI is an atomic load/store stronger than monotonic, do not try to 1758 // eliminate/reorder it. 1759 if (NI->isAtomic()) { 1760 if (auto *LI = dyn_cast<LoadInst>(NI)) 1761 return isStrongerThanMonotonic(LI->getOrdering()); 1762 if (auto *SI = dyn_cast<StoreInst>(NI)) 1763 return isStrongerThanMonotonic(SI->getOrdering()); 1764 if (auto *ARMW = dyn_cast<AtomicRMWInst>(NI)) 1765 return isStrongerThanMonotonic(ARMW->getOrdering()); 1766 if (auto *CmpXchg = dyn_cast<AtomicCmpXchgInst>(NI)) 1767 return isStrongerThanMonotonic(CmpXchg->getSuccessOrdering()) || 1768 isStrongerThanMonotonic(CmpXchg->getFailureOrdering()); 1769 llvm_unreachable("other instructions should be skipped in MemorySSA"); 1770 } 1771 return false; 1772 } 1773 1774 /// Eliminate writes to objects that are not visible in the caller and are not 1775 /// accessed before returning from the function. 1776 bool eliminateDeadWritesAtEndOfFunction() { 1777 bool MadeChange = false; 1778 LLVM_DEBUG( 1779 dbgs() 1780 << "Trying to eliminate MemoryDefs at the end of the function\n"); 1781 for (int I = MemDefs.size() - 1; I >= 0; I--) { 1782 MemoryDef *Def = MemDefs[I]; 1783 if (SkipStores.contains(Def) || !isRemovable(Def->getMemoryInst())) 1784 continue; 1785 1786 Instruction *DefI = Def->getMemoryInst(); 1787 SmallVector<const Value *, 4> Pointers; 1788 auto DefLoc = getLocForWriteEx(DefI); 1789 if (!DefLoc) 1790 continue; 1791 1792 // NOTE: Currently eliminating writes at the end of a function is limited 1793 // to MemoryDefs with a single underlying object, to save compile-time. In 1794 // practice it appears the case with multiple underlying objects is very 1795 // uncommon. If it turns out to be important, we can use 1796 // getUnderlyingObjects here instead. 1797 const Value *UO = getUnderlyingObject(DefLoc->Ptr); 1798 if (!UO || !isInvisibleToCallerAfterRet(UO)) 1799 continue; 1800 1801 if (isWriteAtEndOfFunction(Def)) { 1802 // See through pointer-to-pointer bitcasts 1803 LLVM_DEBUG(dbgs() << " ... MemoryDef is not accessed until the end " 1804 "of the function\n"); 1805 deleteDeadInstruction(DefI); 1806 ++NumFastStores; 1807 MadeChange = true; 1808 } 1809 } 1810 return MadeChange; 1811 } 1812 1813 /// \returns true if \p Def is a no-op store, either because it 1814 /// directly stores back a loaded value or stores zero to a calloced object. 1815 bool storeIsNoop(MemoryDef *Def, const MemoryLocation &DefLoc, 1816 const Value *DefUO) { 1817 StoreInst *Store = dyn_cast<StoreInst>(Def->getMemoryInst()); 1818 MemSetInst *MemSet = dyn_cast<MemSetInst>(Def->getMemoryInst()); 1819 Constant *StoredConstant = nullptr; 1820 if (Store) 1821 StoredConstant = dyn_cast<Constant>(Store->getOperand(0)); 1822 if (MemSet) 1823 StoredConstant = dyn_cast<Constant>(MemSet->getValue()); 1824 1825 if (StoredConstant && StoredConstant->isNullValue()) { 1826 auto *DefUOInst = dyn_cast<Instruction>(DefUO); 1827 if (DefUOInst && isCallocLikeFn(DefUOInst, &TLI)) { 1828 auto *UnderlyingDef = cast<MemoryDef>(MSSA.getMemoryAccess(DefUOInst)); 1829 // If UnderlyingDef is the clobbering access of Def, no instructions 1830 // between them can modify the memory location. 1831 auto *ClobberDef = 1832 MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(Def); 1833 return UnderlyingDef == ClobberDef; 1834 } 1835 } 1836 1837 if (!Store) 1838 return false; 1839 1840 if (auto *LoadI = dyn_cast<LoadInst>(Store->getOperand(0))) { 1841 if (LoadI->getPointerOperand() == Store->getOperand(1)) { 1842 // Get the defining access for the load. 1843 auto *LoadAccess = MSSA.getMemoryAccess(LoadI)->getDefiningAccess(); 1844 // Fast path: the defining accesses are the same. 1845 if (LoadAccess == Def->getDefiningAccess()) 1846 return true; 1847 1848 // Look through phi accesses. Recursively scan all phi accesses by 1849 // adding them to a worklist. Bail when we run into a memory def that 1850 // does not match LoadAccess. 1851 SetVector<MemoryAccess *> ToCheck; 1852 MemoryAccess *Current = 1853 MSSA.getWalker()->getClobberingMemoryAccess(Def); 1854 // We don't want to bail when we run into the store memory def. But, 1855 // the phi access may point to it. So, pretend like we've already 1856 // checked it. 1857 ToCheck.insert(Def); 1858 ToCheck.insert(Current); 1859 // Start at current (1) to simulate already having checked Def. 1860 for (unsigned I = 1; I < ToCheck.size(); ++I) { 1861 Current = ToCheck[I]; 1862 if (auto PhiAccess = dyn_cast<MemoryPhi>(Current)) { 1863 // Check all the operands. 1864 for (auto &Use : PhiAccess->incoming_values()) 1865 ToCheck.insert(cast<MemoryAccess>(&Use)); 1866 continue; 1867 } 1868 1869 // If we found a memory def, bail. This happens when we have an 1870 // unrelated write in between an otherwise noop store. 1871 assert(isa<MemoryDef>(Current) && 1872 "Only MemoryDefs should reach here."); 1873 // TODO: Skip no alias MemoryDefs that have no aliasing reads. 1874 // We are searching for the definition of the store's destination. 1875 // So, if that is the same definition as the load, then this is a 1876 // noop. Otherwise, fail. 1877 if (LoadAccess != Current) 1878 return false; 1879 } 1880 return true; 1881 } 1882 } 1883 1884 return false; 1885 } 1886 }; 1887 1888 static bool eliminateDeadStores(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, 1889 DominatorTree &DT, PostDominatorTree &PDT, 1890 const TargetLibraryInfo &TLI, 1891 const LoopInfo &LI) { 1892 bool MadeChange = false; 1893 1894 DSEState State = DSEState::get(F, AA, MSSA, DT, PDT, TLI, LI); 1895 // For each store: 1896 for (unsigned I = 0; I < State.MemDefs.size(); I++) { 1897 MemoryDef *KillingDef = State.MemDefs[I]; 1898 if (State.SkipStores.count(KillingDef)) 1899 continue; 1900 Instruction *SI = KillingDef->getMemoryInst(); 1901 1902 Optional<MemoryLocation> MaybeSILoc; 1903 if (State.isMemTerminatorInst(SI)) 1904 MaybeSILoc = State.getLocForTerminator(SI).map( 1905 [](const std::pair<MemoryLocation, bool> &P) { return P.first; }); 1906 else 1907 MaybeSILoc = State.getLocForWriteEx(SI); 1908 1909 if (!MaybeSILoc) { 1910 LLVM_DEBUG(dbgs() << "Failed to find analyzable write location for " 1911 << *SI << "\n"); 1912 continue; 1913 } 1914 MemoryLocation SILoc = *MaybeSILoc; 1915 assert(SILoc.Ptr && "SILoc should not be null"); 1916 const Value *SILocUnd = getUnderlyingObject(SILoc.Ptr); 1917 1918 MemoryAccess *Current = KillingDef; 1919 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs killed by " 1920 << *Current << " (" << *SI << ")\n"); 1921 1922 unsigned ScanLimit = MemorySSAScanLimit; 1923 unsigned WalkerStepLimit = MemorySSAUpwardsStepLimit; 1924 unsigned PartialLimit = MemorySSAPartialStoreLimit; 1925 // Worklist of MemoryAccesses that may be killed by KillingDef. 1926 SetVector<MemoryAccess *> ToCheck; 1927 1928 if (SILocUnd) 1929 ToCheck.insert(KillingDef->getDefiningAccess()); 1930 1931 bool Shortend = false; 1932 bool IsMemTerm = State.isMemTerminatorInst(SI); 1933 // Check if MemoryAccesses in the worklist are killed by KillingDef. 1934 for (unsigned I = 0; I < ToCheck.size(); I++) { 1935 Current = ToCheck[I]; 1936 if (State.SkipStores.count(Current)) 1937 continue; 1938 1939 Optional<MemoryAccess *> Next = State.getDomMemoryDef( 1940 KillingDef, Current, SILoc, SILocUnd, ScanLimit, WalkerStepLimit, 1941 IsMemTerm, PartialLimit); 1942 1943 if (!Next) { 1944 LLVM_DEBUG(dbgs() << " finished walk\n"); 1945 continue; 1946 } 1947 1948 MemoryAccess *EarlierAccess = *Next; 1949 LLVM_DEBUG(dbgs() << " Checking if we can kill " << *EarlierAccess); 1950 if (isa<MemoryPhi>(EarlierAccess)) { 1951 LLVM_DEBUG(dbgs() << "\n ... adding incoming values to worklist\n"); 1952 for (Value *V : cast<MemoryPhi>(EarlierAccess)->incoming_values()) { 1953 MemoryAccess *IncomingAccess = cast<MemoryAccess>(V); 1954 BasicBlock *IncomingBlock = IncomingAccess->getBlock(); 1955 BasicBlock *PhiBlock = EarlierAccess->getBlock(); 1956 1957 // We only consider incoming MemoryAccesses that come before the 1958 // MemoryPhi. Otherwise we could discover candidates that do not 1959 // strictly dominate our starting def. 1960 if (State.PostOrderNumbers[IncomingBlock] > 1961 State.PostOrderNumbers[PhiBlock]) 1962 ToCheck.insert(IncomingAccess); 1963 } 1964 continue; 1965 } 1966 auto *NextDef = cast<MemoryDef>(EarlierAccess); 1967 Instruction *NI = NextDef->getMemoryInst(); 1968 LLVM_DEBUG(dbgs() << " (" << *NI << ")\n"); 1969 ToCheck.insert(NextDef->getDefiningAccess()); 1970 NumGetDomMemoryDefPassed++; 1971 1972 if (!DebugCounter::shouldExecute(MemorySSACounter)) 1973 continue; 1974 1975 MemoryLocation NILoc = *State.getLocForWriteEx(NI); 1976 1977 if (IsMemTerm) { 1978 const Value *NIUnd = getUnderlyingObject(NILoc.Ptr); 1979 if (SILocUnd != NIUnd) 1980 continue; 1981 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *NI 1982 << "\n KILLER: " << *SI << '\n'); 1983 State.deleteDeadInstruction(NI); 1984 ++NumFastStores; 1985 MadeChange = true; 1986 } else { 1987 // Check if NI overwrites SI. 1988 int64_t InstWriteOffset, DepWriteOffset; 1989 OverwriteResult OR = State.isOverwrite(SI, NI, SILoc, NILoc, 1990 DepWriteOffset, InstWriteOffset); 1991 if (OR == OW_MaybePartial) { 1992 auto Iter = State.IOLs.insert( 1993 std::make_pair<BasicBlock *, InstOverlapIntervalsTy>( 1994 NI->getParent(), InstOverlapIntervalsTy())); 1995 auto &IOL = Iter.first->second; 1996 OR = isPartialOverwrite(SILoc, NILoc, DepWriteOffset, InstWriteOffset, 1997 NI, IOL); 1998 } 1999 2000 if (EnablePartialStoreMerging && OR == OW_PartialEarlierWithFullLater) { 2001 auto *Earlier = dyn_cast<StoreInst>(NI); 2002 auto *Later = dyn_cast<StoreInst>(SI); 2003 // We are re-using tryToMergePartialOverlappingStores, which requires 2004 // Earlier to domiante Later. 2005 // TODO: implement tryToMergeParialOverlappingStores using MemorySSA. 2006 if (Earlier && Later && DT.dominates(Earlier, Later)) { 2007 if (Constant *Merged = tryToMergePartialOverlappingStores( 2008 Earlier, Later, InstWriteOffset, DepWriteOffset, State.DL, 2009 State.BatchAA, &DT)) { 2010 2011 // Update stored value of earlier store to merged constant. 2012 Earlier->setOperand(0, Merged); 2013 ++NumModifiedStores; 2014 MadeChange = true; 2015 2016 Shortend = true; 2017 // Remove later store and remove any outstanding overlap intervals 2018 // for the updated store. 2019 State.deleteDeadInstruction(Later); 2020 auto I = State.IOLs.find(Earlier->getParent()); 2021 if (I != State.IOLs.end()) 2022 I->second.erase(Earlier); 2023 break; 2024 } 2025 } 2026 } 2027 2028 if (OR == OW_Complete) { 2029 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *NI 2030 << "\n KILLER: " << *SI << '\n'); 2031 State.deleteDeadInstruction(NI); 2032 ++NumFastStores; 2033 MadeChange = true; 2034 } 2035 } 2036 } 2037 2038 // Check if the store is a no-op. 2039 if (!Shortend && isRemovable(SI) && 2040 State.storeIsNoop(KillingDef, SILoc, SILocUnd)) { 2041 LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n DEAD: " << *SI << '\n'); 2042 State.deleteDeadInstruction(SI); 2043 NumRedundantStores++; 2044 MadeChange = true; 2045 continue; 2046 } 2047 } 2048 2049 if (EnablePartialOverwriteTracking) 2050 for (auto &KV : State.IOLs) 2051 MadeChange |= removePartiallyOverlappedStores(State.DL, KV.second, TLI); 2052 2053 MadeChange |= State.eliminateDeadWritesAtEndOfFunction(); 2054 return MadeChange; 2055 } 2056 } // end anonymous namespace 2057 2058 //===----------------------------------------------------------------------===// 2059 // DSE Pass 2060 //===----------------------------------------------------------------------===// 2061 PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) { 2062 AliasAnalysis &AA = AM.getResult<AAManager>(F); 2063 const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(F); 2064 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 2065 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); 2066 PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F); 2067 LoopInfo &LI = AM.getResult<LoopAnalysis>(F); 2068 2069 bool Changed = eliminateDeadStores(F, AA, MSSA, DT, PDT, TLI, LI); 2070 2071 #ifdef LLVM_ENABLE_STATS 2072 if (AreStatisticsEnabled()) 2073 for (auto &I : instructions(F)) 2074 NumRemainingStores += isa<StoreInst>(&I); 2075 #endif 2076 2077 if (!Changed) 2078 return PreservedAnalyses::all(); 2079 2080 PreservedAnalyses PA; 2081 PA.preserveSet<CFGAnalyses>(); 2082 PA.preserve<MemorySSAAnalysis>(); 2083 PA.preserve<LoopAnalysis>(); 2084 return PA; 2085 } 2086 2087 namespace { 2088 2089 /// A legacy pass for the legacy pass manager that wraps \c DSEPass. 2090 class DSELegacyPass : public FunctionPass { 2091 public: 2092 static char ID; // Pass identification, replacement for typeid 2093 2094 DSELegacyPass() : FunctionPass(ID) { 2095 initializeDSELegacyPassPass(*PassRegistry::getPassRegistry()); 2096 } 2097 2098 bool runOnFunction(Function &F) override { 2099 if (skipFunction(F)) 2100 return false; 2101 2102 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 2103 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2104 const TargetLibraryInfo &TLI = 2105 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 2106 MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); 2107 PostDominatorTree &PDT = 2108 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 2109 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 2110 2111 bool Changed = eliminateDeadStores(F, AA, MSSA, DT, PDT, TLI, LI); 2112 2113 #ifdef LLVM_ENABLE_STATS 2114 if (AreStatisticsEnabled()) 2115 for (auto &I : instructions(F)) 2116 NumRemainingStores += isa<StoreInst>(&I); 2117 #endif 2118 2119 return Changed; 2120 } 2121 2122 void getAnalysisUsage(AnalysisUsage &AU) const override { 2123 AU.setPreservesCFG(); 2124 AU.addRequired<AAResultsWrapperPass>(); 2125 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2126 AU.addPreserved<GlobalsAAWrapperPass>(); 2127 AU.addRequired<DominatorTreeWrapperPass>(); 2128 AU.addPreserved<DominatorTreeWrapperPass>(); 2129 AU.addRequired<PostDominatorTreeWrapperPass>(); 2130 AU.addRequired<MemorySSAWrapperPass>(); 2131 AU.addPreserved<PostDominatorTreeWrapperPass>(); 2132 AU.addPreserved<MemorySSAWrapperPass>(); 2133 AU.addRequired<LoopInfoWrapperPass>(); 2134 AU.addPreserved<LoopInfoWrapperPass>(); 2135 } 2136 }; 2137 2138 } // end anonymous namespace 2139 2140 char DSELegacyPass::ID = 0; 2141 2142 INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false, 2143 false) 2144 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2145 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 2146 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 2147 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 2148 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 2149 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 2150 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2151 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 2152 INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false, 2153 false) 2154 2155 FunctionPass *llvm::createDeadStoreEliminationPass() { 2156 return new DSELegacyPass(); 2157 } 2158