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