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