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