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