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