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