1 //===- MemorySSA.cpp - Memory SSA Builder ---------------------------------===//
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 the MemorySSA class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Analysis/MemorySSA.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/DenseMapInfo.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/DepthFirstIterator.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/iterator.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/IteratedDominanceFrontier.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Config/llvm-config.h"
30 #include "llvm/IR/AssemblyAnnotationWriter.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Intrinsics.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/PassManager.h"
40 #include "llvm/IR/Use.h"
41 #include "llvm/InitializePasses.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/AtomicOrdering.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FormattedStream.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include <algorithm>
52 #include <cassert>
53 #include <cstdlib>
54 #include <iterator>
55 #include <memory>
56 #include <utility>
57 
58 using namespace llvm;
59 
60 #define DEBUG_TYPE "memoryssa"
61 
62 INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
63                       true)
64 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
65 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
66 INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
67                     true)
68 
69 INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
70                       "Memory SSA Printer", false, false)
71 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
72 INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
73                     "Memory SSA Printer", false, false)
74 
75 static cl::opt<unsigned> MaxCheckLimit(
76     "memssa-check-limit", cl::Hidden, cl::init(100),
77     cl::desc("The maximum number of stores/phis MemorySSA"
78              "will consider trying to walk past (default = 100)"));
79 
80 // Always verify MemorySSA if expensive checking is enabled.
81 #ifdef EXPENSIVE_CHECKS
82 bool llvm::VerifyMemorySSA = true;
83 #else
84 bool llvm::VerifyMemorySSA = false;
85 #endif
86 /// Enables memory ssa as a dependency for loop passes in legacy pass manager.
87 cl::opt<bool> llvm::EnableMSSALoopDependency(
88     "enable-mssa-loop-dependency", cl::Hidden, cl::init(true),
89     cl::desc("Enable MemorySSA dependency for loop pass manager"));
90 
91 static cl::opt<bool, true>
92     VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA),
93                      cl::Hidden, cl::desc("Enable verification of MemorySSA."));
94 
95 namespace llvm {
96 
97 /// An assembly annotator class to print Memory SSA information in
98 /// comments.
99 class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
100   friend class MemorySSA;
101 
102   const MemorySSA *MSSA;
103 
104 public:
105   MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
106 
107   void emitBasicBlockStartAnnot(const BasicBlock *BB,
108                                 formatted_raw_ostream &OS) override {
109     if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
110       OS << "; " << *MA << "\n";
111   }
112 
113   void emitInstructionAnnot(const Instruction *I,
114                             formatted_raw_ostream &OS) override {
115     if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
116       OS << "; " << *MA << "\n";
117   }
118 };
119 
120 } // end namespace llvm
121 
122 namespace {
123 
124 /// Our current alias analysis API differentiates heavily between calls and
125 /// non-calls, and functions called on one usually assert on the other.
126 /// This class encapsulates the distinction to simplify other code that wants
127 /// "Memory affecting instructions and related data" to use as a key.
128 /// For example, this class is used as a densemap key in the use optimizer.
129 class MemoryLocOrCall {
130 public:
131   bool IsCall = false;
132 
133   MemoryLocOrCall(MemoryUseOrDef *MUD)
134       : MemoryLocOrCall(MUD->getMemoryInst()) {}
135   MemoryLocOrCall(const MemoryUseOrDef *MUD)
136       : MemoryLocOrCall(MUD->getMemoryInst()) {}
137 
138   MemoryLocOrCall(Instruction *Inst) {
139     if (auto *C = dyn_cast<CallBase>(Inst)) {
140       IsCall = true;
141       Call = C;
142     } else {
143       IsCall = false;
144       // There is no such thing as a memorylocation for a fence inst, and it is
145       // unique in that regard.
146       if (!isa<FenceInst>(Inst))
147         Loc = MemoryLocation::get(Inst);
148     }
149   }
150 
151   explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {}
152 
153   const CallBase *getCall() const {
154     assert(IsCall);
155     return Call;
156   }
157 
158   MemoryLocation getLoc() const {
159     assert(!IsCall);
160     return Loc;
161   }
162 
163   bool operator==(const MemoryLocOrCall &Other) const {
164     if (IsCall != Other.IsCall)
165       return false;
166 
167     if (!IsCall)
168       return Loc == Other.Loc;
169 
170     if (Call->getCalledOperand() != Other.Call->getCalledOperand())
171       return false;
172 
173     return Call->arg_size() == Other.Call->arg_size() &&
174            std::equal(Call->arg_begin(), Call->arg_end(),
175                       Other.Call->arg_begin());
176   }
177 
178 private:
179   union {
180     const CallBase *Call;
181     MemoryLocation Loc;
182   };
183 };
184 
185 } // end anonymous namespace
186 
187 namespace llvm {
188 
189 template <> struct DenseMapInfo<MemoryLocOrCall> {
190   static inline MemoryLocOrCall getEmptyKey() {
191     return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
192   }
193 
194   static inline MemoryLocOrCall getTombstoneKey() {
195     return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
196   }
197 
198   static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
199     if (!MLOC.IsCall)
200       return hash_combine(
201           MLOC.IsCall,
202           DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
203 
204     hash_code hash =
205         hash_combine(MLOC.IsCall, DenseMapInfo<const Value *>::getHashValue(
206                                       MLOC.getCall()->getCalledOperand()));
207 
208     for (const Value *Arg : MLOC.getCall()->args())
209       hash = hash_combine(hash, DenseMapInfo<const Value *>::getHashValue(Arg));
210     return hash;
211   }
212 
213   static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
214     return LHS == RHS;
215   }
216 };
217 
218 } // end namespace llvm
219 
220 /// This does one-way checks to see if Use could theoretically be hoisted above
221 /// MayClobber. This will not check the other way around.
222 ///
223 /// This assumes that, for the purposes of MemorySSA, Use comes directly after
224 /// MayClobber, with no potentially clobbering operations in between them.
225 /// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
226 static bool areLoadsReorderable(const LoadInst *Use,
227                                 const LoadInst *MayClobber) {
228   bool VolatileUse = Use->isVolatile();
229   bool VolatileClobber = MayClobber->isVolatile();
230   // Volatile operations may never be reordered with other volatile operations.
231   if (VolatileUse && VolatileClobber)
232     return false;
233   // Otherwise, volatile doesn't matter here. From the language reference:
234   // 'optimizers may change the order of volatile operations relative to
235   // non-volatile operations.'"
236 
237   // If a load is seq_cst, it cannot be moved above other loads. If its ordering
238   // is weaker, it can be moved above other loads. We just need to be sure that
239   // MayClobber isn't an acquire load, because loads can't be moved above
240   // acquire loads.
241   //
242   // Note that this explicitly *does* allow the free reordering of monotonic (or
243   // weaker) loads of the same address.
244   bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
245   bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
246                                                      AtomicOrdering::Acquire);
247   return !(SeqCstUse || MayClobberIsAcquire);
248 }
249 
250 namespace {
251 
252 struct ClobberAlias {
253   bool IsClobber;
254   Optional<AliasResult> AR;
255 };
256 
257 } // end anonymous namespace
258 
259 // Return a pair of {IsClobber (bool), AR (AliasResult)}. It relies on AR being
260 // ignored if IsClobber = false.
261 template <typename AliasAnalysisType>
262 static ClobberAlias
263 instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc,
264                          const Instruction *UseInst, AliasAnalysisType &AA) {
265   Instruction *DefInst = MD->getMemoryInst();
266   assert(DefInst && "Defining instruction not actually an instruction");
267   const auto *UseCall = dyn_cast<CallBase>(UseInst);
268   Optional<AliasResult> AR;
269 
270   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
271     // These intrinsics will show up as affecting memory, but they are just
272     // markers, mostly.
273     //
274     // FIXME: We probably don't actually want MemorySSA to model these at all
275     // (including creating MemoryAccesses for them): we just end up inventing
276     // clobbers where they don't really exist at all. Please see D43269 for
277     // context.
278     switch (II->getIntrinsicID()) {
279     case Intrinsic::lifetime_start:
280       if (UseCall)
281         return {false, NoAlias};
282       AR = AA.alias(MemoryLocation(II->getArgOperand(1)), UseLoc);
283       return {AR != NoAlias, AR};
284     case Intrinsic::lifetime_end:
285     case Intrinsic::invariant_start:
286     case Intrinsic::invariant_end:
287     case Intrinsic::assume:
288       return {false, NoAlias};
289     case Intrinsic::dbg_addr:
290     case Intrinsic::dbg_declare:
291     case Intrinsic::dbg_label:
292     case Intrinsic::dbg_value:
293       llvm_unreachable("debuginfo shouldn't have associated defs!");
294     default:
295       break;
296     }
297   }
298 
299   if (UseCall) {
300     ModRefInfo I = AA.getModRefInfo(DefInst, UseCall);
301     AR = isMustSet(I) ? MustAlias : MayAlias;
302     return {isModOrRefSet(I), AR};
303   }
304 
305   if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
306     if (auto *UseLoad = dyn_cast<LoadInst>(UseInst))
307       return {!areLoadsReorderable(UseLoad, DefLoad), MayAlias};
308 
309   ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
310   AR = isMustSet(I) ? MustAlias : MayAlias;
311   return {isModSet(I), AR};
312 }
313 
314 template <typename AliasAnalysisType>
315 static ClobberAlias instructionClobbersQuery(MemoryDef *MD,
316                                              const MemoryUseOrDef *MU,
317                                              const MemoryLocOrCall &UseMLOC,
318                                              AliasAnalysisType &AA) {
319   // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
320   // to exist while MemoryLocOrCall is pushed through places.
321   if (UseMLOC.IsCall)
322     return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
323                                     AA);
324   return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
325                                   AA);
326 }
327 
328 // Return true when MD may alias MU, return false otherwise.
329 bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
330                                         AliasAnalysis &AA) {
331   return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA).IsClobber;
332 }
333 
334 namespace {
335 
336 struct UpwardsMemoryQuery {
337   // True if our original query started off as a call
338   bool IsCall = false;
339   // The pointer location we started the query with. This will be empty if
340   // IsCall is true.
341   MemoryLocation StartingLoc;
342   // This is the instruction we were querying about.
343   const Instruction *Inst = nullptr;
344   // The MemoryAccess we actually got called with, used to test local domination
345   const MemoryAccess *OriginalAccess = nullptr;
346   Optional<AliasResult> AR = MayAlias;
347   bool SkipSelfAccess = false;
348 
349   UpwardsMemoryQuery() = default;
350 
351   UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
352       : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) {
353     if (!IsCall)
354       StartingLoc = MemoryLocation::get(Inst);
355   }
356 };
357 
358 } // end anonymous namespace
359 
360 static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
361                            BatchAAResults &AA) {
362   Instruction *Inst = MD->getMemoryInst();
363   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
364     switch (II->getIntrinsicID()) {
365     case Intrinsic::lifetime_end:
366       return AA.alias(MemoryLocation(II->getArgOperand(1)), Loc) == MustAlias;
367     default:
368       return false;
369     }
370   }
371   return false;
372 }
373 
374 template <typename AliasAnalysisType>
375 static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA,
376                                                    const Instruction *I) {
377   // If the memory can't be changed, then loads of the memory can't be
378   // clobbered.
379   return isa<LoadInst>(I) && (I->hasMetadata(LLVMContext::MD_invariant_load) ||
380                               AA.pointsToConstantMemory(MemoryLocation(
381                                   cast<LoadInst>(I)->getPointerOperand())));
382 }
383 
384 /// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
385 /// inbetween `Start` and `ClobberAt` can clobbers `Start`.
386 ///
387 /// This is meant to be as simple and self-contained as possible. Because it
388 /// uses no cache, etc., it can be relatively expensive.
389 ///
390 /// \param Start     The MemoryAccess that we want to walk from.
391 /// \param ClobberAt A clobber for Start.
392 /// \param StartLoc  The MemoryLocation for Start.
393 /// \param MSSA      The MemorySSA instance that Start and ClobberAt belong to.
394 /// \param Query     The UpwardsMemoryQuery we used for our search.
395 /// \param AA        The AliasAnalysis we used for our search.
396 /// \param AllowImpreciseClobber Always false, unless we do relaxed verify.
397 
398 template <typename AliasAnalysisType>
399 LLVM_ATTRIBUTE_UNUSED static void
400 checkClobberSanity(const MemoryAccess *Start, MemoryAccess *ClobberAt,
401                    const MemoryLocation &StartLoc, const MemorySSA &MSSA,
402                    const UpwardsMemoryQuery &Query, AliasAnalysisType &AA,
403                    bool AllowImpreciseClobber = false) {
404   assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
405 
406   if (MSSA.isLiveOnEntryDef(Start)) {
407     assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
408            "liveOnEntry must clobber itself");
409     return;
410   }
411 
412   bool FoundClobber = false;
413   DenseSet<ConstMemoryAccessPair> VisitedPhis;
414   SmallVector<ConstMemoryAccessPair, 8> Worklist;
415   Worklist.emplace_back(Start, StartLoc);
416   // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
417   // is found, complain.
418   while (!Worklist.empty()) {
419     auto MAP = Worklist.pop_back_val();
420     // All we care about is that nothing from Start to ClobberAt clobbers Start.
421     // We learn nothing from revisiting nodes.
422     if (!VisitedPhis.insert(MAP).second)
423       continue;
424 
425     for (const auto *MA : def_chain(MAP.first)) {
426       if (MA == ClobberAt) {
427         if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
428           // instructionClobbersQuery isn't essentially free, so don't use `|=`,
429           // since it won't let us short-circuit.
430           //
431           // Also, note that this can't be hoisted out of the `Worklist` loop,
432           // since MD may only act as a clobber for 1 of N MemoryLocations.
433           FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD);
434           if (!FoundClobber) {
435             ClobberAlias CA =
436                 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
437             if (CA.IsClobber) {
438               FoundClobber = true;
439               // Not used: CA.AR;
440             }
441           }
442         }
443         break;
444       }
445 
446       // We should never hit liveOnEntry, unless it's the clobber.
447       assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
448 
449       if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
450         // If Start is a Def, skip self.
451         if (MD == Start)
452           continue;
453 
454         assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA)
455                     .IsClobber &&
456                "Found clobber before reaching ClobberAt!");
457         continue;
458       }
459 
460       if (const auto *MU = dyn_cast<MemoryUse>(MA)) {
461         (void)MU;
462         assert (MU == Start &&
463                 "Can only find use in def chain if Start is a use");
464         continue;
465       }
466 
467       assert(isa<MemoryPhi>(MA));
468       Worklist.append(
469           upward_defs_begin({const_cast<MemoryAccess *>(MA), MAP.second},
470                             MSSA.getDomTree()),
471           upward_defs_end());
472     }
473   }
474 
475   // If the verify is done following an optimization, it's possible that
476   // ClobberAt was a conservative clobbering, that we can now infer is not a
477   // true clobbering access. Don't fail the verify if that's the case.
478   // We do have accesses that claim they're optimized, but could be optimized
479   // further. Updating all these can be expensive, so allow it for now (FIXME).
480   if (AllowImpreciseClobber)
481     return;
482 
483   // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
484   // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
485   assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
486          "ClobberAt never acted as a clobber");
487 }
488 
489 namespace {
490 
491 /// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
492 /// in one class.
493 template <class AliasAnalysisType> class ClobberWalker {
494   /// Save a few bytes by using unsigned instead of size_t.
495   using ListIndex = unsigned;
496 
497   /// Represents a span of contiguous MemoryDefs, potentially ending in a
498   /// MemoryPhi.
499   struct DefPath {
500     MemoryLocation Loc;
501     // Note that, because we always walk in reverse, Last will always dominate
502     // First. Also note that First and Last are inclusive.
503     MemoryAccess *First;
504     MemoryAccess *Last;
505     Optional<ListIndex> Previous;
506 
507     DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
508             Optional<ListIndex> Previous)
509         : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
510 
511     DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
512             Optional<ListIndex> Previous)
513         : DefPath(Loc, Init, Init, Previous) {}
514   };
515 
516   const MemorySSA &MSSA;
517   AliasAnalysisType &AA;
518   DominatorTree &DT;
519   UpwardsMemoryQuery *Query;
520   unsigned *UpwardWalkLimit;
521 
522   // Phi optimization bookkeeping:
523   // List of DefPath to process during the current phi optimization walk.
524   SmallVector<DefPath, 32> Paths;
525   // List of visited <Access, Location> pairs; we can skip paths already
526   // visited with the same memory location.
527   DenseSet<ConstMemoryAccessPair> VisitedPhis;
528   // Record if phi translation has been performed during the current phi
529   // optimization walk, as merging alias results after phi translation can
530   // yield incorrect results. Context in PR46156.
531   bool PerformedPhiTranslation = false;
532 
533   /// Find the nearest def or phi that `From` can legally be optimized to.
534   const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
535     assert(From->getNumOperands() && "Phi with no operands?");
536 
537     BasicBlock *BB = From->getBlock();
538     MemoryAccess *Result = MSSA.getLiveOnEntryDef();
539     DomTreeNode *Node = DT.getNode(BB);
540     while ((Node = Node->getIDom())) {
541       auto *Defs = MSSA.getBlockDefs(Node->getBlock());
542       if (Defs)
543         return &*Defs->rbegin();
544     }
545     return Result;
546   }
547 
548   /// Result of calling walkToPhiOrClobber.
549   struct UpwardsWalkResult {
550     /// The "Result" of the walk. Either a clobber, the last thing we walked, or
551     /// both. Include alias info when clobber found.
552     MemoryAccess *Result;
553     bool IsKnownClobber;
554     Optional<AliasResult> AR;
555   };
556 
557   /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
558   /// This will update Desc.Last as it walks. It will (optionally) also stop at
559   /// StopAt.
560   ///
561   /// This does not test for whether StopAt is a clobber
562   UpwardsWalkResult
563   walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr,
564                      const MemoryAccess *SkipStopAt = nullptr) const {
565     assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
566     assert(UpwardWalkLimit && "Need a valid walk limit");
567     bool LimitAlreadyReached = false;
568     // (*UpwardWalkLimit) may be 0 here, due to the loop in tryOptimizePhi. Set
569     // it to 1. This will not do any alias() calls. It either returns in the
570     // first iteration in the loop below, or is set back to 0 if all def chains
571     // are free of MemoryDefs.
572     if (!*UpwardWalkLimit) {
573       *UpwardWalkLimit = 1;
574       LimitAlreadyReached = true;
575     }
576 
577     for (MemoryAccess *Current : def_chain(Desc.Last)) {
578       Desc.Last = Current;
579       if (Current == StopAt || Current == SkipStopAt)
580         return {Current, false, MayAlias};
581 
582       if (auto *MD = dyn_cast<MemoryDef>(Current)) {
583         if (MSSA.isLiveOnEntryDef(MD))
584           return {MD, true, MustAlias};
585 
586         if (!--*UpwardWalkLimit)
587           return {Current, true, MayAlias};
588 
589         ClobberAlias CA =
590             instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA);
591         if (CA.IsClobber)
592           return {MD, true, CA.AR};
593       }
594     }
595 
596     if (LimitAlreadyReached)
597       *UpwardWalkLimit = 0;
598 
599     assert(isa<MemoryPhi>(Desc.Last) &&
600            "Ended at a non-clobber that's not a phi?");
601     return {Desc.Last, false, MayAlias};
602   }
603 
604   void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
605                    ListIndex PriorNode) {
606     auto UpwardDefsBegin = upward_defs_begin({Phi, Paths[PriorNode].Loc}, DT,
607                                              &PerformedPhiTranslation);
608     auto UpwardDefs = make_range(UpwardDefsBegin, upward_defs_end());
609     for (const MemoryAccessPair &P : UpwardDefs) {
610       PausedSearches.push_back(Paths.size());
611       Paths.emplace_back(P.second, P.first, PriorNode);
612     }
613   }
614 
615   /// Represents a search that terminated after finding a clobber. This clobber
616   /// may or may not be present in the path of defs from LastNode..SearchStart,
617   /// since it may have been retrieved from cache.
618   struct TerminatedPath {
619     MemoryAccess *Clobber;
620     ListIndex LastNode;
621   };
622 
623   /// Get an access that keeps us from optimizing to the given phi.
624   ///
625   /// PausedSearches is an array of indices into the Paths array. Its incoming
626   /// value is the indices of searches that stopped at the last phi optimization
627   /// target. It's left in an unspecified state.
628   ///
629   /// If this returns None, NewPaused is a vector of searches that terminated
630   /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
631   Optional<TerminatedPath>
632   getBlockingAccess(const MemoryAccess *StopWhere,
633                     SmallVectorImpl<ListIndex> &PausedSearches,
634                     SmallVectorImpl<ListIndex> &NewPaused,
635                     SmallVectorImpl<TerminatedPath> &Terminated) {
636     assert(!PausedSearches.empty() && "No searches to continue?");
637 
638     // BFS vs DFS really doesn't make a difference here, so just do a DFS with
639     // PausedSearches as our stack.
640     while (!PausedSearches.empty()) {
641       ListIndex PathIndex = PausedSearches.pop_back_val();
642       DefPath &Node = Paths[PathIndex];
643 
644       // If we've already visited this path with this MemoryLocation, we don't
645       // need to do so again.
646       //
647       // NOTE: That we just drop these paths on the ground makes caching
648       // behavior sporadic. e.g. given a diamond:
649       //  A
650       // B C
651       //  D
652       //
653       // ...If we walk D, B, A, C, we'll only cache the result of phi
654       // optimization for A, B, and D; C will be skipped because it dies here.
655       // This arguably isn't the worst thing ever, since:
656       //   - We generally query things in a top-down order, so if we got below D
657       //     without needing cache entries for {C, MemLoc}, then chances are
658       //     that those cache entries would end up ultimately unused.
659       //   - We still cache things for A, so C only needs to walk up a bit.
660       // If this behavior becomes problematic, we can fix without a ton of extra
661       // work.
662       if (!VisitedPhis.insert({Node.Last, Node.Loc}).second) {
663         if (PerformedPhiTranslation) {
664           // If visiting this path performed Phi translation, don't continue,
665           // since it may not be correct to merge results from two paths if one
666           // relies on the phi translation.
667           TerminatedPath Term{Node.Last, PathIndex};
668           return Term;
669         }
670         continue;
671       }
672 
673       const MemoryAccess *SkipStopWhere = nullptr;
674       if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) {
675         assert(isa<MemoryDef>(Query->OriginalAccess));
676         SkipStopWhere = Query->OriginalAccess;
677       }
678 
679       UpwardsWalkResult Res = walkToPhiOrClobber(Node,
680                                                  /*StopAt=*/StopWhere,
681                                                  /*SkipStopAt=*/SkipStopWhere);
682       if (Res.IsKnownClobber) {
683         assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
684 
685         // If this wasn't a cache hit, we hit a clobber when walking. That's a
686         // failure.
687         TerminatedPath Term{Res.Result, PathIndex};
688         if (!MSSA.dominates(Res.Result, StopWhere))
689           return Term;
690 
691         // Otherwise, it's a valid thing to potentially optimize to.
692         Terminated.push_back(Term);
693         continue;
694       }
695 
696       if (Res.Result == StopWhere || Res.Result == SkipStopWhere) {
697         // We've hit our target. Save this path off for if we want to continue
698         // walking. If we are in the mode of skipping the OriginalAccess, and
699         // we've reached back to the OriginalAccess, do not save path, we've
700         // just looped back to self.
701         if (Res.Result != SkipStopWhere)
702           NewPaused.push_back(PathIndex);
703         continue;
704       }
705 
706       assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
707       addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
708     }
709 
710     return None;
711   }
712 
713   template <typename T, typename Walker>
714   struct generic_def_path_iterator
715       : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
716                                     std::forward_iterator_tag, T *> {
717     generic_def_path_iterator() {}
718     generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
719 
720     T &operator*() const { return curNode(); }
721 
722     generic_def_path_iterator &operator++() {
723       N = curNode().Previous;
724       return *this;
725     }
726 
727     bool operator==(const generic_def_path_iterator &O) const {
728       if (N.hasValue() != O.N.hasValue())
729         return false;
730       return !N.hasValue() || *N == *O.N;
731     }
732 
733   private:
734     T &curNode() const { return W->Paths[*N]; }
735 
736     Walker *W = nullptr;
737     Optional<ListIndex> N = None;
738   };
739 
740   using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
741   using const_def_path_iterator =
742       generic_def_path_iterator<const DefPath, const ClobberWalker>;
743 
744   iterator_range<def_path_iterator> def_path(ListIndex From) {
745     return make_range(def_path_iterator(this, From), def_path_iterator());
746   }
747 
748   iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
749     return make_range(const_def_path_iterator(this, From),
750                       const_def_path_iterator());
751   }
752 
753   struct OptznResult {
754     /// The path that contains our result.
755     TerminatedPath PrimaryClobber;
756     /// The paths that we can legally cache back from, but that aren't
757     /// necessarily the result of the Phi optimization.
758     SmallVector<TerminatedPath, 4> OtherClobbers;
759   };
760 
761   ListIndex defPathIndex(const DefPath &N) const {
762     // The assert looks nicer if we don't need to do &N
763     const DefPath *NP = &N;
764     assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
765            "Out of bounds DefPath!");
766     return NP - &Paths.front();
767   }
768 
769   /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
770   /// that act as legal clobbers. Note that this won't return *all* clobbers.
771   ///
772   /// Phi optimization algorithm tl;dr:
773   ///   - Find the earliest def/phi, A, we can optimize to
774   ///   - Find if all paths from the starting memory access ultimately reach A
775   ///     - If not, optimization isn't possible.
776   ///     - Otherwise, walk from A to another clobber or phi, A'.
777   ///       - If A' is a def, we're done.
778   ///       - If A' is a phi, try to optimize it.
779   ///
780   /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
781   /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
782   OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
783                              const MemoryLocation &Loc) {
784     assert(Paths.empty() && VisitedPhis.empty() && !PerformedPhiTranslation &&
785            "Reset the optimization state.");
786 
787     Paths.emplace_back(Loc, Start, Phi, None);
788     // Stores how many "valid" optimization nodes we had prior to calling
789     // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
790     auto PriorPathsSize = Paths.size();
791 
792     SmallVector<ListIndex, 16> PausedSearches;
793     SmallVector<ListIndex, 8> NewPaused;
794     SmallVector<TerminatedPath, 4> TerminatedPaths;
795 
796     addSearches(Phi, PausedSearches, 0);
797 
798     // Moves the TerminatedPath with the "most dominated" Clobber to the end of
799     // Paths.
800     auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
801       assert(!Paths.empty() && "Need a path to move");
802       auto Dom = Paths.begin();
803       for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
804         if (!MSSA.dominates(I->Clobber, Dom->Clobber))
805           Dom = I;
806       auto Last = Paths.end() - 1;
807       if (Last != Dom)
808         std::iter_swap(Last, Dom);
809     };
810 
811     MemoryPhi *Current = Phi;
812     while (true) {
813       assert(!MSSA.isLiveOnEntryDef(Current) &&
814              "liveOnEntry wasn't treated as a clobber?");
815 
816       const auto *Target = getWalkTarget(Current);
817       // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
818       // optimization for the prior phi.
819       assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
820         return MSSA.dominates(P.Clobber, Target);
821       }));
822 
823       // FIXME: This is broken, because the Blocker may be reported to be
824       // liveOnEntry, and we'll happily wait for that to disappear (read: never)
825       // For the moment, this is fine, since we do nothing with blocker info.
826       if (Optional<TerminatedPath> Blocker = getBlockingAccess(
827               Target, PausedSearches, NewPaused, TerminatedPaths)) {
828 
829         // Find the node we started at. We can't search based on N->Last, since
830         // we may have gone around a loop with a different MemoryLocation.
831         auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
832           return defPathIndex(N) < PriorPathsSize;
833         });
834         assert(Iter != def_path_iterator());
835 
836         DefPath &CurNode = *Iter;
837         assert(CurNode.Last == Current);
838 
839         // Two things:
840         // A. We can't reliably cache all of NewPaused back. Consider a case
841         //    where we have two paths in NewPaused; one of which can't optimize
842         //    above this phi, whereas the other can. If we cache the second path
843         //    back, we'll end up with suboptimal cache entries. We can handle
844         //    cases like this a bit better when we either try to find all
845         //    clobbers that block phi optimization, or when our cache starts
846         //    supporting unfinished searches.
847         // B. We can't reliably cache TerminatedPaths back here without doing
848         //    extra checks; consider a case like:
849         //       T
850         //      / \
851         //     D   C
852         //      \ /
853         //       S
854         //    Where T is our target, C is a node with a clobber on it, D is a
855         //    diamond (with a clobber *only* on the left or right node, N), and
856         //    S is our start. Say we walk to D, through the node opposite N
857         //    (read: ignoring the clobber), and see a cache entry in the top
858         //    node of D. That cache entry gets put into TerminatedPaths. We then
859         //    walk up to C (N is later in our worklist), find the clobber, and
860         //    quit. If we append TerminatedPaths to OtherClobbers, we'll cache
861         //    the bottom part of D to the cached clobber, ignoring the clobber
862         //    in N. Again, this problem goes away if we start tracking all
863         //    blockers for a given phi optimization.
864         TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
865         return {Result, {}};
866       }
867 
868       // If there's nothing left to search, then all paths led to valid clobbers
869       // that we got from our cache; pick the nearest to the start, and allow
870       // the rest to be cached back.
871       if (NewPaused.empty()) {
872         MoveDominatedPathToEnd(TerminatedPaths);
873         TerminatedPath Result = TerminatedPaths.pop_back_val();
874         return {Result, std::move(TerminatedPaths)};
875       }
876 
877       MemoryAccess *DefChainEnd = nullptr;
878       SmallVector<TerminatedPath, 4> Clobbers;
879       for (ListIndex Paused : NewPaused) {
880         UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
881         if (WR.IsKnownClobber)
882           Clobbers.push_back({WR.Result, Paused});
883         else
884           // Micro-opt: If we hit the end of the chain, save it.
885           DefChainEnd = WR.Result;
886       }
887 
888       if (!TerminatedPaths.empty()) {
889         // If we couldn't find the dominating phi/liveOnEntry in the above loop,
890         // do it now.
891         if (!DefChainEnd)
892           for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
893             DefChainEnd = MA;
894         assert(DefChainEnd && "Failed to find dominating phi/liveOnEntry");
895 
896         // If any of the terminated paths don't dominate the phi we'll try to
897         // optimize, we need to figure out what they are and quit.
898         const BasicBlock *ChainBB = DefChainEnd->getBlock();
899         for (const TerminatedPath &TP : TerminatedPaths) {
900           // Because we know that DefChainEnd is as "high" as we can go, we
901           // don't need local dominance checks; BB dominance is sufficient.
902           if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
903             Clobbers.push_back(TP);
904         }
905       }
906 
907       // If we have clobbers in the def chain, find the one closest to Current
908       // and quit.
909       if (!Clobbers.empty()) {
910         MoveDominatedPathToEnd(Clobbers);
911         TerminatedPath Result = Clobbers.pop_back_val();
912         return {Result, std::move(Clobbers)};
913       }
914 
915       assert(all_of(NewPaused,
916                     [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
917 
918       // Because liveOnEntry is a clobber, this must be a phi.
919       auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
920 
921       PriorPathsSize = Paths.size();
922       PausedSearches.clear();
923       for (ListIndex I : NewPaused)
924         addSearches(DefChainPhi, PausedSearches, I);
925       NewPaused.clear();
926 
927       Current = DefChainPhi;
928     }
929   }
930 
931   void verifyOptResult(const OptznResult &R) const {
932     assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
933       return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
934     }));
935   }
936 
937   void resetPhiOptznState() {
938     Paths.clear();
939     VisitedPhis.clear();
940     PerformedPhiTranslation = false;
941   }
942 
943 public:
944   ClobberWalker(const MemorySSA &MSSA, AliasAnalysisType &AA, DominatorTree &DT)
945       : MSSA(MSSA), AA(AA), DT(DT) {}
946 
947   AliasAnalysisType *getAA() { return &AA; }
948   /// Finds the nearest clobber for the given query, optimizing phis if
949   /// possible.
950   MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
951                             unsigned &UpWalkLimit) {
952     Query = &Q;
953     UpwardWalkLimit = &UpWalkLimit;
954     // Starting limit must be > 0.
955     if (!UpWalkLimit)
956       UpWalkLimit++;
957 
958     MemoryAccess *Current = Start;
959     // This walker pretends uses don't exist. If we're handed one, silently grab
960     // its def. (This has the nice side-effect of ensuring we never cache uses)
961     if (auto *MU = dyn_cast<MemoryUse>(Start))
962       Current = MU->getDefiningAccess();
963 
964     DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
965     // Fast path for the overly-common case (no crazy phi optimization
966     // necessary)
967     UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
968     MemoryAccess *Result;
969     if (WalkResult.IsKnownClobber) {
970       Result = WalkResult.Result;
971       Q.AR = WalkResult.AR;
972     } else {
973       OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
974                                           Current, Q.StartingLoc);
975       verifyOptResult(OptRes);
976       resetPhiOptznState();
977       Result = OptRes.PrimaryClobber.Clobber;
978     }
979 
980 #ifdef EXPENSIVE_CHECKS
981     if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
982       checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
983 #endif
984     return Result;
985   }
986 };
987 
988 struct RenamePassData {
989   DomTreeNode *DTN;
990   DomTreeNode::const_iterator ChildIt;
991   MemoryAccess *IncomingVal;
992 
993   RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
994                  MemoryAccess *M)
995       : DTN(D), ChildIt(It), IncomingVal(M) {}
996 
997   void swap(RenamePassData &RHS) {
998     std::swap(DTN, RHS.DTN);
999     std::swap(ChildIt, RHS.ChildIt);
1000     std::swap(IncomingVal, RHS.IncomingVal);
1001   }
1002 };
1003 
1004 } // end anonymous namespace
1005 
1006 namespace llvm {
1007 
1008 template <class AliasAnalysisType> class MemorySSA::ClobberWalkerBase {
1009   ClobberWalker<AliasAnalysisType> Walker;
1010   MemorySSA *MSSA;
1011 
1012 public:
1013   ClobberWalkerBase(MemorySSA *M, AliasAnalysisType *A, DominatorTree *D)
1014       : Walker(*M, *A, *D), MSSA(M) {}
1015 
1016   MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *,
1017                                               const MemoryLocation &,
1018                                               unsigned &);
1019   // Third argument (bool), defines whether the clobber search should skip the
1020   // original queried access. If true, there will be a follow-up query searching
1021   // for a clobber access past "self". Note that the Optimized access is not
1022   // updated if a new clobber is found by this SkipSelf search. If this
1023   // additional query becomes heavily used we may decide to cache the result.
1024   // Walker instantiations will decide how to set the SkipSelf bool.
1025   MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *, unsigned &, bool);
1026 };
1027 
1028 /// A MemorySSAWalker that does AA walks to disambiguate accesses. It no
1029 /// longer does caching on its own, but the name has been retained for the
1030 /// moment.
1031 template <class AliasAnalysisType>
1032 class MemorySSA::CachingWalker final : public MemorySSAWalker {
1033   ClobberWalkerBase<AliasAnalysisType> *Walker;
1034 
1035 public:
1036   CachingWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
1037       : MemorySSAWalker(M), Walker(W) {}
1038   ~CachingWalker() override = default;
1039 
1040   using MemorySSAWalker::getClobberingMemoryAccess;
1041 
1042   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
1043     return Walker->getClobberingMemoryAccessBase(MA, UWL, false);
1044   }
1045   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1046                                           const MemoryLocation &Loc,
1047                                           unsigned &UWL) {
1048     return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1049   }
1050 
1051   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
1052     unsigned UpwardWalkLimit = MaxCheckLimit;
1053     return getClobberingMemoryAccess(MA, UpwardWalkLimit);
1054   }
1055   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1056                                           const MemoryLocation &Loc) override {
1057     unsigned UpwardWalkLimit = MaxCheckLimit;
1058     return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
1059   }
1060 
1061   void invalidateInfo(MemoryAccess *MA) override {
1062     if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1063       MUD->resetOptimized();
1064   }
1065 };
1066 
1067 template <class AliasAnalysisType>
1068 class MemorySSA::SkipSelfWalker final : public MemorySSAWalker {
1069   ClobberWalkerBase<AliasAnalysisType> *Walker;
1070 
1071 public:
1072   SkipSelfWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
1073       : MemorySSAWalker(M), Walker(W) {}
1074   ~SkipSelfWalker() override = default;
1075 
1076   using MemorySSAWalker::getClobberingMemoryAccess;
1077 
1078   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
1079     return Walker->getClobberingMemoryAccessBase(MA, UWL, true);
1080   }
1081   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1082                                           const MemoryLocation &Loc,
1083                                           unsigned &UWL) {
1084     return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1085   }
1086 
1087   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
1088     unsigned UpwardWalkLimit = MaxCheckLimit;
1089     return getClobberingMemoryAccess(MA, UpwardWalkLimit);
1090   }
1091   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1092                                           const MemoryLocation &Loc) override {
1093     unsigned UpwardWalkLimit = MaxCheckLimit;
1094     return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
1095   }
1096 
1097   void invalidateInfo(MemoryAccess *MA) override {
1098     if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1099       MUD->resetOptimized();
1100   }
1101 };
1102 
1103 } // end namespace llvm
1104 
1105 void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
1106                                     bool RenameAllUses) {
1107   // Pass through values to our successors
1108   for (const BasicBlock *S : successors(BB)) {
1109     auto It = PerBlockAccesses.find(S);
1110     // Rename the phi nodes in our successor block
1111     if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1112       continue;
1113     AccessList *Accesses = It->second.get();
1114     auto *Phi = cast<MemoryPhi>(&Accesses->front());
1115     if (RenameAllUses) {
1116       bool ReplacementDone = false;
1117       for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1118         if (Phi->getIncomingBlock(I) == BB) {
1119           Phi->setIncomingValue(I, IncomingVal);
1120           ReplacementDone = true;
1121         }
1122       (void) ReplacementDone;
1123       assert(ReplacementDone && "Incomplete phi during partial rename");
1124     } else
1125       Phi->addIncoming(IncomingVal, BB);
1126   }
1127 }
1128 
1129 /// Rename a single basic block into MemorySSA form.
1130 /// Uses the standard SSA renaming algorithm.
1131 /// \returns The new incoming value.
1132 MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
1133                                      bool RenameAllUses) {
1134   auto It = PerBlockAccesses.find(BB);
1135   // Skip most processing if the list is empty.
1136   if (It != PerBlockAccesses.end()) {
1137     AccessList *Accesses = It->second.get();
1138     for (MemoryAccess &L : *Accesses) {
1139       if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1140         if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
1141           MUD->setDefiningAccess(IncomingVal);
1142         if (isa<MemoryDef>(&L))
1143           IncomingVal = &L;
1144       } else {
1145         IncomingVal = &L;
1146       }
1147     }
1148   }
1149   return IncomingVal;
1150 }
1151 
1152 /// This is the standard SSA renaming algorithm.
1153 ///
1154 /// We walk the dominator tree in preorder, renaming accesses, and then filling
1155 /// in phi nodes in our successors.
1156 void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
1157                            SmallPtrSetImpl<BasicBlock *> &Visited,
1158                            bool SkipVisited, bool RenameAllUses) {
1159   assert(Root && "Trying to rename accesses in an unreachable block");
1160 
1161   SmallVector<RenamePassData, 32> WorkStack;
1162   // Skip everything if we already renamed this block and we are skipping.
1163   // Note: You can't sink this into the if, because we need it to occur
1164   // regardless of whether we skip blocks or not.
1165   bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
1166   if (SkipVisited && AlreadyVisited)
1167     return;
1168 
1169   IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
1170   renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
1171   WorkStack.push_back({Root, Root->begin(), IncomingVal});
1172 
1173   while (!WorkStack.empty()) {
1174     DomTreeNode *Node = WorkStack.back().DTN;
1175     DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1176     IncomingVal = WorkStack.back().IncomingVal;
1177 
1178     if (ChildIt == Node->end()) {
1179       WorkStack.pop_back();
1180     } else {
1181       DomTreeNode *Child = *ChildIt;
1182       ++WorkStack.back().ChildIt;
1183       BasicBlock *BB = Child->getBlock();
1184       // Note: You can't sink this into the if, because we need it to occur
1185       // regardless of whether we skip blocks or not.
1186       AlreadyVisited = !Visited.insert(BB).second;
1187       if (SkipVisited && AlreadyVisited) {
1188         // We already visited this during our renaming, which can happen when
1189         // being asked to rename multiple blocks. Figure out the incoming val,
1190         // which is the last def.
1191         // Incoming value can only change if there is a block def, and in that
1192         // case, it's the last block def in the list.
1193         if (auto *BlockDefs = getWritableBlockDefs(BB))
1194           IncomingVal = &*BlockDefs->rbegin();
1195       } else
1196         IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1197       renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
1198       WorkStack.push_back({Child, Child->begin(), IncomingVal});
1199     }
1200   }
1201 }
1202 
1203 /// This handles unreachable block accesses by deleting phi nodes in
1204 /// unreachable blocks, and marking all other unreachable MemoryAccess's as
1205 /// being uses of the live on entry definition.
1206 void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1207   assert(!DT->isReachableFromEntry(BB) &&
1208          "Reachable block found while handling unreachable blocks");
1209 
1210   // Make sure phi nodes in our reachable successors end up with a
1211   // LiveOnEntryDef for our incoming edge, even though our block is forward
1212   // unreachable.  We could just disconnect these blocks from the CFG fully,
1213   // but we do not right now.
1214   for (const BasicBlock *S : successors(BB)) {
1215     if (!DT->isReachableFromEntry(S))
1216       continue;
1217     auto It = PerBlockAccesses.find(S);
1218     // Rename the phi nodes in our successor block
1219     if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1220       continue;
1221     AccessList *Accesses = It->second.get();
1222     auto *Phi = cast<MemoryPhi>(&Accesses->front());
1223     Phi->addIncoming(LiveOnEntryDef.get(), BB);
1224   }
1225 
1226   auto It = PerBlockAccesses.find(BB);
1227   if (It == PerBlockAccesses.end())
1228     return;
1229 
1230   auto &Accesses = It->second;
1231   for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1232     auto Next = std::next(AI);
1233     // If we have a phi, just remove it. We are going to replace all
1234     // users with live on entry.
1235     if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1236       UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1237     else
1238       Accesses->erase(AI);
1239     AI = Next;
1240   }
1241 }
1242 
1243 MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1244     : AA(nullptr), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1245       SkipWalker(nullptr), NextID(0) {
1246   // Build MemorySSA using a batch alias analysis. This reuses the internal
1247   // state that AA collects during an alias()/getModRefInfo() call. This is
1248   // safe because there are no CFG changes while building MemorySSA and can
1249   // significantly reduce the time spent by the compiler in AA, because we will
1250   // make queries about all the instructions in the Function.
1251   assert(AA && "No alias analysis?");
1252   BatchAAResults BatchAA(*AA);
1253   buildMemorySSA(BatchAA);
1254   // Intentionally leave AA to nullptr while building so we don't accidently
1255   // use non-batch AliasAnalysis.
1256   this->AA = AA;
1257   // Also create the walker here.
1258   getWalker();
1259 }
1260 
1261 MemorySSA::~MemorySSA() {
1262   // Drop all our references
1263   for (const auto &Pair : PerBlockAccesses)
1264     for (MemoryAccess &MA : *Pair.second)
1265       MA.dropAllReferences();
1266 }
1267 
1268 MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
1269   auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1270 
1271   if (Res.second)
1272     Res.first->second = std::make_unique<AccessList>();
1273   return Res.first->second.get();
1274 }
1275 
1276 MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1277   auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1278 
1279   if (Res.second)
1280     Res.first->second = std::make_unique<DefsList>();
1281   return Res.first->second.get();
1282 }
1283 
1284 namespace llvm {
1285 
1286 /// This class is a batch walker of all MemoryUse's in the program, and points
1287 /// their defining access at the thing that actually clobbers them.  Because it
1288 /// is a batch walker that touches everything, it does not operate like the
1289 /// other walkers.  This walker is basically performing a top-down SSA renaming
1290 /// pass, where the version stack is used as the cache.  This enables it to be
1291 /// significantly more time and memory efficient than using the regular walker,
1292 /// which is walking bottom-up.
1293 class MemorySSA::OptimizeUses {
1294 public:
1295   OptimizeUses(MemorySSA *MSSA, CachingWalker<BatchAAResults> *Walker,
1296                BatchAAResults *BAA, DominatorTree *DT)
1297       : MSSA(MSSA), Walker(Walker), AA(BAA), DT(DT) {}
1298 
1299   void optimizeUses();
1300 
1301 private:
1302   /// This represents where a given memorylocation is in the stack.
1303   struct MemlocStackInfo {
1304     // This essentially is keeping track of versions of the stack. Whenever
1305     // the stack changes due to pushes or pops, these versions increase.
1306     unsigned long StackEpoch;
1307     unsigned long PopEpoch;
1308     // This is the lower bound of places on the stack to check. It is equal to
1309     // the place the last stack walk ended.
1310     // Note: Correctness depends on this being initialized to 0, which densemap
1311     // does
1312     unsigned long LowerBound;
1313     const BasicBlock *LowerBoundBlock;
1314     // This is where the last walk for this memory location ended.
1315     unsigned long LastKill;
1316     bool LastKillValid;
1317     Optional<AliasResult> AR;
1318   };
1319 
1320   void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1321                            SmallVectorImpl<MemoryAccess *> &,
1322                            DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1323 
1324   MemorySSA *MSSA;
1325   CachingWalker<BatchAAResults> *Walker;
1326   BatchAAResults *AA;
1327   DominatorTree *DT;
1328 };
1329 
1330 } // end namespace llvm
1331 
1332 /// Optimize the uses in a given block This is basically the SSA renaming
1333 /// algorithm, with one caveat: We are able to use a single stack for all
1334 /// MemoryUses.  This is because the set of *possible* reaching MemoryDefs is
1335 /// the same for every MemoryUse.  The *actual* clobbering MemoryDef is just
1336 /// going to be some position in that stack of possible ones.
1337 ///
1338 /// We track the stack positions that each MemoryLocation needs
1339 /// to check, and last ended at.  This is because we only want to check the
1340 /// things that changed since last time.  The same MemoryLocation should
1341 /// get clobbered by the same store (getModRefInfo does not use invariantness or
1342 /// things like this, and if they start, we can modify MemoryLocOrCall to
1343 /// include relevant data)
1344 void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1345     const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1346     SmallVectorImpl<MemoryAccess *> &VersionStack,
1347     DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1348 
1349   /// If no accesses, nothing to do.
1350   MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1351   if (Accesses == nullptr)
1352     return;
1353 
1354   // Pop everything that doesn't dominate the current block off the stack,
1355   // increment the PopEpoch to account for this.
1356   while (true) {
1357     assert(
1358         !VersionStack.empty() &&
1359         "Version stack should have liveOnEntry sentinel dominating everything");
1360     BasicBlock *BackBlock = VersionStack.back()->getBlock();
1361     if (DT->dominates(BackBlock, BB))
1362       break;
1363     while (VersionStack.back()->getBlock() == BackBlock)
1364       VersionStack.pop_back();
1365     ++PopEpoch;
1366   }
1367 
1368   for (MemoryAccess &MA : *Accesses) {
1369     auto *MU = dyn_cast<MemoryUse>(&MA);
1370     if (!MU) {
1371       VersionStack.push_back(&MA);
1372       ++StackEpoch;
1373       continue;
1374     }
1375 
1376     if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
1377       MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true, None);
1378       continue;
1379     }
1380 
1381     MemoryLocOrCall UseMLOC(MU);
1382     auto &LocInfo = LocStackInfo[UseMLOC];
1383     // If the pop epoch changed, it means we've removed stuff from top of
1384     // stack due to changing blocks. We may have to reset the lower bound or
1385     // last kill info.
1386     if (LocInfo.PopEpoch != PopEpoch) {
1387       LocInfo.PopEpoch = PopEpoch;
1388       LocInfo.StackEpoch = StackEpoch;
1389       // If the lower bound was in something that no longer dominates us, we
1390       // have to reset it.
1391       // We can't simply track stack size, because the stack may have had
1392       // pushes/pops in the meantime.
1393       // XXX: This is non-optimal, but only is slower cases with heavily
1394       // branching dominator trees.  To get the optimal number of queries would
1395       // be to make lowerbound and lastkill a per-loc stack, and pop it until
1396       // the top of that stack dominates us.  This does not seem worth it ATM.
1397       // A much cheaper optimization would be to always explore the deepest
1398       // branch of the dominator tree first. This will guarantee this resets on
1399       // the smallest set of blocks.
1400       if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
1401           !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
1402         // Reset the lower bound of things to check.
1403         // TODO: Some day we should be able to reset to last kill, rather than
1404         // 0.
1405         LocInfo.LowerBound = 0;
1406         LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
1407         LocInfo.LastKillValid = false;
1408       }
1409     } else if (LocInfo.StackEpoch != StackEpoch) {
1410       // If all that has changed is the StackEpoch, we only have to check the
1411       // new things on the stack, because we've checked everything before.  In
1412       // this case, the lower bound of things to check remains the same.
1413       LocInfo.PopEpoch = PopEpoch;
1414       LocInfo.StackEpoch = StackEpoch;
1415     }
1416     if (!LocInfo.LastKillValid) {
1417       LocInfo.LastKill = VersionStack.size() - 1;
1418       LocInfo.LastKillValid = true;
1419       LocInfo.AR = MayAlias;
1420     }
1421 
1422     // At this point, we should have corrected last kill and LowerBound to be
1423     // in bounds.
1424     assert(LocInfo.LowerBound < VersionStack.size() &&
1425            "Lower bound out of range");
1426     assert(LocInfo.LastKill < VersionStack.size() &&
1427            "Last kill info out of range");
1428     // In any case, the new upper bound is the top of the stack.
1429     unsigned long UpperBound = VersionStack.size() - 1;
1430 
1431     if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
1432       LLVM_DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1433                         << *(MU->getMemoryInst()) << ")"
1434                         << " because there are "
1435                         << UpperBound - LocInfo.LowerBound
1436                         << " stores to disambiguate\n");
1437       // Because we did not walk, LastKill is no longer valid, as this may
1438       // have been a kill.
1439       LocInfo.LastKillValid = false;
1440       continue;
1441     }
1442     bool FoundClobberResult = false;
1443     unsigned UpwardWalkLimit = MaxCheckLimit;
1444     while (UpperBound > LocInfo.LowerBound) {
1445       if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1446         // For phis, use the walker, see where we ended up, go there
1447         MemoryAccess *Result =
1448             Walker->getClobberingMemoryAccess(MU, UpwardWalkLimit);
1449         // We are guaranteed to find it or something is wrong
1450         while (VersionStack[UpperBound] != Result) {
1451           assert(UpperBound != 0);
1452           --UpperBound;
1453         }
1454         FoundClobberResult = true;
1455         break;
1456       }
1457 
1458       MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
1459       // If the lifetime of the pointer ends at this instruction, it's live on
1460       // entry.
1461       if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1462         // Reset UpperBound to liveOnEntryDef's place in the stack
1463         UpperBound = 0;
1464         FoundClobberResult = true;
1465         LocInfo.AR = MustAlias;
1466         break;
1467       }
1468       ClobberAlias CA = instructionClobbersQuery(MD, MU, UseMLOC, *AA);
1469       if (CA.IsClobber) {
1470         FoundClobberResult = true;
1471         LocInfo.AR = CA.AR;
1472         break;
1473       }
1474       --UpperBound;
1475     }
1476 
1477     // Note: Phis always have AliasResult AR set to MayAlias ATM.
1478 
1479     // At the end of this loop, UpperBound is either a clobber, or lower bound
1480     // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1481     if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1482       // We were last killed now by where we got to
1483       if (MSSA->isLiveOnEntryDef(VersionStack[UpperBound]))
1484         LocInfo.AR = None;
1485       MU->setDefiningAccess(VersionStack[UpperBound], true, LocInfo.AR);
1486       LocInfo.LastKill = UpperBound;
1487     } else {
1488       // Otherwise, we checked all the new ones, and now we know we can get to
1489       // LastKill.
1490       MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true, LocInfo.AR);
1491     }
1492     LocInfo.LowerBound = VersionStack.size() - 1;
1493     LocInfo.LowerBoundBlock = BB;
1494   }
1495 }
1496 
1497 /// Optimize uses to point to their actual clobbering definitions.
1498 void MemorySSA::OptimizeUses::optimizeUses() {
1499   SmallVector<MemoryAccess *, 16> VersionStack;
1500   DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
1501   VersionStack.push_back(MSSA->getLiveOnEntryDef());
1502 
1503   unsigned long StackEpoch = 1;
1504   unsigned long PopEpoch = 1;
1505   // We perform a non-recursive top-down dominator tree walk.
1506   for (const auto *DomNode : depth_first(DT->getRootNode()))
1507     optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1508                         LocStackInfo);
1509 }
1510 
1511 void MemorySSA::placePHINodes(
1512     const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
1513   // Determine where our MemoryPhi's should go
1514   ForwardIDFCalculator IDFs(*DT);
1515   IDFs.setDefiningBlocks(DefiningBlocks);
1516   SmallVector<BasicBlock *, 32> IDFBlocks;
1517   IDFs.calculate(IDFBlocks);
1518 
1519   // Now place MemoryPhi nodes.
1520   for (auto &BB : IDFBlocks)
1521     createMemoryPhi(BB);
1522 }
1523 
1524 void MemorySSA::buildMemorySSA(BatchAAResults &BAA) {
1525   // We create an access to represent "live on entry", for things like
1526   // arguments or users of globals, where the memory they use is defined before
1527   // the beginning of the function. We do not actually insert it into the IR.
1528   // We do not define a live on exit for the immediate uses, and thus our
1529   // semantics do *not* imply that something with no immediate uses can simply
1530   // be removed.
1531   BasicBlock &StartingPoint = F.getEntryBlock();
1532   LiveOnEntryDef.reset(new MemoryDef(F.getContext(), nullptr, nullptr,
1533                                      &StartingPoint, NextID++));
1534 
1535   // We maintain lists of memory accesses per-block, trading memory for time. We
1536   // could just look up the memory access for every possible instruction in the
1537   // stream.
1538   SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
1539   // Go through each block, figure out where defs occur, and chain together all
1540   // the accesses.
1541   for (BasicBlock &B : F) {
1542     bool InsertIntoDef = false;
1543     AccessList *Accesses = nullptr;
1544     DefsList *Defs = nullptr;
1545     for (Instruction &I : B) {
1546       MemoryUseOrDef *MUD = createNewAccess(&I, &BAA);
1547       if (!MUD)
1548         continue;
1549 
1550       if (!Accesses)
1551         Accesses = getOrCreateAccessList(&B);
1552       Accesses->push_back(MUD);
1553       if (isa<MemoryDef>(MUD)) {
1554         InsertIntoDef = true;
1555         if (!Defs)
1556           Defs = getOrCreateDefsList(&B);
1557         Defs->push_back(*MUD);
1558       }
1559     }
1560     if (InsertIntoDef)
1561       DefiningBlocks.insert(&B);
1562   }
1563   placePHINodes(DefiningBlocks);
1564 
1565   // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1566   // filled in with all blocks.
1567   SmallPtrSet<BasicBlock *, 16> Visited;
1568   renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1569 
1570   ClobberWalkerBase<BatchAAResults> WalkerBase(this, &BAA, DT);
1571   CachingWalker<BatchAAResults> WalkerLocal(this, &WalkerBase);
1572   OptimizeUses(this, &WalkerLocal, &BAA, DT).optimizeUses();
1573 
1574   // Mark the uses in unreachable blocks as live on entry, so that they go
1575   // somewhere.
1576   for (auto &BB : F)
1577     if (!Visited.count(&BB))
1578       markUnreachableAsLiveOnEntry(&BB);
1579 }
1580 
1581 MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1582 
1583 MemorySSA::CachingWalker<AliasAnalysis> *MemorySSA::getWalkerImpl() {
1584   if (Walker)
1585     return Walker.get();
1586 
1587   if (!WalkerBase)
1588     WalkerBase =
1589         std::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
1590 
1591   Walker =
1592       std::make_unique<CachingWalker<AliasAnalysis>>(this, WalkerBase.get());
1593   return Walker.get();
1594 }
1595 
1596 MemorySSAWalker *MemorySSA::getSkipSelfWalker() {
1597   if (SkipWalker)
1598     return SkipWalker.get();
1599 
1600   if (!WalkerBase)
1601     WalkerBase =
1602         std::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
1603 
1604   SkipWalker =
1605       std::make_unique<SkipSelfWalker<AliasAnalysis>>(this, WalkerBase.get());
1606   return SkipWalker.get();
1607  }
1608 
1609 
1610 // This is a helper function used by the creation routines. It places NewAccess
1611 // into the access and defs lists for a given basic block, at the given
1612 // insertion point.
1613 void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1614                                         const BasicBlock *BB,
1615                                         InsertionPlace Point) {
1616   auto *Accesses = getOrCreateAccessList(BB);
1617   if (Point == Beginning) {
1618     // If it's a phi node, it goes first, otherwise, it goes after any phi
1619     // nodes.
1620     if (isa<MemoryPhi>(NewAccess)) {
1621       Accesses->push_front(NewAccess);
1622       auto *Defs = getOrCreateDefsList(BB);
1623       Defs->push_front(*NewAccess);
1624     } else {
1625       auto AI = find_if_not(
1626           *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1627       Accesses->insert(AI, NewAccess);
1628       if (!isa<MemoryUse>(NewAccess)) {
1629         auto *Defs = getOrCreateDefsList(BB);
1630         auto DI = find_if_not(
1631             *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1632         Defs->insert(DI, *NewAccess);
1633       }
1634     }
1635   } else {
1636     Accesses->push_back(NewAccess);
1637     if (!isa<MemoryUse>(NewAccess)) {
1638       auto *Defs = getOrCreateDefsList(BB);
1639       Defs->push_back(*NewAccess);
1640     }
1641   }
1642   BlockNumberingValid.erase(BB);
1643 }
1644 
1645 void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1646                                       AccessList::iterator InsertPt) {
1647   auto *Accesses = getWritableBlockAccesses(BB);
1648   bool WasEnd = InsertPt == Accesses->end();
1649   Accesses->insert(AccessList::iterator(InsertPt), What);
1650   if (!isa<MemoryUse>(What)) {
1651     auto *Defs = getOrCreateDefsList(BB);
1652     // If we got asked to insert at the end, we have an easy job, just shove it
1653     // at the end. If we got asked to insert before an existing def, we also get
1654     // an iterator. If we got asked to insert before a use, we have to hunt for
1655     // the next def.
1656     if (WasEnd) {
1657       Defs->push_back(*What);
1658     } else if (isa<MemoryDef>(InsertPt)) {
1659       Defs->insert(InsertPt->getDefsIterator(), *What);
1660     } else {
1661       while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1662         ++InsertPt;
1663       // Either we found a def, or we are inserting at the end
1664       if (InsertPt == Accesses->end())
1665         Defs->push_back(*What);
1666       else
1667         Defs->insert(InsertPt->getDefsIterator(), *What);
1668     }
1669   }
1670   BlockNumberingValid.erase(BB);
1671 }
1672 
1673 void MemorySSA::prepareForMoveTo(MemoryAccess *What, BasicBlock *BB) {
1674   // Keep it in the lookup tables, remove from the lists
1675   removeFromLists(What, false);
1676 
1677   // Note that moving should implicitly invalidate the optimized state of a
1678   // MemoryUse (and Phis can't be optimized). However, it doesn't do so for a
1679   // MemoryDef.
1680   if (auto *MD = dyn_cast<MemoryDef>(What))
1681     MD->resetOptimized();
1682   What->setBlock(BB);
1683 }
1684 
1685 // Move What before Where in the IR.  The end result is that What will belong to
1686 // the right lists and have the right Block set, but will not otherwise be
1687 // correct. It will not have the right defining access, and if it is a def,
1688 // things below it will not properly be updated.
1689 void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1690                        AccessList::iterator Where) {
1691   prepareForMoveTo(What, BB);
1692   insertIntoListsBefore(What, BB, Where);
1693 }
1694 
1695 void MemorySSA::moveTo(MemoryAccess *What, BasicBlock *BB,
1696                        InsertionPlace Point) {
1697   if (isa<MemoryPhi>(What)) {
1698     assert(Point == Beginning &&
1699            "Can only move a Phi at the beginning of the block");
1700     // Update lookup table entry
1701     ValueToMemoryAccess.erase(What->getBlock());
1702     bool Inserted = ValueToMemoryAccess.insert({BB, What}).second;
1703     (void)Inserted;
1704     assert(Inserted && "Cannot move a Phi to a block that already has one");
1705   }
1706 
1707   prepareForMoveTo(What, BB);
1708   insertIntoListsForBlock(What, BB, Point);
1709 }
1710 
1711 MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1712   assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1713   MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
1714   // Phi's always are placed at the front of the block.
1715   insertIntoListsForBlock(Phi, BB, Beginning);
1716   ValueToMemoryAccess[BB] = Phi;
1717   return Phi;
1718 }
1719 
1720 MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1721                                                MemoryAccess *Definition,
1722                                                const MemoryUseOrDef *Template,
1723                                                bool CreationMustSucceed) {
1724   assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1725   MemoryUseOrDef *NewAccess = createNewAccess(I, AA, Template);
1726   if (CreationMustSucceed)
1727     assert(NewAccess != nullptr && "Tried to create a memory access for a "
1728                                    "non-memory touching instruction");
1729   if (NewAccess) {
1730     assert((!Definition || !isa<MemoryUse>(Definition)) &&
1731            "A use cannot be a defining access");
1732     NewAccess->setDefiningAccess(Definition);
1733   }
1734   return NewAccess;
1735 }
1736 
1737 // Return true if the instruction has ordering constraints.
1738 // Note specifically that this only considers stores and loads
1739 // because others are still considered ModRef by getModRefInfo.
1740 static inline bool isOrdered(const Instruction *I) {
1741   if (auto *SI = dyn_cast<StoreInst>(I)) {
1742     if (!SI->isUnordered())
1743       return true;
1744   } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1745     if (!LI->isUnordered())
1746       return true;
1747   }
1748   return false;
1749 }
1750 
1751 /// Helper function to create new memory accesses
1752 template <typename AliasAnalysisType>
1753 MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I,
1754                                            AliasAnalysisType *AAP,
1755                                            const MemoryUseOrDef *Template) {
1756   // The assume intrinsic has a control dependency which we model by claiming
1757   // that it writes arbitrarily. Debuginfo intrinsics may be considered
1758   // clobbers when we have a nonstandard AA pipeline. Ignore these fake memory
1759   // dependencies here.
1760   // FIXME: Replace this special casing with a more accurate modelling of
1761   // assume's control dependency.
1762   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1763     if (II->getIntrinsicID() == Intrinsic::assume)
1764       return nullptr;
1765 
1766   // Using a nonstandard AA pipelines might leave us with unexpected modref
1767   // results for I, so add a check to not model instructions that may not read
1768   // from or write to memory. This is necessary for correctness.
1769   if (!I->mayReadFromMemory() && !I->mayWriteToMemory())
1770     return nullptr;
1771 
1772   bool Def, Use;
1773   if (Template) {
1774     Def = dyn_cast_or_null<MemoryDef>(Template) != nullptr;
1775     Use = dyn_cast_or_null<MemoryUse>(Template) != nullptr;
1776 #if !defined(NDEBUG)
1777     ModRefInfo ModRef = AAP->getModRefInfo(I, None);
1778     bool DefCheck, UseCheck;
1779     DefCheck = isModSet(ModRef) || isOrdered(I);
1780     UseCheck = isRefSet(ModRef);
1781     assert(Def == DefCheck && (Def || Use == UseCheck) && "Invalid template");
1782 #endif
1783   } else {
1784     // Find out what affect this instruction has on memory.
1785     ModRefInfo ModRef = AAP->getModRefInfo(I, None);
1786     // The isOrdered check is used to ensure that volatiles end up as defs
1787     // (atomics end up as ModRef right now anyway).  Until we separate the
1788     // ordering chain from the memory chain, this enables people to see at least
1789     // some relative ordering to volatiles.  Note that getClobberingMemoryAccess
1790     // will still give an answer that bypasses other volatile loads.  TODO:
1791     // Separate memory aliasing and ordering into two different chains so that
1792     // we can precisely represent both "what memory will this read/write/is
1793     // clobbered by" and "what instructions can I move this past".
1794     Def = isModSet(ModRef) || isOrdered(I);
1795     Use = isRefSet(ModRef);
1796   }
1797 
1798   // It's possible for an instruction to not modify memory at all. During
1799   // construction, we ignore them.
1800   if (!Def && !Use)
1801     return nullptr;
1802 
1803   MemoryUseOrDef *MUD;
1804   if (Def)
1805     MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
1806   else
1807     MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
1808   ValueToMemoryAccess[I] = MUD;
1809   return MUD;
1810 }
1811 
1812 /// Returns true if \p Replacer dominates \p Replacee .
1813 bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1814                              const MemoryAccess *Replacee) const {
1815   if (isa<MemoryUseOrDef>(Replacee))
1816     return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1817   const auto *MP = cast<MemoryPhi>(Replacee);
1818   // For a phi node, the use occurs in the predecessor block of the phi node.
1819   // Since we may occur multiple times in the phi node, we have to check each
1820   // operand to ensure Replacer dominates each operand where Replacee occurs.
1821   for (const Use &Arg : MP->operands()) {
1822     if (Arg.get() != Replacee &&
1823         !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1824       return false;
1825   }
1826   return true;
1827 }
1828 
1829 /// Properly remove \p MA from all of MemorySSA's lookup tables.
1830 void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1831   assert(MA->use_empty() &&
1832          "Trying to remove memory access that still has uses");
1833   BlockNumbering.erase(MA);
1834   if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1835     MUD->setDefiningAccess(nullptr);
1836   // Invalidate our walker's cache if necessary
1837   if (!isa<MemoryUse>(MA))
1838     getWalker()->invalidateInfo(MA);
1839 
1840   Value *MemoryInst;
1841   if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1842     MemoryInst = MUD->getMemoryInst();
1843   else
1844     MemoryInst = MA->getBlock();
1845 
1846   auto VMA = ValueToMemoryAccess.find(MemoryInst);
1847   if (VMA->second == MA)
1848     ValueToMemoryAccess.erase(VMA);
1849 }
1850 
1851 /// Properly remove \p MA from all of MemorySSA's lists.
1852 ///
1853 /// Because of the way the intrusive list and use lists work, it is important to
1854 /// do removal in the right order.
1855 /// ShouldDelete defaults to true, and will cause the memory access to also be
1856 /// deleted, not just removed.
1857 void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
1858   BasicBlock *BB = MA->getBlock();
1859   // The access list owns the reference, so we erase it from the non-owning list
1860   // first.
1861   if (!isa<MemoryUse>(MA)) {
1862     auto DefsIt = PerBlockDefs.find(BB);
1863     std::unique_ptr<DefsList> &Defs = DefsIt->second;
1864     Defs->remove(*MA);
1865     if (Defs->empty())
1866       PerBlockDefs.erase(DefsIt);
1867   }
1868 
1869   // The erase call here will delete it. If we don't want it deleted, we call
1870   // remove instead.
1871   auto AccessIt = PerBlockAccesses.find(BB);
1872   std::unique_ptr<AccessList> &Accesses = AccessIt->second;
1873   if (ShouldDelete)
1874     Accesses->erase(MA);
1875   else
1876     Accesses->remove(MA);
1877 
1878   if (Accesses->empty()) {
1879     PerBlockAccesses.erase(AccessIt);
1880     BlockNumberingValid.erase(BB);
1881   }
1882 }
1883 
1884 void MemorySSA::print(raw_ostream &OS) const {
1885   MemorySSAAnnotatedWriter Writer(this);
1886   F.print(OS, &Writer);
1887 }
1888 
1889 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1890 LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
1891 #endif
1892 
1893 void MemorySSA::verifyMemorySSA() const {
1894   verifyOrderingDominationAndDefUses(F);
1895   verifyDominationNumbers(F);
1896   verifyPrevDefInPhis(F);
1897   // Previously, the verification used to also verify that the clobberingAccess
1898   // cached by MemorySSA is the same as the clobberingAccess found at a later
1899   // query to AA. This does not hold true in general due to the current fragility
1900   // of BasicAA which has arbitrary caps on the things it analyzes before giving
1901   // up. As a result, transformations that are correct, will lead to BasicAA
1902   // returning different Alias answers before and after that transformation.
1903   // Invalidating MemorySSA is not an option, as the results in BasicAA can be so
1904   // random, in the worst case we'd need to rebuild MemorySSA from scratch after
1905   // every transformation, which defeats the purpose of using it. For such an
1906   // example, see test4 added in D51960.
1907 }
1908 
1909 void MemorySSA::verifyPrevDefInPhis(Function &F) const {
1910 #if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS)
1911   for (const BasicBlock &BB : F) {
1912     if (MemoryPhi *Phi = getMemoryAccess(&BB)) {
1913       for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
1914         auto *Pred = Phi->getIncomingBlock(I);
1915         auto *IncAcc = Phi->getIncomingValue(I);
1916         // If Pred has no unreachable predecessors, get last def looking at
1917         // IDoms. If, while walkings IDoms, any of these has an unreachable
1918         // predecessor, then the incoming def can be any access.
1919         if (auto *DTNode = DT->getNode(Pred)) {
1920           while (DTNode) {
1921             if (auto *DefList = getBlockDefs(DTNode->getBlock())) {
1922               auto *LastAcc = &*(--DefList->end());
1923               assert(LastAcc == IncAcc &&
1924                      "Incorrect incoming access into phi.");
1925               break;
1926             }
1927             DTNode = DTNode->getIDom();
1928           }
1929         } else {
1930           // If Pred has unreachable predecessors, but has at least a Def, the
1931           // incoming access can be the last Def in Pred, or it could have been
1932           // optimized to LoE. After an update, though, the LoE may have been
1933           // replaced by another access, so IncAcc may be any access.
1934           // If Pred has unreachable predecessors and no Defs, incoming access
1935           // should be LoE; However, after an update, it may be any access.
1936         }
1937       }
1938     }
1939   }
1940 #endif
1941 }
1942 
1943 /// Verify that all of the blocks we believe to have valid domination numbers
1944 /// actually have valid domination numbers.
1945 void MemorySSA::verifyDominationNumbers(const Function &F) const {
1946 #ifndef NDEBUG
1947   if (BlockNumberingValid.empty())
1948     return;
1949 
1950   SmallPtrSet<const BasicBlock *, 16> ValidBlocks = BlockNumberingValid;
1951   for (const BasicBlock &BB : F) {
1952     if (!ValidBlocks.count(&BB))
1953       continue;
1954 
1955     ValidBlocks.erase(&BB);
1956 
1957     const AccessList *Accesses = getBlockAccesses(&BB);
1958     // It's correct to say an empty block has valid numbering.
1959     if (!Accesses)
1960       continue;
1961 
1962     // Block numbering starts at 1.
1963     unsigned long LastNumber = 0;
1964     for (const MemoryAccess &MA : *Accesses) {
1965       auto ThisNumberIter = BlockNumbering.find(&MA);
1966       assert(ThisNumberIter != BlockNumbering.end() &&
1967              "MemoryAccess has no domination number in a valid block!");
1968 
1969       unsigned long ThisNumber = ThisNumberIter->second;
1970       assert(ThisNumber > LastNumber &&
1971              "Domination numbers should be strictly increasing!");
1972       LastNumber = ThisNumber;
1973     }
1974   }
1975 
1976   assert(ValidBlocks.empty() &&
1977          "All valid BasicBlocks should exist in F -- dangling pointers?");
1978 #endif
1979 }
1980 
1981 /// Verify ordering: the order and existence of MemoryAccesses matches the
1982 /// order and existence of memory affecting instructions.
1983 /// Verify domination: each definition dominates all of its uses.
1984 /// Verify def-uses: the immediate use information - walk all the memory
1985 /// accesses and verifying that, for each use, it appears in the appropriate
1986 /// def's use list
1987 void MemorySSA::verifyOrderingDominationAndDefUses(Function &F) const {
1988 #if !defined(NDEBUG)
1989   // Walk all the blocks, comparing what the lookups think and what the access
1990   // lists think, as well as the order in the blocks vs the order in the access
1991   // lists.
1992   SmallVector<MemoryAccess *, 32> ActualAccesses;
1993   SmallVector<MemoryAccess *, 32> ActualDefs;
1994   for (BasicBlock &B : F) {
1995     const AccessList *AL = getBlockAccesses(&B);
1996     const auto *DL = getBlockDefs(&B);
1997     MemoryPhi *Phi = getMemoryAccess(&B);
1998     if (Phi) {
1999       // Verify ordering.
2000       ActualAccesses.push_back(Phi);
2001       ActualDefs.push_back(Phi);
2002       // Verify domination
2003       for (const Use &U : Phi->uses())
2004         assert(dominates(Phi, U) && "Memory PHI does not dominate it's uses");
2005 #if defined(EXPENSIVE_CHECKS)
2006       // Verify def-uses.
2007       assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
2008                                           pred_begin(&B), pred_end(&B))) &&
2009              "Incomplete MemoryPhi Node");
2010       for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
2011         verifyUseInDefs(Phi->getIncomingValue(I), Phi);
2012         assert(find(predecessors(&B), Phi->getIncomingBlock(I)) !=
2013                    pred_end(&B) &&
2014                "Incoming phi block not a block predecessor");
2015       }
2016 #endif
2017     }
2018 
2019     for (Instruction &I : B) {
2020       MemoryUseOrDef *MA = getMemoryAccess(&I);
2021       assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
2022              "We have memory affecting instructions "
2023              "in this block but they are not in the "
2024              "access list or defs list");
2025       if (MA) {
2026         // Verify ordering.
2027         ActualAccesses.push_back(MA);
2028         if (MemoryAccess *MD = dyn_cast<MemoryDef>(MA)) {
2029           // Verify ordering.
2030           ActualDefs.push_back(MA);
2031           // Verify domination.
2032           for (const Use &U : MD->uses())
2033             assert(dominates(MD, U) &&
2034                    "Memory Def does not dominate it's uses");
2035         }
2036 #if defined(EXPENSIVE_CHECKS)
2037         // Verify def-uses.
2038         verifyUseInDefs(MA->getDefiningAccess(), MA);
2039 #endif
2040       }
2041     }
2042     // Either we hit the assert, really have no accesses, or we have both
2043     // accesses and an access list. Same with defs.
2044     if (!AL && !DL)
2045       continue;
2046     // Verify ordering.
2047     assert(AL->size() == ActualAccesses.size() &&
2048            "We don't have the same number of accesses in the block as on the "
2049            "access list");
2050     assert((DL || ActualDefs.size() == 0) &&
2051            "Either we should have a defs list, or we should have no defs");
2052     assert((!DL || DL->size() == ActualDefs.size()) &&
2053            "We don't have the same number of defs in the block as on the "
2054            "def list");
2055     auto ALI = AL->begin();
2056     auto AAI = ActualAccesses.begin();
2057     while (ALI != AL->end() && AAI != ActualAccesses.end()) {
2058       assert(&*ALI == *AAI && "Not the same accesses in the same order");
2059       ++ALI;
2060       ++AAI;
2061     }
2062     ActualAccesses.clear();
2063     if (DL) {
2064       auto DLI = DL->begin();
2065       auto ADI = ActualDefs.begin();
2066       while (DLI != DL->end() && ADI != ActualDefs.end()) {
2067         assert(&*DLI == *ADI && "Not the same defs in the same order");
2068         ++DLI;
2069         ++ADI;
2070       }
2071     }
2072     ActualDefs.clear();
2073   }
2074 #endif
2075 }
2076 
2077 /// Verify the def-use lists in MemorySSA, by verifying that \p Use
2078 /// appears in the use list of \p Def.
2079 void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
2080 #ifndef NDEBUG
2081   // The live on entry use may cause us to get a NULL def here
2082   if (!Def)
2083     assert(isLiveOnEntryDef(Use) &&
2084            "Null def but use not point to live on entry def");
2085   else
2086     assert(is_contained(Def->users(), Use) &&
2087            "Did not find use in def's use list");
2088 #endif
2089 }
2090 
2091 /// Perform a local numbering on blocks so that instruction ordering can be
2092 /// determined in constant time.
2093 /// TODO: We currently just number in order.  If we numbered by N, we could
2094 /// allow at least N-1 sequences of insertBefore or insertAfter (and at least
2095 /// log2(N) sequences of mixed before and after) without needing to invalidate
2096 /// the numbering.
2097 void MemorySSA::renumberBlock(const BasicBlock *B) const {
2098   // The pre-increment ensures the numbers really start at 1.
2099   unsigned long CurrentNumber = 0;
2100   const AccessList *AL = getBlockAccesses(B);
2101   assert(AL != nullptr && "Asking to renumber an empty block");
2102   for (const auto &I : *AL)
2103     BlockNumbering[&I] = ++CurrentNumber;
2104   BlockNumberingValid.insert(B);
2105 }
2106 
2107 /// Determine, for two memory accesses in the same block,
2108 /// whether \p Dominator dominates \p Dominatee.
2109 /// \returns True if \p Dominator dominates \p Dominatee.
2110 bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
2111                                  const MemoryAccess *Dominatee) const {
2112   const BasicBlock *DominatorBlock = Dominator->getBlock();
2113 
2114   assert((DominatorBlock == Dominatee->getBlock()) &&
2115          "Asking for local domination when accesses are in different blocks!");
2116   // A node dominates itself.
2117   if (Dominatee == Dominator)
2118     return true;
2119 
2120   // When Dominatee is defined on function entry, it is not dominated by another
2121   // memory access.
2122   if (isLiveOnEntryDef(Dominatee))
2123     return false;
2124 
2125   // When Dominator is defined on function entry, it dominates the other memory
2126   // access.
2127   if (isLiveOnEntryDef(Dominator))
2128     return true;
2129 
2130   if (!BlockNumberingValid.count(DominatorBlock))
2131     renumberBlock(DominatorBlock);
2132 
2133   unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
2134   // All numbers start with 1
2135   assert(DominatorNum != 0 && "Block was not numbered properly");
2136   unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
2137   assert(DominateeNum != 0 && "Block was not numbered properly");
2138   return DominatorNum < DominateeNum;
2139 }
2140 
2141 bool MemorySSA::dominates(const MemoryAccess *Dominator,
2142                           const MemoryAccess *Dominatee) const {
2143   if (Dominator == Dominatee)
2144     return true;
2145 
2146   if (isLiveOnEntryDef(Dominatee))
2147     return false;
2148 
2149   if (Dominator->getBlock() != Dominatee->getBlock())
2150     return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
2151   return locallyDominates(Dominator, Dominatee);
2152 }
2153 
2154 bool MemorySSA::dominates(const MemoryAccess *Dominator,
2155                           const Use &Dominatee) const {
2156   if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
2157     BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
2158     // The def must dominate the incoming block of the phi.
2159     if (UseBB != Dominator->getBlock())
2160       return DT->dominates(Dominator->getBlock(), UseBB);
2161     // If the UseBB and the DefBB are the same, compare locally.
2162     return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
2163   }
2164   // If it's not a PHI node use, the normal dominates can already handle it.
2165   return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
2166 }
2167 
2168 const static char LiveOnEntryStr[] = "liveOnEntry";
2169 
2170 void MemoryAccess::print(raw_ostream &OS) const {
2171   switch (getValueID()) {
2172   case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS);
2173   case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS);
2174   case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS);
2175   }
2176   llvm_unreachable("invalid value id");
2177 }
2178 
2179 void MemoryDef::print(raw_ostream &OS) const {
2180   MemoryAccess *UO = getDefiningAccess();
2181 
2182   auto printID = [&OS](MemoryAccess *A) {
2183     if (A && A->getID())
2184       OS << A->getID();
2185     else
2186       OS << LiveOnEntryStr;
2187   };
2188 
2189   OS << getID() << " = MemoryDef(";
2190   printID(UO);
2191   OS << ")";
2192 
2193   if (isOptimized()) {
2194     OS << "->";
2195     printID(getOptimized());
2196 
2197     if (Optional<AliasResult> AR = getOptimizedAccessType())
2198       OS << " " << *AR;
2199   }
2200 }
2201 
2202 void MemoryPhi::print(raw_ostream &OS) const {
2203   bool First = true;
2204   OS << getID() << " = MemoryPhi(";
2205   for (const auto &Op : operands()) {
2206     BasicBlock *BB = getIncomingBlock(Op);
2207     MemoryAccess *MA = cast<MemoryAccess>(Op);
2208     if (!First)
2209       OS << ',';
2210     else
2211       First = false;
2212 
2213     OS << '{';
2214     if (BB->hasName())
2215       OS << BB->getName();
2216     else
2217       BB->printAsOperand(OS, false);
2218     OS << ',';
2219     if (unsigned ID = MA->getID())
2220       OS << ID;
2221     else
2222       OS << LiveOnEntryStr;
2223     OS << '}';
2224   }
2225   OS << ')';
2226 }
2227 
2228 void MemoryUse::print(raw_ostream &OS) const {
2229   MemoryAccess *UO = getDefiningAccess();
2230   OS << "MemoryUse(";
2231   if (UO && UO->getID())
2232     OS << UO->getID();
2233   else
2234     OS << LiveOnEntryStr;
2235   OS << ')';
2236 
2237   if (Optional<AliasResult> AR = getOptimizedAccessType())
2238     OS << " " << *AR;
2239 }
2240 
2241 void MemoryAccess::dump() const {
2242 // Cannot completely remove virtual function even in release mode.
2243 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2244   print(dbgs());
2245   dbgs() << "\n";
2246 #endif
2247 }
2248 
2249 char MemorySSAPrinterLegacyPass::ID = 0;
2250 
2251 MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2252   initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2253 }
2254 
2255 void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2256   AU.setPreservesAll();
2257   AU.addRequired<MemorySSAWrapperPass>();
2258 }
2259 
2260 bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2261   auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2262   MSSA.print(dbgs());
2263   if (VerifyMemorySSA)
2264     MSSA.verifyMemorySSA();
2265   return false;
2266 }
2267 
2268 AnalysisKey MemorySSAAnalysis::Key;
2269 
2270 MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
2271                                                  FunctionAnalysisManager &AM) {
2272   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2273   auto &AA = AM.getResult<AAManager>(F);
2274   return MemorySSAAnalysis::Result(std::make_unique<MemorySSA>(F, &AA, &DT));
2275 }
2276 
2277 bool MemorySSAAnalysis::Result::invalidate(
2278     Function &F, const PreservedAnalyses &PA,
2279     FunctionAnalysisManager::Invalidator &Inv) {
2280   auto PAC = PA.getChecker<MemorySSAAnalysis>();
2281   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
2282          Inv.invalidate<AAManager>(F, PA) ||
2283          Inv.invalidate<DominatorTreeAnalysis>(F, PA);
2284 }
2285 
2286 PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2287                                             FunctionAnalysisManager &AM) {
2288   OS << "MemorySSA for function: " << F.getName() << "\n";
2289   AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
2290 
2291   return PreservedAnalyses::all();
2292 }
2293 
2294 PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2295                                              FunctionAnalysisManager &AM) {
2296   AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
2297 
2298   return PreservedAnalyses::all();
2299 }
2300 
2301 char MemorySSAWrapperPass::ID = 0;
2302 
2303 MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2304   initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2305 }
2306 
2307 void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2308 
2309 void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
2310   AU.setPreservesAll();
2311   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2312   AU.addRequiredTransitive<AAResultsWrapperPass>();
2313 }
2314 
2315 bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2316   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2317   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2318   MSSA.reset(new MemorySSA(F, &AA, &DT));
2319   return false;
2320 }
2321 
2322 void MemorySSAWrapperPass::verifyAnalysis() const {
2323   if (VerifyMemorySSA)
2324     MSSA->verifyMemorySSA();
2325 }
2326 
2327 void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
2328   MSSA->print(OS);
2329 }
2330 
2331 MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2332 
2333 /// Walk the use-def chains starting at \p StartingAccess and find
2334 /// the MemoryAccess that actually clobbers Loc.
2335 ///
2336 /// \returns our clobbering memory access
2337 template <typename AliasAnalysisType>
2338 MemoryAccess *
2339 MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
2340     MemoryAccess *StartingAccess, const MemoryLocation &Loc,
2341     unsigned &UpwardWalkLimit) {
2342   if (isa<MemoryPhi>(StartingAccess))
2343     return StartingAccess;
2344 
2345   auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2346   if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2347     return StartingUseOrDef;
2348 
2349   Instruction *I = StartingUseOrDef->getMemoryInst();
2350 
2351   // Conservatively, fences are always clobbers, so don't perform the walk if we
2352   // hit a fence.
2353   if (!isa<CallBase>(I) && I->isFenceLike())
2354     return StartingUseOrDef;
2355 
2356   UpwardsMemoryQuery Q;
2357   Q.OriginalAccess = StartingUseOrDef;
2358   Q.StartingLoc = Loc;
2359   Q.Inst = I;
2360   Q.IsCall = false;
2361 
2362   // Unlike the other function, do not walk to the def of a def, because we are
2363   // handed something we already believe is the clobbering access.
2364   // We never set SkipSelf to true in Q in this method.
2365   MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2366                                      ? StartingUseOrDef->getDefiningAccess()
2367                                      : StartingUseOrDef;
2368 
2369   MemoryAccess *Clobber =
2370       Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
2371   LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2372   LLVM_DEBUG(dbgs() << *StartingUseOrDef << "\n");
2373   LLVM_DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2374   LLVM_DEBUG(dbgs() << *Clobber << "\n");
2375   return Clobber;
2376 }
2377 
2378 template <typename AliasAnalysisType>
2379 MemoryAccess *
2380 MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
2381     MemoryAccess *MA, unsigned &UpwardWalkLimit, bool SkipSelf) {
2382   auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2383   // If this is a MemoryPhi, we can't do anything.
2384   if (!StartingAccess)
2385     return MA;
2386 
2387   bool IsOptimized = false;
2388 
2389   // If this is an already optimized use or def, return the optimized result.
2390   // Note: Currently, we store the optimized def result in a separate field,
2391   // since we can't use the defining access.
2392   if (StartingAccess->isOptimized()) {
2393     if (!SkipSelf || !isa<MemoryDef>(StartingAccess))
2394       return StartingAccess->getOptimized();
2395     IsOptimized = true;
2396   }
2397 
2398   const Instruction *I = StartingAccess->getMemoryInst();
2399   // We can't sanely do anything with a fence, since they conservatively clobber
2400   // all memory, and have no locations to get pointers from to try to
2401   // disambiguate.
2402   if (!isa<CallBase>(I) && I->isFenceLike())
2403     return StartingAccess;
2404 
2405   UpwardsMemoryQuery Q(I, StartingAccess);
2406 
2407   if (isUseTriviallyOptimizableToLiveOnEntry(*Walker.getAA(), I)) {
2408     MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2409     StartingAccess->setOptimized(LiveOnEntry);
2410     StartingAccess->setOptimizedAccessType(None);
2411     return LiveOnEntry;
2412   }
2413 
2414   MemoryAccess *OptimizedAccess;
2415   if (!IsOptimized) {
2416     // Start with the thing we already think clobbers this location
2417     MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2418 
2419     // At this point, DefiningAccess may be the live on entry def.
2420     // If it is, we will not get a better result.
2421     if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
2422       StartingAccess->setOptimized(DefiningAccess);
2423       StartingAccess->setOptimizedAccessType(None);
2424       return DefiningAccess;
2425     }
2426 
2427     OptimizedAccess = Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
2428     StartingAccess->setOptimized(OptimizedAccess);
2429     if (MSSA->isLiveOnEntryDef(OptimizedAccess))
2430       StartingAccess->setOptimizedAccessType(None);
2431     else if (Q.AR == MustAlias)
2432       StartingAccess->setOptimizedAccessType(MustAlias);
2433   } else
2434     OptimizedAccess = StartingAccess->getOptimized();
2435 
2436   LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2437   LLVM_DEBUG(dbgs() << *StartingAccess << "\n");
2438   LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ");
2439   LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n");
2440 
2441   MemoryAccess *Result;
2442   if (SkipSelf && isa<MemoryPhi>(OptimizedAccess) &&
2443       isa<MemoryDef>(StartingAccess) && UpwardWalkLimit) {
2444     assert(isa<MemoryDef>(Q.OriginalAccess));
2445     Q.SkipSelfAccess = true;
2446     Result = Walker.findClobber(OptimizedAccess, Q, UpwardWalkLimit);
2447   } else
2448     Result = OptimizedAccess;
2449 
2450   LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf);
2451   LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n");
2452 
2453   return Result;
2454 }
2455 
2456 MemoryAccess *
2457 DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2458   if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2459     return Use->getDefiningAccess();
2460   return MA;
2461 }
2462 
2463 MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
2464     MemoryAccess *StartingAccess, const MemoryLocation &) {
2465   if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2466     return Use->getDefiningAccess();
2467   return StartingAccess;
2468 }
2469 
2470 void MemoryPhi::deleteMe(DerivedUser *Self) {
2471   delete static_cast<MemoryPhi *>(Self);
2472 }
2473 
2474 void MemoryDef::deleteMe(DerivedUser *Self) {
2475   delete static_cast<MemoryDef *>(Self);
2476 }
2477 
2478 void MemoryUse::deleteMe(DerivedUser *Self) {
2479   delete static_cast<MemoryUse *>(Self);
2480 }
2481