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