1 //===- DeadStoreElimination.cpp - Fast 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 // This file implements a trivial dead store elimination that only considers
10 // basic-block local redundant stores.
11 //
12 // FIXME: This should eventually be extended to be a post-dominator tree
13 // traversal.  Doing so would be pretty trivial.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/PostOrderIterator.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/CaptureTracking.h"
29 #include "llvm/Analysis/GlobalsModRef.h"
30 #include "llvm/Analysis/MemoryBuiltins.h"
31 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/MemorySSA.h"
34 #include "llvm/Analysis/MemorySSAUpdater.h"
35 #include "llvm/Analysis/PostDominators.h"
36 #include "llvm/Analysis/TargetLibraryInfo.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/IR/Argument.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/Constant.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/InstIterator.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/Intrinsics.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/IR/PassManager.h"
54 #include "llvm/IR/PatternMatch.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/InitializePasses.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/DebugCounter.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/MathExtras.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Transforms/Scalar.h"
66 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
67 #include "llvm/Transforms/Utils/Local.h"
68 #include <algorithm>
69 #include <cassert>
70 #include <cstddef>
71 #include <cstdint>
72 #include <iterator>
73 #include <map>
74 #include <utility>
75 
76 using namespace llvm;
77 using namespace PatternMatch;
78 
79 #define DEBUG_TYPE "dse"
80 
81 STATISTIC(NumRemainingStores, "Number of stores remaining after DSE");
82 STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
83 STATISTIC(NumFastStores, "Number of stores deleted");
84 STATISTIC(NumFastOther, "Number of other instrs removed");
85 STATISTIC(NumCompletePartials, "Number of stores dead by later partials");
86 STATISTIC(NumModifiedStores, "Number of stores modified");
87 STATISTIC(NumCFGChecks, "Number of stores modified");
88 STATISTIC(NumCFGTries, "Number of stores modified");
89 STATISTIC(NumCFGSuccess, "Number of stores modified");
90 STATISTIC(NumGetDomMemoryDefPassed,
91           "Number of times a valid candidate is returned from getDomMemoryDef");
92 STATISTIC(NumDomMemDefChecks,
93           "Number iterations check for reads in getDomMemoryDef");
94 
95 DEBUG_COUNTER(MemorySSACounter, "dse-memoryssa",
96               "Controls which MemoryDefs are eliminated.");
97 
98 static cl::opt<bool>
99 EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking",
100   cl::init(true), cl::Hidden,
101   cl::desc("Enable partial-overwrite tracking in DSE"));
102 
103 static cl::opt<bool>
104 EnablePartialStoreMerging("enable-dse-partial-store-merging",
105   cl::init(true), cl::Hidden,
106   cl::desc("Enable partial store merging in DSE"));
107 
108 static cl::opt<bool>
109     EnableMemorySSA("enable-dse-memoryssa", cl::init(false), cl::Hidden,
110                     cl::desc("Use the new MemorySSA-backed DSE."));
111 
112 static cl::opt<unsigned>
113     MemorySSAScanLimit("dse-memoryssa-scanlimit", cl::init(150), cl::Hidden,
114                        cl::desc("The number of memory instructions to scan for "
115                                 "dead store elimination (default = 100)"));
116 static cl::opt<unsigned> MemorySSAUpwardsStepLimit(
117     "dse-memoryssa-walklimit", cl::init(70), cl::Hidden,
118     cl::desc("The maximum number of steps while walking upwards to find "
119              "MemoryDefs that may be killed (default = 70)"));
120 
121 static cl::opt<unsigned> MemorySSAPartialStoreLimit(
122     "dse-memoryssa-partial-store-limit", cl::init(5), cl::Hidden,
123     cl::desc("The maximum number candidates that only partially overwrite the "
124              "killing MemoryDef to consider"
125              " (default = 5)"));
126 
127 static cl::opt<unsigned> MemorySSADefsPerBlockLimit(
128     "dse-memoryssa-defs-per-block-limit", cl::init(5000), cl::Hidden,
129     cl::desc("The number of MemoryDefs we consider as candidates to eliminated "
130              "other stores per basic block (default = 5000)"));
131 
132 static cl::opt<unsigned> MemorySSASameBBStepCost(
133     "dse-memoryssa-samebb-cost", cl::init(1), cl::Hidden,
134     cl::desc(
135         "The cost of a step in the same basic block as the killing MemoryDef"
136         "(default = 1)"));
137 
138 static cl::opt<unsigned>
139     MemorySSAOtherBBStepCost("dse-memoryssa-otherbb-cost", cl::init(5),
140                              cl::Hidden,
141                              cl::desc("The cost of a step in a different basic "
142                                       "block than the killing MemoryDef"
143                                       "(default = 5)"));
144 
145 static cl::opt<unsigned> MemorySSAPathCheckLimit(
146     "dse-memoryssa-path-check-limit", cl::init(50), cl::Hidden,
147     cl::desc("The maximum number of blocks to check when trying to prove that "
148              "all paths to an exit go through a killing block (default = 50)"));
149 
150 //===----------------------------------------------------------------------===//
151 // Helper functions
152 //===----------------------------------------------------------------------===//
153 using OverlapIntervalsTy = std::map<int64_t, int64_t>;
154 using InstOverlapIntervalsTy = DenseMap<Instruction *, OverlapIntervalsTy>;
155 
156 /// Delete this instruction.  Before we do, go through and zero out all the
157 /// operands of this instruction.  If any of them become dead, delete them and
158 /// the computation tree that feeds them.
159 /// If ValueSet is non-null, remove any deleted instructions from it as well.
160 static void
161 deleteDeadInstruction(Instruction *I, BasicBlock::iterator *BBI,
162                       MemoryDependenceResults &MD, const TargetLibraryInfo &TLI,
163                       InstOverlapIntervalsTy &IOL,
164                       MapVector<Instruction *, bool> &ThrowableInst,
165                       SmallSetVector<const Value *, 16> *ValueSet = nullptr) {
166   SmallVector<Instruction*, 32> NowDeadInsts;
167 
168   NowDeadInsts.push_back(I);
169   --NumFastOther;
170 
171   // Keeping the iterator straight is a pain, so we let this routine tell the
172   // caller what the next instruction is after we're done mucking about.
173   BasicBlock::iterator NewIter = *BBI;
174 
175   // Before we touch this instruction, remove it from memdep!
176   do {
177     Instruction *DeadInst = NowDeadInsts.pop_back_val();
178     // Mark the DeadInst as dead in the list of throwable instructions.
179     auto It = ThrowableInst.find(DeadInst);
180     if (It != ThrowableInst.end())
181       ThrowableInst[It->first] = false;
182     ++NumFastOther;
183 
184     // Try to preserve debug information attached to the dead instruction.
185     salvageDebugInfo(*DeadInst);
186     salvageKnowledge(DeadInst);
187 
188     // This instruction is dead, zap it, in stages.  Start by removing it from
189     // MemDep, which needs to know the operands and needs it to be in the
190     // function.
191     MD.removeInstruction(DeadInst);
192 
193     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
194       Value *Op = DeadInst->getOperand(op);
195       DeadInst->setOperand(op, nullptr);
196 
197       // If this operand just became dead, add it to the NowDeadInsts list.
198       if (!Op->use_empty()) continue;
199 
200       if (Instruction *OpI = dyn_cast<Instruction>(Op))
201         if (isInstructionTriviallyDead(OpI, &TLI))
202           NowDeadInsts.push_back(OpI);
203     }
204 
205     if (ValueSet) ValueSet->remove(DeadInst);
206     IOL.erase(DeadInst);
207 
208     if (NewIter == DeadInst->getIterator())
209       NewIter = DeadInst->eraseFromParent();
210     else
211       DeadInst->eraseFromParent();
212   } while (!NowDeadInsts.empty());
213   *BBI = NewIter;
214   // Pop dead entries from back of ThrowableInst till we find an alive entry.
215   while (!ThrowableInst.empty() && !ThrowableInst.back().second)
216     ThrowableInst.pop_back();
217 }
218 
219 /// Does this instruction write some memory?  This only returns true for things
220 /// that we can analyze with other helpers below.
221 static bool hasAnalyzableMemoryWrite(Instruction *I,
222                                      const TargetLibraryInfo &TLI) {
223   if (isa<StoreInst>(I))
224     return true;
225   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
226     switch (II->getIntrinsicID()) {
227     default:
228       return false;
229     case Intrinsic::memset:
230     case Intrinsic::memmove:
231     case Intrinsic::memcpy:
232     case Intrinsic::memcpy_element_unordered_atomic:
233     case Intrinsic::memmove_element_unordered_atomic:
234     case Intrinsic::memset_element_unordered_atomic:
235     case Intrinsic::init_trampoline:
236     case Intrinsic::lifetime_end:
237       return true;
238     }
239   }
240   if (auto *CB = dyn_cast<CallBase>(I)) {
241     LibFunc LF;
242     if (TLI.getLibFunc(*CB, LF) && TLI.has(LF)) {
243       switch (LF) {
244       case LibFunc_strcpy:
245       case LibFunc_strncpy:
246       case LibFunc_strcat:
247       case LibFunc_strncat:
248         return true;
249       default:
250         return false;
251       }
252     }
253   }
254   return false;
255 }
256 
257 /// Return a Location stored to by the specified instruction. If isRemovable
258 /// returns true, this function and getLocForRead completely describe the memory
259 /// operations for this instruction.
260 static MemoryLocation getLocForWrite(Instruction *Inst) {
261 
262   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
263     return MemoryLocation::get(SI);
264 
265   if (auto *MI = dyn_cast<AnyMemIntrinsic>(Inst)) {
266     // memcpy/memmove/memset.
267     MemoryLocation Loc = MemoryLocation::getForDest(MI);
268     return Loc;
269   }
270 
271   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
272     switch (II->getIntrinsicID()) {
273     default:
274       return MemoryLocation(); // Unhandled intrinsic.
275     case Intrinsic::init_trampoline:
276       return MemoryLocation(II->getArgOperand(0));
277     case Intrinsic::lifetime_end: {
278       uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
279       return MemoryLocation(II->getArgOperand(1), Len);
280     }
281     }
282   }
283   if (auto *CB = dyn_cast<CallBase>(Inst))
284     // All the supported TLI functions so far happen to have dest as their
285     // first argument.
286     return MemoryLocation(CB->getArgOperand(0));
287   return MemoryLocation();
288 }
289 
290 /// Return the location read by the specified "hasAnalyzableMemoryWrite"
291 /// instruction if any.
292 static MemoryLocation getLocForRead(Instruction *Inst,
293                                     const TargetLibraryInfo &TLI) {
294   assert(hasAnalyzableMemoryWrite(Inst, TLI) && "Unknown instruction case");
295 
296   // The only instructions that both read and write are the mem transfer
297   // instructions (memcpy/memmove).
298   if (auto *MTI = dyn_cast<AnyMemTransferInst>(Inst))
299     return MemoryLocation::getForSource(MTI);
300   return MemoryLocation();
301 }
302 
303 /// If the value of this instruction and the memory it writes to is unused, may
304 /// we delete this instruction?
305 static bool isRemovable(Instruction *I) {
306   // Don't remove volatile/atomic stores.
307   if (StoreInst *SI = dyn_cast<StoreInst>(I))
308     return SI->isUnordered();
309 
310   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
311     switch (II->getIntrinsicID()) {
312     default: llvm_unreachable("doesn't pass 'hasAnalyzableMemoryWrite' predicate");
313     case Intrinsic::lifetime_end:
314       // Never remove dead lifetime_end's, e.g. because it is followed by a
315       // free.
316       return false;
317     case Intrinsic::init_trampoline:
318       // Always safe to remove init_trampoline.
319       return true;
320     case Intrinsic::memset:
321     case Intrinsic::memmove:
322     case Intrinsic::memcpy:
323       // Don't remove volatile memory intrinsics.
324       return !cast<MemIntrinsic>(II)->isVolatile();
325     case Intrinsic::memcpy_element_unordered_atomic:
326     case Intrinsic::memmove_element_unordered_atomic:
327     case Intrinsic::memset_element_unordered_atomic:
328       return true;
329     }
330   }
331 
332   // note: only get here for calls with analyzable writes - i.e. libcalls
333   if (auto *CB = dyn_cast<CallBase>(I))
334     return CB->use_empty();
335 
336   return false;
337 }
338 
339 /// Returns true if the end of this instruction can be safely shortened in
340 /// length.
341 static bool isShortenableAtTheEnd(Instruction *I) {
342   // Don't shorten stores for now
343   if (isa<StoreInst>(I))
344     return false;
345 
346   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
347     switch (II->getIntrinsicID()) {
348       default: return false;
349       case Intrinsic::memset:
350       case Intrinsic::memcpy:
351       case Intrinsic::memcpy_element_unordered_atomic:
352       case Intrinsic::memset_element_unordered_atomic:
353         // Do shorten memory intrinsics.
354         // FIXME: Add memmove if it's also safe to transform.
355         return true;
356     }
357   }
358 
359   // Don't shorten libcalls calls for now.
360 
361   return false;
362 }
363 
364 /// Returns true if the beginning of this instruction can be safely shortened
365 /// in length.
366 static bool isShortenableAtTheBeginning(Instruction *I) {
367   // FIXME: Handle only memset for now. Supporting memcpy/memmove should be
368   // easily done by offsetting the source address.
369   return isa<AnyMemSetInst>(I);
370 }
371 
372 /// Return the pointer that is being written to.
373 static Value *getStoredPointerOperand(Instruction *I) {
374   //TODO: factor this to reuse getLocForWrite
375   MemoryLocation Loc = getLocForWrite(I);
376   assert(Loc.Ptr &&
377          "unable to find pointer written for analyzable instruction?");
378   // TODO: most APIs don't expect const Value *
379   return const_cast<Value*>(Loc.Ptr);
380 }
381 
382 static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
383                                const TargetLibraryInfo &TLI,
384                                const Function *F) {
385   uint64_t Size;
386   ObjectSizeOpts Opts;
387   Opts.NullIsUnknownSize = NullPointerIsDefined(F);
388 
389   if (getObjectSize(V, Size, DL, &TLI, Opts))
390     return Size;
391   return MemoryLocation::UnknownSize;
392 }
393 
394 namespace {
395 
396 enum OverwriteResult {
397   OW_Begin,
398   OW_Complete,
399   OW_End,
400   OW_PartialEarlierWithFullLater,
401   OW_MaybePartial,
402   OW_Unknown
403 };
404 
405 } // end anonymous namespace
406 
407 /// Return 'OW_Complete' if a store to the 'Later' location completely
408 /// overwrites a store to the 'Earlier' location. Return OW_MaybePartial
409 /// if \p Later does not completely overwrite \p Earlier, but they both
410 /// write to the same underlying object. In that case, use isPartialOverwrite to
411 /// check if \p Later partially overwrites \p Earlier. Returns 'OW_Unknown' if
412 /// nothing can be determined.
413 template <typename AATy>
414 static OverwriteResult
415 isOverwrite(const MemoryLocation &Later, const MemoryLocation &Earlier,
416             const DataLayout &DL, const TargetLibraryInfo &TLI,
417             int64_t &EarlierOff, int64_t &LaterOff, AATy &AA,
418             const Function *F) {
419   // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll
420   // get imprecise values here, though (except for unknown sizes).
421   if (!Later.Size.isPrecise() || !Earlier.Size.isPrecise())
422     return OW_Unknown;
423 
424   const uint64_t LaterSize = Later.Size.getValue();
425   const uint64_t EarlierSize = Earlier.Size.getValue();
426 
427   const Value *P1 = Earlier.Ptr->stripPointerCasts();
428   const Value *P2 = Later.Ptr->stripPointerCasts();
429 
430   // If the start pointers are the same, we just have to compare sizes to see if
431   // the later store was larger than the earlier store.
432   if (P1 == P2 || AA.isMustAlias(P1, P2)) {
433     // Make sure that the Later size is >= the Earlier size.
434     if (LaterSize >= EarlierSize)
435       return OW_Complete;
436   }
437 
438   // Check to see if the later store is to the entire object (either a global,
439   // an alloca, or a byval/inalloca argument).  If so, then it clearly
440   // overwrites any other store to the same object.
441   const Value *UO1 = getUnderlyingObject(P1), *UO2 = getUnderlyingObject(P2);
442 
443   // If we can't resolve the same pointers to the same object, then we can't
444   // analyze them at all.
445   if (UO1 != UO2)
446     return OW_Unknown;
447 
448   // If the "Later" store is to a recognizable object, get its size.
449   uint64_t ObjectSize = getPointerSize(UO2, DL, TLI, F);
450   if (ObjectSize != MemoryLocation::UnknownSize)
451     if (ObjectSize == LaterSize && ObjectSize >= EarlierSize)
452       return OW_Complete;
453 
454   // Okay, we have stores to two completely different pointers.  Try to
455   // decompose the pointer into a "base + constant_offset" form.  If the base
456   // pointers are equal, then we can reason about the two stores.
457   EarlierOff = 0;
458   LaterOff = 0;
459   const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
460   const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
461 
462   // If the base pointers still differ, we have two completely different stores.
463   if (BP1 != BP2)
464     return OW_Unknown;
465 
466   // The later store completely overlaps the earlier store if:
467   //
468   // 1. Both start at the same offset and the later one's size is greater than
469   //    or equal to the earlier one's, or
470   //
471   //      |--earlier--|
472   //      |--   later   --|
473   //
474   // 2. The earlier store has an offset greater than the later offset, but which
475   //    still lies completely within the later store.
476   //
477   //        |--earlier--|
478   //    |-----  later  ------|
479   //
480   // We have to be careful here as *Off is signed while *.Size is unsigned.
481   if (EarlierOff >= LaterOff &&
482       LaterSize >= EarlierSize &&
483       uint64_t(EarlierOff - LaterOff) + EarlierSize <= LaterSize)
484     return OW_Complete;
485 
486   // Later may overwrite earlier completely with other partial writes.
487   return OW_MaybePartial;
488 }
489 
490 /// Return 'OW_Complete' if a store to the 'Later' location completely
491 /// overwrites a store to the 'Earlier' location, 'OW_End' if the end of the
492 /// 'Earlier' location is completely overwritten by 'Later', 'OW_Begin' if the
493 /// beginning of the 'Earlier' location is overwritten by 'Later'.
494 /// 'OW_PartialEarlierWithFullLater' means that an earlier (big) store was
495 /// overwritten by a latter (smaller) store which doesn't write outside the big
496 /// store's memory locations. Returns 'OW_Unknown' if nothing can be determined.
497 /// NOTE: This function must only be called if both \p Later and \p Earlier
498 /// write to the same underlying object with valid \p EarlierOff and \p
499 /// LaterOff.
500 static OverwriteResult isPartialOverwrite(const MemoryLocation &Later,
501                                           const MemoryLocation &Earlier,
502                                           int64_t EarlierOff, int64_t LaterOff,
503                                           Instruction *DepWrite,
504                                           InstOverlapIntervalsTy &IOL) {
505   const uint64_t LaterSize = Later.Size.getValue();
506   const uint64_t EarlierSize = Earlier.Size.getValue();
507   // We may now overlap, although the overlap is not complete. There might also
508   // be other incomplete overlaps, and together, they might cover the complete
509   // earlier write.
510   // Note: The correctness of this logic depends on the fact that this function
511   // is not even called providing DepWrite when there are any intervening reads.
512   if (EnablePartialOverwriteTracking &&
513       LaterOff < int64_t(EarlierOff + EarlierSize) &&
514       int64_t(LaterOff + LaterSize) >= EarlierOff) {
515 
516     // Insert our part of the overlap into the map.
517     auto &IM = IOL[DepWrite];
518     LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: Earlier [" << EarlierOff
519                       << ", " << int64_t(EarlierOff + EarlierSize)
520                       << ") Later [" << LaterOff << ", "
521                       << int64_t(LaterOff + LaterSize) << ")\n");
522 
523     // Make sure that we only insert non-overlapping intervals and combine
524     // adjacent intervals. The intervals are stored in the map with the ending
525     // offset as the key (in the half-open sense) and the starting offset as
526     // the value.
527     int64_t LaterIntStart = LaterOff, LaterIntEnd = LaterOff + LaterSize;
528 
529     // Find any intervals ending at, or after, LaterIntStart which start
530     // before LaterIntEnd.
531     auto ILI = IM.lower_bound(LaterIntStart);
532     if (ILI != IM.end() && ILI->second <= LaterIntEnd) {
533       // This existing interval is overlapped with the current store somewhere
534       // in [LaterIntStart, LaterIntEnd]. Merge them by erasing the existing
535       // intervals and adjusting our start and end.
536       LaterIntStart = std::min(LaterIntStart, ILI->second);
537       LaterIntEnd = std::max(LaterIntEnd, ILI->first);
538       ILI = IM.erase(ILI);
539 
540       // Continue erasing and adjusting our end in case other previous
541       // intervals are also overlapped with the current store.
542       //
543       // |--- ealier 1 ---|  |--- ealier 2 ---|
544       //     |------- later---------|
545       //
546       while (ILI != IM.end() && ILI->second <= LaterIntEnd) {
547         assert(ILI->second > LaterIntStart && "Unexpected interval");
548         LaterIntEnd = std::max(LaterIntEnd, ILI->first);
549         ILI = IM.erase(ILI);
550       }
551     }
552 
553     IM[LaterIntEnd] = LaterIntStart;
554 
555     ILI = IM.begin();
556     if (ILI->second <= EarlierOff &&
557         ILI->first >= int64_t(EarlierOff + EarlierSize)) {
558       LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: Earlier ["
559                         << EarlierOff << ", "
560                         << int64_t(EarlierOff + EarlierSize)
561                         << ") Composite Later [" << ILI->second << ", "
562                         << ILI->first << ")\n");
563       ++NumCompletePartials;
564       return OW_Complete;
565     }
566   }
567 
568   // Check for an earlier store which writes to all the memory locations that
569   // the later store writes to.
570   if (EnablePartialStoreMerging && LaterOff >= EarlierOff &&
571       int64_t(EarlierOff + EarlierSize) > LaterOff &&
572       uint64_t(LaterOff - EarlierOff) + LaterSize <= EarlierSize) {
573     LLVM_DEBUG(dbgs() << "DSE: Partial overwrite an earlier load ["
574                       << EarlierOff << ", "
575                       << int64_t(EarlierOff + EarlierSize)
576                       << ") by a later store [" << LaterOff << ", "
577                       << int64_t(LaterOff + LaterSize) << ")\n");
578     // TODO: Maybe come up with a better name?
579     return OW_PartialEarlierWithFullLater;
580   }
581 
582   // Another interesting case is if the later store overwrites the end of the
583   // earlier store.
584   //
585   //      |--earlier--|
586   //                |--   later   --|
587   //
588   // In this case we may want to trim the size of earlier to avoid generating
589   // writes to addresses which will definitely be overwritten later
590   if (!EnablePartialOverwriteTracking &&
591       (LaterOff > EarlierOff && LaterOff < int64_t(EarlierOff + EarlierSize) &&
592        int64_t(LaterOff + LaterSize) >= int64_t(EarlierOff + EarlierSize)))
593     return OW_End;
594 
595   // Finally, we also need to check if the later store overwrites the beginning
596   // of the earlier store.
597   //
598   //                |--earlier--|
599   //      |--   later   --|
600   //
601   // In this case we may want to move the destination address and trim the size
602   // of earlier to avoid generating writes to addresses which will definitely
603   // be overwritten later.
604   if (!EnablePartialOverwriteTracking &&
605       (LaterOff <= EarlierOff && int64_t(LaterOff + LaterSize) > EarlierOff)) {
606     assert(int64_t(LaterOff + LaterSize) < int64_t(EarlierOff + EarlierSize) &&
607            "Expect to be handled as OW_Complete");
608     return OW_Begin;
609   }
610   // Otherwise, they don't completely overlap.
611   return OW_Unknown;
612 }
613 
614 /// If 'Inst' might be a self read (i.e. a noop copy of a
615 /// memory region into an identical pointer) then it doesn't actually make its
616 /// input dead in the traditional sense.  Consider this case:
617 ///
618 ///   memmove(A <- B)
619 ///   memmove(A <- A)
620 ///
621 /// In this case, the second store to A does not make the first store to A dead.
622 /// The usual situation isn't an explicit A<-A store like this (which can be
623 /// trivially removed) but a case where two pointers may alias.
624 ///
625 /// This function detects when it is unsafe to remove a dependent instruction
626 /// because the DSE inducing instruction may be a self-read.
627 static bool isPossibleSelfRead(Instruction *Inst,
628                                const MemoryLocation &InstStoreLoc,
629                                Instruction *DepWrite,
630                                const TargetLibraryInfo &TLI,
631                                AliasAnalysis &AA) {
632   // Self reads can only happen for instructions that read memory.  Get the
633   // location read.
634   MemoryLocation InstReadLoc = getLocForRead(Inst, TLI);
635   if (!InstReadLoc.Ptr)
636     return false; // Not a reading instruction.
637 
638   // If the read and written loc obviously don't alias, it isn't a read.
639   if (AA.isNoAlias(InstReadLoc, InstStoreLoc))
640     return false;
641 
642   if (isa<AnyMemCpyInst>(Inst)) {
643     // LLVM's memcpy overlap semantics are not fully fleshed out (see PR11763)
644     // but in practice memcpy(A <- B) either means that A and B are disjoint or
645     // are equal (i.e. there are not partial overlaps).  Given that, if we have:
646     //
647     //   memcpy/memmove(A <- B)  // DepWrite
648     //   memcpy(A <- B)  // Inst
649     //
650     // with Inst reading/writing a >= size than DepWrite, we can reason as
651     // follows:
652     //
653     //   - If A == B then both the copies are no-ops, so the DepWrite can be
654     //     removed.
655     //   - If A != B then A and B are disjoint locations in Inst.  Since
656     //     Inst.size >= DepWrite.size A and B are disjoint in DepWrite too.
657     //     Therefore DepWrite can be removed.
658     MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI);
659 
660     if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
661       return false;
662   }
663 
664   // If DepWrite doesn't read memory or if we can't prove it is a must alias,
665   // then it can't be considered dead.
666   return true;
667 }
668 
669 /// Returns true if the memory which is accessed by the second instruction is not
670 /// modified between the first and the second instruction.
671 /// Precondition: Second instruction must be dominated by the first
672 /// instruction.
673 template <typename AATy>
674 static bool
675 memoryIsNotModifiedBetween(Instruction *FirstI, Instruction *SecondI, AATy &AA,
676                            const DataLayout &DL, DominatorTree *DT) {
677   // Do a backwards scan through the CFG from SecondI to FirstI. Look for
678   // instructions which can modify the memory location accessed by SecondI.
679   //
680   // While doing the walk keep track of the address to check. It might be
681   // different in different basic blocks due to PHI translation.
682   using BlockAddressPair = std::pair<BasicBlock *, PHITransAddr>;
683   SmallVector<BlockAddressPair, 16> WorkList;
684   // Keep track of the address we visited each block with. Bail out if we
685   // visit a block with different addresses.
686   DenseMap<BasicBlock *, Value *> Visited;
687 
688   BasicBlock::iterator FirstBBI(FirstI);
689   ++FirstBBI;
690   BasicBlock::iterator SecondBBI(SecondI);
691   BasicBlock *FirstBB = FirstI->getParent();
692   BasicBlock *SecondBB = SecondI->getParent();
693   MemoryLocation MemLoc = MemoryLocation::get(SecondI);
694   auto *MemLocPtr = const_cast<Value *>(MemLoc.Ptr);
695 
696   // Start checking the SecondBB.
697   WorkList.push_back(
698       std::make_pair(SecondBB, PHITransAddr(MemLocPtr, DL, nullptr)));
699   bool isFirstBlock = true;
700 
701   // Check all blocks going backward until we reach the FirstBB.
702   while (!WorkList.empty()) {
703     BlockAddressPair Current = WorkList.pop_back_val();
704     BasicBlock *B = Current.first;
705     PHITransAddr &Addr = Current.second;
706     Value *Ptr = Addr.getAddr();
707 
708     // Ignore instructions before FirstI if this is the FirstBB.
709     BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin());
710 
711     BasicBlock::iterator EI;
712     if (isFirstBlock) {
713       // Ignore instructions after SecondI if this is the first visit of SecondBB.
714       assert(B == SecondBB && "first block is not the store block");
715       EI = SecondBBI;
716       isFirstBlock = false;
717     } else {
718       // It's not SecondBB or (in case of a loop) the second visit of SecondBB.
719       // In this case we also have to look at instructions after SecondI.
720       EI = B->end();
721     }
722     for (; BI != EI; ++BI) {
723       Instruction *I = &*BI;
724       if (I->mayWriteToMemory() && I != SecondI)
725         if (isModSet(AA.getModRefInfo(I, MemLoc.getWithNewPtr(Ptr))))
726           return false;
727     }
728     if (B != FirstBB) {
729       assert(B != &FirstBB->getParent()->getEntryBlock() &&
730           "Should not hit the entry block because SI must be dominated by LI");
731       for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) {
732         PHITransAddr PredAddr = Addr;
733         if (PredAddr.NeedsPHITranslationFromBlock(B)) {
734           if (!PredAddr.IsPotentiallyPHITranslatable())
735             return false;
736           if (PredAddr.PHITranslateValue(B, *PredI, DT, false))
737             return false;
738         }
739         Value *TranslatedPtr = PredAddr.getAddr();
740         auto Inserted = Visited.insert(std::make_pair(*PredI, TranslatedPtr));
741         if (!Inserted.second) {
742           // We already visited this block before. If it was with a different
743           // address - bail out!
744           if (TranslatedPtr != Inserted.first->second)
745             return false;
746           // ... otherwise just skip it.
747           continue;
748         }
749         WorkList.push_back(std::make_pair(*PredI, PredAddr));
750       }
751     }
752   }
753   return true;
754 }
755 
756 /// Find all blocks that will unconditionally lead to the block BB and append
757 /// them to F.
758 static void findUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
759                                    BasicBlock *BB, DominatorTree *DT) {
760   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
761     BasicBlock *Pred = *I;
762     if (Pred == BB) continue;
763     Instruction *PredTI = Pred->getTerminator();
764     if (PredTI->getNumSuccessors() != 1)
765       continue;
766 
767     if (DT->isReachableFromEntry(Pred))
768       Blocks.push_back(Pred);
769   }
770 }
771 
772 /// Handle frees of entire structures whose dependency is a store
773 /// to a field of that structure.
774 static bool handleFree(CallInst *F, AliasAnalysis *AA,
775                        MemoryDependenceResults *MD, DominatorTree *DT,
776                        const TargetLibraryInfo *TLI,
777                        InstOverlapIntervalsTy &IOL,
778                        MapVector<Instruction *, bool> &ThrowableInst) {
779   bool MadeChange = false;
780 
781   MemoryLocation Loc = MemoryLocation(F->getOperand(0));
782   SmallVector<BasicBlock *, 16> Blocks;
783   Blocks.push_back(F->getParent());
784 
785   while (!Blocks.empty()) {
786     BasicBlock *BB = Blocks.pop_back_val();
787     Instruction *InstPt = BB->getTerminator();
788     if (BB == F->getParent()) InstPt = F;
789 
790     MemDepResult Dep =
791         MD->getPointerDependencyFrom(Loc, false, InstPt->getIterator(), BB);
792     while (Dep.isDef() || Dep.isClobber()) {
793       Instruction *Dependency = Dep.getInst();
794       if (!hasAnalyzableMemoryWrite(Dependency, *TLI) ||
795           !isRemovable(Dependency))
796         break;
797 
798       Value *DepPointer =
799           getUnderlyingObject(getStoredPointerOperand(Dependency));
800 
801       // Check for aliasing.
802       if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
803         break;
804 
805       LLVM_DEBUG(
806           dbgs() << "DSE: Dead Store to soon to be freed memory:\n  DEAD: "
807                  << *Dependency << '\n');
808 
809       // DCE instructions only used to calculate that store.
810       BasicBlock::iterator BBI(Dependency);
811       deleteDeadInstruction(Dependency, &BBI, *MD, *TLI, IOL,
812                             ThrowableInst);
813       ++NumFastStores;
814       MadeChange = true;
815 
816       // Inst's old Dependency is now deleted. Compute the next dependency,
817       // which may also be dead, as in
818       //    s[0] = 0;
819       //    s[1] = 0; // This has just been deleted.
820       //    free(s);
821       Dep = MD->getPointerDependencyFrom(Loc, false, BBI, BB);
822     }
823 
824     if (Dep.isNonLocal())
825       findUnconditionalPreds(Blocks, BB, DT);
826   }
827 
828   return MadeChange;
829 }
830 
831 /// Check to see if the specified location may alias any of the stack objects in
832 /// the DeadStackObjects set. If so, they become live because the location is
833 /// being loaded.
834 static void removeAccessedObjects(const MemoryLocation &LoadedLoc,
835                                   SmallSetVector<const Value *, 16> &DeadStackObjects,
836                                   const DataLayout &DL, AliasAnalysis *AA,
837                                   const TargetLibraryInfo *TLI,
838                                   const Function *F) {
839   const Value *UnderlyingPointer = getUnderlyingObject(LoadedLoc.Ptr);
840 
841   // A constant can't be in the dead pointer set.
842   if (isa<Constant>(UnderlyingPointer))
843     return;
844 
845   // If the kill pointer can be easily reduced to an alloca, don't bother doing
846   // extraneous AA queries.
847   if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
848     DeadStackObjects.remove(UnderlyingPointer);
849     return;
850   }
851 
852   // Remove objects that could alias LoadedLoc.
853   DeadStackObjects.remove_if([&](const Value *I) {
854     // See if the loaded location could alias the stack location.
855     MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI, F));
856     return !AA->isNoAlias(StackLoc, LoadedLoc);
857   });
858 }
859 
860 /// Remove dead stores to stack-allocated locations in the function end block.
861 /// Ex:
862 /// %A = alloca i32
863 /// ...
864 /// store i32 1, i32* %A
865 /// ret void
866 static bool handleEndBlock(BasicBlock &BB, AliasAnalysis *AA,
867                            MemoryDependenceResults *MD,
868                            const TargetLibraryInfo *TLI,
869                            InstOverlapIntervalsTy &IOL,
870                            MapVector<Instruction *, bool> &ThrowableInst) {
871   bool MadeChange = false;
872 
873   // Keep track of all of the stack objects that are dead at the end of the
874   // function.
875   SmallSetVector<const Value*, 16> DeadStackObjects;
876 
877   // Find all of the alloca'd pointers in the entry block.
878   BasicBlock &Entry = BB.getParent()->front();
879   for (Instruction &I : Entry) {
880     if (isa<AllocaInst>(&I))
881       DeadStackObjects.insert(&I);
882 
883     // Okay, so these are dead heap objects, but if the pointer never escapes
884     // then it's leaked by this function anyways.
885     else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true))
886       DeadStackObjects.insert(&I);
887   }
888 
889   // Treat byval or inalloca arguments the same, stores to them are dead at the
890   // end of the function.
891   for (Argument &AI : BB.getParent()->args())
892     if (AI.hasPassPointeeByValueCopyAttr())
893       DeadStackObjects.insert(&AI);
894 
895   const DataLayout &DL = BB.getModule()->getDataLayout();
896 
897   // Scan the basic block backwards
898   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
899     --BBI;
900 
901     // If we find a store, check to see if it points into a dead stack value.
902     if (hasAnalyzableMemoryWrite(&*BBI, *TLI) && isRemovable(&*BBI)) {
903       // See through pointer-to-pointer bitcasts
904       SmallVector<const Value *, 4> Pointers;
905       getUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers);
906 
907       // Stores to stack values are valid candidates for removal.
908       bool AllDead = true;
909       for (const Value *Pointer : Pointers)
910         if (!DeadStackObjects.count(Pointer)) {
911           AllDead = false;
912           break;
913         }
914 
915       if (AllDead) {
916         Instruction *Dead = &*BBI;
917 
918         LLVM_DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n  DEAD: "
919                           << *Dead << "\n  Objects: ";
920                    for (SmallVectorImpl<const Value *>::iterator I =
921                             Pointers.begin(),
922                         E = Pointers.end();
923                         I != E; ++I) {
924                      dbgs() << **I;
925                      if (std::next(I) != E)
926                        dbgs() << ", ";
927                    } dbgs()
928                    << '\n');
929 
930         // DCE instructions only used to calculate that store.
931         deleteDeadInstruction(Dead, &BBI, *MD, *TLI, IOL, ThrowableInst,
932                               &DeadStackObjects);
933         ++NumFastStores;
934         MadeChange = true;
935         continue;
936       }
937     }
938 
939     // Remove any dead non-memory-mutating instructions.
940     if (isInstructionTriviallyDead(&*BBI, TLI)) {
941       LLVM_DEBUG(dbgs() << "DSE: Removing trivially dead instruction:\n  DEAD: "
942                         << *&*BBI << '\n');
943       deleteDeadInstruction(&*BBI, &BBI, *MD, *TLI, IOL, ThrowableInst,
944                             &DeadStackObjects);
945       ++NumFastOther;
946       MadeChange = true;
947       continue;
948     }
949 
950     if (isa<AllocaInst>(BBI)) {
951       // Remove allocas from the list of dead stack objects; there can't be
952       // any references before the definition.
953       DeadStackObjects.remove(&*BBI);
954       continue;
955     }
956 
957     if (auto *Call = dyn_cast<CallBase>(&*BBI)) {
958       // Remove allocation function calls from the list of dead stack objects;
959       // there can't be any references before the definition.
960       if (isAllocLikeFn(&*BBI, TLI))
961         DeadStackObjects.remove(&*BBI);
962 
963       // If this call does not access memory, it can't be loading any of our
964       // pointers.
965       if (AA->doesNotAccessMemory(Call))
966         continue;
967 
968       // If the call might load from any of our allocas, then any store above
969       // the call is live.
970       DeadStackObjects.remove_if([&](const Value *I) {
971         // See if the call site touches the value.
972         return isRefSet(AA->getModRefInfo(
973             Call, I, getPointerSize(I, DL, *TLI, BB.getParent())));
974       });
975 
976       // If all of the allocas were clobbered by the call then we're not going
977       // to find anything else to process.
978       if (DeadStackObjects.empty())
979         break;
980 
981       continue;
982     }
983 
984     // We can remove the dead stores, irrespective of the fence and its ordering
985     // (release/acquire/seq_cst). Fences only constraints the ordering of
986     // already visible stores, it does not make a store visible to other
987     // threads. So, skipping over a fence does not change a store from being
988     // dead.
989     if (isa<FenceInst>(*BBI))
990       continue;
991 
992     MemoryLocation LoadedLoc;
993 
994     // If we encounter a use of the pointer, it is no longer considered dead
995     if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
996       if (!L->isUnordered()) // Be conservative with atomic/volatile load
997         break;
998       LoadedLoc = MemoryLocation::get(L);
999     } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
1000       LoadedLoc = MemoryLocation::get(V);
1001     } else if (!BBI->mayReadFromMemory()) {
1002       // Instruction doesn't read memory.  Note that stores that weren't removed
1003       // above will hit this case.
1004       continue;
1005     } else {
1006       // Unknown inst; assume it clobbers everything.
1007       break;
1008     }
1009 
1010     // Remove any allocas from the DeadPointer set that are loaded, as this
1011     // makes any stores above the access live.
1012     removeAccessedObjects(LoadedLoc, DeadStackObjects, DL, AA, TLI, BB.getParent());
1013 
1014     // If all of the allocas were clobbered by the access then we're not going
1015     // to find anything else to process.
1016     if (DeadStackObjects.empty())
1017       break;
1018   }
1019 
1020   return MadeChange;
1021 }
1022 
1023 static bool tryToShorten(Instruction *EarlierWrite, int64_t &EarlierOffset,
1024                          int64_t &EarlierSize, int64_t LaterOffset,
1025                          int64_t LaterSize, bool IsOverwriteEnd) {
1026   // TODO: base this on the target vector size so that if the earlier
1027   // store was too small to get vector writes anyway then its likely
1028   // a good idea to shorten it
1029   // Power of 2 vector writes are probably always a bad idea to optimize
1030   // as any store/memset/memcpy is likely using vector instructions so
1031   // shortening it to not vector size is likely to be slower
1032   auto *EarlierIntrinsic = cast<AnyMemIntrinsic>(EarlierWrite);
1033   unsigned EarlierWriteAlign = EarlierIntrinsic->getDestAlignment();
1034   if (!IsOverwriteEnd)
1035     LaterOffset = int64_t(LaterOffset + LaterSize);
1036 
1037   if (!(isPowerOf2_64(LaterOffset) && EarlierWriteAlign <= LaterOffset) &&
1038       !((EarlierWriteAlign != 0) && LaterOffset % EarlierWriteAlign == 0))
1039     return false;
1040 
1041   int64_t NewLength = IsOverwriteEnd
1042                           ? LaterOffset - EarlierOffset
1043                           : EarlierSize - (LaterOffset - EarlierOffset);
1044 
1045   if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(EarlierWrite)) {
1046     // When shortening an atomic memory intrinsic, the newly shortened
1047     // length must remain an integer multiple of the element size.
1048     const uint32_t ElementSize = AMI->getElementSizeInBytes();
1049     if (0 != NewLength % ElementSize)
1050       return false;
1051   }
1052 
1053   LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  OW "
1054                     << (IsOverwriteEnd ? "END" : "BEGIN") << ": "
1055                     << *EarlierWrite << "\n  KILLER (offset " << LaterOffset
1056                     << ", " << EarlierSize << ")\n");
1057 
1058   Value *EarlierWriteLength = EarlierIntrinsic->getLength();
1059   Value *TrimmedLength =
1060       ConstantInt::get(EarlierWriteLength->getType(), NewLength);
1061   EarlierIntrinsic->setLength(TrimmedLength);
1062 
1063   EarlierSize = NewLength;
1064   if (!IsOverwriteEnd) {
1065     int64_t OffsetMoved = (LaterOffset - EarlierOffset);
1066     Value *Indices[1] = {
1067         ConstantInt::get(EarlierWriteLength->getType(), OffsetMoved)};
1068     GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds(
1069         EarlierIntrinsic->getRawDest()->getType()->getPointerElementType(),
1070         EarlierIntrinsic->getRawDest(), Indices, "", EarlierWrite);
1071     NewDestGEP->setDebugLoc(EarlierIntrinsic->getDebugLoc());
1072     EarlierIntrinsic->setDest(NewDestGEP);
1073     EarlierOffset = EarlierOffset + OffsetMoved;
1074   }
1075   return true;
1076 }
1077 
1078 static bool tryToShortenEnd(Instruction *EarlierWrite,
1079                             OverlapIntervalsTy &IntervalMap,
1080                             int64_t &EarlierStart, int64_t &EarlierSize) {
1081   if (IntervalMap.empty() || !isShortenableAtTheEnd(EarlierWrite))
1082     return false;
1083 
1084   OverlapIntervalsTy::iterator OII = --IntervalMap.end();
1085   int64_t LaterStart = OII->second;
1086   int64_t LaterSize = OII->first - LaterStart;
1087 
1088   if (LaterStart > EarlierStart && LaterStart < EarlierStart + EarlierSize &&
1089       LaterStart + LaterSize >= EarlierStart + EarlierSize) {
1090     if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart,
1091                      LaterSize, true)) {
1092       IntervalMap.erase(OII);
1093       return true;
1094     }
1095   }
1096   return false;
1097 }
1098 
1099 static bool tryToShortenBegin(Instruction *EarlierWrite,
1100                               OverlapIntervalsTy &IntervalMap,
1101                               int64_t &EarlierStart, int64_t &EarlierSize) {
1102   if (IntervalMap.empty() || !isShortenableAtTheBeginning(EarlierWrite))
1103     return false;
1104 
1105   OverlapIntervalsTy::iterator OII = IntervalMap.begin();
1106   int64_t LaterStart = OII->second;
1107   int64_t LaterSize = OII->first - LaterStart;
1108 
1109   if (LaterStart <= EarlierStart && LaterStart + LaterSize > EarlierStart) {
1110     assert(LaterStart + LaterSize < EarlierStart + EarlierSize &&
1111            "Should have been handled as OW_Complete");
1112     if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart,
1113                      LaterSize, false)) {
1114       IntervalMap.erase(OII);
1115       return true;
1116     }
1117   }
1118   return false;
1119 }
1120 
1121 static bool removePartiallyOverlappedStores(const DataLayout &DL,
1122                                             InstOverlapIntervalsTy &IOL) {
1123   bool Changed = false;
1124   for (auto OI : IOL) {
1125     Instruction *EarlierWrite = OI.first;
1126     MemoryLocation Loc = getLocForWrite(EarlierWrite);
1127     assert(isRemovable(EarlierWrite) && "Expect only removable instruction");
1128 
1129     const Value *Ptr = Loc.Ptr->stripPointerCasts();
1130     int64_t EarlierStart = 0;
1131     int64_t EarlierSize = int64_t(Loc.Size.getValue());
1132     GetPointerBaseWithConstantOffset(Ptr, EarlierStart, DL);
1133     OverlapIntervalsTy &IntervalMap = OI.second;
1134     Changed |=
1135         tryToShortenEnd(EarlierWrite, IntervalMap, EarlierStart, EarlierSize);
1136     if (IntervalMap.empty())
1137       continue;
1138     Changed |=
1139         tryToShortenBegin(EarlierWrite, IntervalMap, EarlierStart, EarlierSize);
1140   }
1141   return Changed;
1142 }
1143 
1144 static bool eliminateNoopStore(Instruction *Inst, BasicBlock::iterator &BBI,
1145                                AliasAnalysis *AA, MemoryDependenceResults *MD,
1146                                const DataLayout &DL,
1147                                const TargetLibraryInfo *TLI,
1148                                InstOverlapIntervalsTy &IOL,
1149                                MapVector<Instruction *, bool> &ThrowableInst,
1150                                DominatorTree *DT) {
1151   // Must be a store instruction.
1152   StoreInst *SI = dyn_cast<StoreInst>(Inst);
1153   if (!SI)
1154     return false;
1155 
1156   // If we're storing the same value back to a pointer that we just loaded from,
1157   // then the store can be removed.
1158   if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) {
1159     if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
1160         isRemovable(SI) &&
1161         memoryIsNotModifiedBetween(DepLoad, SI, *AA, DL, DT)) {
1162 
1163       LLVM_DEBUG(
1164           dbgs() << "DSE: Remove Store Of Load from same pointer:\n  LOAD: "
1165                  << *DepLoad << "\n  STORE: " << *SI << '\n');
1166 
1167       deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, ThrowableInst);
1168       ++NumRedundantStores;
1169       return true;
1170     }
1171   }
1172 
1173   // Remove null stores into the calloc'ed objects
1174   Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand());
1175   if (StoredConstant && StoredConstant->isNullValue() && isRemovable(SI)) {
1176     Instruction *UnderlyingPointer =
1177         dyn_cast<Instruction>(getUnderlyingObject(SI->getPointerOperand()));
1178 
1179     if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) &&
1180         memoryIsNotModifiedBetween(UnderlyingPointer, SI, *AA, DL, DT)) {
1181       LLVM_DEBUG(
1182           dbgs() << "DSE: Remove null store to the calloc'ed object:\n  DEAD: "
1183                  << *Inst << "\n  OBJECT: " << *UnderlyingPointer << '\n');
1184 
1185       deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, ThrowableInst);
1186       ++NumRedundantStores;
1187       return true;
1188     }
1189   }
1190   return false;
1191 }
1192 
1193 template <typename AATy>
1194 static Constant *tryToMergePartialOverlappingStores(
1195     StoreInst *Earlier, StoreInst *Later, int64_t InstWriteOffset,
1196     int64_t DepWriteOffset, const DataLayout &DL, AATy &AA, DominatorTree *DT) {
1197 
1198   if (Earlier && isa<ConstantInt>(Earlier->getValueOperand()) &&
1199       DL.typeSizeEqualsStoreSize(Earlier->getValueOperand()->getType()) &&
1200       Later && isa<ConstantInt>(Later->getValueOperand()) &&
1201       DL.typeSizeEqualsStoreSize(Later->getValueOperand()->getType()) &&
1202       memoryIsNotModifiedBetween(Earlier, Later, AA, DL, DT)) {
1203     // If the store we find is:
1204     //   a) partially overwritten by the store to 'Loc'
1205     //   b) the later store is fully contained in the earlier one and
1206     //   c) they both have a constant value
1207     //   d) none of the two stores need padding
1208     // Merge the two stores, replacing the earlier store's value with a
1209     // merge of both values.
1210     // TODO: Deal with other constant types (vectors, etc), and probably
1211     // some mem intrinsics (if needed)
1212 
1213     APInt EarlierValue =
1214         cast<ConstantInt>(Earlier->getValueOperand())->getValue();
1215     APInt LaterValue = cast<ConstantInt>(Later->getValueOperand())->getValue();
1216     unsigned LaterBits = LaterValue.getBitWidth();
1217     assert(EarlierValue.getBitWidth() > LaterValue.getBitWidth());
1218     LaterValue = LaterValue.zext(EarlierValue.getBitWidth());
1219 
1220     // Offset of the smaller store inside the larger store
1221     unsigned BitOffsetDiff = (InstWriteOffset - DepWriteOffset) * 8;
1222     unsigned LShiftAmount = DL.isBigEndian() ? EarlierValue.getBitWidth() -
1223                                                    BitOffsetDiff - LaterBits
1224                                              : BitOffsetDiff;
1225     APInt Mask = APInt::getBitsSet(EarlierValue.getBitWidth(), LShiftAmount,
1226                                    LShiftAmount + LaterBits);
1227     // Clear the bits we'll be replacing, then OR with the smaller
1228     // store, shifted appropriately.
1229     APInt Merged = (EarlierValue & ~Mask) | (LaterValue << LShiftAmount);
1230     LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n  Earlier: " << *Earlier
1231                       << "\n  Later: " << *Later
1232                       << "\n  Merged Value: " << Merged << '\n');
1233     return ConstantInt::get(Earlier->getValueOperand()->getType(), Merged);
1234   }
1235   return nullptr;
1236 }
1237 
1238 static bool eliminateDeadStores(BasicBlock &BB, AliasAnalysis *AA,
1239                                 MemoryDependenceResults *MD, DominatorTree *DT,
1240                                 const TargetLibraryInfo *TLI) {
1241   const DataLayout &DL = BB.getModule()->getDataLayout();
1242   bool MadeChange = false;
1243 
1244   MapVector<Instruction *, bool> ThrowableInst;
1245 
1246   // A map of interval maps representing partially-overwritten value parts.
1247   InstOverlapIntervalsTy IOL;
1248 
1249   // Do a top-down walk on the BB.
1250   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
1251     // Handle 'free' calls specially.
1252     if (CallInst *F = isFreeCall(&*BBI, TLI)) {
1253       MadeChange |= handleFree(F, AA, MD, DT, TLI, IOL, ThrowableInst);
1254       // Increment BBI after handleFree has potentially deleted instructions.
1255       // This ensures we maintain a valid iterator.
1256       ++BBI;
1257       continue;
1258     }
1259 
1260     Instruction *Inst = &*BBI++;
1261 
1262     if (Inst->mayThrow()) {
1263       ThrowableInst[Inst] = true;
1264       continue;
1265     }
1266 
1267     // Check to see if Inst writes to memory.  If not, continue.
1268     if (!hasAnalyzableMemoryWrite(Inst, *TLI))
1269       continue;
1270 
1271     // eliminateNoopStore will update in iterator, if necessary.
1272     if (eliminateNoopStore(Inst, BBI, AA, MD, DL, TLI, IOL,
1273                            ThrowableInst, DT)) {
1274       MadeChange = true;
1275       continue;
1276     }
1277 
1278     // If we find something that writes memory, get its memory dependence.
1279     MemDepResult InstDep = MD->getDependency(Inst);
1280 
1281     // Ignore any store where we can't find a local dependence.
1282     // FIXME: cross-block DSE would be fun. :)
1283     if (!InstDep.isDef() && !InstDep.isClobber())
1284       continue;
1285 
1286     // Figure out what location is being stored to.
1287     MemoryLocation Loc = getLocForWrite(Inst);
1288 
1289     // If we didn't get a useful location, fail.
1290     if (!Loc.Ptr)
1291       continue;
1292 
1293     // Loop until we find a store we can eliminate or a load that
1294     // invalidates the analysis. Without an upper bound on the number of
1295     // instructions examined, this analysis can become very time-consuming.
1296     // However, the potential gain diminishes as we process more instructions
1297     // without eliminating any of them. Therefore, we limit the number of
1298     // instructions we look at.
1299     auto Limit = MD->getDefaultBlockScanLimit();
1300     while (InstDep.isDef() || InstDep.isClobber()) {
1301       // Get the memory clobbered by the instruction we depend on.  MemDep will
1302       // skip any instructions that 'Loc' clearly doesn't interact with.  If we
1303       // end up depending on a may- or must-aliased load, then we can't optimize
1304       // away the store and we bail out.  However, if we depend on something
1305       // that overwrites the memory location we *can* potentially optimize it.
1306       //
1307       // Find out what memory location the dependent instruction stores.
1308       Instruction *DepWrite = InstDep.getInst();
1309       if (!hasAnalyzableMemoryWrite(DepWrite, *TLI))
1310         break;
1311       MemoryLocation DepLoc = getLocForWrite(DepWrite);
1312       // If we didn't get a useful location, or if it isn't a size, bail out.
1313       if (!DepLoc.Ptr)
1314         break;
1315 
1316       // Find the last throwable instruction not removed by call to
1317       // deleteDeadInstruction.
1318       Instruction *LastThrowing = nullptr;
1319       if (!ThrowableInst.empty())
1320         LastThrowing = ThrowableInst.back().first;
1321 
1322       // Make sure we don't look past a call which might throw. This is an
1323       // issue because MemoryDependenceAnalysis works in the wrong direction:
1324       // it finds instructions which dominate the current instruction, rather than
1325       // instructions which are post-dominated by the current instruction.
1326       //
1327       // If the underlying object is a non-escaping memory allocation, any store
1328       // to it is dead along the unwind edge. Otherwise, we need to preserve
1329       // the store.
1330       if (LastThrowing && DepWrite->comesBefore(LastThrowing)) {
1331         const Value *Underlying = getUnderlyingObject(DepLoc.Ptr);
1332         bool IsStoreDeadOnUnwind = isa<AllocaInst>(Underlying);
1333         if (!IsStoreDeadOnUnwind) {
1334             // We're looking for a call to an allocation function
1335             // where the allocation doesn't escape before the last
1336             // throwing instruction; PointerMayBeCaptured
1337             // reasonably fast approximation.
1338             IsStoreDeadOnUnwind = isAllocLikeFn(Underlying, TLI) &&
1339                 !PointerMayBeCaptured(Underlying, false, true);
1340         }
1341         if (!IsStoreDeadOnUnwind)
1342           break;
1343       }
1344 
1345       // If we find a write that is a) removable (i.e., non-volatile), b) is
1346       // completely obliterated by the store to 'Loc', and c) which we know that
1347       // 'Inst' doesn't load from, then we can remove it.
1348       // Also try to merge two stores if a later one only touches memory written
1349       // to by the earlier one.
1350       if (isRemovable(DepWrite) &&
1351           !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) {
1352         int64_t InstWriteOffset, DepWriteOffset;
1353         OverwriteResult OR = isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset,
1354                                          InstWriteOffset, *AA, BB.getParent());
1355         if (OR == OW_MaybePartial)
1356           OR = isPartialOverwrite(Loc, DepLoc, DepWriteOffset, InstWriteOffset,
1357                                   DepWrite, IOL);
1358 
1359         if (OR == OW_Complete) {
1360           LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: " << *DepWrite
1361                             << "\n  KILLER: " << *Inst << '\n');
1362 
1363           // Delete the store and now-dead instructions that feed it.
1364           deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL,
1365                                 ThrowableInst);
1366           ++NumFastStores;
1367           MadeChange = true;
1368 
1369           // We erased DepWrite; start over.
1370           InstDep = MD->getDependency(Inst);
1371           continue;
1372         } else if ((OR == OW_End && isShortenableAtTheEnd(DepWrite)) ||
1373                    ((OR == OW_Begin &&
1374                      isShortenableAtTheBeginning(DepWrite)))) {
1375           assert(!EnablePartialOverwriteTracking && "Do not expect to perform "
1376                                                     "when partial-overwrite "
1377                                                     "tracking is enabled");
1378           // The overwrite result is known, so these must be known, too.
1379           int64_t EarlierSize = DepLoc.Size.getValue();
1380           int64_t LaterSize = Loc.Size.getValue();
1381           bool IsOverwriteEnd = (OR == OW_End);
1382           MadeChange |= tryToShorten(DepWrite, DepWriteOffset, EarlierSize,
1383                                     InstWriteOffset, LaterSize, IsOverwriteEnd);
1384         } else if (EnablePartialStoreMerging &&
1385                    OR == OW_PartialEarlierWithFullLater) {
1386           auto *Earlier = dyn_cast<StoreInst>(DepWrite);
1387           auto *Later = dyn_cast<StoreInst>(Inst);
1388           if (Constant *C = tryToMergePartialOverlappingStores(
1389                   Earlier, Later, InstWriteOffset, DepWriteOffset, DL, *AA,
1390                   DT)) {
1391             auto *SI = new StoreInst(
1392                 C, Earlier->getPointerOperand(), false, Earlier->getAlign(),
1393                 Earlier->getOrdering(), Earlier->getSyncScopeID(), DepWrite);
1394 
1395             unsigned MDToKeep[] = {LLVMContext::MD_dbg, LLVMContext::MD_tbaa,
1396                                    LLVMContext::MD_alias_scope,
1397                                    LLVMContext::MD_noalias,
1398                                    LLVMContext::MD_nontemporal};
1399             SI->copyMetadata(*DepWrite, MDToKeep);
1400             ++NumModifiedStores;
1401 
1402             // Delete the old stores and now-dead instructions that feed them.
1403             deleteDeadInstruction(Inst, &BBI, *MD, *TLI, IOL,
1404                                   ThrowableInst);
1405             deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL,
1406                                   ThrowableInst);
1407             MadeChange = true;
1408 
1409             // We erased DepWrite and Inst (Loc); start over.
1410             break;
1411           }
1412         }
1413       }
1414 
1415       // If this is a may-aliased store that is clobbering the store value, we
1416       // can keep searching past it for another must-aliased pointer that stores
1417       // to the same location.  For example, in:
1418       //   store -> P
1419       //   store -> Q
1420       //   store -> P
1421       // we can remove the first store to P even though we don't know if P and Q
1422       // alias.
1423       if (DepWrite == &BB.front()) break;
1424 
1425       // Can't look past this instruction if it might read 'Loc'.
1426       if (isRefSet(AA->getModRefInfo(DepWrite, Loc)))
1427         break;
1428 
1429       InstDep = MD->getPointerDependencyFrom(Loc, /*isLoad=*/ false,
1430                                              DepWrite->getIterator(), &BB,
1431                                              /*QueryInst=*/ nullptr, &Limit);
1432     }
1433   }
1434 
1435   if (EnablePartialOverwriteTracking)
1436     MadeChange |= removePartiallyOverlappedStores(DL, IOL);
1437 
1438   // If this block ends in a return, unwind, or unreachable, all allocas are
1439   // dead at its end, which means stores to them are also dead.
1440   if (BB.getTerminator()->getNumSuccessors() == 0)
1441     MadeChange |= handleEndBlock(BB, AA, MD, TLI, IOL, ThrowableInst);
1442 
1443   return MadeChange;
1444 }
1445 
1446 static bool eliminateDeadStores(Function &F, AliasAnalysis *AA,
1447                                 MemoryDependenceResults *MD, DominatorTree *DT,
1448                                 const TargetLibraryInfo *TLI) {
1449   bool MadeChange = false;
1450   for (BasicBlock &BB : F)
1451     // Only check non-dead blocks.  Dead blocks may have strange pointer
1452     // cycles that will confuse alias analysis.
1453     if (DT->isReachableFromEntry(&BB))
1454       MadeChange |= eliminateDeadStores(BB, AA, MD, DT, TLI);
1455 
1456   return MadeChange;
1457 }
1458 
1459 namespace {
1460 //=============================================================================
1461 // MemorySSA backed dead store elimination.
1462 //
1463 // The code below implements dead store elimination using MemorySSA. It uses
1464 // the following general approach: given a MemoryDef, walk upwards to find
1465 // clobbering MemoryDefs that may be killed by the starting def. Then check
1466 // that there are no uses that may read the location of the original MemoryDef
1467 // in between both MemoryDefs. A bit more concretely:
1468 //
1469 // For all MemoryDefs StartDef:
1470 // 1. Get the next dominating clobbering MemoryDef (EarlierAccess) by walking
1471 //    upwards.
1472 // 2. Check that there are no reads between EarlierAccess and the StartDef by
1473 //    checking all uses starting at EarlierAccess and walking until we see
1474 //    StartDef.
1475 // 3. For each found CurrentDef, check that:
1476 //   1. There are no barrier instructions between CurrentDef and StartDef (like
1477 //       throws or stores with ordering constraints).
1478 //   2. StartDef is executed whenever CurrentDef is executed.
1479 //   3. StartDef completely overwrites CurrentDef.
1480 // 4. Erase CurrentDef from the function and MemorySSA.
1481 
1482 // Returns true if \p M is an intrisnic that does not read or write memory.
1483 bool isNoopIntrinsic(MemoryUseOrDef *M) {
1484   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(M->getMemoryInst())) {
1485     switch (II->getIntrinsicID()) {
1486     case Intrinsic::lifetime_start:
1487     case Intrinsic::lifetime_end:
1488     case Intrinsic::invariant_end:
1489     case Intrinsic::launder_invariant_group:
1490     case Intrinsic::assume:
1491       return true;
1492     case Intrinsic::dbg_addr:
1493     case Intrinsic::dbg_declare:
1494     case Intrinsic::dbg_label:
1495     case Intrinsic::dbg_value:
1496       llvm_unreachable("Intrinsic should not be modeled in MemorySSA");
1497     default:
1498       return false;
1499     }
1500   }
1501   return false;
1502 }
1503 
1504 // Check if we can ignore \p D for DSE.
1505 bool canSkipDef(MemoryDef *D, bool DefVisibleToCaller) {
1506   Instruction *DI = D->getMemoryInst();
1507   // Calls that only access inaccessible memory cannot read or write any memory
1508   // locations we consider for elimination.
1509   if (auto *CB = dyn_cast<CallBase>(DI))
1510     if (CB->onlyAccessesInaccessibleMemory())
1511       return true;
1512 
1513   // We can eliminate stores to locations not visible to the caller across
1514   // throwing instructions.
1515   if (DI->mayThrow() && !DefVisibleToCaller)
1516     return true;
1517 
1518   // We can remove the dead stores, irrespective of the fence and its ordering
1519   // (release/acquire/seq_cst). Fences only constraints the ordering of
1520   // already visible stores, it does not make a store visible to other
1521   // threads. So, skipping over a fence does not change a store from being
1522   // dead.
1523   if (isa<FenceInst>(DI))
1524     return true;
1525 
1526   // Skip intrinsics that do not really read or modify memory.
1527   if (isNoopIntrinsic(D))
1528     return true;
1529 
1530   return false;
1531 }
1532 
1533 struct DSEState {
1534   Function &F;
1535   AliasAnalysis &AA;
1536 
1537   /// The single BatchAA instance that is used to cache AA queries. It will
1538   /// not be invalidated over the whole run. This is safe, because:
1539   /// 1. Only memory writes are removed, so the alias cache for memory
1540   ///    locations remains valid.
1541   /// 2. No new instructions are added (only instructions removed), so cached
1542   ///    information for a deleted value cannot be accessed by a re-used new
1543   ///    value pointer.
1544   BatchAAResults BatchAA;
1545 
1546   MemorySSA &MSSA;
1547   DominatorTree &DT;
1548   PostDominatorTree &PDT;
1549   const TargetLibraryInfo &TLI;
1550   const DataLayout &DL;
1551 
1552   // All MemoryDefs that potentially could kill other MemDefs.
1553   SmallVector<MemoryDef *, 64> MemDefs;
1554   // Any that should be skipped as they are already deleted
1555   SmallPtrSet<MemoryAccess *, 4> SkipStores;
1556   // Keep track of all of the objects that are invisible to the caller before
1557   // the function returns.
1558   // SmallPtrSet<const Value *, 16> InvisibleToCallerBeforeRet;
1559   DenseMap<const Value *, bool> InvisibleToCallerBeforeRet;
1560   // Keep track of all of the objects that are invisible to the caller after
1561   // the function returns.
1562   DenseMap<const Value *, bool> InvisibleToCallerAfterRet;
1563   // Keep track of blocks with throwing instructions not modeled in MemorySSA.
1564   SmallPtrSet<BasicBlock *, 16> ThrowingBlocks;
1565   // Post-order numbers for each basic block. Used to figure out if memory
1566   // accesses are executed before another access.
1567   DenseMap<BasicBlock *, unsigned> PostOrderNumbers;
1568 
1569   /// Keep track of instructions (partly) overlapping with killing MemoryDefs per
1570   /// basic block.
1571   DenseMap<BasicBlock *, InstOverlapIntervalsTy> IOLs;
1572 
1573   struct CheckCache {
1574     SmallPtrSet<MemoryAccess *, 16> KnownNoReads;
1575     SmallPtrSet<MemoryAccess *, 16> KnownReads;
1576 
1577     bool isKnownNoRead(MemoryAccess *A) const {
1578       return KnownNoReads.find(A) != KnownNoReads.end();
1579     }
1580     bool isKnownRead(MemoryAccess *A) const {
1581       return KnownReads.find(A) != KnownReads.end();
1582     }
1583   };
1584 
1585   DSEState(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, DominatorTree &DT,
1586            PostDominatorTree &PDT, const TargetLibraryInfo &TLI)
1587       : F(F), AA(AA), BatchAA(AA), MSSA(MSSA), DT(DT), PDT(PDT), TLI(TLI),
1588         DL(F.getParent()->getDataLayout()) {}
1589 
1590   static DSEState get(Function &F, AliasAnalysis &AA, MemorySSA &MSSA,
1591                       DominatorTree &DT, PostDominatorTree &PDT,
1592                       const TargetLibraryInfo &TLI) {
1593     DSEState State(F, AA, MSSA, DT, PDT, TLI);
1594     // Collect blocks with throwing instructions not modeled in MemorySSA and
1595     // alloc-like objects.
1596     unsigned PO = 0;
1597     for (BasicBlock *BB : post_order(&F)) {
1598       State.PostOrderNumbers[BB] = PO++;
1599       for (Instruction &I : *BB) {
1600         MemoryAccess *MA = MSSA.getMemoryAccess(&I);
1601         if (I.mayThrow() && !MA)
1602           State.ThrowingBlocks.insert(I.getParent());
1603 
1604         auto *MD = dyn_cast_or_null<MemoryDef>(MA);
1605         if (MD && State.MemDefs.size() < MemorySSADefsPerBlockLimit &&
1606             (State.getLocForWriteEx(&I) || State.isMemTerminatorInst(&I)))
1607           State.MemDefs.push_back(MD);
1608       }
1609     }
1610 
1611     // Treat byval or inalloca arguments the same as Allocas, stores to them are
1612     // dead at the end of the function.
1613     for (Argument &AI : F.args())
1614       if (AI.hasPassPointeeByValueCopyAttr()) {
1615         // For byval, the caller doesn't know the address of the allocation.
1616         if (AI.hasByValAttr())
1617           State.InvisibleToCallerBeforeRet.insert({&AI, true});
1618         State.InvisibleToCallerAfterRet.insert({&AI, true});
1619       }
1620 
1621     return State;
1622   }
1623 
1624   bool isInvisibleToCallerAfterRet(const Value *V) {
1625     if (isa<AllocaInst>(V))
1626       return true;
1627     auto I = InvisibleToCallerAfterRet.insert({V, false});
1628     if (I.second) {
1629       if (!isInvisibleToCallerBeforeRet(V)) {
1630         I.first->second = false;
1631       } else {
1632         auto *Inst = dyn_cast<Instruction>(V);
1633         if (Inst && isAllocLikeFn(Inst, &TLI))
1634           I.first->second = !PointerMayBeCaptured(V, true, false);
1635       }
1636     }
1637     return I.first->second;
1638   }
1639 
1640   bool isInvisibleToCallerBeforeRet(const Value *V) {
1641     if (isa<AllocaInst>(V))
1642       return true;
1643     auto I = InvisibleToCallerBeforeRet.insert({V, false});
1644     if (I.second) {
1645       auto *Inst = dyn_cast<Instruction>(V);
1646       if (Inst && isAllocLikeFn(Inst, &TLI))
1647         // NOTE: This could be made more precise by PointerMayBeCapturedBefore
1648         // with the killing MemoryDef. But we refrain from doing so for now to
1649         // limit compile-time and this does not cause any changes to the number
1650         // of stores removed on a large test set in practice.
1651         I.first->second = !PointerMayBeCaptured(V, false, true);
1652     }
1653     return I.first->second;
1654   }
1655 
1656   Optional<MemoryLocation> getLocForWriteEx(Instruction *I) const {
1657     if (!I->mayWriteToMemory())
1658       return None;
1659 
1660     if (auto *MTI = dyn_cast<AnyMemIntrinsic>(I))
1661       return {MemoryLocation::getForDest(MTI)};
1662 
1663     if (auto *CB = dyn_cast<CallBase>(I)) {
1664       LibFunc LF;
1665       if (TLI.getLibFunc(*CB, LF) && TLI.has(LF)) {
1666         switch (LF) {
1667         case LibFunc_strcpy:
1668         case LibFunc_strncpy:
1669         case LibFunc_strcat:
1670         case LibFunc_strncat:
1671           return {MemoryLocation(CB->getArgOperand(0))};
1672         default:
1673           break;
1674         }
1675       }
1676       switch (CB->getIntrinsicID()) {
1677       case Intrinsic::init_trampoline:
1678         return {MemoryLocation(CB->getArgOperand(0))};
1679       default:
1680         break;
1681       }
1682       return None;
1683     }
1684 
1685     return MemoryLocation::getOrNone(I);
1686   }
1687 
1688   /// Returns true if \p Use completely overwrites \p DefLoc.
1689   bool isCompleteOverwrite(MemoryLocation DefLoc, Instruction *UseInst) {
1690     // UseInst has a MemoryDef associated in MemorySSA. It's possible for a
1691     // MemoryDef to not write to memory, e.g. a volatile load is modeled as a
1692     // MemoryDef.
1693     if (!UseInst->mayWriteToMemory())
1694       return false;
1695 
1696     if (auto *CB = dyn_cast<CallBase>(UseInst))
1697       if (CB->onlyAccessesInaccessibleMemory())
1698         return false;
1699 
1700     int64_t InstWriteOffset, DepWriteOffset;
1701     auto CC = getLocForWriteEx(UseInst);
1702     return CC && isOverwrite(*CC, DefLoc, DL, TLI, DepWriteOffset,
1703                              InstWriteOffset, BatchAA, &F) == OW_Complete;
1704   }
1705 
1706   /// Returns true if \p Def is not read before returning from the function.
1707   bool isWriteAtEndOfFunction(MemoryDef *Def) {
1708     LLVM_DEBUG(dbgs() << "  Check if def " << *Def << " ("
1709                       << *Def->getMemoryInst()
1710                       << ") is at the end the function \n");
1711 
1712     auto MaybeLoc = getLocForWriteEx(Def->getMemoryInst());
1713     if (!MaybeLoc) {
1714       LLVM_DEBUG(dbgs() << "  ... could not get location for write.\n");
1715       return false;
1716     }
1717 
1718     SmallVector<MemoryAccess *, 4> WorkList;
1719     SmallPtrSet<MemoryAccess *, 8> Visited;
1720     auto PushMemUses = [&WorkList, &Visited](MemoryAccess *Acc) {
1721       if (!Visited.insert(Acc).second)
1722         return;
1723       for (Use &U : Acc->uses())
1724         WorkList.push_back(cast<MemoryAccess>(U.getUser()));
1725     };
1726     PushMemUses(Def);
1727     for (unsigned I = 0; I < WorkList.size(); I++) {
1728       if (WorkList.size() >= MemorySSAScanLimit) {
1729         LLVM_DEBUG(dbgs() << "  ... hit exploration limit.\n");
1730         return false;
1731       }
1732 
1733       MemoryAccess *UseAccess = WorkList[I];
1734       if (isa<MemoryPhi>(UseAccess)) {
1735         PushMemUses(UseAccess);
1736         continue;
1737       }
1738 
1739       // TODO: Checking for aliasing is expensive. Consider reducing the amount
1740       // of times this is called and/or caching it.
1741       Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst();
1742       if (isReadClobber(*MaybeLoc, UseInst)) {
1743         LLVM_DEBUG(dbgs() << "  ... hit read clobber " << *UseInst << ".\n");
1744         return false;
1745       }
1746 
1747       if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess))
1748         PushMemUses(UseDef);
1749     }
1750     return true;
1751   }
1752 
1753   /// If \p I is a memory  terminator like llvm.lifetime.end or free, return a
1754   /// pair with the MemoryLocation terminated by \p I and a boolean flag
1755   /// indicating whether \p I is a free-like call.
1756   Optional<std::pair<MemoryLocation, bool>>
1757   getLocForTerminator(Instruction *I) const {
1758     uint64_t Len;
1759     Value *Ptr;
1760     if (match(I, m_Intrinsic<Intrinsic::lifetime_end>(m_ConstantInt(Len),
1761                                                       m_Value(Ptr))))
1762       return {std::make_pair(MemoryLocation(Ptr, Len), false)};
1763 
1764     if (auto *CB = dyn_cast<CallBase>(I)) {
1765       if (isFreeCall(I, &TLI))
1766         return {std::make_pair(MemoryLocation(CB->getArgOperand(0)), true)};
1767     }
1768 
1769     return None;
1770   }
1771 
1772   /// Returns true if \p I is a memory terminator instruction like
1773   /// llvm.lifetime.end or free.
1774   bool isMemTerminatorInst(Instruction *I) const {
1775     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1776     return (II && II->getIntrinsicID() == Intrinsic::lifetime_end) ||
1777            isFreeCall(I, &TLI);
1778   }
1779 
1780   /// Returns true if \p MaybeTerm is a memory terminator for the same
1781   /// underlying object as \p DefLoc.
1782   bool isMemTerminator(MemoryLocation DefLoc, Instruction *MaybeTerm) {
1783     Optional<std::pair<MemoryLocation, bool>> MaybeTermLoc =
1784         getLocForTerminator(MaybeTerm);
1785 
1786     if (!MaybeTermLoc)
1787       return false;
1788 
1789     // If the terminator is a free-like call, all accesses to the underlying
1790     // object can be considered terminated.
1791     if (MaybeTermLoc->second)
1792       DefLoc = MemoryLocation(getUnderlyingObject(DefLoc.Ptr));
1793     return BatchAA.isMustAlias(MaybeTermLoc->first, DefLoc);
1794   }
1795 
1796   // Returns true if \p Use may read from \p DefLoc.
1797   bool isReadClobber(MemoryLocation DefLoc, Instruction *UseInst) {
1798     if (!UseInst->mayReadFromMemory())
1799       return false;
1800 
1801     if (auto *CB = dyn_cast<CallBase>(UseInst))
1802       if (CB->onlyAccessesInaccessibleMemory())
1803         return false;
1804 
1805     // NOTE: For calls, the number of stores removed could be slightly improved
1806     // by using AA.callCapturesBefore(UseInst, DefLoc, &DT), but that showed to
1807     // be expensive compared to the benefits in practice. For now, avoid more
1808     // expensive analysis to limit compile-time.
1809     return isRefSet(BatchAA.getModRefInfo(UseInst, DefLoc));
1810   }
1811 
1812   // Find a MemoryDef writing to \p DefLoc and dominating \p StartAccess, with
1813   // no read access between them or on any other path to a function exit block
1814   // if \p DefLoc is not accessible after the function returns. If there is no
1815   // such MemoryDef, return None. The returned value may not (completely)
1816   // overwrite \p DefLoc. Currently we bail out when we encounter an aliasing
1817   // MemoryUse (read).
1818   Optional<MemoryAccess *>
1819   getDomMemoryDef(MemoryDef *KillingDef, MemoryAccess *StartAccess,
1820                   MemoryLocation DefLoc, const Value *DefUO, CheckCache &Cache,
1821                   unsigned &ScanLimit, unsigned &WalkerStepLimit,
1822                   bool IsMemTerm, unsigned &PartialLimit) {
1823     if (ScanLimit == 0 || WalkerStepLimit == 0) {
1824       LLVM_DEBUG(dbgs() << "\n    ...  hit scan limit\n");
1825       return None;
1826     }
1827 
1828     MemoryAccess *Current = StartAccess;
1829     Instruction *KillingI = KillingDef->getMemoryInst();
1830     bool StepAgain;
1831     LLVM_DEBUG(dbgs() << "  trying to get dominating access for "
1832                       << *StartAccess << "\n");
1833 
1834     // Find the next clobbering Mod access for DefLoc, starting at StartAccess.
1835     do {
1836       StepAgain = false;
1837       // Reached TOP.
1838       if (MSSA.isLiveOnEntryDef(Current))
1839         return None;
1840 
1841       // Cost of a step. Accesses in the same block are more likely to be valid
1842       // candidates for elimination, hence consider them cheaper.
1843       unsigned StepCost = KillingDef->getBlock() == Current->getBlock()
1844                               ? MemorySSASameBBStepCost
1845                               : MemorySSAOtherBBStepCost;
1846       if (WalkerStepLimit <= StepCost)
1847         return None;
1848       WalkerStepLimit -= StepCost;
1849 
1850       // Return for MemoryPhis. They cannot be eliminated directly and the
1851       // caller is responsible for traversing them.
1852       if (isa<MemoryPhi>(Current))
1853         return Current;
1854 
1855       // Below, check if CurrentDef is a valid candidate to be eliminated by
1856       // KillingDef. If it is not, check the next candidate.
1857       MemoryDef *CurrentDef = cast<MemoryDef>(Current);
1858       Instruction *CurrentI = CurrentDef->getMemoryInst();
1859 
1860       if (canSkipDef(CurrentDef, !isInvisibleToCallerBeforeRet(DefUO))) {
1861         StepAgain = true;
1862         Current = CurrentDef->getDefiningAccess();
1863         continue;
1864       }
1865 
1866       // Before we try to remove anything, check for any extra throwing
1867       // instructions that block us from DSEing
1868       if (mayThrowBetween(KillingI, CurrentI, DefUO)) {
1869         LLVM_DEBUG(dbgs() << "  ... skip, may throw!\n");
1870         return None;
1871       }
1872 
1873       // Check for anything that looks like it will be a barrier to further
1874       // removal
1875       if (isDSEBarrier(DefUO, CurrentI)) {
1876         LLVM_DEBUG(dbgs() << "  ... skip, barrier\n");
1877         return None;
1878       }
1879 
1880       // If Current is known to be on path that reads DefLoc or is a read
1881       // clobber, bail out, as the path is not profitable. We skip this check
1882       // for intrinsic calls, because the code knows how to handle memcpy
1883       // intrinsics.
1884       if (!isa<IntrinsicInst>(CurrentI) &&
1885           (Cache.KnownReads.contains(Current) ||
1886            isReadClobber(DefLoc, CurrentI))) {
1887         Cache.KnownReads.insert(Current);
1888         return None;
1889       }
1890 
1891       // If Current cannot be analyzed or is not removable, check the next
1892       // candidate.
1893       if (!hasAnalyzableMemoryWrite(CurrentI, TLI) || !isRemovable(CurrentI)) {
1894         StepAgain = true;
1895         Current = CurrentDef->getDefiningAccess();
1896         continue;
1897       }
1898 
1899       // If Current does not have an analyzable write location, skip it
1900       auto CurrentLoc = getLocForWriteEx(CurrentI);
1901       if (!CurrentLoc) {
1902         StepAgain = true;
1903         Current = CurrentDef->getDefiningAccess();
1904         continue;
1905       }
1906 
1907       if (IsMemTerm) {
1908         // If the killing def is a memory terminator (e.g. lifetime.end), check
1909         // the next candidate if the current Current does not write the same
1910         // underlying object as the terminator.
1911         const Value *NIUnd = getUnderlyingObject(CurrentLoc->Ptr);
1912         if (DefUO != NIUnd) {
1913           StepAgain = true;
1914           Current = CurrentDef->getDefiningAccess();
1915         }
1916         continue;
1917       } else {
1918         int64_t InstWriteOffset, DepWriteOffset;
1919         auto OR = isOverwrite(DefLoc, *CurrentLoc, DL, TLI, DepWriteOffset,
1920                               InstWriteOffset, BatchAA, &F);
1921         // If Current does not write to the same object as KillingDef, check
1922         // the next candidate.
1923         if (OR == OW_Unknown) {
1924           StepAgain = true;
1925           Current = CurrentDef->getDefiningAccess();
1926         } else if (OR == OW_MaybePartial) {
1927           // If KillingDef only partially overwrites Current, check the next
1928           // candidate if the partial step limit is exceeded. This aggressively
1929           // limits the number of candidates for partial store elimination,
1930           // which are less likely to be removable in the end.
1931           if (PartialLimit <= 1) {
1932             StepAgain = true;
1933             Current = CurrentDef->getDefiningAccess();
1934             WalkerStepLimit -= 1;
1935             continue;
1936           }
1937           PartialLimit -= 1;
1938         }
1939       }
1940     } while (StepAgain);
1941 
1942     // Accesses to objects accessible after the function returns can only be
1943     // eliminated if the access is killed along all paths to the exit. Collect
1944     // the blocks with killing (=completely overwriting MemoryDefs) and check if
1945     // they cover all paths from EarlierAccess to any function exit.
1946     SmallPtrSet<Instruction *, 16> KillingDefs;
1947     KillingDefs.insert(KillingDef->getMemoryInst());
1948     MemoryAccess *EarlierAccess = Current;
1949     Instruction *EarlierMemInst =
1950         cast<MemoryDef>(EarlierAccess)->getMemoryInst();
1951     LLVM_DEBUG(dbgs() << "  Checking for reads of " << *EarlierAccess << " ("
1952                       << *EarlierMemInst << ")\n");
1953 
1954     SmallSetVector<MemoryAccess *, 32> WorkList;
1955     auto PushMemUses = [&WorkList](MemoryAccess *Acc) {
1956       for (Use &U : Acc->uses())
1957         WorkList.insert(cast<MemoryAccess>(U.getUser()));
1958     };
1959     PushMemUses(EarlierAccess);
1960 
1961     // Optimistically collect all accesses for reads. If we do not find any
1962     // read clobbers, add them to the cache.
1963     SmallPtrSet<MemoryAccess *, 16> KnownNoReads;
1964     if (!EarlierMemInst->mayReadFromMemory())
1965       KnownNoReads.insert(EarlierAccess);
1966     // Check if EarlierDef may be read.
1967     for (unsigned I = 0; I < WorkList.size(); I++) {
1968       MemoryAccess *UseAccess = WorkList[I];
1969 
1970       LLVM_DEBUG(dbgs() << "   " << *UseAccess);
1971       // Bail out if the number of accesses to check exceeds the scan limit.
1972       if (ScanLimit < (WorkList.size() - I)) {
1973         LLVM_DEBUG(dbgs() << "\n    ...  hit scan limit\n");
1974         return None;
1975       }
1976       --ScanLimit;
1977       NumDomMemDefChecks++;
1978 
1979       // Check if we already visited this access.
1980       if (Cache.isKnownNoRead(UseAccess)) {
1981         LLVM_DEBUG(dbgs() << " ... skip, discovered that " << *UseAccess
1982                           << " is safe earlier.\n");
1983         continue;
1984       }
1985       if (Cache.isKnownRead(UseAccess)) {
1986         LLVM_DEBUG(dbgs() << " ... bail out, discovered that " << *UseAccess
1987                           << " has a read-clobber earlier.\n");
1988         return None;
1989       }
1990       KnownNoReads.insert(UseAccess);
1991 
1992       if (isa<MemoryPhi>(UseAccess)) {
1993         if (any_of(KillingDefs, [this, UseAccess](Instruction *KI) {
1994               return DT.properlyDominates(KI->getParent(),
1995                                           UseAccess->getBlock());
1996             })) {
1997           LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing block\n");
1998           continue;
1999         }
2000         LLVM_DEBUG(dbgs() << "\n    ... adding PHI uses\n");
2001         PushMemUses(UseAccess);
2002         continue;
2003       }
2004 
2005       Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst();
2006       LLVM_DEBUG(dbgs() << " (" << *UseInst << ")\n");
2007 
2008       if (any_of(KillingDefs, [this, UseInst](Instruction *KI) {
2009             return DT.dominates(KI, UseInst);
2010           })) {
2011         LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing def\n");
2012         continue;
2013       }
2014 
2015       if (isNoopIntrinsic(cast<MemoryUseOrDef>(UseAccess))) {
2016         LLVM_DEBUG(dbgs() << "    ... adding uses of intrinsic\n");
2017         PushMemUses(UseAccess);
2018         continue;
2019       }
2020 
2021       // A memory terminator kills all preceeding MemoryDefs and all succeeding
2022       // MemoryAccesses. We do not have to check it's users.
2023       if (isMemTerminator(DefLoc, UseInst))
2024         continue;
2025 
2026       // Uses which may read the original MemoryDef mean we cannot eliminate the
2027       // original MD. Stop walk.
2028       if (isReadClobber(DefLoc, UseInst)) {
2029         LLVM_DEBUG(dbgs() << "    ... found read clobber\n");
2030         Cache.KnownReads.insert(UseAccess);
2031         Cache.KnownReads.insert(StartAccess);
2032         Cache.KnownReads.insert(EarlierAccess);
2033         return None;
2034       }
2035 
2036       // For the KillingDef and EarlierAccess we only have to check if it reads
2037       // the memory location.
2038       // TODO: It would probably be better to check for self-reads before
2039       // calling the function.
2040       if (KillingDef == UseAccess || EarlierAccess == UseAccess) {
2041         LLVM_DEBUG(dbgs() << "    ... skipping killing def/dom access\n");
2042         continue;
2043       }
2044 
2045       // Check all uses for MemoryDefs, except for defs completely overwriting
2046       // the original location. Otherwise we have to check uses of *all*
2047       // MemoryDefs we discover, including non-aliasing ones. Otherwise we might
2048       // miss cases like the following
2049       //   1 = Def(LoE) ; <----- EarlierDef stores [0,1]
2050       //   2 = Def(1)   ; (2, 1) = NoAlias,   stores [2,3]
2051       //   Use(2)       ; MayAlias 2 *and* 1, loads [0, 3].
2052       //                  (The Use points to the *first* Def it may alias)
2053       //   3 = Def(1)   ; <---- Current  (3, 2) = NoAlias, (3,1) = MayAlias,
2054       //                  stores [0,1]
2055       if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) {
2056         if (isCompleteOverwrite(DefLoc, UseInst)) {
2057           if (!isInvisibleToCallerAfterRet(DefUO) &&
2058               UseAccess != EarlierAccess) {
2059             BasicBlock *MaybeKillingBlock = UseInst->getParent();
2060             if (PostOrderNumbers.find(MaybeKillingBlock)->second <
2061                 PostOrderNumbers.find(EarlierAccess->getBlock())->second) {
2062 
2063               LLVM_DEBUG(dbgs()
2064                          << "    ... found killing def " << *UseInst << "\n");
2065               KillingDefs.insert(UseInst);
2066             }
2067           }
2068         } else
2069           PushMemUses(UseDef);
2070       }
2071     }
2072 
2073     // For accesses to locations visible after the function returns, make sure
2074     // that the location is killed (=overwritten) along all paths from
2075     // EarlierAccess to the exit.
2076     if (!isInvisibleToCallerAfterRet(DefUO)) {
2077       SmallPtrSet<BasicBlock *, 16> KillingBlocks;
2078       for (Instruction *KD : KillingDefs)
2079         KillingBlocks.insert(KD->getParent());
2080       assert(!KillingBlocks.empty() &&
2081              "Expected at least a single killing block");
2082 
2083       // Find the common post-dominator of all killing blocks.
2084       BasicBlock *CommonPred = *KillingBlocks.begin();
2085       for (auto I = std::next(KillingBlocks.begin()), E = KillingBlocks.end();
2086            I != E; I++) {
2087         if (!CommonPred)
2088           break;
2089         CommonPred = PDT.findNearestCommonDominator(CommonPred, *I);
2090       }
2091 
2092       // If CommonPred is in the set of killing blocks, just check if it
2093       // post-dominates EarlierAccess.
2094       if (KillingBlocks.count(CommonPred)) {
2095         if (PDT.dominates(CommonPred, EarlierAccess->getBlock()))
2096           return {EarlierAccess};
2097         return None;
2098       }
2099 
2100       // If the common post-dominator does not post-dominate EarlierAccess,
2101       // there is a path from EarlierAccess to an exit not going through a
2102       // killing block.
2103       if (PDT.dominates(CommonPred, EarlierAccess->getBlock())) {
2104         SetVector<BasicBlock *> WorkList;
2105 
2106         // If CommonPred is null, there are multiple exits from the function.
2107         // They all have to be added to the worklist.
2108         if (CommonPred)
2109           WorkList.insert(CommonPred);
2110         else
2111           for (BasicBlock *R : PDT.roots())
2112             WorkList.insert(R);
2113 
2114         NumCFGTries++;
2115         // Check if all paths starting from an exit node go through one of the
2116         // killing blocks before reaching EarlierAccess.
2117         for (unsigned I = 0; I < WorkList.size(); I++) {
2118           NumCFGChecks++;
2119           BasicBlock *Current = WorkList[I];
2120           if (KillingBlocks.count(Current))
2121             continue;
2122           if (Current == EarlierAccess->getBlock())
2123             return None;
2124 
2125           // EarlierAccess is reachable from the entry, so we don't have to
2126           // explore unreachable blocks further.
2127           if (!DT.isReachableFromEntry(Current))
2128             continue;
2129 
2130           for (BasicBlock *Pred : predecessors(Current))
2131             WorkList.insert(Pred);
2132 
2133           if (WorkList.size() >= MemorySSAPathCheckLimit)
2134             return None;
2135         }
2136         NumCFGSuccess++;
2137         return {EarlierAccess};
2138       }
2139       return None;
2140     }
2141 
2142     // No aliasing MemoryUses of EarlierAccess found, EarlierAccess is
2143     // potentially dead.
2144     Cache.KnownNoReads.insert(KnownNoReads.begin(), KnownNoReads.end());
2145     return {EarlierAccess};
2146   }
2147 
2148   // Delete dead memory defs
2149   void deleteDeadInstruction(Instruction *SI) {
2150     MemorySSAUpdater Updater(&MSSA);
2151     SmallVector<Instruction *, 32> NowDeadInsts;
2152     NowDeadInsts.push_back(SI);
2153     --NumFastOther;
2154 
2155     while (!NowDeadInsts.empty()) {
2156       Instruction *DeadInst = NowDeadInsts.pop_back_val();
2157       ++NumFastOther;
2158 
2159       // Try to preserve debug information attached to the dead instruction.
2160       salvageDebugInfo(*DeadInst);
2161       salvageKnowledge(DeadInst);
2162 
2163       // Remove the Instruction from MSSA.
2164       if (MemoryAccess *MA = MSSA.getMemoryAccess(DeadInst)) {
2165         if (MemoryDef *MD = dyn_cast<MemoryDef>(MA)) {
2166           SkipStores.insert(MD);
2167         }
2168         Updater.removeMemoryAccess(MA);
2169       }
2170 
2171       auto I = IOLs.find(DeadInst->getParent());
2172       if (I != IOLs.end())
2173         I->second.erase(DeadInst);
2174       // Remove its operands
2175       for (Use &O : DeadInst->operands())
2176         if (Instruction *OpI = dyn_cast<Instruction>(O)) {
2177           O = nullptr;
2178           if (isInstructionTriviallyDead(OpI, &TLI))
2179             NowDeadInsts.push_back(OpI);
2180         }
2181 
2182       DeadInst->eraseFromParent();
2183     }
2184   }
2185 
2186   // Check for any extra throws between SI and NI that block DSE.  This only
2187   // checks extra maythrows (those that aren't MemoryDef's). MemoryDef that may
2188   // throw are handled during the walk from one def to the next.
2189   bool mayThrowBetween(Instruction *SI, Instruction *NI,
2190                        const Value *SILocUnd) {
2191     // First see if we can ignore it by using the fact that SI is an
2192     // alloca/alloca like object that is not visible to the caller during
2193     // execution of the function.
2194     if (SILocUnd && isInvisibleToCallerBeforeRet(SILocUnd))
2195       return false;
2196 
2197     if (SI->getParent() == NI->getParent())
2198       return ThrowingBlocks.count(SI->getParent());
2199     return !ThrowingBlocks.empty();
2200   }
2201 
2202   // Check if \p NI acts as a DSE barrier for \p SI. The following instructions
2203   // act as barriers:
2204   //  * A memory instruction that may throw and \p SI accesses a non-stack
2205   //  object.
2206   //  * Atomic stores stronger that monotonic.
2207   bool isDSEBarrier(const Value *SILocUnd, Instruction *NI) {
2208     // If NI may throw it acts as a barrier, unless we are to an alloca/alloca
2209     // like object that does not escape.
2210     if (NI->mayThrow() && !isInvisibleToCallerBeforeRet(SILocUnd))
2211       return true;
2212 
2213     // If NI is an atomic load/store stronger than monotonic, do not try to
2214     // eliminate/reorder it.
2215     if (NI->isAtomic()) {
2216       if (auto *LI = dyn_cast<LoadInst>(NI))
2217         return isStrongerThanMonotonic(LI->getOrdering());
2218       if (auto *SI = dyn_cast<StoreInst>(NI))
2219         return isStrongerThanMonotonic(SI->getOrdering());
2220       if (auto *ARMW = dyn_cast<AtomicRMWInst>(NI))
2221         return isStrongerThanMonotonic(ARMW->getOrdering());
2222       if (auto *CmpXchg = dyn_cast<AtomicCmpXchgInst>(NI))
2223         return isStrongerThanMonotonic(CmpXchg->getSuccessOrdering()) ||
2224                isStrongerThanMonotonic(CmpXchg->getFailureOrdering());
2225       llvm_unreachable("other instructions should be skipped in MemorySSA");
2226     }
2227     return false;
2228   }
2229 
2230   /// Eliminate writes to objects that are not visible in the caller and are not
2231   /// accessed before returning from the function.
2232   bool eliminateDeadWritesAtEndOfFunction() {
2233     bool MadeChange = false;
2234     LLVM_DEBUG(
2235         dbgs()
2236         << "Trying to eliminate MemoryDefs at the end of the function\n");
2237     for (int I = MemDefs.size() - 1; I >= 0; I--) {
2238       MemoryDef *Def = MemDefs[I];
2239       if (SkipStores.find(Def) != SkipStores.end() ||
2240           !isRemovable(Def->getMemoryInst()))
2241         continue;
2242 
2243       Instruction *DefI = Def->getMemoryInst();
2244       SmallVector<const Value *, 4> Pointers;
2245       auto DefLoc = getLocForWriteEx(DefI);
2246       if (!DefLoc)
2247         continue;
2248 
2249       // NOTE: Currently eliminating writes at the end of a function is limited
2250       // to MemoryDefs with a single underlying object, to save compile-time. In
2251       // practice it appears the case with multiple underlying objects is very
2252       // uncommon. If it turns out to be important, we can use
2253       // getUnderlyingObjects here instead.
2254       const Value *UO = getUnderlyingObject(DefLoc->Ptr);
2255       if (!UO || !isInvisibleToCallerAfterRet(UO))
2256         continue;
2257 
2258       if (isWriteAtEndOfFunction(Def)) {
2259         // See through pointer-to-pointer bitcasts
2260         LLVM_DEBUG(dbgs() << "   ... MemoryDef is not accessed until the end "
2261                              "of the function\n");
2262         deleteDeadInstruction(DefI);
2263         ++NumFastStores;
2264         MadeChange = true;
2265       }
2266     }
2267     return MadeChange;
2268   }
2269 
2270   /// \returns true if \p Def is a no-op store, either because it
2271   /// directly stores back a loaded value or stores zero to a calloced object.
2272   bool storeIsNoop(MemoryDef *Def, MemoryLocation DefLoc, const Value *DefUO) {
2273     StoreInst *Store = dyn_cast<StoreInst>(Def->getMemoryInst());
2274     if (!Store)
2275       return false;
2276 
2277     if (auto *LoadI = dyn_cast<LoadInst>(Store->getOperand(0))) {
2278       if (LoadI->getPointerOperand() == Store->getOperand(1)) {
2279         auto *LoadAccess = MSSA.getMemoryAccess(LoadI)->getDefiningAccess();
2280         // If both accesses share the same defining access, no instructions
2281         // between them can modify the memory location.
2282         return LoadAccess == Def->getDefiningAccess();
2283       }
2284     }
2285 
2286     Constant *StoredConstant = dyn_cast<Constant>(Store->getOperand(0));
2287     if (StoredConstant && StoredConstant->isNullValue()) {
2288       auto *DefUOInst = dyn_cast<Instruction>(DefUO);
2289       if (DefUOInst && isCallocLikeFn(DefUOInst, &TLI)) {
2290         auto *UnderlyingDef = cast<MemoryDef>(MSSA.getMemoryAccess(DefUOInst));
2291         // If UnderlyingDef is the clobbering access of Def, no instructions
2292         // between them can modify the memory location.
2293         auto *ClobberDef =
2294             MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(Def);
2295         return UnderlyingDef == ClobberDef;
2296       }
2297     }
2298     return false;
2299   }
2300 };
2301 
2302 bool eliminateDeadStoresMemorySSA(Function &F, AliasAnalysis &AA,
2303                                   MemorySSA &MSSA, DominatorTree &DT,
2304                                   PostDominatorTree &PDT,
2305                                   const TargetLibraryInfo &TLI) {
2306   bool MadeChange = false;
2307 
2308   DSEState State = DSEState::get(F, AA, MSSA, DT, PDT, TLI);
2309   // For each store:
2310   for (unsigned I = 0; I < State.MemDefs.size(); I++) {
2311     MemoryDef *KillingDef = State.MemDefs[I];
2312     if (State.SkipStores.count(KillingDef))
2313       continue;
2314     Instruction *SI = KillingDef->getMemoryInst();
2315 
2316     auto MaybeSILoc = State.getLocForWriteEx(SI);
2317     if (State.isMemTerminatorInst(SI))
2318       MaybeSILoc = State.getLocForTerminator(SI).map(
2319           [](const std::pair<MemoryLocation, bool> &P) { return P.first; });
2320     else
2321       MaybeSILoc = State.getLocForWriteEx(SI);
2322 
2323     if (!MaybeSILoc) {
2324       LLVM_DEBUG(dbgs() << "Failed to find analyzable write location for "
2325                         << *SI << "\n");
2326       continue;
2327     }
2328     MemoryLocation SILoc = *MaybeSILoc;
2329     assert(SILoc.Ptr && "SILoc should not be null");
2330     const Value *SILocUnd = getUnderlyingObject(SILoc.Ptr);
2331 
2332     // Check if the store is a no-op.
2333     if (isRemovable(SI) && State.storeIsNoop(KillingDef, SILoc, SILocUnd)) {
2334       LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n  DEAD: " << *SI << '\n');
2335       State.deleteDeadInstruction(SI);
2336       NumRedundantStores++;
2337       MadeChange = true;
2338       continue;
2339     }
2340 
2341     MemoryAccess *Current = KillingDef;
2342     LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs killed by "
2343                       << *KillingDef << " (" << *SI << ")\n");
2344 
2345     unsigned ScanLimit = MemorySSAScanLimit;
2346     unsigned WalkerStepLimit = MemorySSAUpwardsStepLimit;
2347     unsigned PartialLimit = MemorySSAPartialStoreLimit;
2348     // Worklist of MemoryAccesses that may be killed by KillingDef.
2349     SetVector<MemoryAccess *> ToCheck;
2350     ToCheck.insert(KillingDef->getDefiningAccess());
2351 
2352     if (!SILocUnd)
2353       continue;
2354     bool IsMemTerm = State.isMemTerminatorInst(SI);
2355     DSEState::CheckCache Cache;
2356     // Check if MemoryAccesses in the worklist are killed by KillingDef.
2357     for (unsigned I = 0; I < ToCheck.size(); I++) {
2358       Current = ToCheck[I];
2359       if (State.SkipStores.count(Current))
2360         continue;
2361 
2362       Optional<MemoryAccess *> Next = State.getDomMemoryDef(
2363           KillingDef, Current, SILoc, SILocUnd, Cache, ScanLimit,
2364           WalkerStepLimit, IsMemTerm, PartialLimit);
2365 
2366       if (!Next) {
2367         LLVM_DEBUG(dbgs() << "  finished walk\n");
2368         continue;
2369       }
2370 
2371       MemoryAccess *EarlierAccess = *Next;
2372       LLVM_DEBUG(dbgs() << " Checking if we can kill " << *EarlierAccess);
2373       if (isa<MemoryPhi>(EarlierAccess)) {
2374         LLVM_DEBUG(dbgs() << "\n  ... adding incoming values to worklist\n");
2375         for (Value *V : cast<MemoryPhi>(EarlierAccess)->incoming_values()) {
2376           MemoryAccess *IncomingAccess = cast<MemoryAccess>(V);
2377           BasicBlock *IncomingBlock = IncomingAccess->getBlock();
2378           BasicBlock *PhiBlock = EarlierAccess->getBlock();
2379 
2380           // We only consider incoming MemoryAccesses that come before the
2381           // MemoryPhi. Otherwise we could discover candidates that do not
2382           // strictly dominate our starting def.
2383           if (State.PostOrderNumbers[IncomingBlock] >
2384               State.PostOrderNumbers[PhiBlock])
2385             ToCheck.insert(IncomingAccess);
2386         }
2387         continue;
2388       }
2389       MemoryDef *NextDef = dyn_cast<MemoryDef>(EarlierAccess);
2390       Instruction *NI = NextDef->getMemoryInst();
2391       LLVM_DEBUG(dbgs() << " (" << *NI << ")\n");
2392       ToCheck.insert(NextDef->getDefiningAccess());
2393       NumGetDomMemoryDefPassed++;
2394 
2395       if (!DebugCounter::shouldExecute(MemorySSACounter))
2396         continue;
2397 
2398       MemoryLocation NILoc = *State.getLocForWriteEx(NI);
2399 
2400       if (IsMemTerm) {
2401         const Value *NIUnd = getUnderlyingObject(NILoc.Ptr);
2402         if (SILocUnd != NIUnd)
2403           continue;
2404         LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: " << *NI
2405                           << "\n  KILLER: " << *SI << '\n');
2406         State.deleteDeadInstruction(NI);
2407         ++NumFastStores;
2408         MadeChange = true;
2409       } else {
2410         // Check if NI overwrites SI.
2411         int64_t InstWriteOffset, DepWriteOffset;
2412         OverwriteResult OR =
2413             isOverwrite(SILoc, NILoc, State.DL, TLI, DepWriteOffset,
2414                         InstWriteOffset, State.BatchAA, &F);
2415         if (OR == OW_MaybePartial) {
2416           auto Iter = State.IOLs.insert(
2417               std::make_pair<BasicBlock *, InstOverlapIntervalsTy>(
2418                   NI->getParent(), InstOverlapIntervalsTy()));
2419           auto &IOL = Iter.first->second;
2420           OR = isPartialOverwrite(SILoc, NILoc, DepWriteOffset, InstWriteOffset,
2421                                   NI, IOL);
2422         }
2423 
2424         if (EnablePartialStoreMerging && OR == OW_PartialEarlierWithFullLater) {
2425           auto *Earlier = dyn_cast<StoreInst>(NI);
2426           auto *Later = dyn_cast<StoreInst>(SI);
2427           // We are re-using tryToMergePartialOverlappingStores, which requires
2428           // Earlier to domiante Later.
2429           // TODO: implement tryToMergeParialOverlappingStores using MemorySSA.
2430           if (Earlier && Later && DT.dominates(Earlier, Later)) {
2431             if (Constant *Merged = tryToMergePartialOverlappingStores(
2432                     Earlier, Later, InstWriteOffset, DepWriteOffset, State.DL,
2433                     State.BatchAA, &DT)) {
2434 
2435               // Update stored value of earlier store to merged constant.
2436               Earlier->setOperand(0, Merged);
2437               ++NumModifiedStores;
2438               MadeChange = true;
2439 
2440               // Remove later store and remove any outstanding overlap intervals
2441               // for the updated store.
2442               State.deleteDeadInstruction(Later);
2443               auto I = State.IOLs.find(Earlier->getParent());
2444               if (I != State.IOLs.end())
2445                 I->second.erase(Earlier);
2446               break;
2447             }
2448           }
2449         }
2450 
2451         if (OR == OW_Complete) {
2452           LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: " << *NI
2453                             << "\n  KILLER: " << *SI << '\n');
2454           State.deleteDeadInstruction(NI);
2455           ++NumFastStores;
2456           MadeChange = true;
2457         }
2458       }
2459     }
2460   }
2461 
2462   if (EnablePartialOverwriteTracking)
2463     for (auto &KV : State.IOLs)
2464       MadeChange |= removePartiallyOverlappedStores(State.DL, KV.second);
2465 
2466   MadeChange |= State.eliminateDeadWritesAtEndOfFunction();
2467   return MadeChange;
2468 }
2469 } // end anonymous namespace
2470 
2471 //===----------------------------------------------------------------------===//
2472 // DSE Pass
2473 //===----------------------------------------------------------------------===//
2474 PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) {
2475   AliasAnalysis &AA = AM.getResult<AAManager>(F);
2476   const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2477   DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
2478 
2479   bool Changed = false;
2480   if (EnableMemorySSA) {
2481     MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2482     PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
2483 
2484     Changed = eliminateDeadStoresMemorySSA(F, AA, MSSA, DT, PDT, TLI);
2485   } else {
2486     MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
2487 
2488     Changed = eliminateDeadStores(F, &AA, &MD, &DT, &TLI);
2489   }
2490 
2491 #ifdef LLVM_ENABLE_STATS
2492   if (AreStatisticsEnabled())
2493     for (auto &I : instructions(F))
2494       NumRemainingStores += isa<StoreInst>(&I);
2495 #endif
2496 
2497   if (!Changed)
2498     return PreservedAnalyses::all();
2499 
2500   PreservedAnalyses PA;
2501   PA.preserveSet<CFGAnalyses>();
2502   PA.preserve<GlobalsAA>();
2503   if (EnableMemorySSA)
2504     PA.preserve<MemorySSAAnalysis>();
2505   else
2506     PA.preserve<MemoryDependenceAnalysis>();
2507   return PA;
2508 }
2509 
2510 namespace {
2511 
2512 /// A legacy pass for the legacy pass manager that wraps \c DSEPass.
2513 class DSELegacyPass : public FunctionPass {
2514 public:
2515   static char ID; // Pass identification, replacement for typeid
2516 
2517   DSELegacyPass() : FunctionPass(ID) {
2518     initializeDSELegacyPassPass(*PassRegistry::getPassRegistry());
2519   }
2520 
2521   bool runOnFunction(Function &F) override {
2522     if (skipFunction(F))
2523       return false;
2524 
2525     AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2526     DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2527     const TargetLibraryInfo &TLI =
2528         getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2529 
2530     bool Changed = false;
2531     if (EnableMemorySSA) {
2532       MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2533       PostDominatorTree &PDT =
2534           getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
2535 
2536       Changed = eliminateDeadStoresMemorySSA(F, AA, MSSA, DT, PDT, TLI);
2537     } else {
2538       MemoryDependenceResults &MD =
2539           getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
2540 
2541       Changed = eliminateDeadStores(F, &AA, &MD, &DT, &TLI);
2542     }
2543 
2544 #ifdef LLVM_ENABLE_STATS
2545     if (AreStatisticsEnabled())
2546       for (auto &I : instructions(F))
2547         NumRemainingStores += isa<StoreInst>(&I);
2548 #endif
2549 
2550     return Changed;
2551   }
2552 
2553   void getAnalysisUsage(AnalysisUsage &AU) const override {
2554     AU.setPreservesCFG();
2555     AU.addRequired<AAResultsWrapperPass>();
2556     AU.addRequired<TargetLibraryInfoWrapperPass>();
2557     AU.addPreserved<GlobalsAAWrapperPass>();
2558     AU.addRequired<DominatorTreeWrapperPass>();
2559     AU.addPreserved<DominatorTreeWrapperPass>();
2560 
2561     if (EnableMemorySSA) {
2562       AU.addRequired<PostDominatorTreeWrapperPass>();
2563       AU.addRequired<MemorySSAWrapperPass>();
2564       AU.addPreserved<PostDominatorTreeWrapperPass>();
2565       AU.addPreserved<MemorySSAWrapperPass>();
2566     } else {
2567       AU.addRequired<MemoryDependenceWrapperPass>();
2568       AU.addPreserved<MemoryDependenceWrapperPass>();
2569     }
2570   }
2571 };
2572 
2573 } // end anonymous namespace
2574 
2575 char DSELegacyPass::ID = 0;
2576 
2577 INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false,
2578                       false)
2579 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2580 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
2581 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2582 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
2583 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
2584 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
2585 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2586 INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false,
2587                     false)
2588 
2589 FunctionPass *llvm::createDeadStoreEliminationPass() {
2590   return new DSELegacyPass();
2591 }
2592