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