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