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