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 of
1279     // 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 
1289     // Otherwise check the memory location is invariant to any loops.
1290     auto IsGuaranteedLoopInvariantBase = [this](const Value *Ptr) {
1291       Ptr = Ptr->stripPointerCasts();
1292       if (auto *I = dyn_cast<Instruction>(Ptr)) {
1293         if (isa<AllocaInst>(Ptr))
1294           return true;
1295 
1296         if (isAllocLikeFn(I, &TLI))
1297           return true;
1298 
1299         return false;
1300       }
1301       return true;
1302     };
1303 
1304     const Value *Ptr = CurrentLoc.Ptr->stripPointerCasts();
1305     if (auto *I = dyn_cast<Instruction>(Ptr)) {
1306       if (I->getParent()->isEntryBlock())
1307         return true;
1308     }
1309     if (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
1310       return IsGuaranteedLoopInvariantBase(GEP->getPointerOperand()) &&
1311              GEP->hasAllConstantIndices();
1312     }
1313     return IsGuaranteedLoopInvariantBase(Ptr);
1314   }
1315 
1316   // Find a MemoryDef writing to \p DefLoc and dominating \p StartAccess, with
1317   // no read access between them or on any other path to a function exit block
1318   // if \p DefLoc is not accessible after the function returns. If there is no
1319   // such MemoryDef, return None. The returned value may not (completely)
1320   // overwrite \p DefLoc. Currently we bail out when we encounter an aliasing
1321   // MemoryUse (read).
1322   Optional<MemoryAccess *>
1323   getDomMemoryDef(MemoryDef *KillingDef, MemoryAccess *StartAccess,
1324                   const MemoryLocation &DefLoc, const Value *DefUO,
1325                   unsigned &ScanLimit, unsigned &WalkerStepLimit,
1326                   bool IsMemTerm, unsigned &PartialLimit) {
1327     if (ScanLimit == 0 || WalkerStepLimit == 0) {
1328       LLVM_DEBUG(dbgs() << "\n    ...  hit scan limit\n");
1329       return None;
1330     }
1331 
1332     MemoryAccess *Current = StartAccess;
1333     Instruction *KillingI = KillingDef->getMemoryInst();
1334     bool StepAgain;
1335     LLVM_DEBUG(dbgs() << "  trying to get dominating access\n");
1336 
1337     // Find the next clobbering Mod access for DefLoc, starting at StartAccess.
1338     Optional<MemoryLocation> CurrentLoc;
1339     do {
1340       StepAgain = false;
1341       LLVM_DEBUG({
1342         dbgs() << "   visiting " << *Current;
1343         if (!MSSA.isLiveOnEntryDef(Current) && isa<MemoryUseOrDef>(Current))
1344           dbgs() << " (" << *cast<MemoryUseOrDef>(Current)->getMemoryInst()
1345                  << ")";
1346         dbgs() << "\n";
1347       });
1348 
1349       // Reached TOP.
1350       if (MSSA.isLiveOnEntryDef(Current)) {
1351         LLVM_DEBUG(dbgs() << "   ...  found LiveOnEntryDef\n");
1352         return None;
1353       }
1354 
1355       // Cost of a step. Accesses in the same block are more likely to be valid
1356       // candidates for elimination, hence consider them cheaper.
1357       unsigned StepCost = KillingDef->getBlock() == Current->getBlock()
1358                               ? MemorySSASameBBStepCost
1359                               : MemorySSAOtherBBStepCost;
1360       if (WalkerStepLimit <= StepCost) {
1361         LLVM_DEBUG(dbgs() << "   ...  hit walker step limit\n");
1362         return None;
1363       }
1364       WalkerStepLimit -= StepCost;
1365 
1366       // Return for MemoryPhis. They cannot be eliminated directly and the
1367       // caller is responsible for traversing them.
1368       if (isa<MemoryPhi>(Current)) {
1369         LLVM_DEBUG(dbgs() << "   ...  found MemoryPhi\n");
1370         return Current;
1371       }
1372 
1373       // Below, check if CurrentDef is a valid candidate to be eliminated by
1374       // KillingDef. If it is not, check the next candidate.
1375       MemoryDef *CurrentDef = cast<MemoryDef>(Current);
1376       Instruction *CurrentI = CurrentDef->getMemoryInst();
1377 
1378       if (canSkipDef(CurrentDef, !isInvisibleToCallerBeforeRet(DefUO))) {
1379         StepAgain = true;
1380         Current = CurrentDef->getDefiningAccess();
1381         continue;
1382       }
1383 
1384       // Before we try to remove anything, check for any extra throwing
1385       // instructions that block us from DSEing
1386       if (mayThrowBetween(KillingI, CurrentI, DefUO)) {
1387         LLVM_DEBUG(dbgs() << "  ... skip, may throw!\n");
1388         return None;
1389       }
1390 
1391       // Check for anything that looks like it will be a barrier to further
1392       // removal
1393       if (isDSEBarrier(DefUO, CurrentI)) {
1394         LLVM_DEBUG(dbgs() << "  ... skip, barrier\n");
1395         return None;
1396       }
1397 
1398       // If Current is known to be on path that reads DefLoc or is a read
1399       // clobber, bail out, as the path is not profitable. We skip this check
1400       // for intrinsic calls, because the code knows how to handle memcpy
1401       // intrinsics.
1402       if (!isa<IntrinsicInst>(CurrentI) && isReadClobber(DefLoc, CurrentI))
1403         return None;
1404 
1405       // Quick check if there are direct uses that are read-clobbers.
1406       if (any_of(Current->uses(), [this, &DefLoc, StartAccess](Use &U) {
1407             if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(U.getUser()))
1408               return !MSSA.dominates(StartAccess, UseOrDef) &&
1409                      isReadClobber(DefLoc, UseOrDef->getMemoryInst());
1410             return false;
1411           })) {
1412         LLVM_DEBUG(dbgs() << "   ...  found a read clobber\n");
1413         return None;
1414       }
1415 
1416       // If Current cannot be analyzed or is not removable, check the next
1417       // candidate.
1418       if (!hasAnalyzableMemoryWrite(CurrentI, TLI) || !isRemovable(CurrentI)) {
1419         StepAgain = true;
1420         Current = CurrentDef->getDefiningAccess();
1421         continue;
1422       }
1423 
1424       // If Current does not have an analyzable write location, skip it
1425       CurrentLoc = getLocForWriteEx(CurrentI);
1426       if (!CurrentLoc) {
1427         StepAgain = true;
1428         Current = CurrentDef->getDefiningAccess();
1429         continue;
1430       }
1431 
1432       // AliasAnalysis does not account for loops. Limit elimination to
1433       // candidates for which we can guarantee they always store to the same
1434       // memory location and not located in different loops.
1435       if (!isGuaranteedLoopIndependent(CurrentI, KillingI, *CurrentLoc)) {
1436         LLVM_DEBUG(dbgs() << "  ... not guaranteed loop independent\n");
1437         StepAgain = true;
1438         Current = CurrentDef->getDefiningAccess();
1439         WalkerStepLimit -= 1;
1440         continue;
1441       }
1442 
1443       if (IsMemTerm) {
1444         // If the killing def is a memory terminator (e.g. lifetime.end), check
1445         // the next candidate if the current Current does not write the same
1446         // underlying object as the terminator.
1447         if (!isMemTerminator(*CurrentLoc, CurrentI, KillingI)) {
1448           StepAgain = true;
1449           Current = CurrentDef->getDefiningAccess();
1450         }
1451         continue;
1452       } else {
1453         int64_t InstWriteOffset, DepWriteOffset;
1454         auto OR = isOverwrite(KillingI, CurrentI, DefLoc, *CurrentLoc,
1455                               DepWriteOffset, InstWriteOffset);
1456         // If Current does not write to the same object as KillingDef, check
1457         // the next candidate.
1458         if (OR == OW_Unknown) {
1459           StepAgain = true;
1460           Current = CurrentDef->getDefiningAccess();
1461         } else if (OR == OW_MaybePartial) {
1462           // If KillingDef only partially overwrites Current, check the next
1463           // candidate if the partial step limit is exceeded. This aggressively
1464           // limits the number of candidates for partial store elimination,
1465           // which are less likely to be removable in the end.
1466           if (PartialLimit <= 1) {
1467             StepAgain = true;
1468             Current = CurrentDef->getDefiningAccess();
1469             WalkerStepLimit -= 1;
1470             continue;
1471           }
1472           PartialLimit -= 1;
1473         }
1474       }
1475     } while (StepAgain);
1476 
1477     // Accesses to objects accessible after the function returns can only be
1478     // eliminated if the access is killed along all paths to the exit. Collect
1479     // the blocks with killing (=completely overwriting MemoryDefs) and check if
1480     // they cover all paths from EarlierAccess to any function exit.
1481     SmallPtrSet<Instruction *, 16> KillingDefs;
1482     KillingDefs.insert(KillingDef->getMemoryInst());
1483     MemoryAccess *EarlierAccess = Current;
1484     Instruction *EarlierMemInst =
1485         cast<MemoryDef>(EarlierAccess)->getMemoryInst();
1486     LLVM_DEBUG(dbgs() << "  Checking for reads of " << *EarlierAccess << " ("
1487                       << *EarlierMemInst << ")\n");
1488 
1489     SmallSetVector<MemoryAccess *, 32> WorkList;
1490     auto PushMemUses = [&WorkList](MemoryAccess *Acc) {
1491       for (Use &U : Acc->uses())
1492         WorkList.insert(cast<MemoryAccess>(U.getUser()));
1493     };
1494     PushMemUses(EarlierAccess);
1495 
1496     // Optimistically collect all accesses for reads. If we do not find any
1497     // read clobbers, add them to the cache.
1498     SmallPtrSet<MemoryAccess *, 16> KnownNoReads;
1499     if (!EarlierMemInst->mayReadFromMemory())
1500       KnownNoReads.insert(EarlierAccess);
1501     // Check if EarlierDef may be read.
1502     for (unsigned I = 0; I < WorkList.size(); I++) {
1503       MemoryAccess *UseAccess = WorkList[I];
1504 
1505       LLVM_DEBUG(dbgs() << "   " << *UseAccess);
1506       // Bail out if the number of accesses to check exceeds the scan limit.
1507       if (ScanLimit < (WorkList.size() - I)) {
1508         LLVM_DEBUG(dbgs() << "\n    ...  hit scan limit\n");
1509         return None;
1510       }
1511       --ScanLimit;
1512       NumDomMemDefChecks++;
1513       KnownNoReads.insert(UseAccess);
1514 
1515       if (isa<MemoryPhi>(UseAccess)) {
1516         if (any_of(KillingDefs, [this, UseAccess](Instruction *KI) {
1517               return DT.properlyDominates(KI->getParent(),
1518                                           UseAccess->getBlock());
1519             })) {
1520           LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing block\n");
1521           continue;
1522         }
1523         LLVM_DEBUG(dbgs() << "\n    ... adding PHI uses\n");
1524         PushMemUses(UseAccess);
1525         continue;
1526       }
1527 
1528       Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst();
1529       LLVM_DEBUG(dbgs() << " (" << *UseInst << ")\n");
1530 
1531       if (any_of(KillingDefs, [this, UseInst](Instruction *KI) {
1532             return DT.dominates(KI, UseInst);
1533           })) {
1534         LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing def\n");
1535         continue;
1536       }
1537 
1538       // A memory terminator kills all preceeding MemoryDefs and all succeeding
1539       // MemoryAccesses. We do not have to check it's users.
1540       if (isMemTerminator(*CurrentLoc, EarlierMemInst, UseInst)) {
1541         LLVM_DEBUG(
1542             dbgs()
1543             << " ... skipping, memterminator invalidates following accesses\n");
1544         continue;
1545       }
1546 
1547       if (isNoopIntrinsic(cast<MemoryUseOrDef>(UseAccess)->getMemoryInst())) {
1548         LLVM_DEBUG(dbgs() << "    ... adding uses of intrinsic\n");
1549         PushMemUses(UseAccess);
1550         continue;
1551       }
1552 
1553       if (UseInst->mayThrow() && !isInvisibleToCallerBeforeRet(DefUO)) {
1554         LLVM_DEBUG(dbgs() << "  ... found throwing instruction\n");
1555         return None;
1556       }
1557 
1558       // Uses which may read the original MemoryDef mean we cannot eliminate the
1559       // original MD. Stop walk.
1560       if (isReadClobber(*CurrentLoc, UseInst)) {
1561         LLVM_DEBUG(dbgs() << "    ... found read clobber\n");
1562         return None;
1563       }
1564 
1565       // For the KillingDef and EarlierAccess we only have to check if it reads
1566       // the memory location.
1567       // TODO: It would probably be better to check for self-reads before
1568       // calling the function.
1569       if (KillingDef == UseAccess || EarlierAccess == UseAccess) {
1570         LLVM_DEBUG(dbgs() << "    ... skipping killing def/dom access\n");
1571         continue;
1572       }
1573 
1574       // Check all uses for MemoryDefs, except for defs completely overwriting
1575       // the original location. Otherwise we have to check uses of *all*
1576       // MemoryDefs we discover, including non-aliasing ones. Otherwise we might
1577       // miss cases like the following
1578       //   1 = Def(LoE) ; <----- EarlierDef stores [0,1]
1579       //   2 = Def(1)   ; (2, 1) = NoAlias,   stores [2,3]
1580       //   Use(2)       ; MayAlias 2 *and* 1, loads [0, 3].
1581       //                  (The Use points to the *first* Def it may alias)
1582       //   3 = Def(1)   ; <---- Current  (3, 2) = NoAlias, (3,1) = MayAlias,
1583       //                  stores [0,1]
1584       if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) {
1585         if (isCompleteOverwrite(*CurrentLoc, EarlierMemInst, UseInst)) {
1586           if (!isInvisibleToCallerAfterRet(DefUO) &&
1587               UseAccess != EarlierAccess) {
1588             BasicBlock *MaybeKillingBlock = UseInst->getParent();
1589             if (PostOrderNumbers.find(MaybeKillingBlock)->second <
1590                 PostOrderNumbers.find(EarlierAccess->getBlock())->second) {
1591 
1592               LLVM_DEBUG(dbgs()
1593                          << "    ... found killing def " << *UseInst << "\n");
1594               KillingDefs.insert(UseInst);
1595             }
1596           }
1597         } else
1598           PushMemUses(UseDef);
1599       }
1600     }
1601 
1602     // For accesses to locations visible after the function returns, make sure
1603     // that the location is killed (=overwritten) along all paths from
1604     // EarlierAccess to the exit.
1605     if (!isInvisibleToCallerAfterRet(DefUO)) {
1606       SmallPtrSet<BasicBlock *, 16> KillingBlocks;
1607       for (Instruction *KD : KillingDefs)
1608         KillingBlocks.insert(KD->getParent());
1609       assert(!KillingBlocks.empty() &&
1610              "Expected at least a single killing block");
1611 
1612       // Find the common post-dominator of all killing blocks.
1613       BasicBlock *CommonPred = *KillingBlocks.begin();
1614       for (auto I = std::next(KillingBlocks.begin()), E = KillingBlocks.end();
1615            I != E; I++) {
1616         if (!CommonPred)
1617           break;
1618         CommonPred = PDT.findNearestCommonDominator(CommonPred, *I);
1619       }
1620 
1621       // If CommonPred is in the set of killing blocks, just check if it
1622       // post-dominates EarlierAccess.
1623       if (KillingBlocks.count(CommonPred)) {
1624         if (PDT.dominates(CommonPred, EarlierAccess->getBlock()))
1625           return {EarlierAccess};
1626         return None;
1627       }
1628 
1629       // If the common post-dominator does not post-dominate EarlierAccess,
1630       // there is a path from EarlierAccess to an exit not going through a
1631       // killing block.
1632       if (PDT.dominates(CommonPred, EarlierAccess->getBlock())) {
1633         SetVector<BasicBlock *> WorkList;
1634 
1635         // If CommonPred is null, there are multiple exits from the function.
1636         // They all have to be added to the worklist.
1637         if (CommonPred)
1638           WorkList.insert(CommonPred);
1639         else
1640           for (BasicBlock *R : PDT.roots())
1641             WorkList.insert(R);
1642 
1643         NumCFGTries++;
1644         // Check if all paths starting from an exit node go through one of the
1645         // killing blocks before reaching EarlierAccess.
1646         for (unsigned I = 0; I < WorkList.size(); I++) {
1647           NumCFGChecks++;
1648           BasicBlock *Current = WorkList[I];
1649           if (KillingBlocks.count(Current))
1650             continue;
1651           if (Current == EarlierAccess->getBlock())
1652             return None;
1653 
1654           // EarlierAccess is reachable from the entry, so we don't have to
1655           // explore unreachable blocks further.
1656           if (!DT.isReachableFromEntry(Current))
1657             continue;
1658 
1659           for (BasicBlock *Pred : predecessors(Current))
1660             WorkList.insert(Pred);
1661 
1662           if (WorkList.size() >= MemorySSAPathCheckLimit)
1663             return None;
1664         }
1665         NumCFGSuccess++;
1666         return {EarlierAccess};
1667       }
1668       return None;
1669     }
1670 
1671     // No aliasing MemoryUses of EarlierAccess found, EarlierAccess is
1672     // potentially dead.
1673     return {EarlierAccess};
1674   }
1675 
1676   // Delete dead memory defs
1677   void deleteDeadInstruction(Instruction *SI) {
1678     MemorySSAUpdater Updater(&MSSA);
1679     SmallVector<Instruction *, 32> NowDeadInsts;
1680     NowDeadInsts.push_back(SI);
1681     --NumFastOther;
1682 
1683     while (!NowDeadInsts.empty()) {
1684       Instruction *DeadInst = NowDeadInsts.pop_back_val();
1685       ++NumFastOther;
1686 
1687       // Try to preserve debug information attached to the dead instruction.
1688       salvageDebugInfo(*DeadInst);
1689       salvageKnowledge(DeadInst);
1690 
1691       // Remove the Instruction from MSSA.
1692       if (MemoryAccess *MA = MSSA.getMemoryAccess(DeadInst)) {
1693         if (MemoryDef *MD = dyn_cast<MemoryDef>(MA)) {
1694           SkipStores.insert(MD);
1695         }
1696         Updater.removeMemoryAccess(MA);
1697       }
1698 
1699       auto I = IOLs.find(DeadInst->getParent());
1700       if (I != IOLs.end())
1701         I->second.erase(DeadInst);
1702       // Remove its operands
1703       for (Use &O : DeadInst->operands())
1704         if (Instruction *OpI = dyn_cast<Instruction>(O)) {
1705           O = nullptr;
1706           if (isInstructionTriviallyDead(OpI, &TLI))
1707             NowDeadInsts.push_back(OpI);
1708         }
1709 
1710       DeadInst->eraseFromParent();
1711     }
1712   }
1713 
1714   // Check for any extra throws between SI and NI that block DSE.  This only
1715   // checks extra maythrows (those that aren't MemoryDef's). MemoryDef that may
1716   // throw are handled during the walk from one def to the next.
1717   bool mayThrowBetween(Instruction *SI, Instruction *NI,
1718                        const Value *SILocUnd) {
1719     // First see if we can ignore it by using the fact that SI is an
1720     // alloca/alloca like object that is not visible to the caller during
1721     // execution of the function.
1722     if (SILocUnd && isInvisibleToCallerBeforeRet(SILocUnd))
1723       return false;
1724 
1725     if (SI->getParent() == NI->getParent())
1726       return ThrowingBlocks.count(SI->getParent());
1727     return !ThrowingBlocks.empty();
1728   }
1729 
1730   // Check if \p NI acts as a DSE barrier for \p SI. The following instructions
1731   // act as barriers:
1732   //  * A memory instruction that may throw and \p SI accesses a non-stack
1733   //  object.
1734   //  * Atomic stores stronger that monotonic.
1735   bool isDSEBarrier(const Value *SILocUnd, Instruction *NI) {
1736     // If NI may throw it acts as a barrier, unless we are to an alloca/alloca
1737     // like object that does not escape.
1738     if (NI->mayThrow() && !isInvisibleToCallerBeforeRet(SILocUnd))
1739       return true;
1740 
1741     // If NI is an atomic load/store stronger than monotonic, do not try to
1742     // eliminate/reorder it.
1743     if (NI->isAtomic()) {
1744       if (auto *LI = dyn_cast<LoadInst>(NI))
1745         return isStrongerThanMonotonic(LI->getOrdering());
1746       if (auto *SI = dyn_cast<StoreInst>(NI))
1747         return isStrongerThanMonotonic(SI->getOrdering());
1748       if (auto *ARMW = dyn_cast<AtomicRMWInst>(NI))
1749         return isStrongerThanMonotonic(ARMW->getOrdering());
1750       if (auto *CmpXchg = dyn_cast<AtomicCmpXchgInst>(NI))
1751         return isStrongerThanMonotonic(CmpXchg->getSuccessOrdering()) ||
1752                isStrongerThanMonotonic(CmpXchg->getFailureOrdering());
1753       llvm_unreachable("other instructions should be skipped in MemorySSA");
1754     }
1755     return false;
1756   }
1757 
1758   /// Eliminate writes to objects that are not visible in the caller and are not
1759   /// accessed before returning from the function.
1760   bool eliminateDeadWritesAtEndOfFunction() {
1761     bool MadeChange = false;
1762     LLVM_DEBUG(
1763         dbgs()
1764         << "Trying to eliminate MemoryDefs at the end of the function\n");
1765     for (int I = MemDefs.size() - 1; I >= 0; I--) {
1766       MemoryDef *Def = MemDefs[I];
1767       if (SkipStores.contains(Def) || !isRemovable(Def->getMemoryInst()))
1768         continue;
1769 
1770       Instruction *DefI = Def->getMemoryInst();
1771       SmallVector<const Value *, 4> Pointers;
1772       auto DefLoc = getLocForWriteEx(DefI);
1773       if (!DefLoc)
1774         continue;
1775 
1776       // NOTE: Currently eliminating writes at the end of a function is limited
1777       // to MemoryDefs with a single underlying object, to save compile-time. In
1778       // practice it appears the case with multiple underlying objects is very
1779       // uncommon. If it turns out to be important, we can use
1780       // getUnderlyingObjects here instead.
1781       const Value *UO = getUnderlyingObject(DefLoc->Ptr);
1782       if (!UO || !isInvisibleToCallerAfterRet(UO))
1783         continue;
1784 
1785       if (isWriteAtEndOfFunction(Def)) {
1786         // See through pointer-to-pointer bitcasts
1787         LLVM_DEBUG(dbgs() << "   ... MemoryDef is not accessed until the end "
1788                              "of the function\n");
1789         deleteDeadInstruction(DefI);
1790         ++NumFastStores;
1791         MadeChange = true;
1792       }
1793     }
1794     return MadeChange;
1795   }
1796 
1797   /// \returns true if \p Def is a no-op store, either because it
1798   /// directly stores back a loaded value or stores zero to a calloced object.
1799   bool storeIsNoop(MemoryDef *Def, const MemoryLocation &DefLoc,
1800                    const Value *DefUO) {
1801     StoreInst *Store = dyn_cast<StoreInst>(Def->getMemoryInst());
1802     MemSetInst *MemSet = dyn_cast<MemSetInst>(Def->getMemoryInst());
1803     Constant *StoredConstant = nullptr;
1804     if (Store)
1805       StoredConstant = dyn_cast<Constant>(Store->getOperand(0));
1806     if (MemSet)
1807       StoredConstant = dyn_cast<Constant>(MemSet->getValue());
1808 
1809     if (StoredConstant && StoredConstant->isNullValue()) {
1810       auto *DefUOInst = dyn_cast<Instruction>(DefUO);
1811       if (DefUOInst && isCallocLikeFn(DefUOInst, &TLI)) {
1812         auto *UnderlyingDef = cast<MemoryDef>(MSSA.getMemoryAccess(DefUOInst));
1813         // If UnderlyingDef is the clobbering access of Def, no instructions
1814         // between them can modify the memory location.
1815         auto *ClobberDef =
1816             MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(Def);
1817         return UnderlyingDef == ClobberDef;
1818       }
1819     }
1820 
1821     if (!Store)
1822       return false;
1823 
1824     if (auto *LoadI = dyn_cast<LoadInst>(Store->getOperand(0))) {
1825       if (LoadI->getPointerOperand() == Store->getOperand(1)) {
1826         // Get the defining access for the load.
1827         auto *LoadAccess = MSSA.getMemoryAccess(LoadI)->getDefiningAccess();
1828         // Fast path: the defining accesses are the same.
1829         if (LoadAccess == Def->getDefiningAccess())
1830           return true;
1831 
1832         // Look through phi accesses. Recursively scan all phi accesses by
1833         // adding them to a worklist. Bail when we run into a memory def that
1834         // does not match LoadAccess.
1835         SetVector<MemoryAccess *> ToCheck;
1836         MemoryAccess *Current =
1837             MSSA.getWalker()->getClobberingMemoryAccess(Def);
1838         // We don't want to bail when we run into the store memory def. But,
1839         // the phi access may point to it. So, pretend like we've already
1840         // checked it.
1841         ToCheck.insert(Def);
1842         ToCheck.insert(Current);
1843         // Start at current (1) to simulate already having checked Def.
1844         for (unsigned I = 1; I < ToCheck.size(); ++I) {
1845           Current = ToCheck[I];
1846           if (auto PhiAccess = dyn_cast<MemoryPhi>(Current)) {
1847             // Check all the operands.
1848             for (auto &Use : PhiAccess->incoming_values())
1849               ToCheck.insert(cast<MemoryAccess>(&Use));
1850             continue;
1851           }
1852 
1853           // If we found a memory def, bail. This happens when we have an
1854           // unrelated write in between an otherwise noop store.
1855           assert(isa<MemoryDef>(Current) &&
1856                  "Only MemoryDefs should reach here.");
1857           // TODO: Skip no alias MemoryDefs that have no aliasing reads.
1858           // We are searching for the definition of the store's destination.
1859           // So, if that is the same definition as the load, then this is a
1860           // noop. Otherwise, fail.
1861           if (LoadAccess != Current)
1862             return false;
1863         }
1864         return true;
1865       }
1866     }
1867 
1868     return false;
1869   }
1870 };
1871 
1872 static bool eliminateDeadStores(Function &F, AliasAnalysis &AA, MemorySSA &MSSA,
1873                                 DominatorTree &DT, PostDominatorTree &PDT,
1874                                 const TargetLibraryInfo &TLI,
1875                                 const LoopInfo &LI) {
1876   bool MadeChange = false;
1877 
1878   DSEState State = DSEState::get(F, AA, MSSA, DT, PDT, TLI, LI);
1879   // For each store:
1880   for (unsigned I = 0; I < State.MemDefs.size(); I++) {
1881     MemoryDef *KillingDef = State.MemDefs[I];
1882     if (State.SkipStores.count(KillingDef))
1883       continue;
1884     Instruction *SI = KillingDef->getMemoryInst();
1885 
1886     Optional<MemoryLocation> MaybeSILoc;
1887     if (State.isMemTerminatorInst(SI))
1888       MaybeSILoc = State.getLocForTerminator(SI).map(
1889           [](const std::pair<MemoryLocation, bool> &P) { return P.first; });
1890     else
1891       MaybeSILoc = State.getLocForWriteEx(SI);
1892 
1893     if (!MaybeSILoc) {
1894       LLVM_DEBUG(dbgs() << "Failed to find analyzable write location for "
1895                         << *SI << "\n");
1896       continue;
1897     }
1898     MemoryLocation SILoc = *MaybeSILoc;
1899     assert(SILoc.Ptr && "SILoc should not be null");
1900     const Value *SILocUnd = getUnderlyingObject(SILoc.Ptr);
1901 
1902     MemoryAccess *Current = KillingDef;
1903     LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs killed by "
1904                       << *Current << " (" << *SI << ")\n");
1905 
1906     unsigned ScanLimit = MemorySSAScanLimit;
1907     unsigned WalkerStepLimit = MemorySSAUpwardsStepLimit;
1908     unsigned PartialLimit = MemorySSAPartialStoreLimit;
1909     // Worklist of MemoryAccesses that may be killed by KillingDef.
1910     SetVector<MemoryAccess *> ToCheck;
1911 
1912     if (SILocUnd)
1913       ToCheck.insert(KillingDef->getDefiningAccess());
1914 
1915     bool Shortend = false;
1916     bool IsMemTerm = State.isMemTerminatorInst(SI);
1917     // Check if MemoryAccesses in the worklist are killed by KillingDef.
1918     for (unsigned I = 0; I < ToCheck.size(); I++) {
1919       Current = ToCheck[I];
1920       if (State.SkipStores.count(Current))
1921         continue;
1922 
1923       Optional<MemoryAccess *> Next = State.getDomMemoryDef(
1924           KillingDef, Current, SILoc, SILocUnd, ScanLimit, WalkerStepLimit,
1925           IsMemTerm, PartialLimit);
1926 
1927       if (!Next) {
1928         LLVM_DEBUG(dbgs() << "  finished walk\n");
1929         continue;
1930       }
1931 
1932       MemoryAccess *EarlierAccess = *Next;
1933       LLVM_DEBUG(dbgs() << " Checking if we can kill " << *EarlierAccess);
1934       if (isa<MemoryPhi>(EarlierAccess)) {
1935         LLVM_DEBUG(dbgs() << "\n  ... adding incoming values to worklist\n");
1936         for (Value *V : cast<MemoryPhi>(EarlierAccess)->incoming_values()) {
1937           MemoryAccess *IncomingAccess = cast<MemoryAccess>(V);
1938           BasicBlock *IncomingBlock = IncomingAccess->getBlock();
1939           BasicBlock *PhiBlock = EarlierAccess->getBlock();
1940 
1941           // We only consider incoming MemoryAccesses that come before the
1942           // MemoryPhi. Otherwise we could discover candidates that do not
1943           // strictly dominate our starting def.
1944           if (State.PostOrderNumbers[IncomingBlock] >
1945               State.PostOrderNumbers[PhiBlock])
1946             ToCheck.insert(IncomingAccess);
1947         }
1948         continue;
1949       }
1950       auto *NextDef = cast<MemoryDef>(EarlierAccess);
1951       Instruction *NI = NextDef->getMemoryInst();
1952       LLVM_DEBUG(dbgs() << " (" << *NI << ")\n");
1953       ToCheck.insert(NextDef->getDefiningAccess());
1954       NumGetDomMemoryDefPassed++;
1955 
1956       if (!DebugCounter::shouldExecute(MemorySSACounter))
1957         continue;
1958 
1959       MemoryLocation NILoc = *State.getLocForWriteEx(NI);
1960 
1961       if (IsMemTerm) {
1962         const Value *NIUnd = getUnderlyingObject(NILoc.Ptr);
1963         if (SILocUnd != NIUnd)
1964           continue;
1965         LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: " << *NI
1966                           << "\n  KILLER: " << *SI << '\n');
1967         State.deleteDeadInstruction(NI);
1968         ++NumFastStores;
1969         MadeChange = true;
1970       } else {
1971         // Check if NI overwrites SI.
1972         int64_t InstWriteOffset, DepWriteOffset;
1973         OverwriteResult OR = State.isOverwrite(SI, NI, SILoc, NILoc,
1974                                                DepWriteOffset, InstWriteOffset);
1975         if (OR == OW_MaybePartial) {
1976           auto Iter = State.IOLs.insert(
1977               std::make_pair<BasicBlock *, InstOverlapIntervalsTy>(
1978                   NI->getParent(), InstOverlapIntervalsTy()));
1979           auto &IOL = Iter.first->second;
1980           OR = isPartialOverwrite(SILoc, NILoc, DepWriteOffset, InstWriteOffset,
1981                                   NI, IOL);
1982         }
1983 
1984         if (EnablePartialStoreMerging && OR == OW_PartialEarlierWithFullLater) {
1985           auto *Earlier = dyn_cast<StoreInst>(NI);
1986           auto *Later = dyn_cast<StoreInst>(SI);
1987           // We are re-using tryToMergePartialOverlappingStores, which requires
1988           // Earlier to domiante Later.
1989           // TODO: implement tryToMergeParialOverlappingStores using MemorySSA.
1990           if (Earlier && Later && DT.dominates(Earlier, Later)) {
1991             if (Constant *Merged = tryToMergePartialOverlappingStores(
1992                     Earlier, Later, InstWriteOffset, DepWriteOffset, State.DL,
1993                     State.BatchAA, &DT)) {
1994 
1995               // Update stored value of earlier store to merged constant.
1996               Earlier->setOperand(0, Merged);
1997               ++NumModifiedStores;
1998               MadeChange = true;
1999 
2000               Shortend = true;
2001               // Remove later store and remove any outstanding overlap intervals
2002               // for the updated store.
2003               State.deleteDeadInstruction(Later);
2004               auto I = State.IOLs.find(Earlier->getParent());
2005               if (I != State.IOLs.end())
2006                 I->second.erase(Earlier);
2007               break;
2008             }
2009           }
2010         }
2011 
2012         if (OR == OW_Complete) {
2013           LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: " << *NI
2014                             << "\n  KILLER: " << *SI << '\n');
2015           State.deleteDeadInstruction(NI);
2016           ++NumFastStores;
2017           MadeChange = true;
2018         }
2019       }
2020     }
2021 
2022     // Check if the store is a no-op.
2023     if (!Shortend && isRemovable(SI) &&
2024         State.storeIsNoop(KillingDef, SILoc, SILocUnd)) {
2025       LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n  DEAD: " << *SI << '\n');
2026       State.deleteDeadInstruction(SI);
2027       NumRedundantStores++;
2028       MadeChange = true;
2029       continue;
2030     }
2031   }
2032 
2033   if (EnablePartialOverwriteTracking)
2034     for (auto &KV : State.IOLs)
2035       MadeChange |= removePartiallyOverlappedStores(State.DL, KV.second, TLI);
2036 
2037   MadeChange |= State.eliminateDeadWritesAtEndOfFunction();
2038   return MadeChange;
2039 }
2040 } // end anonymous namespace
2041 
2042 //===----------------------------------------------------------------------===//
2043 // DSE Pass
2044 //===----------------------------------------------------------------------===//
2045 PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) {
2046   AliasAnalysis &AA = AM.getResult<AAManager>(F);
2047   const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2048   DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
2049   MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2050   PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
2051   LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
2052 
2053   bool Changed = eliminateDeadStores(F, AA, MSSA, DT, PDT, TLI, LI);
2054 
2055 #ifdef LLVM_ENABLE_STATS
2056   if (AreStatisticsEnabled())
2057     for (auto &I : instructions(F))
2058       NumRemainingStores += isa<StoreInst>(&I);
2059 #endif
2060 
2061   if (!Changed)
2062     return PreservedAnalyses::all();
2063 
2064   PreservedAnalyses PA;
2065   PA.preserveSet<CFGAnalyses>();
2066   PA.preserve<MemorySSAAnalysis>();
2067   PA.preserve<LoopAnalysis>();
2068   return PA;
2069 }
2070 
2071 namespace {
2072 
2073 /// A legacy pass for the legacy pass manager that wraps \c DSEPass.
2074 class DSELegacyPass : public FunctionPass {
2075 public:
2076   static char ID; // Pass identification, replacement for typeid
2077 
2078   DSELegacyPass() : FunctionPass(ID) {
2079     initializeDSELegacyPassPass(*PassRegistry::getPassRegistry());
2080   }
2081 
2082   bool runOnFunction(Function &F) override {
2083     if (skipFunction(F))
2084       return false;
2085 
2086     AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2087     DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2088     const TargetLibraryInfo &TLI =
2089         getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2090     MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2091     PostDominatorTree &PDT =
2092         getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
2093     LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2094 
2095     bool Changed = eliminateDeadStores(F, AA, MSSA, DT, PDT, TLI, LI);
2096 
2097 #ifdef LLVM_ENABLE_STATS
2098     if (AreStatisticsEnabled())
2099       for (auto &I : instructions(F))
2100         NumRemainingStores += isa<StoreInst>(&I);
2101 #endif
2102 
2103     return Changed;
2104   }
2105 
2106   void getAnalysisUsage(AnalysisUsage &AU) const override {
2107     AU.setPreservesCFG();
2108     AU.addRequired<AAResultsWrapperPass>();
2109     AU.addRequired<TargetLibraryInfoWrapperPass>();
2110     AU.addPreserved<GlobalsAAWrapperPass>();
2111     AU.addRequired<DominatorTreeWrapperPass>();
2112     AU.addPreserved<DominatorTreeWrapperPass>();
2113     AU.addRequired<PostDominatorTreeWrapperPass>();
2114     AU.addRequired<MemorySSAWrapperPass>();
2115     AU.addPreserved<PostDominatorTreeWrapperPass>();
2116     AU.addPreserved<MemorySSAWrapperPass>();
2117     AU.addRequired<LoopInfoWrapperPass>();
2118     AU.addPreserved<LoopInfoWrapperPass>();
2119   }
2120 };
2121 
2122 } // end anonymous namespace
2123 
2124 char DSELegacyPass::ID = 0;
2125 
2126 INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false,
2127                       false)
2128 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2129 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
2130 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2131 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
2132 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
2133 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
2134 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2135 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
2136 INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false,
2137                     false)
2138 
2139 FunctionPass *llvm::createDeadStoreEliminationPass() {
2140   return new DSELegacyPass();
2141 }
2142