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