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