10b57cec5SDimitry Andric //===- MemorySSA.cpp - Memory SSA Builder ---------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the MemorySSA class.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
140b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
150b57cec5SDimitry Andric #include "llvm/ADT/DenseMapInfo.h"
160b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
180b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
22fe6060f1SDimitry Andric #include "llvm/ADT/StringExtras.h"
230b57cec5SDimitry Andric #include "llvm/ADT/iterator.h"
240b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
26e8d8bef9SDimitry Andric #include "llvm/Analysis/CFGPrinter.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/IteratedDominanceFrontier.h"
280b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
290b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
300b57cec5SDimitry Andric #include "llvm/IR/AssemblyAnnotationWriter.h"
310b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
320b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
330b57cec5SDimitry Andric #include "llvm/IR/Function.h"
340b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
350b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
360b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
370b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
3881ad6265SDimitry Andric #include "llvm/IR/Operator.h"
390b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
400b57cec5SDimitry Andric #include "llvm/IR/Use.h"
41480093f4SDimitry Andric #include "llvm/InitializePasses.h"
420b57cec5SDimitry Andric #include "llvm/Pass.h"
430b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
440b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
450b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
460b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
470b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
480b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
490b57cec5SDimitry Andric #include "llvm/Support/FormattedStream.h"
5081ad6265SDimitry Andric #include "llvm/Support/GraphWriter.h"
510b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
520b57cec5SDimitry Andric #include <algorithm>
530b57cec5SDimitry Andric #include <cassert>
540b57cec5SDimitry Andric #include <iterator>
550b57cec5SDimitry Andric #include <memory>
560b57cec5SDimitry Andric #include <utility>
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric using namespace llvm;
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric #define DEBUG_TYPE "memoryssa"
610b57cec5SDimitry Andric 
62e8d8bef9SDimitry Andric static cl::opt<std::string>
63e8d8bef9SDimitry Andric     DotCFGMSSA("dot-cfg-mssa",
64e8d8bef9SDimitry Andric                cl::value_desc("file name for generated dot file"),
65e8d8bef9SDimitry Andric                cl::desc("file name for generated dot file"), cl::init(""));
66e8d8bef9SDimitry Andric 
670b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
680b57cec5SDimitry Andric                       true)
690b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
700b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
710b57cec5SDimitry Andric INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
720b57cec5SDimitry Andric                     true)
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric static cl::opt<unsigned> MaxCheckLimit(
750b57cec5SDimitry Andric     "memssa-check-limit", cl::Hidden, cl::init(100),
760b57cec5SDimitry Andric     cl::desc("The maximum number of stores/phis MemorySSA"
770b57cec5SDimitry Andric              "will consider trying to walk past (default = 100)"));
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric // Always verify MemorySSA if expensive checking is enabled.
800b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS
810b57cec5SDimitry Andric bool llvm::VerifyMemorySSA = true;
820b57cec5SDimitry Andric #else
830b57cec5SDimitry Andric bool llvm::VerifyMemorySSA = false;
840b57cec5SDimitry Andric #endif
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric static cl::opt<bool, true>
870b57cec5SDimitry Andric     VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA),
880b57cec5SDimitry Andric                      cl::Hidden, cl::desc("Enable verification of MemorySSA."));
890b57cec5SDimitry Andric 
90349cc55cSDimitry Andric const static char LiveOnEntryStr[] = "liveOnEntry";
91349cc55cSDimitry Andric 
92349cc55cSDimitry Andric namespace {
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric /// An assembly annotator class to print Memory SSA information in
950b57cec5SDimitry Andric /// comments.
960b57cec5SDimitry Andric class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
970b57cec5SDimitry Andric   const MemorySSA *MSSA;
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric public:
MemorySSAAnnotatedWriter(const MemorySSA * M)1000b57cec5SDimitry Andric   MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
1010b57cec5SDimitry Andric 
emitBasicBlockStartAnnot(const BasicBlock * BB,formatted_raw_ostream & OS)1020b57cec5SDimitry Andric   void emitBasicBlockStartAnnot(const BasicBlock *BB,
1030b57cec5SDimitry Andric                                 formatted_raw_ostream &OS) override {
1040b57cec5SDimitry Andric     if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
1050b57cec5SDimitry Andric       OS << "; " << *MA << "\n";
1060b57cec5SDimitry Andric   }
1070b57cec5SDimitry Andric 
emitInstructionAnnot(const Instruction * I,formatted_raw_ostream & OS)1080b57cec5SDimitry Andric   void emitInstructionAnnot(const Instruction *I,
1090b57cec5SDimitry Andric                             formatted_raw_ostream &OS) override {
1100b57cec5SDimitry Andric     if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
1110b57cec5SDimitry Andric       OS << "; " << *MA << "\n";
1120b57cec5SDimitry Andric   }
1130b57cec5SDimitry Andric };
1140b57cec5SDimitry Andric 
115349cc55cSDimitry Andric /// An assembly annotator class to print Memory SSA information in
116349cc55cSDimitry Andric /// comments.
117349cc55cSDimitry Andric class MemorySSAWalkerAnnotatedWriter : public AssemblyAnnotationWriter {
118349cc55cSDimitry Andric   MemorySSA *MSSA;
119349cc55cSDimitry Andric   MemorySSAWalker *Walker;
120bdd1243dSDimitry Andric   BatchAAResults BAA;
121349cc55cSDimitry Andric 
122349cc55cSDimitry Andric public:
MemorySSAWalkerAnnotatedWriter(MemorySSA * M)123349cc55cSDimitry Andric   MemorySSAWalkerAnnotatedWriter(MemorySSA *M)
124bdd1243dSDimitry Andric       : MSSA(M), Walker(M->getWalker()), BAA(M->getAA()) {}
125349cc55cSDimitry Andric 
emitBasicBlockStartAnnot(const BasicBlock * BB,formatted_raw_ostream & OS)12681ad6265SDimitry Andric   void emitBasicBlockStartAnnot(const BasicBlock *BB,
12781ad6265SDimitry Andric                                 formatted_raw_ostream &OS) override {
12881ad6265SDimitry Andric     if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
12981ad6265SDimitry Andric       OS << "; " << *MA << "\n";
13081ad6265SDimitry Andric   }
13181ad6265SDimitry Andric 
emitInstructionAnnot(const Instruction * I,formatted_raw_ostream & OS)132349cc55cSDimitry Andric   void emitInstructionAnnot(const Instruction *I,
133349cc55cSDimitry Andric                             formatted_raw_ostream &OS) override {
134349cc55cSDimitry Andric     if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) {
135bdd1243dSDimitry Andric       MemoryAccess *Clobber = Walker->getClobberingMemoryAccess(MA, BAA);
136349cc55cSDimitry Andric       OS << "; " << *MA;
137349cc55cSDimitry Andric       if (Clobber) {
138349cc55cSDimitry Andric         OS << " - clobbered by ";
139349cc55cSDimitry Andric         if (MSSA->isLiveOnEntryDef(Clobber))
140349cc55cSDimitry Andric           OS << LiveOnEntryStr;
141349cc55cSDimitry Andric         else
142349cc55cSDimitry Andric           OS << *Clobber;
143349cc55cSDimitry Andric       }
144349cc55cSDimitry Andric       OS << "\n";
145349cc55cSDimitry Andric     }
146349cc55cSDimitry Andric   }
147349cc55cSDimitry Andric };
148349cc55cSDimitry Andric 
149349cc55cSDimitry Andric } // namespace
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric namespace {
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric /// Our current alias analysis API differentiates heavily between calls and
1540b57cec5SDimitry Andric /// non-calls, and functions called on one usually assert on the other.
1550b57cec5SDimitry Andric /// This class encapsulates the distinction to simplify other code that wants
1560b57cec5SDimitry Andric /// "Memory affecting instructions and related data" to use as a key.
1570b57cec5SDimitry Andric /// For example, this class is used as a densemap key in the use optimizer.
1580b57cec5SDimitry Andric class MemoryLocOrCall {
1590b57cec5SDimitry Andric public:
1600b57cec5SDimitry Andric   bool IsCall = false;
1610b57cec5SDimitry Andric 
MemoryLocOrCall(MemoryUseOrDef * MUD)1620b57cec5SDimitry Andric   MemoryLocOrCall(MemoryUseOrDef *MUD)
1630b57cec5SDimitry Andric       : MemoryLocOrCall(MUD->getMemoryInst()) {}
MemoryLocOrCall(const MemoryUseOrDef * MUD)1640b57cec5SDimitry Andric   MemoryLocOrCall(const MemoryUseOrDef *MUD)
1650b57cec5SDimitry Andric       : MemoryLocOrCall(MUD->getMemoryInst()) {}
1660b57cec5SDimitry Andric 
MemoryLocOrCall(Instruction * Inst)1670b57cec5SDimitry Andric   MemoryLocOrCall(Instruction *Inst) {
1680b57cec5SDimitry Andric     if (auto *C = dyn_cast<CallBase>(Inst)) {
1690b57cec5SDimitry Andric       IsCall = true;
1700b57cec5SDimitry Andric       Call = C;
1710b57cec5SDimitry Andric     } else {
1720b57cec5SDimitry Andric       IsCall = false;
1730b57cec5SDimitry Andric       // There is no such thing as a memorylocation for a fence inst, and it is
1740b57cec5SDimitry Andric       // unique in that regard.
1750b57cec5SDimitry Andric       if (!isa<FenceInst>(Inst))
1760b57cec5SDimitry Andric         Loc = MemoryLocation::get(Inst);
1770b57cec5SDimitry Andric     }
1780b57cec5SDimitry Andric   }
1790b57cec5SDimitry Andric 
MemoryLocOrCall(const MemoryLocation & Loc)1800b57cec5SDimitry Andric   explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {}
1810b57cec5SDimitry Andric 
getCall() const1820b57cec5SDimitry Andric   const CallBase *getCall() const {
1830b57cec5SDimitry Andric     assert(IsCall);
1840b57cec5SDimitry Andric     return Call;
1850b57cec5SDimitry Andric   }
1860b57cec5SDimitry Andric 
getLoc() const1870b57cec5SDimitry Andric   MemoryLocation getLoc() const {
1880b57cec5SDimitry Andric     assert(!IsCall);
1890b57cec5SDimitry Andric     return Loc;
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric 
operator ==(const MemoryLocOrCall & Other) const1920b57cec5SDimitry Andric   bool operator==(const MemoryLocOrCall &Other) const {
1930b57cec5SDimitry Andric     if (IsCall != Other.IsCall)
1940b57cec5SDimitry Andric       return false;
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric     if (!IsCall)
1970b57cec5SDimitry Andric       return Loc == Other.Loc;
1980b57cec5SDimitry Andric 
1995ffd83dbSDimitry Andric     if (Call->getCalledOperand() != Other.Call->getCalledOperand())
2000b57cec5SDimitry Andric       return false;
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric     return Call->arg_size() == Other.Call->arg_size() &&
2030b57cec5SDimitry Andric            std::equal(Call->arg_begin(), Call->arg_end(),
2040b57cec5SDimitry Andric                       Other.Call->arg_begin());
2050b57cec5SDimitry Andric   }
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric private:
2080b57cec5SDimitry Andric   union {
2090b57cec5SDimitry Andric     const CallBase *Call;
2100b57cec5SDimitry Andric     MemoryLocation Loc;
2110b57cec5SDimitry Andric   };
2120b57cec5SDimitry Andric };
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric } // end anonymous namespace
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric namespace llvm {
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric template <> struct DenseMapInfo<MemoryLocOrCall> {
getEmptyKeyllvm::DenseMapInfo2190b57cec5SDimitry Andric   static inline MemoryLocOrCall getEmptyKey() {
2200b57cec5SDimitry Andric     return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
2210b57cec5SDimitry Andric   }
2220b57cec5SDimitry Andric 
getTombstoneKeyllvm::DenseMapInfo2230b57cec5SDimitry Andric   static inline MemoryLocOrCall getTombstoneKey() {
2240b57cec5SDimitry Andric     return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
2250b57cec5SDimitry Andric   }
2260b57cec5SDimitry Andric 
getHashValuellvm::DenseMapInfo2270b57cec5SDimitry Andric   static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
2280b57cec5SDimitry Andric     if (!MLOC.IsCall)
2290b57cec5SDimitry Andric       return hash_combine(
2300b57cec5SDimitry Andric           MLOC.IsCall,
2310b57cec5SDimitry Andric           DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric     hash_code hash =
2340b57cec5SDimitry Andric         hash_combine(MLOC.IsCall, DenseMapInfo<const Value *>::getHashValue(
2355ffd83dbSDimitry Andric                                       MLOC.getCall()->getCalledOperand()));
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric     for (const Value *Arg : MLOC.getCall()->args())
2380b57cec5SDimitry Andric       hash = hash_combine(hash, DenseMapInfo<const Value *>::getHashValue(Arg));
2390b57cec5SDimitry Andric     return hash;
2400b57cec5SDimitry Andric   }
2410b57cec5SDimitry Andric 
isEqualllvm::DenseMapInfo2420b57cec5SDimitry Andric   static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
2430b57cec5SDimitry Andric     return LHS == RHS;
2440b57cec5SDimitry Andric   }
2450b57cec5SDimitry Andric };
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric } // end namespace llvm
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric /// This does one-way checks to see if Use could theoretically be hoisted above
2500b57cec5SDimitry Andric /// MayClobber. This will not check the other way around.
2510b57cec5SDimitry Andric ///
2520b57cec5SDimitry Andric /// This assumes that, for the purposes of MemorySSA, Use comes directly after
2530b57cec5SDimitry Andric /// MayClobber, with no potentially clobbering operations in between them.
2540b57cec5SDimitry Andric /// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
areLoadsReorderable(const LoadInst * Use,const LoadInst * MayClobber)2550b57cec5SDimitry Andric static bool areLoadsReorderable(const LoadInst *Use,
2560b57cec5SDimitry Andric                                 const LoadInst *MayClobber) {
2570b57cec5SDimitry Andric   bool VolatileUse = Use->isVolatile();
2580b57cec5SDimitry Andric   bool VolatileClobber = MayClobber->isVolatile();
2590b57cec5SDimitry Andric   // Volatile operations may never be reordered with other volatile operations.
2600b57cec5SDimitry Andric   if (VolatileUse && VolatileClobber)
2610b57cec5SDimitry Andric     return false;
2620b57cec5SDimitry Andric   // Otherwise, volatile doesn't matter here. From the language reference:
2630b57cec5SDimitry Andric   // 'optimizers may change the order of volatile operations relative to
2640b57cec5SDimitry Andric   // non-volatile operations.'"
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric   // If a load is seq_cst, it cannot be moved above other loads. If its ordering
2670b57cec5SDimitry Andric   // is weaker, it can be moved above other loads. We just need to be sure that
2680b57cec5SDimitry Andric   // MayClobber isn't an acquire load, because loads can't be moved above
2690b57cec5SDimitry Andric   // acquire loads.
2700b57cec5SDimitry Andric   //
2710b57cec5SDimitry Andric   // Note that this explicitly *does* allow the free reordering of monotonic (or
2720b57cec5SDimitry Andric   // weaker) loads of the same address.
2730b57cec5SDimitry Andric   bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
2740b57cec5SDimitry Andric   bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
2750b57cec5SDimitry Andric                                                      AtomicOrdering::Acquire);
2760b57cec5SDimitry Andric   return !(SeqCstUse || MayClobberIsAcquire);
2770b57cec5SDimitry Andric }
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric template <typename AliasAnalysisType>
280bdd1243dSDimitry Andric static bool
instructionClobbersQuery(const MemoryDef * MD,const MemoryLocation & UseLoc,const Instruction * UseInst,AliasAnalysisType & AA)2810b57cec5SDimitry Andric instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc,
2820b57cec5SDimitry Andric                          const Instruction *UseInst, AliasAnalysisType &AA) {
2830b57cec5SDimitry Andric   Instruction *DefInst = MD->getMemoryInst();
2840b57cec5SDimitry Andric   assert(DefInst && "Defining instruction not actually an instruction");
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
2870b57cec5SDimitry Andric     // These intrinsics will show up as affecting memory, but they are just
2880b57cec5SDimitry Andric     // markers, mostly.
2890b57cec5SDimitry Andric     //
2900b57cec5SDimitry Andric     // FIXME: We probably don't actually want MemorySSA to model these at all
2910b57cec5SDimitry Andric     // (including creating MemoryAccesses for them): we just end up inventing
2920b57cec5SDimitry Andric     // clobbers where they don't really exist at all. Please see D43269 for
2930b57cec5SDimitry Andric     // context.
2940b57cec5SDimitry Andric     switch (II->getIntrinsicID()) {
2950b57cec5SDimitry Andric     case Intrinsic::invariant_start:
2960b57cec5SDimitry Andric     case Intrinsic::invariant_end:
2970b57cec5SDimitry Andric     case Intrinsic::assume:
298e8d8bef9SDimitry Andric     case Intrinsic::experimental_noalias_scope_decl:
299349cc55cSDimitry Andric     case Intrinsic::pseudoprobe:
300bdd1243dSDimitry Andric       return false;
3018bcb0991SDimitry Andric     case Intrinsic::dbg_declare:
3028bcb0991SDimitry Andric     case Intrinsic::dbg_label:
3038bcb0991SDimitry Andric     case Intrinsic::dbg_value:
3048bcb0991SDimitry Andric       llvm_unreachable("debuginfo shouldn't have associated defs!");
3050b57cec5SDimitry Andric     default:
3060b57cec5SDimitry Andric       break;
3070b57cec5SDimitry Andric     }
3080b57cec5SDimitry Andric   }
3090b57cec5SDimitry Andric 
310e8d8bef9SDimitry Andric   if (auto *CB = dyn_cast_or_null<CallBase>(UseInst)) {
311e8d8bef9SDimitry Andric     ModRefInfo I = AA.getModRefInfo(DefInst, CB);
312bdd1243dSDimitry Andric     return isModOrRefSet(I);
3130b57cec5SDimitry Andric   }
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric   if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
316e8d8bef9SDimitry Andric     if (auto *UseLoad = dyn_cast_or_null<LoadInst>(UseInst))
317bdd1243dSDimitry Andric       return !areLoadsReorderable(UseLoad, DefLoad);
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric   ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
320bdd1243dSDimitry Andric   return isModSet(I);
3210b57cec5SDimitry Andric }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric template <typename AliasAnalysisType>
instructionClobbersQuery(MemoryDef * MD,const MemoryUseOrDef * MU,const MemoryLocOrCall & UseMLOC,AliasAnalysisType & AA)324bdd1243dSDimitry Andric static bool instructionClobbersQuery(MemoryDef *MD, const MemoryUseOrDef *MU,
3250b57cec5SDimitry Andric                                      const MemoryLocOrCall &UseMLOC,
3260b57cec5SDimitry Andric                                      AliasAnalysisType &AA) {
3270b57cec5SDimitry Andric   // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
3280b57cec5SDimitry Andric   // to exist while MemoryLocOrCall is pushed through places.
3290b57cec5SDimitry Andric   if (UseMLOC.IsCall)
3300b57cec5SDimitry Andric     return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
3310b57cec5SDimitry Andric                                     AA);
3320b57cec5SDimitry Andric   return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
3330b57cec5SDimitry Andric                                   AA);
3340b57cec5SDimitry Andric }
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric // Return true when MD may alias MU, return false otherwise.
defClobbersUseOrDef(MemoryDef * MD,const MemoryUseOrDef * MU,AliasAnalysis & AA)3370b57cec5SDimitry Andric bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
3380b57cec5SDimitry Andric                                         AliasAnalysis &AA) {
339bdd1243dSDimitry Andric   return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA);
3400b57cec5SDimitry Andric }
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric namespace {
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric struct UpwardsMemoryQuery {
3450b57cec5SDimitry Andric   // True if our original query started off as a call
3460b57cec5SDimitry Andric   bool IsCall = false;
3470b57cec5SDimitry Andric   // The pointer location we started the query with. This will be empty if
3480b57cec5SDimitry Andric   // IsCall is true.
3490b57cec5SDimitry Andric   MemoryLocation StartingLoc;
3500b57cec5SDimitry Andric   // This is the instruction we were querying about.
3510b57cec5SDimitry Andric   const Instruction *Inst = nullptr;
3520b57cec5SDimitry Andric   // The MemoryAccess we actually got called with, used to test local domination
3530b57cec5SDimitry Andric   const MemoryAccess *OriginalAccess = nullptr;
3540b57cec5SDimitry Andric   bool SkipSelfAccess = false;
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   UpwardsMemoryQuery() = default;
3570b57cec5SDimitry Andric 
UpwardsMemoryQuery__anonad0781eb0411::UpwardsMemoryQuery3580b57cec5SDimitry Andric   UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
3590b57cec5SDimitry Andric       : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) {
3600b57cec5SDimitry Andric     if (!IsCall)
3610b57cec5SDimitry Andric       StartingLoc = MemoryLocation::get(Inst);
3620b57cec5SDimitry Andric   }
3630b57cec5SDimitry Andric };
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric } // end anonymous namespace
3660b57cec5SDimitry Andric 
36706c3fb27SDimitry Andric template <typename AliasAnalysisType>
isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType & AA,const Instruction * I)36806c3fb27SDimitry Andric static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA,
3690b57cec5SDimitry Andric                                                    const Instruction *I) {
3700b57cec5SDimitry Andric   // If the memory can't be changed, then loads of the memory can't be
3710b57cec5SDimitry Andric   // clobbered.
372bdd1243dSDimitry Andric   if (auto *LI = dyn_cast<LoadInst>(I)) {
373e8d8bef9SDimitry Andric     return I->hasMetadata(LLVMContext::MD_invariant_load) ||
374bdd1243dSDimitry Andric            !isModSet(AA.getModRefInfoMask(MemoryLocation::get(LI)));
375bdd1243dSDimitry Andric   }
376e8d8bef9SDimitry Andric   return false;
3770b57cec5SDimitry Andric }
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric /// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
3800b57cec5SDimitry Andric /// inbetween `Start` and `ClobberAt` can clobbers `Start`.
3810b57cec5SDimitry Andric ///
3820b57cec5SDimitry Andric /// This is meant to be as simple and self-contained as possible. Because it
3830b57cec5SDimitry Andric /// uses no cache, etc., it can be relatively expensive.
3840b57cec5SDimitry Andric ///
3850b57cec5SDimitry Andric /// \param Start     The MemoryAccess that we want to walk from.
3860b57cec5SDimitry Andric /// \param ClobberAt A clobber for Start.
3870b57cec5SDimitry Andric /// \param StartLoc  The MemoryLocation for Start.
3880b57cec5SDimitry Andric /// \param MSSA      The MemorySSA instance that Start and ClobberAt belong to.
3890b57cec5SDimitry Andric /// \param Query     The UpwardsMemoryQuery we used for our search.
3900b57cec5SDimitry Andric /// \param AA        The AliasAnalysis we used for our search.
3910b57cec5SDimitry Andric /// \param AllowImpreciseClobber Always false, unless we do relaxed verify.
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric LLVM_ATTRIBUTE_UNUSED static void
checkClobberSanity(const MemoryAccess * Start,MemoryAccess * ClobberAt,const MemoryLocation & StartLoc,const MemorySSA & MSSA,const UpwardsMemoryQuery & Query,BatchAAResults & AA,bool AllowImpreciseClobber=false)3940b57cec5SDimitry Andric checkClobberSanity(const MemoryAccess *Start, MemoryAccess *ClobberAt,
3950b57cec5SDimitry Andric                    const MemoryLocation &StartLoc, const MemorySSA &MSSA,
396bdd1243dSDimitry Andric                    const UpwardsMemoryQuery &Query, BatchAAResults &AA,
3970b57cec5SDimitry Andric                    bool AllowImpreciseClobber = false) {
3980b57cec5SDimitry Andric   assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric   if (MSSA.isLiveOnEntryDef(Start)) {
4010b57cec5SDimitry Andric     assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
4020b57cec5SDimitry Andric            "liveOnEntry must clobber itself");
4030b57cec5SDimitry Andric     return;
4040b57cec5SDimitry Andric   }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric   bool FoundClobber = false;
4070b57cec5SDimitry Andric   DenseSet<ConstMemoryAccessPair> VisitedPhis;
4080b57cec5SDimitry Andric   SmallVector<ConstMemoryAccessPair, 8> Worklist;
4090b57cec5SDimitry Andric   Worklist.emplace_back(Start, StartLoc);
4100b57cec5SDimitry Andric   // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
4110b57cec5SDimitry Andric   // is found, complain.
4120b57cec5SDimitry Andric   while (!Worklist.empty()) {
4130b57cec5SDimitry Andric     auto MAP = Worklist.pop_back_val();
4140b57cec5SDimitry Andric     // All we care about is that nothing from Start to ClobberAt clobbers Start.
4150b57cec5SDimitry Andric     // We learn nothing from revisiting nodes.
4160b57cec5SDimitry Andric     if (!VisitedPhis.insert(MAP).second)
4170b57cec5SDimitry Andric       continue;
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric     for (const auto *MA : def_chain(MAP.first)) {
4200b57cec5SDimitry Andric       if (MA == ClobberAt) {
4210b57cec5SDimitry Andric         if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
4220b57cec5SDimitry Andric           // instructionClobbersQuery isn't essentially free, so don't use `|=`,
4230b57cec5SDimitry Andric           // since it won't let us short-circuit.
4240b57cec5SDimitry Andric           //
4250b57cec5SDimitry Andric           // Also, note that this can't be hoisted out of the `Worklist` loop,
4260b57cec5SDimitry Andric           // since MD may only act as a clobber for 1 of N MemoryLocations.
4270b57cec5SDimitry Andric           FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD);
4280b57cec5SDimitry Andric           if (!FoundClobber) {
429bdd1243dSDimitry Andric             if (instructionClobbersQuery(MD, MAP.second, Query.Inst, AA))
4300b57cec5SDimitry Andric               FoundClobber = true;
4310b57cec5SDimitry Andric           }
4320b57cec5SDimitry Andric         }
4330b57cec5SDimitry Andric         break;
4340b57cec5SDimitry Andric       }
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric       // We should never hit liveOnEntry, unless it's the clobber.
4370b57cec5SDimitry Andric       assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric       if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
4400b57cec5SDimitry Andric         // If Start is a Def, skip self.
4410b57cec5SDimitry Andric         if (MD == Start)
4420b57cec5SDimitry Andric           continue;
4430b57cec5SDimitry Andric 
444bdd1243dSDimitry Andric         assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) &&
4450b57cec5SDimitry Andric                "Found clobber before reaching ClobberAt!");
4460b57cec5SDimitry Andric         continue;
4470b57cec5SDimitry Andric       }
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric       if (const auto *MU = dyn_cast<MemoryUse>(MA)) {
4500b57cec5SDimitry Andric         (void)MU;
4510b57cec5SDimitry Andric         assert (MU == Start &&
4520b57cec5SDimitry Andric                 "Can only find use in def chain if Start is a use");
4530b57cec5SDimitry Andric         continue;
4540b57cec5SDimitry Andric       }
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric       assert(isa<MemoryPhi>(MA));
457e8d8bef9SDimitry Andric 
458e8d8bef9SDimitry Andric       // Add reachable phi predecessors
459e8d8bef9SDimitry Andric       for (auto ItB = upward_defs_begin(
460e8d8bef9SDimitry Andric                     {const_cast<MemoryAccess *>(MA), MAP.second},
4615ffd83dbSDimitry Andric                     MSSA.getDomTree()),
462e8d8bef9SDimitry Andric                 ItE = upward_defs_end();
463e8d8bef9SDimitry Andric            ItB != ItE; ++ItB)
464e8d8bef9SDimitry Andric         if (MSSA.getDomTree().isReachableFromEntry(ItB.getPhiArgBlock()))
465e8d8bef9SDimitry Andric           Worklist.emplace_back(*ItB);
4660b57cec5SDimitry Andric     }
4670b57cec5SDimitry Andric   }
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   // If the verify is done following an optimization, it's possible that
4700b57cec5SDimitry Andric   // ClobberAt was a conservative clobbering, that we can now infer is not a
4710b57cec5SDimitry Andric   // true clobbering access. Don't fail the verify if that's the case.
4720b57cec5SDimitry Andric   // We do have accesses that claim they're optimized, but could be optimized
4730b57cec5SDimitry Andric   // further. Updating all these can be expensive, so allow it for now (FIXME).
4740b57cec5SDimitry Andric   if (AllowImpreciseClobber)
4750b57cec5SDimitry Andric     return;
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
4780b57cec5SDimitry Andric   // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
4790b57cec5SDimitry Andric   assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
4800b57cec5SDimitry Andric          "ClobberAt never acted as a clobber");
4810b57cec5SDimitry Andric }
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric namespace {
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric /// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
4860b57cec5SDimitry Andric /// in one class.
487bdd1243dSDimitry Andric class ClobberWalker {
4880b57cec5SDimitry Andric   /// Save a few bytes by using unsigned instead of size_t.
4890b57cec5SDimitry Andric   using ListIndex = unsigned;
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric   /// Represents a span of contiguous MemoryDefs, potentially ending in a
4920b57cec5SDimitry Andric   /// MemoryPhi.
4930b57cec5SDimitry Andric   struct DefPath {
4940b57cec5SDimitry Andric     MemoryLocation Loc;
4950b57cec5SDimitry Andric     // Note that, because we always walk in reverse, Last will always dominate
4960b57cec5SDimitry Andric     // First. Also note that First and Last are inclusive.
4970b57cec5SDimitry Andric     MemoryAccess *First;
4980b57cec5SDimitry Andric     MemoryAccess *Last;
499bdd1243dSDimitry Andric     std::optional<ListIndex> Previous;
5000b57cec5SDimitry Andric 
DefPath__anonad0781eb0511::ClobberWalker::DefPath5010b57cec5SDimitry Andric     DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
502bdd1243dSDimitry Andric             std::optional<ListIndex> Previous)
5030b57cec5SDimitry Andric         : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
5040b57cec5SDimitry Andric 
DefPath__anonad0781eb0511::ClobberWalker::DefPath5050b57cec5SDimitry Andric     DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
506bdd1243dSDimitry Andric             std::optional<ListIndex> Previous)
5070b57cec5SDimitry Andric         : DefPath(Loc, Init, Init, Previous) {}
5080b57cec5SDimitry Andric   };
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric   const MemorySSA &MSSA;
5110b57cec5SDimitry Andric   DominatorTree &DT;
512bdd1243dSDimitry Andric   BatchAAResults *AA;
5130b57cec5SDimitry Andric   UpwardsMemoryQuery *Query;
5140b57cec5SDimitry Andric   unsigned *UpwardWalkLimit;
5150b57cec5SDimitry Andric 
516e8d8bef9SDimitry Andric   // Phi optimization bookkeeping:
517e8d8bef9SDimitry Andric   // List of DefPath to process during the current phi optimization walk.
5180b57cec5SDimitry Andric   SmallVector<DefPath, 32> Paths;
519e8d8bef9SDimitry Andric   // List of visited <Access, Location> pairs; we can skip paths already
520e8d8bef9SDimitry Andric   // visited with the same memory location.
5210b57cec5SDimitry Andric   DenseSet<ConstMemoryAccessPair> VisitedPhis;
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric   /// Find the nearest def or phi that `From` can legally be optimized to.
getWalkTarget(const MemoryPhi * From) const5240b57cec5SDimitry Andric   const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
5250b57cec5SDimitry Andric     assert(From->getNumOperands() && "Phi with no operands?");
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric     BasicBlock *BB = From->getBlock();
5280b57cec5SDimitry Andric     MemoryAccess *Result = MSSA.getLiveOnEntryDef();
5290b57cec5SDimitry Andric     DomTreeNode *Node = DT.getNode(BB);
5300b57cec5SDimitry Andric     while ((Node = Node->getIDom())) {
5310b57cec5SDimitry Andric       auto *Defs = MSSA.getBlockDefs(Node->getBlock());
5320b57cec5SDimitry Andric       if (Defs)
5330b57cec5SDimitry Andric         return &*Defs->rbegin();
5340b57cec5SDimitry Andric     }
5350b57cec5SDimitry Andric     return Result;
5360b57cec5SDimitry Andric   }
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric   /// Result of calling walkToPhiOrClobber.
5390b57cec5SDimitry Andric   struct UpwardsWalkResult {
5400b57cec5SDimitry Andric     /// The "Result" of the walk. Either a clobber, the last thing we walked, or
5410b57cec5SDimitry Andric     /// both. Include alias info when clobber found.
5420b57cec5SDimitry Andric     MemoryAccess *Result;
5430b57cec5SDimitry Andric     bool IsKnownClobber;
5440b57cec5SDimitry Andric   };
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric   /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
5470b57cec5SDimitry Andric   /// This will update Desc.Last as it walks. It will (optionally) also stop at
5480b57cec5SDimitry Andric   /// StopAt.
5490b57cec5SDimitry Andric   ///
5500b57cec5SDimitry Andric   /// This does not test for whether StopAt is a clobber
5510b57cec5SDimitry Andric   UpwardsWalkResult
walkToPhiOrClobber(DefPath & Desc,const MemoryAccess * StopAt=nullptr,const MemoryAccess * SkipStopAt=nullptr) const5520b57cec5SDimitry Andric   walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr,
5530b57cec5SDimitry Andric                      const MemoryAccess *SkipStopAt = nullptr) const {
5540b57cec5SDimitry Andric     assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
5550b57cec5SDimitry Andric     assert(UpwardWalkLimit && "Need a valid walk limit");
5560b57cec5SDimitry Andric     bool LimitAlreadyReached = false;
5570b57cec5SDimitry Andric     // (*UpwardWalkLimit) may be 0 here, due to the loop in tryOptimizePhi. Set
5580b57cec5SDimitry Andric     // it to 1. This will not do any alias() calls. It either returns in the
5590b57cec5SDimitry Andric     // first iteration in the loop below, or is set back to 0 if all def chains
5600b57cec5SDimitry Andric     // are free of MemoryDefs.
5610b57cec5SDimitry Andric     if (!*UpwardWalkLimit) {
5620b57cec5SDimitry Andric       *UpwardWalkLimit = 1;
5630b57cec5SDimitry Andric       LimitAlreadyReached = true;
5640b57cec5SDimitry Andric     }
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric     for (MemoryAccess *Current : def_chain(Desc.Last)) {
5670b57cec5SDimitry Andric       Desc.Last = Current;
5680b57cec5SDimitry Andric       if (Current == StopAt || Current == SkipStopAt)
569bdd1243dSDimitry Andric         return {Current, false};
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric       if (auto *MD = dyn_cast<MemoryDef>(Current)) {
5720b57cec5SDimitry Andric         if (MSSA.isLiveOnEntryDef(MD))
573bdd1243dSDimitry Andric           return {MD, true};
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric         if (!--*UpwardWalkLimit)
576bdd1243dSDimitry Andric           return {Current, true};
5770b57cec5SDimitry Andric 
578bdd1243dSDimitry Andric         if (instructionClobbersQuery(MD, Desc.Loc, Query->Inst, *AA))
579bdd1243dSDimitry Andric           return {MD, true};
5800b57cec5SDimitry Andric       }
5810b57cec5SDimitry Andric     }
5820b57cec5SDimitry Andric 
5830b57cec5SDimitry Andric     if (LimitAlreadyReached)
5840b57cec5SDimitry Andric       *UpwardWalkLimit = 0;
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric     assert(isa<MemoryPhi>(Desc.Last) &&
5870b57cec5SDimitry Andric            "Ended at a non-clobber that's not a phi?");
588bdd1243dSDimitry Andric     return {Desc.Last, false};
5890b57cec5SDimitry Andric   }
5900b57cec5SDimitry Andric 
addSearches(MemoryPhi * Phi,SmallVectorImpl<ListIndex> & PausedSearches,ListIndex PriorNode)5910b57cec5SDimitry Andric   void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
5920b57cec5SDimitry Andric                    ListIndex PriorNode) {
593bdd1243dSDimitry Andric     auto UpwardDefsBegin = upward_defs_begin({Phi, Paths[PriorNode].Loc}, DT);
594e8d8bef9SDimitry Andric     auto UpwardDefs = make_range(UpwardDefsBegin, upward_defs_end());
5950b57cec5SDimitry Andric     for (const MemoryAccessPair &P : UpwardDefs) {
5960b57cec5SDimitry Andric       PausedSearches.push_back(Paths.size());
5970b57cec5SDimitry Andric       Paths.emplace_back(P.second, P.first, PriorNode);
5980b57cec5SDimitry Andric     }
5990b57cec5SDimitry Andric   }
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric   /// Represents a search that terminated after finding a clobber. This clobber
6020b57cec5SDimitry Andric   /// may or may not be present in the path of defs from LastNode..SearchStart,
6030b57cec5SDimitry Andric   /// since it may have been retrieved from cache.
6040b57cec5SDimitry Andric   struct TerminatedPath {
6050b57cec5SDimitry Andric     MemoryAccess *Clobber;
6060b57cec5SDimitry Andric     ListIndex LastNode;
6070b57cec5SDimitry Andric   };
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric   /// Get an access that keeps us from optimizing to the given phi.
6100b57cec5SDimitry Andric   ///
6110b57cec5SDimitry Andric   /// PausedSearches is an array of indices into the Paths array. Its incoming
6120b57cec5SDimitry Andric   /// value is the indices of searches that stopped at the last phi optimization
6130b57cec5SDimitry Andric   /// target. It's left in an unspecified state.
6140b57cec5SDimitry Andric   ///
615bdd1243dSDimitry Andric   /// If this returns std::nullopt, NewPaused is a vector of searches that
616bdd1243dSDimitry Andric   /// terminated at StopWhere. Otherwise, NewPaused is left in an unspecified
617bdd1243dSDimitry Andric   /// state.
618bdd1243dSDimitry Andric   std::optional<TerminatedPath>
getBlockingAccess(const MemoryAccess * StopWhere,SmallVectorImpl<ListIndex> & PausedSearches,SmallVectorImpl<ListIndex> & NewPaused,SmallVectorImpl<TerminatedPath> & Terminated)6190b57cec5SDimitry Andric   getBlockingAccess(const MemoryAccess *StopWhere,
6200b57cec5SDimitry Andric                     SmallVectorImpl<ListIndex> &PausedSearches,
6210b57cec5SDimitry Andric                     SmallVectorImpl<ListIndex> &NewPaused,
6220b57cec5SDimitry Andric                     SmallVectorImpl<TerminatedPath> &Terminated) {
6230b57cec5SDimitry Andric     assert(!PausedSearches.empty() && "No searches to continue?");
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric     // BFS vs DFS really doesn't make a difference here, so just do a DFS with
6260b57cec5SDimitry Andric     // PausedSearches as our stack.
6270b57cec5SDimitry Andric     while (!PausedSearches.empty()) {
6280b57cec5SDimitry Andric       ListIndex PathIndex = PausedSearches.pop_back_val();
6290b57cec5SDimitry Andric       DefPath &Node = Paths[PathIndex];
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric       // If we've already visited this path with this MemoryLocation, we don't
6320b57cec5SDimitry Andric       // need to do so again.
6330b57cec5SDimitry Andric       //
6340b57cec5SDimitry Andric       // NOTE: That we just drop these paths on the ground makes caching
6350b57cec5SDimitry Andric       // behavior sporadic. e.g. given a diamond:
6360b57cec5SDimitry Andric       //  A
6370b57cec5SDimitry Andric       // B C
6380b57cec5SDimitry Andric       //  D
6390b57cec5SDimitry Andric       //
6400b57cec5SDimitry Andric       // ...If we walk D, B, A, C, we'll only cache the result of phi
6410b57cec5SDimitry Andric       // optimization for A, B, and D; C will be skipped because it dies here.
6420b57cec5SDimitry Andric       // This arguably isn't the worst thing ever, since:
6430b57cec5SDimitry Andric       //   - We generally query things in a top-down order, so if we got below D
6440b57cec5SDimitry Andric       //     without needing cache entries for {C, MemLoc}, then chances are
6450b57cec5SDimitry Andric       //     that those cache entries would end up ultimately unused.
6460b57cec5SDimitry Andric       //   - We still cache things for A, so C only needs to walk up a bit.
6470b57cec5SDimitry Andric       // If this behavior becomes problematic, we can fix without a ton of extra
6480b57cec5SDimitry Andric       // work.
649bdd1243dSDimitry Andric       if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
6500b57cec5SDimitry Andric         continue;
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric       const MemoryAccess *SkipStopWhere = nullptr;
6530b57cec5SDimitry Andric       if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) {
6540b57cec5SDimitry Andric         assert(isa<MemoryDef>(Query->OriginalAccess));
6550b57cec5SDimitry Andric         SkipStopWhere = Query->OriginalAccess;
6560b57cec5SDimitry Andric       }
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric       UpwardsWalkResult Res = walkToPhiOrClobber(Node,
6590b57cec5SDimitry Andric                                                  /*StopAt=*/StopWhere,
6600b57cec5SDimitry Andric                                                  /*SkipStopAt=*/SkipStopWhere);
6610b57cec5SDimitry Andric       if (Res.IsKnownClobber) {
6620b57cec5SDimitry Andric         assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric         // If this wasn't a cache hit, we hit a clobber when walking. That's a
6650b57cec5SDimitry Andric         // failure.
6660b57cec5SDimitry Andric         TerminatedPath Term{Res.Result, PathIndex};
6670b57cec5SDimitry Andric         if (!MSSA.dominates(Res.Result, StopWhere))
6680b57cec5SDimitry Andric           return Term;
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric         // Otherwise, it's a valid thing to potentially optimize to.
6710b57cec5SDimitry Andric         Terminated.push_back(Term);
6720b57cec5SDimitry Andric         continue;
6730b57cec5SDimitry Andric       }
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric       if (Res.Result == StopWhere || Res.Result == SkipStopWhere) {
6760b57cec5SDimitry Andric         // We've hit our target. Save this path off for if we want to continue
6770b57cec5SDimitry Andric         // walking. If we are in the mode of skipping the OriginalAccess, and
6780b57cec5SDimitry Andric         // we've reached back to the OriginalAccess, do not save path, we've
6790b57cec5SDimitry Andric         // just looped back to self.
6800b57cec5SDimitry Andric         if (Res.Result != SkipStopWhere)
6810b57cec5SDimitry Andric           NewPaused.push_back(PathIndex);
6820b57cec5SDimitry Andric         continue;
6830b57cec5SDimitry Andric       }
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric       assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
6860b57cec5SDimitry Andric       addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
6870b57cec5SDimitry Andric     }
6880b57cec5SDimitry Andric 
689bdd1243dSDimitry Andric     return std::nullopt;
6900b57cec5SDimitry Andric   }
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric   template <typename T, typename Walker>
6930b57cec5SDimitry Andric   struct generic_def_path_iterator
6940b57cec5SDimitry Andric       : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
6950b57cec5SDimitry Andric                                     std::forward_iterator_tag, T *> {
69681ad6265SDimitry Andric     generic_def_path_iterator() = default;
generic_def_path_iterator__anonad0781eb0511::ClobberWalker::generic_def_path_iterator6970b57cec5SDimitry Andric     generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
6980b57cec5SDimitry Andric 
operator *__anonad0781eb0511::ClobberWalker::generic_def_path_iterator6990b57cec5SDimitry Andric     T &operator*() const { return curNode(); }
7000b57cec5SDimitry Andric 
operator ++__anonad0781eb0511::ClobberWalker::generic_def_path_iterator7010b57cec5SDimitry Andric     generic_def_path_iterator &operator++() {
7020b57cec5SDimitry Andric       N = curNode().Previous;
7030b57cec5SDimitry Andric       return *this;
7040b57cec5SDimitry Andric     }
7050b57cec5SDimitry Andric 
operator ==__anonad0781eb0511::ClobberWalker::generic_def_path_iterator7060b57cec5SDimitry Andric     bool operator==(const generic_def_path_iterator &O) const {
70781ad6265SDimitry Andric       if (N.has_value() != O.N.has_value())
7080b57cec5SDimitry Andric         return false;
70981ad6265SDimitry Andric       return !N || *N == *O.N;
7100b57cec5SDimitry Andric     }
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric   private:
curNode__anonad0781eb0511::ClobberWalker::generic_def_path_iterator7130b57cec5SDimitry Andric     T &curNode() const { return W->Paths[*N]; }
7140b57cec5SDimitry Andric 
7150b57cec5SDimitry Andric     Walker *W = nullptr;
716bdd1243dSDimitry Andric     std::optional<ListIndex> N;
7170b57cec5SDimitry Andric   };
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
7200b57cec5SDimitry Andric   using const_def_path_iterator =
7210b57cec5SDimitry Andric       generic_def_path_iterator<const DefPath, const ClobberWalker>;
7220b57cec5SDimitry Andric 
def_path(ListIndex From)7230b57cec5SDimitry Andric   iterator_range<def_path_iterator> def_path(ListIndex From) {
7240b57cec5SDimitry Andric     return make_range(def_path_iterator(this, From), def_path_iterator());
7250b57cec5SDimitry Andric   }
7260b57cec5SDimitry Andric 
const_def_path(ListIndex From) const7270b57cec5SDimitry Andric   iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
7280b57cec5SDimitry Andric     return make_range(const_def_path_iterator(this, From),
7290b57cec5SDimitry Andric                       const_def_path_iterator());
7300b57cec5SDimitry Andric   }
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric   struct OptznResult {
7330b57cec5SDimitry Andric     /// The path that contains our result.
7340b57cec5SDimitry Andric     TerminatedPath PrimaryClobber;
7350b57cec5SDimitry Andric     /// The paths that we can legally cache back from, but that aren't
7360b57cec5SDimitry Andric     /// necessarily the result of the Phi optimization.
7370b57cec5SDimitry Andric     SmallVector<TerminatedPath, 4> OtherClobbers;
7380b57cec5SDimitry Andric   };
7390b57cec5SDimitry Andric 
defPathIndex(const DefPath & N) const7400b57cec5SDimitry Andric   ListIndex defPathIndex(const DefPath &N) const {
7410b57cec5SDimitry Andric     // The assert looks nicer if we don't need to do &N
7420b57cec5SDimitry Andric     const DefPath *NP = &N;
7430b57cec5SDimitry Andric     assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
7440b57cec5SDimitry Andric            "Out of bounds DefPath!");
7450b57cec5SDimitry Andric     return NP - &Paths.front();
7460b57cec5SDimitry Andric   }
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric   /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
7490b57cec5SDimitry Andric   /// that act as legal clobbers. Note that this won't return *all* clobbers.
7500b57cec5SDimitry Andric   ///
7510b57cec5SDimitry Andric   /// Phi optimization algorithm tl;dr:
7520b57cec5SDimitry Andric   ///   - Find the earliest def/phi, A, we can optimize to
7530b57cec5SDimitry Andric   ///   - Find if all paths from the starting memory access ultimately reach A
7540b57cec5SDimitry Andric   ///     - If not, optimization isn't possible.
7550b57cec5SDimitry Andric   ///     - Otherwise, walk from A to another clobber or phi, A'.
7560b57cec5SDimitry Andric   ///       - If A' is a def, we're done.
7570b57cec5SDimitry Andric   ///       - If A' is a phi, try to optimize it.
7580b57cec5SDimitry Andric   ///
7590b57cec5SDimitry Andric   /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
7600b57cec5SDimitry Andric   /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
tryOptimizePhi(MemoryPhi * Phi,MemoryAccess * Start,const MemoryLocation & Loc)7610b57cec5SDimitry Andric   OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
7620b57cec5SDimitry Andric                              const MemoryLocation &Loc) {
763bdd1243dSDimitry Andric     assert(Paths.empty() && VisitedPhis.empty() &&
7640b57cec5SDimitry Andric            "Reset the optimization state.");
7650b57cec5SDimitry Andric 
766bdd1243dSDimitry Andric     Paths.emplace_back(Loc, Start, Phi, std::nullopt);
7670b57cec5SDimitry Andric     // Stores how many "valid" optimization nodes we had prior to calling
7680b57cec5SDimitry Andric     // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
7690b57cec5SDimitry Andric     auto PriorPathsSize = Paths.size();
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric     SmallVector<ListIndex, 16> PausedSearches;
7720b57cec5SDimitry Andric     SmallVector<ListIndex, 8> NewPaused;
7730b57cec5SDimitry Andric     SmallVector<TerminatedPath, 4> TerminatedPaths;
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric     addSearches(Phi, PausedSearches, 0);
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric     // Moves the TerminatedPath with the "most dominated" Clobber to the end of
7780b57cec5SDimitry Andric     // Paths.
7790b57cec5SDimitry Andric     auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
7800b57cec5SDimitry Andric       assert(!Paths.empty() && "Need a path to move");
7810b57cec5SDimitry Andric       auto Dom = Paths.begin();
7820b57cec5SDimitry Andric       for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
7830b57cec5SDimitry Andric         if (!MSSA.dominates(I->Clobber, Dom->Clobber))
7840b57cec5SDimitry Andric           Dom = I;
7850b57cec5SDimitry Andric       auto Last = Paths.end() - 1;
7860b57cec5SDimitry Andric       if (Last != Dom)
7870b57cec5SDimitry Andric         std::iter_swap(Last, Dom);
7880b57cec5SDimitry Andric     };
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric     MemoryPhi *Current = Phi;
7910b57cec5SDimitry Andric     while (true) {
7920b57cec5SDimitry Andric       assert(!MSSA.isLiveOnEntryDef(Current) &&
7930b57cec5SDimitry Andric              "liveOnEntry wasn't treated as a clobber?");
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric       const auto *Target = getWalkTarget(Current);
7960b57cec5SDimitry Andric       // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
7970b57cec5SDimitry Andric       // optimization for the prior phi.
7980b57cec5SDimitry Andric       assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
7990b57cec5SDimitry Andric         return MSSA.dominates(P.Clobber, Target);
8000b57cec5SDimitry Andric       }));
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric       // FIXME: This is broken, because the Blocker may be reported to be
8030b57cec5SDimitry Andric       // liveOnEntry, and we'll happily wait for that to disappear (read: never)
8040b57cec5SDimitry Andric       // For the moment, this is fine, since we do nothing with blocker info.
805bdd1243dSDimitry Andric       if (std::optional<TerminatedPath> Blocker = getBlockingAccess(
8060b57cec5SDimitry Andric               Target, PausedSearches, NewPaused, TerminatedPaths)) {
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric         // Find the node we started at. We can't search based on N->Last, since
8090b57cec5SDimitry Andric         // we may have gone around a loop with a different MemoryLocation.
8100b57cec5SDimitry Andric         auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
8110b57cec5SDimitry Andric           return defPathIndex(N) < PriorPathsSize;
8120b57cec5SDimitry Andric         });
8130b57cec5SDimitry Andric         assert(Iter != def_path_iterator());
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric         DefPath &CurNode = *Iter;
8160b57cec5SDimitry Andric         assert(CurNode.Last == Current);
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric         // Two things:
8190b57cec5SDimitry Andric         // A. We can't reliably cache all of NewPaused back. Consider a case
8200b57cec5SDimitry Andric         //    where we have two paths in NewPaused; one of which can't optimize
8210b57cec5SDimitry Andric         //    above this phi, whereas the other can. If we cache the second path
8220b57cec5SDimitry Andric         //    back, we'll end up with suboptimal cache entries. We can handle
8230b57cec5SDimitry Andric         //    cases like this a bit better when we either try to find all
8240b57cec5SDimitry Andric         //    clobbers that block phi optimization, or when our cache starts
8250b57cec5SDimitry Andric         //    supporting unfinished searches.
8260b57cec5SDimitry Andric         // B. We can't reliably cache TerminatedPaths back here without doing
8270b57cec5SDimitry Andric         //    extra checks; consider a case like:
8280b57cec5SDimitry Andric         //       T
8290b57cec5SDimitry Andric         //      / \
8300b57cec5SDimitry Andric         //     D   C
8310b57cec5SDimitry Andric         //      \ /
8320b57cec5SDimitry Andric         //       S
8330b57cec5SDimitry Andric         //    Where T is our target, C is a node with a clobber on it, D is a
8340b57cec5SDimitry Andric         //    diamond (with a clobber *only* on the left or right node, N), and
8350b57cec5SDimitry Andric         //    S is our start. Say we walk to D, through the node opposite N
8360b57cec5SDimitry Andric         //    (read: ignoring the clobber), and see a cache entry in the top
8370b57cec5SDimitry Andric         //    node of D. That cache entry gets put into TerminatedPaths. We then
8380b57cec5SDimitry Andric         //    walk up to C (N is later in our worklist), find the clobber, and
8390b57cec5SDimitry Andric         //    quit. If we append TerminatedPaths to OtherClobbers, we'll cache
8400b57cec5SDimitry Andric         //    the bottom part of D to the cached clobber, ignoring the clobber
8410b57cec5SDimitry Andric         //    in N. Again, this problem goes away if we start tracking all
8420b57cec5SDimitry Andric         //    blockers for a given phi optimization.
8430b57cec5SDimitry Andric         TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
8440b57cec5SDimitry Andric         return {Result, {}};
8450b57cec5SDimitry Andric       }
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric       // If there's nothing left to search, then all paths led to valid clobbers
8480b57cec5SDimitry Andric       // that we got from our cache; pick the nearest to the start, and allow
8490b57cec5SDimitry Andric       // the rest to be cached back.
8500b57cec5SDimitry Andric       if (NewPaused.empty()) {
8510b57cec5SDimitry Andric         MoveDominatedPathToEnd(TerminatedPaths);
8520b57cec5SDimitry Andric         TerminatedPath Result = TerminatedPaths.pop_back_val();
8530b57cec5SDimitry Andric         return {Result, std::move(TerminatedPaths)};
8540b57cec5SDimitry Andric       }
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric       MemoryAccess *DefChainEnd = nullptr;
8570b57cec5SDimitry Andric       SmallVector<TerminatedPath, 4> Clobbers;
8580b57cec5SDimitry Andric       for (ListIndex Paused : NewPaused) {
8590b57cec5SDimitry Andric         UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
8600b57cec5SDimitry Andric         if (WR.IsKnownClobber)
8610b57cec5SDimitry Andric           Clobbers.push_back({WR.Result, Paused});
8620b57cec5SDimitry Andric         else
8630b57cec5SDimitry Andric           // Micro-opt: If we hit the end of the chain, save it.
8640b57cec5SDimitry Andric           DefChainEnd = WR.Result;
8650b57cec5SDimitry Andric       }
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric       if (!TerminatedPaths.empty()) {
8680b57cec5SDimitry Andric         // If we couldn't find the dominating phi/liveOnEntry in the above loop,
8690b57cec5SDimitry Andric         // do it now.
8700b57cec5SDimitry Andric         if (!DefChainEnd)
8710b57cec5SDimitry Andric           for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
8720b57cec5SDimitry Andric             DefChainEnd = MA;
8738bcb0991SDimitry Andric         assert(DefChainEnd && "Failed to find dominating phi/liveOnEntry");
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric         // If any of the terminated paths don't dominate the phi we'll try to
8760b57cec5SDimitry Andric         // optimize, we need to figure out what they are and quit.
8770b57cec5SDimitry Andric         const BasicBlock *ChainBB = DefChainEnd->getBlock();
8780b57cec5SDimitry Andric         for (const TerminatedPath &TP : TerminatedPaths) {
8790b57cec5SDimitry Andric           // Because we know that DefChainEnd is as "high" as we can go, we
8800b57cec5SDimitry Andric           // don't need local dominance checks; BB dominance is sufficient.
8810b57cec5SDimitry Andric           if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
8820b57cec5SDimitry Andric             Clobbers.push_back(TP);
8830b57cec5SDimitry Andric         }
8840b57cec5SDimitry Andric       }
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric       // If we have clobbers in the def chain, find the one closest to Current
8870b57cec5SDimitry Andric       // and quit.
8880b57cec5SDimitry Andric       if (!Clobbers.empty()) {
8890b57cec5SDimitry Andric         MoveDominatedPathToEnd(Clobbers);
8900b57cec5SDimitry Andric         TerminatedPath Result = Clobbers.pop_back_val();
8910b57cec5SDimitry Andric         return {Result, std::move(Clobbers)};
8920b57cec5SDimitry Andric       }
8930b57cec5SDimitry Andric 
8940b57cec5SDimitry Andric       assert(all_of(NewPaused,
8950b57cec5SDimitry Andric                     [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric       // Because liveOnEntry is a clobber, this must be a phi.
8980b57cec5SDimitry Andric       auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric       PriorPathsSize = Paths.size();
9010b57cec5SDimitry Andric       PausedSearches.clear();
9020b57cec5SDimitry Andric       for (ListIndex I : NewPaused)
9030b57cec5SDimitry Andric         addSearches(DefChainPhi, PausedSearches, I);
9040b57cec5SDimitry Andric       NewPaused.clear();
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric       Current = DefChainPhi;
9070b57cec5SDimitry Andric     }
9080b57cec5SDimitry Andric   }
9090b57cec5SDimitry Andric 
verifyOptResult(const OptznResult & R) const9100b57cec5SDimitry Andric   void verifyOptResult(const OptznResult &R) const {
9110b57cec5SDimitry Andric     assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
9120b57cec5SDimitry Andric       return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
9130b57cec5SDimitry Andric     }));
9140b57cec5SDimitry Andric   }
9150b57cec5SDimitry Andric 
resetPhiOptznState()9160b57cec5SDimitry Andric   void resetPhiOptznState() {
9170b57cec5SDimitry Andric     Paths.clear();
9180b57cec5SDimitry Andric     VisitedPhis.clear();
9190b57cec5SDimitry Andric   }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric public:
ClobberWalker(const MemorySSA & MSSA,DominatorTree & DT)922bdd1243dSDimitry Andric   ClobberWalker(const MemorySSA &MSSA, DominatorTree &DT)
923bdd1243dSDimitry Andric       : MSSA(MSSA), DT(DT) {}
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric   /// Finds the nearest clobber for the given query, optimizing phis if
9260b57cec5SDimitry Andric   /// possible.
findClobber(BatchAAResults & BAA,MemoryAccess * Start,UpwardsMemoryQuery & Q,unsigned & UpWalkLimit)927bdd1243dSDimitry Andric   MemoryAccess *findClobber(BatchAAResults &BAA, MemoryAccess *Start,
928bdd1243dSDimitry Andric                             UpwardsMemoryQuery &Q, unsigned &UpWalkLimit) {
929bdd1243dSDimitry Andric     AA = &BAA;
9300b57cec5SDimitry Andric     Query = &Q;
9310b57cec5SDimitry Andric     UpwardWalkLimit = &UpWalkLimit;
9320b57cec5SDimitry Andric     // Starting limit must be > 0.
9330b57cec5SDimitry Andric     if (!UpWalkLimit)
9340b57cec5SDimitry Andric       UpWalkLimit++;
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric     MemoryAccess *Current = Start;
9370b57cec5SDimitry Andric     // This walker pretends uses don't exist. If we're handed one, silently grab
9380b57cec5SDimitry Andric     // its def. (This has the nice side-effect of ensuring we never cache uses)
9390b57cec5SDimitry Andric     if (auto *MU = dyn_cast<MemoryUse>(Start))
9400b57cec5SDimitry Andric       Current = MU->getDefiningAccess();
9410b57cec5SDimitry Andric 
942bdd1243dSDimitry Andric     DefPath FirstDesc(Q.StartingLoc, Current, Current, std::nullopt);
9430b57cec5SDimitry Andric     // Fast path for the overly-common case (no crazy phi optimization
9440b57cec5SDimitry Andric     // necessary)
9450b57cec5SDimitry Andric     UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
9460b57cec5SDimitry Andric     MemoryAccess *Result;
9470b57cec5SDimitry Andric     if (WalkResult.IsKnownClobber) {
9480b57cec5SDimitry Andric       Result = WalkResult.Result;
9490b57cec5SDimitry Andric     } else {
9500b57cec5SDimitry Andric       OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
9510b57cec5SDimitry Andric                                           Current, Q.StartingLoc);
9520b57cec5SDimitry Andric       verifyOptResult(OptRes);
9530b57cec5SDimitry Andric       resetPhiOptznState();
9540b57cec5SDimitry Andric       Result = OptRes.PrimaryClobber.Clobber;
9550b57cec5SDimitry Andric     }
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS
9580b57cec5SDimitry Andric     if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
959bdd1243dSDimitry Andric       checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, BAA);
9600b57cec5SDimitry Andric #endif
9610b57cec5SDimitry Andric     return Result;
9620b57cec5SDimitry Andric   }
9630b57cec5SDimitry Andric };
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric struct RenamePassData {
9660b57cec5SDimitry Andric   DomTreeNode *DTN;
9670b57cec5SDimitry Andric   DomTreeNode::const_iterator ChildIt;
9680b57cec5SDimitry Andric   MemoryAccess *IncomingVal;
9690b57cec5SDimitry Andric 
RenamePassData__anonad0781eb0511::RenamePassData9700b57cec5SDimitry Andric   RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
9710b57cec5SDimitry Andric                  MemoryAccess *M)
9720b57cec5SDimitry Andric       : DTN(D), ChildIt(It), IncomingVal(M) {}
9730b57cec5SDimitry Andric 
swap__anonad0781eb0511::RenamePassData9740b57cec5SDimitry Andric   void swap(RenamePassData &RHS) {
9750b57cec5SDimitry Andric     std::swap(DTN, RHS.DTN);
9760b57cec5SDimitry Andric     std::swap(ChildIt, RHS.ChildIt);
9770b57cec5SDimitry Andric     std::swap(IncomingVal, RHS.IncomingVal);
9780b57cec5SDimitry Andric   }
9790b57cec5SDimitry Andric };
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric } // end anonymous namespace
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric namespace llvm {
9840b57cec5SDimitry Andric 
985bdd1243dSDimitry Andric class MemorySSA::ClobberWalkerBase {
986bdd1243dSDimitry Andric   ClobberWalker Walker;
9870b57cec5SDimitry Andric   MemorySSA *MSSA;
9880b57cec5SDimitry Andric 
9890b57cec5SDimitry Andric public:
ClobberWalkerBase(MemorySSA * M,DominatorTree * D)990bdd1243dSDimitry Andric   ClobberWalkerBase(MemorySSA *M, DominatorTree *D) : Walker(*M, *D), MSSA(M) {}
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric   MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *,
9930b57cec5SDimitry Andric                                               const MemoryLocation &,
994bdd1243dSDimitry Andric                                               BatchAAResults &, unsigned &);
9950b57cec5SDimitry Andric   // Third argument (bool), defines whether the clobber search should skip the
9960b57cec5SDimitry Andric   // original queried access. If true, there will be a follow-up query searching
9970b57cec5SDimitry Andric   // for a clobber access past "self". Note that the Optimized access is not
9980b57cec5SDimitry Andric   // updated if a new clobber is found by this SkipSelf search. If this
9990b57cec5SDimitry Andric   // additional query becomes heavily used we may decide to cache the result.
10000b57cec5SDimitry Andric   // Walker instantiations will decide how to set the SkipSelf bool.
1001bdd1243dSDimitry Andric   MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *, BatchAAResults &,
1002bdd1243dSDimitry Andric                                               unsigned &, bool,
1003349cc55cSDimitry Andric                                               bool UseInvariantGroup = true);
10040b57cec5SDimitry Andric };
10050b57cec5SDimitry Andric 
10060b57cec5SDimitry Andric /// A MemorySSAWalker that does AA walks to disambiguate accesses. It no
10070b57cec5SDimitry Andric /// longer does caching on its own, but the name has been retained for the
10080b57cec5SDimitry Andric /// moment.
10090b57cec5SDimitry Andric class MemorySSA::CachingWalker final : public MemorySSAWalker {
1010bdd1243dSDimitry Andric   ClobberWalkerBase *Walker;
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric public:
CachingWalker(MemorySSA * M,ClobberWalkerBase * W)1013bdd1243dSDimitry Andric   CachingWalker(MemorySSA *M, ClobberWalkerBase *W)
10140b57cec5SDimitry Andric       : MemorySSAWalker(M), Walker(W) {}
10150b57cec5SDimitry Andric   ~CachingWalker() override = default;
10160b57cec5SDimitry Andric 
10170b57cec5SDimitry Andric   using MemorySSAWalker::getClobberingMemoryAccess;
10180b57cec5SDimitry Andric 
getClobberingMemoryAccess(MemoryAccess * MA,BatchAAResults & BAA,unsigned & UWL)1019bdd1243dSDimitry Andric   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA,
1020bdd1243dSDimitry Andric                                           unsigned &UWL) {
1021bdd1243dSDimitry Andric     return Walker->getClobberingMemoryAccessBase(MA, BAA, UWL, false);
10220b57cec5SDimitry Andric   }
getClobberingMemoryAccess(MemoryAccess * MA,const MemoryLocation & Loc,BatchAAResults & BAA,unsigned & UWL)10230b57cec5SDimitry Andric   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
10240b57cec5SDimitry Andric                                           const MemoryLocation &Loc,
1025bdd1243dSDimitry Andric                                           BatchAAResults &BAA, unsigned &UWL) {
1026bdd1243dSDimitry Andric     return Walker->getClobberingMemoryAccessBase(MA, Loc, BAA, UWL);
10270b57cec5SDimitry Andric   }
1028349cc55cSDimitry Andric   // This method is not accessible outside of this file.
getClobberingMemoryAccessWithoutInvariantGroup(MemoryAccess * MA,BatchAAResults & BAA,unsigned & UWL)1029bdd1243dSDimitry Andric   MemoryAccess *getClobberingMemoryAccessWithoutInvariantGroup(
1030bdd1243dSDimitry Andric       MemoryAccess *MA, BatchAAResults &BAA, unsigned &UWL) {
1031bdd1243dSDimitry Andric     return Walker->getClobberingMemoryAccessBase(MA, BAA, UWL, false, false);
1032349cc55cSDimitry Andric   }
10330b57cec5SDimitry Andric 
getClobberingMemoryAccess(MemoryAccess * MA,BatchAAResults & BAA)1034bdd1243dSDimitry Andric   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1035bdd1243dSDimitry Andric                                           BatchAAResults &BAA) override {
10360b57cec5SDimitry Andric     unsigned UpwardWalkLimit = MaxCheckLimit;
1037bdd1243dSDimitry Andric     return getClobberingMemoryAccess(MA, BAA, UpwardWalkLimit);
10380b57cec5SDimitry Andric   }
getClobberingMemoryAccess(MemoryAccess * MA,const MemoryLocation & Loc,BatchAAResults & BAA)10390b57cec5SDimitry Andric   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1040bdd1243dSDimitry Andric                                           const MemoryLocation &Loc,
1041bdd1243dSDimitry Andric                                           BatchAAResults &BAA) override {
10420b57cec5SDimitry Andric     unsigned UpwardWalkLimit = MaxCheckLimit;
1043bdd1243dSDimitry Andric     return getClobberingMemoryAccess(MA, Loc, BAA, UpwardWalkLimit);
10440b57cec5SDimitry Andric   }
10450b57cec5SDimitry Andric 
invalidateInfo(MemoryAccess * MA)10460b57cec5SDimitry Andric   void invalidateInfo(MemoryAccess *MA) override {
10470b57cec5SDimitry Andric     if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
10480b57cec5SDimitry Andric       MUD->resetOptimized();
10490b57cec5SDimitry Andric   }
10500b57cec5SDimitry Andric };
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric class MemorySSA::SkipSelfWalker final : public MemorySSAWalker {
1053bdd1243dSDimitry Andric   ClobberWalkerBase *Walker;
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric public:
SkipSelfWalker(MemorySSA * M,ClobberWalkerBase * W)1056bdd1243dSDimitry Andric   SkipSelfWalker(MemorySSA *M, ClobberWalkerBase *W)
10570b57cec5SDimitry Andric       : MemorySSAWalker(M), Walker(W) {}
10580b57cec5SDimitry Andric   ~SkipSelfWalker() override = default;
10590b57cec5SDimitry Andric 
10600b57cec5SDimitry Andric   using MemorySSAWalker::getClobberingMemoryAccess;
10610b57cec5SDimitry Andric 
getClobberingMemoryAccess(MemoryAccess * MA,BatchAAResults & BAA,unsigned & UWL)1062bdd1243dSDimitry Andric   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA,
1063bdd1243dSDimitry Andric                                           unsigned &UWL) {
1064bdd1243dSDimitry Andric     return Walker->getClobberingMemoryAccessBase(MA, BAA, UWL, true);
10650b57cec5SDimitry Andric   }
getClobberingMemoryAccess(MemoryAccess * MA,const MemoryLocation & Loc,BatchAAResults & BAA,unsigned & UWL)10660b57cec5SDimitry Andric   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
10670b57cec5SDimitry Andric                                           const MemoryLocation &Loc,
1068bdd1243dSDimitry Andric                                           BatchAAResults &BAA, unsigned &UWL) {
1069bdd1243dSDimitry Andric     return Walker->getClobberingMemoryAccessBase(MA, Loc, BAA, UWL);
10700b57cec5SDimitry Andric   }
10710b57cec5SDimitry Andric 
getClobberingMemoryAccess(MemoryAccess * MA,BatchAAResults & BAA)1072bdd1243dSDimitry Andric   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1073bdd1243dSDimitry Andric                                           BatchAAResults &BAA) override {
10740b57cec5SDimitry Andric     unsigned UpwardWalkLimit = MaxCheckLimit;
1075bdd1243dSDimitry Andric     return getClobberingMemoryAccess(MA, BAA, UpwardWalkLimit);
10760b57cec5SDimitry Andric   }
getClobberingMemoryAccess(MemoryAccess * MA,const MemoryLocation & Loc,BatchAAResults & BAA)10770b57cec5SDimitry Andric   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1078bdd1243dSDimitry Andric                                           const MemoryLocation &Loc,
1079bdd1243dSDimitry Andric                                           BatchAAResults &BAA) override {
10800b57cec5SDimitry Andric     unsigned UpwardWalkLimit = MaxCheckLimit;
1081bdd1243dSDimitry Andric     return getClobberingMemoryAccess(MA, Loc, BAA, UpwardWalkLimit);
10820b57cec5SDimitry Andric   }
10830b57cec5SDimitry Andric 
invalidateInfo(MemoryAccess * MA)10840b57cec5SDimitry Andric   void invalidateInfo(MemoryAccess *MA) override {
10850b57cec5SDimitry Andric     if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
10860b57cec5SDimitry Andric       MUD->resetOptimized();
10870b57cec5SDimitry Andric   }
10880b57cec5SDimitry Andric };
10890b57cec5SDimitry Andric 
10900b57cec5SDimitry Andric } // end namespace llvm
10910b57cec5SDimitry Andric 
renameSuccessorPhis(BasicBlock * BB,MemoryAccess * IncomingVal,bool RenameAllUses)10920b57cec5SDimitry Andric void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
10930b57cec5SDimitry Andric                                     bool RenameAllUses) {
10940b57cec5SDimitry Andric   // Pass through values to our successors
10950b57cec5SDimitry Andric   for (const BasicBlock *S : successors(BB)) {
10960b57cec5SDimitry Andric     auto It = PerBlockAccesses.find(S);
10970b57cec5SDimitry Andric     // Rename the phi nodes in our successor block
10980b57cec5SDimitry Andric     if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
10990b57cec5SDimitry Andric       continue;
11000b57cec5SDimitry Andric     AccessList *Accesses = It->second.get();
11010b57cec5SDimitry Andric     auto *Phi = cast<MemoryPhi>(&Accesses->front());
11020b57cec5SDimitry Andric     if (RenameAllUses) {
11038bcb0991SDimitry Andric       bool ReplacementDone = false;
11048bcb0991SDimitry Andric       for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
11058bcb0991SDimitry Andric         if (Phi->getIncomingBlock(I) == BB) {
11068bcb0991SDimitry Andric           Phi->setIncomingValue(I, IncomingVal);
11078bcb0991SDimitry Andric           ReplacementDone = true;
11088bcb0991SDimitry Andric         }
11098bcb0991SDimitry Andric       (void) ReplacementDone;
11108bcb0991SDimitry Andric       assert(ReplacementDone && "Incomplete phi during partial rename");
11110b57cec5SDimitry Andric     } else
11120b57cec5SDimitry Andric       Phi->addIncoming(IncomingVal, BB);
11130b57cec5SDimitry Andric   }
11140b57cec5SDimitry Andric }
11150b57cec5SDimitry Andric 
11160b57cec5SDimitry Andric /// Rename a single basic block into MemorySSA form.
11170b57cec5SDimitry Andric /// Uses the standard SSA renaming algorithm.
11180b57cec5SDimitry Andric /// \returns The new incoming value.
renameBlock(BasicBlock * BB,MemoryAccess * IncomingVal,bool RenameAllUses)11190b57cec5SDimitry Andric MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
11200b57cec5SDimitry Andric                                      bool RenameAllUses) {
11210b57cec5SDimitry Andric   auto It = PerBlockAccesses.find(BB);
11220b57cec5SDimitry Andric   // Skip most processing if the list is empty.
11230b57cec5SDimitry Andric   if (It != PerBlockAccesses.end()) {
11240b57cec5SDimitry Andric     AccessList *Accesses = It->second.get();
11250b57cec5SDimitry Andric     for (MemoryAccess &L : *Accesses) {
11260b57cec5SDimitry Andric       if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
11270b57cec5SDimitry Andric         if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
11280b57cec5SDimitry Andric           MUD->setDefiningAccess(IncomingVal);
11290b57cec5SDimitry Andric         if (isa<MemoryDef>(&L))
11300b57cec5SDimitry Andric           IncomingVal = &L;
11310b57cec5SDimitry Andric       } else {
11320b57cec5SDimitry Andric         IncomingVal = &L;
11330b57cec5SDimitry Andric       }
11340b57cec5SDimitry Andric     }
11350b57cec5SDimitry Andric   }
11360b57cec5SDimitry Andric   return IncomingVal;
11370b57cec5SDimitry Andric }
11380b57cec5SDimitry Andric 
11390b57cec5SDimitry Andric /// This is the standard SSA renaming algorithm.
11400b57cec5SDimitry Andric ///
11410b57cec5SDimitry Andric /// We walk the dominator tree in preorder, renaming accesses, and then filling
11420b57cec5SDimitry Andric /// in phi nodes in our successors.
renamePass(DomTreeNode * Root,MemoryAccess * IncomingVal,SmallPtrSetImpl<BasicBlock * > & Visited,bool SkipVisited,bool RenameAllUses)11430b57cec5SDimitry Andric void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
11440b57cec5SDimitry Andric                            SmallPtrSetImpl<BasicBlock *> &Visited,
11450b57cec5SDimitry Andric                            bool SkipVisited, bool RenameAllUses) {
11460b57cec5SDimitry Andric   assert(Root && "Trying to rename accesses in an unreachable block");
11470b57cec5SDimitry Andric 
11480b57cec5SDimitry Andric   SmallVector<RenamePassData, 32> WorkStack;
11490b57cec5SDimitry Andric   // Skip everything if we already renamed this block and we are skipping.
11500b57cec5SDimitry Andric   // Note: You can't sink this into the if, because we need it to occur
11510b57cec5SDimitry Andric   // regardless of whether we skip blocks or not.
11520b57cec5SDimitry Andric   bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
11530b57cec5SDimitry Andric   if (SkipVisited && AlreadyVisited)
11540b57cec5SDimitry Andric     return;
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric   IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
11570b57cec5SDimitry Andric   renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
11580b57cec5SDimitry Andric   WorkStack.push_back({Root, Root->begin(), IncomingVal});
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric   while (!WorkStack.empty()) {
11610b57cec5SDimitry Andric     DomTreeNode *Node = WorkStack.back().DTN;
11620b57cec5SDimitry Andric     DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
11630b57cec5SDimitry Andric     IncomingVal = WorkStack.back().IncomingVal;
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric     if (ChildIt == Node->end()) {
11660b57cec5SDimitry Andric       WorkStack.pop_back();
11670b57cec5SDimitry Andric     } else {
11680b57cec5SDimitry Andric       DomTreeNode *Child = *ChildIt;
11690b57cec5SDimitry Andric       ++WorkStack.back().ChildIt;
11700b57cec5SDimitry Andric       BasicBlock *BB = Child->getBlock();
11710b57cec5SDimitry Andric       // Note: You can't sink this into the if, because we need it to occur
11720b57cec5SDimitry Andric       // regardless of whether we skip blocks or not.
11730b57cec5SDimitry Andric       AlreadyVisited = !Visited.insert(BB).second;
11740b57cec5SDimitry Andric       if (SkipVisited && AlreadyVisited) {
11750b57cec5SDimitry Andric         // We already visited this during our renaming, which can happen when
11760b57cec5SDimitry Andric         // being asked to rename multiple blocks. Figure out the incoming val,
11770b57cec5SDimitry Andric         // which is the last def.
11780b57cec5SDimitry Andric         // Incoming value can only change if there is a block def, and in that
11790b57cec5SDimitry Andric         // case, it's the last block def in the list.
11800b57cec5SDimitry Andric         if (auto *BlockDefs = getWritableBlockDefs(BB))
11810b57cec5SDimitry Andric           IncomingVal = &*BlockDefs->rbegin();
11820b57cec5SDimitry Andric       } else
11830b57cec5SDimitry Andric         IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
11840b57cec5SDimitry Andric       renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
11850b57cec5SDimitry Andric       WorkStack.push_back({Child, Child->begin(), IncomingVal});
11860b57cec5SDimitry Andric     }
11870b57cec5SDimitry Andric   }
11880b57cec5SDimitry Andric }
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric /// This handles unreachable block accesses by deleting phi nodes in
11910b57cec5SDimitry Andric /// unreachable blocks, and marking all other unreachable MemoryAccess's as
11920b57cec5SDimitry Andric /// being uses of the live on entry definition.
markUnreachableAsLiveOnEntry(BasicBlock * BB)11930b57cec5SDimitry Andric void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
11940b57cec5SDimitry Andric   assert(!DT->isReachableFromEntry(BB) &&
11950b57cec5SDimitry Andric          "Reachable block found while handling unreachable blocks");
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric   // Make sure phi nodes in our reachable successors end up with a
11980b57cec5SDimitry Andric   // LiveOnEntryDef for our incoming edge, even though our block is forward
11990b57cec5SDimitry Andric   // unreachable.  We could just disconnect these blocks from the CFG fully,
12000b57cec5SDimitry Andric   // but we do not right now.
12010b57cec5SDimitry Andric   for (const BasicBlock *S : successors(BB)) {
12020b57cec5SDimitry Andric     if (!DT->isReachableFromEntry(S))
12030b57cec5SDimitry Andric       continue;
12040b57cec5SDimitry Andric     auto It = PerBlockAccesses.find(S);
12050b57cec5SDimitry Andric     // Rename the phi nodes in our successor block
12060b57cec5SDimitry Andric     if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
12070b57cec5SDimitry Andric       continue;
12080b57cec5SDimitry Andric     AccessList *Accesses = It->second.get();
12090b57cec5SDimitry Andric     auto *Phi = cast<MemoryPhi>(&Accesses->front());
12100b57cec5SDimitry Andric     Phi->addIncoming(LiveOnEntryDef.get(), BB);
12110b57cec5SDimitry Andric   }
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric   auto It = PerBlockAccesses.find(BB);
12140b57cec5SDimitry Andric   if (It == PerBlockAccesses.end())
12150b57cec5SDimitry Andric     return;
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric   auto &Accesses = It->second;
12180b57cec5SDimitry Andric   for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
12190b57cec5SDimitry Andric     auto Next = std::next(AI);
12200b57cec5SDimitry Andric     // If we have a phi, just remove it. We are going to replace all
12210b57cec5SDimitry Andric     // users with live on entry.
12220b57cec5SDimitry Andric     if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
12230b57cec5SDimitry Andric       UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
12240b57cec5SDimitry Andric     else
12250b57cec5SDimitry Andric       Accesses->erase(AI);
12260b57cec5SDimitry Andric     AI = Next;
12270b57cec5SDimitry Andric   }
12280b57cec5SDimitry Andric }
12290b57cec5SDimitry Andric 
MemorySSA(Function & Func,AliasAnalysis * AA,DominatorTree * DT)12300b57cec5SDimitry Andric MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
123104eeddc0SDimitry Andric     : DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
123204eeddc0SDimitry Andric       SkipWalker(nullptr) {
12330b57cec5SDimitry Andric   // Build MemorySSA using a batch alias analysis. This reuses the internal
12340b57cec5SDimitry Andric   // state that AA collects during an alias()/getModRefInfo() call. This is
12350b57cec5SDimitry Andric   // safe because there are no CFG changes while building MemorySSA and can
12360b57cec5SDimitry Andric   // significantly reduce the time spent by the compiler in AA, because we will
12370b57cec5SDimitry Andric   // make queries about all the instructions in the Function.
1238480093f4SDimitry Andric   assert(AA && "No alias analysis?");
12390b57cec5SDimitry Andric   BatchAAResults BatchAA(*AA);
12400b57cec5SDimitry Andric   buildMemorySSA(BatchAA);
12410b57cec5SDimitry Andric   // Intentionally leave AA to nullptr while building so we don't accidently
12420b57cec5SDimitry Andric   // use non-batch AliasAnalysis.
12430b57cec5SDimitry Andric   this->AA = AA;
12440b57cec5SDimitry Andric   // Also create the walker here.
12450b57cec5SDimitry Andric   getWalker();
12460b57cec5SDimitry Andric }
12470b57cec5SDimitry Andric 
~MemorySSA()12480b57cec5SDimitry Andric MemorySSA::~MemorySSA() {
12490b57cec5SDimitry Andric   // Drop all our references
12500b57cec5SDimitry Andric   for (const auto &Pair : PerBlockAccesses)
12510b57cec5SDimitry Andric     for (MemoryAccess &MA : *Pair.second)
12520b57cec5SDimitry Andric       MA.dropAllReferences();
12530b57cec5SDimitry Andric }
12540b57cec5SDimitry Andric 
getOrCreateAccessList(const BasicBlock * BB)12550b57cec5SDimitry Andric MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
12560b57cec5SDimitry Andric   auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric   if (Res.second)
12598bcb0991SDimitry Andric     Res.first->second = std::make_unique<AccessList>();
12600b57cec5SDimitry Andric   return Res.first->second.get();
12610b57cec5SDimitry Andric }
12620b57cec5SDimitry Andric 
getOrCreateDefsList(const BasicBlock * BB)12630b57cec5SDimitry Andric MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
12640b57cec5SDimitry Andric   auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
12650b57cec5SDimitry Andric 
12660b57cec5SDimitry Andric   if (Res.second)
12678bcb0991SDimitry Andric     Res.first->second = std::make_unique<DefsList>();
12680b57cec5SDimitry Andric   return Res.first->second.get();
12690b57cec5SDimitry Andric }
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric namespace llvm {
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric /// This class is a batch walker of all MemoryUse's in the program, and points
12740b57cec5SDimitry Andric /// their defining access at the thing that actually clobbers them.  Because it
12750b57cec5SDimitry Andric /// is a batch walker that touches everything, it does not operate like the
12760b57cec5SDimitry Andric /// other walkers.  This walker is basically performing a top-down SSA renaming
12770b57cec5SDimitry Andric /// pass, where the version stack is used as the cache.  This enables it to be
12780b57cec5SDimitry Andric /// significantly more time and memory efficient than using the regular walker,
12790b57cec5SDimitry Andric /// which is walking bottom-up.
12800b57cec5SDimitry Andric class MemorySSA::OptimizeUses {
12810b57cec5SDimitry Andric public:
OptimizeUses(MemorySSA * MSSA,CachingWalker * Walker,BatchAAResults * BAA,DominatorTree * DT)1282bdd1243dSDimitry Andric   OptimizeUses(MemorySSA *MSSA, CachingWalker *Walker, BatchAAResults *BAA,
1283bdd1243dSDimitry Andric                DominatorTree *DT)
12840b57cec5SDimitry Andric       : MSSA(MSSA), Walker(Walker), AA(BAA), DT(DT) {}
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric   void optimizeUses();
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric private:
12890b57cec5SDimitry Andric   /// This represents where a given memorylocation is in the stack.
12900b57cec5SDimitry Andric   struct MemlocStackInfo {
12910b57cec5SDimitry Andric     // This essentially is keeping track of versions of the stack. Whenever
12920b57cec5SDimitry Andric     // the stack changes due to pushes or pops, these versions increase.
12930b57cec5SDimitry Andric     unsigned long StackEpoch;
12940b57cec5SDimitry Andric     unsigned long PopEpoch;
12950b57cec5SDimitry Andric     // This is the lower bound of places on the stack to check. It is equal to
12960b57cec5SDimitry Andric     // the place the last stack walk ended.
12970b57cec5SDimitry Andric     // Note: Correctness depends on this being initialized to 0, which densemap
12980b57cec5SDimitry Andric     // does
12990b57cec5SDimitry Andric     unsigned long LowerBound;
13000b57cec5SDimitry Andric     const BasicBlock *LowerBoundBlock;
13010b57cec5SDimitry Andric     // This is where the last walk for this memory location ended.
13020b57cec5SDimitry Andric     unsigned long LastKill;
13030b57cec5SDimitry Andric     bool LastKillValid;
13040b57cec5SDimitry Andric   };
13050b57cec5SDimitry Andric 
13060b57cec5SDimitry Andric   void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
13070b57cec5SDimitry Andric                            SmallVectorImpl<MemoryAccess *> &,
13080b57cec5SDimitry Andric                            DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric   MemorySSA *MSSA;
1311bdd1243dSDimitry Andric   CachingWalker *Walker;
13120b57cec5SDimitry Andric   BatchAAResults *AA;
13130b57cec5SDimitry Andric   DominatorTree *DT;
13140b57cec5SDimitry Andric };
13150b57cec5SDimitry Andric 
13160b57cec5SDimitry Andric } // end namespace llvm
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric /// Optimize the uses in a given block This is basically the SSA renaming
13190b57cec5SDimitry Andric /// algorithm, with one caveat: We are able to use a single stack for all
13200b57cec5SDimitry Andric /// MemoryUses.  This is because the set of *possible* reaching MemoryDefs is
13210b57cec5SDimitry Andric /// the same for every MemoryUse.  The *actual* clobbering MemoryDef is just
13220b57cec5SDimitry Andric /// going to be some position in that stack of possible ones.
13230b57cec5SDimitry Andric ///
13240b57cec5SDimitry Andric /// We track the stack positions that each MemoryLocation needs
13250b57cec5SDimitry Andric /// to check, and last ended at.  This is because we only want to check the
13260b57cec5SDimitry Andric /// things that changed since last time.  The same MemoryLocation should
13270b57cec5SDimitry Andric /// get clobbered by the same store (getModRefInfo does not use invariantness or
13280b57cec5SDimitry Andric /// things like this, and if they start, we can modify MemoryLocOrCall to
13290b57cec5SDimitry Andric /// include relevant data)
optimizeUsesInBlock(const BasicBlock * BB,unsigned long & StackEpoch,unsigned long & PopEpoch,SmallVectorImpl<MemoryAccess * > & VersionStack,DenseMap<MemoryLocOrCall,MemlocStackInfo> & LocStackInfo)13300b57cec5SDimitry Andric void MemorySSA::OptimizeUses::optimizeUsesInBlock(
13310b57cec5SDimitry Andric     const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
13320b57cec5SDimitry Andric     SmallVectorImpl<MemoryAccess *> &VersionStack,
13330b57cec5SDimitry Andric     DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
13340b57cec5SDimitry Andric 
13350b57cec5SDimitry Andric   /// If no accesses, nothing to do.
13360b57cec5SDimitry Andric   MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
13370b57cec5SDimitry Andric   if (Accesses == nullptr)
13380b57cec5SDimitry Andric     return;
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric   // Pop everything that doesn't dominate the current block off the stack,
13410b57cec5SDimitry Andric   // increment the PopEpoch to account for this.
13420b57cec5SDimitry Andric   while (true) {
13430b57cec5SDimitry Andric     assert(
13440b57cec5SDimitry Andric         !VersionStack.empty() &&
13450b57cec5SDimitry Andric         "Version stack should have liveOnEntry sentinel dominating everything");
13460b57cec5SDimitry Andric     BasicBlock *BackBlock = VersionStack.back()->getBlock();
13470b57cec5SDimitry Andric     if (DT->dominates(BackBlock, BB))
13480b57cec5SDimitry Andric       break;
13490b57cec5SDimitry Andric     while (VersionStack.back()->getBlock() == BackBlock)
13500b57cec5SDimitry Andric       VersionStack.pop_back();
13510b57cec5SDimitry Andric     ++PopEpoch;
13520b57cec5SDimitry Andric   }
13530b57cec5SDimitry Andric 
13540b57cec5SDimitry Andric   for (MemoryAccess &MA : *Accesses) {
13550b57cec5SDimitry Andric     auto *MU = dyn_cast<MemoryUse>(&MA);
13560b57cec5SDimitry Andric     if (!MU) {
13570b57cec5SDimitry Andric       VersionStack.push_back(&MA);
13580b57cec5SDimitry Andric       ++StackEpoch;
13590b57cec5SDimitry Andric       continue;
13600b57cec5SDimitry Andric     }
13610b57cec5SDimitry Andric 
136281ad6265SDimitry Andric     if (MU->isOptimized())
136381ad6265SDimitry Andric       continue;
136481ad6265SDimitry Andric 
13650b57cec5SDimitry Andric     MemoryLocOrCall UseMLOC(MU);
13660b57cec5SDimitry Andric     auto &LocInfo = LocStackInfo[UseMLOC];
13670b57cec5SDimitry Andric     // If the pop epoch changed, it means we've removed stuff from top of
13680b57cec5SDimitry Andric     // stack due to changing blocks. We may have to reset the lower bound or
13690b57cec5SDimitry Andric     // last kill info.
13700b57cec5SDimitry Andric     if (LocInfo.PopEpoch != PopEpoch) {
13710b57cec5SDimitry Andric       LocInfo.PopEpoch = PopEpoch;
13720b57cec5SDimitry Andric       LocInfo.StackEpoch = StackEpoch;
13730b57cec5SDimitry Andric       // If the lower bound was in something that no longer dominates us, we
13740b57cec5SDimitry Andric       // have to reset it.
13750b57cec5SDimitry Andric       // We can't simply track stack size, because the stack may have had
13760b57cec5SDimitry Andric       // pushes/pops in the meantime.
13770b57cec5SDimitry Andric       // XXX: This is non-optimal, but only is slower cases with heavily
13780b57cec5SDimitry Andric       // branching dominator trees.  To get the optimal number of queries would
13790b57cec5SDimitry Andric       // be to make lowerbound and lastkill a per-loc stack, and pop it until
13800b57cec5SDimitry Andric       // the top of that stack dominates us.  This does not seem worth it ATM.
13810b57cec5SDimitry Andric       // A much cheaper optimization would be to always explore the deepest
13820b57cec5SDimitry Andric       // branch of the dominator tree first. This will guarantee this resets on
13830b57cec5SDimitry Andric       // the smallest set of blocks.
13840b57cec5SDimitry Andric       if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
13850b57cec5SDimitry Andric           !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
13860b57cec5SDimitry Andric         // Reset the lower bound of things to check.
13870b57cec5SDimitry Andric         // TODO: Some day we should be able to reset to last kill, rather than
13880b57cec5SDimitry Andric         // 0.
13890b57cec5SDimitry Andric         LocInfo.LowerBound = 0;
13900b57cec5SDimitry Andric         LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
13910b57cec5SDimitry Andric         LocInfo.LastKillValid = false;
13920b57cec5SDimitry Andric       }
13930b57cec5SDimitry Andric     } else if (LocInfo.StackEpoch != StackEpoch) {
13940b57cec5SDimitry Andric       // If all that has changed is the StackEpoch, we only have to check the
13950b57cec5SDimitry Andric       // new things on the stack, because we've checked everything before.  In
13960b57cec5SDimitry Andric       // this case, the lower bound of things to check remains the same.
13970b57cec5SDimitry Andric       LocInfo.PopEpoch = PopEpoch;
13980b57cec5SDimitry Andric       LocInfo.StackEpoch = StackEpoch;
13990b57cec5SDimitry Andric     }
14000b57cec5SDimitry Andric     if (!LocInfo.LastKillValid) {
14010b57cec5SDimitry Andric       LocInfo.LastKill = VersionStack.size() - 1;
14020b57cec5SDimitry Andric       LocInfo.LastKillValid = true;
14030b57cec5SDimitry Andric     }
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric     // At this point, we should have corrected last kill and LowerBound to be
14060b57cec5SDimitry Andric     // in bounds.
14070b57cec5SDimitry Andric     assert(LocInfo.LowerBound < VersionStack.size() &&
14080b57cec5SDimitry Andric            "Lower bound out of range");
14090b57cec5SDimitry Andric     assert(LocInfo.LastKill < VersionStack.size() &&
14100b57cec5SDimitry Andric            "Last kill info out of range");
14110b57cec5SDimitry Andric     // In any case, the new upper bound is the top of the stack.
14120b57cec5SDimitry Andric     unsigned long UpperBound = VersionStack.size() - 1;
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric     if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
14150b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
14160b57cec5SDimitry Andric                         << *(MU->getMemoryInst()) << ")"
14170b57cec5SDimitry Andric                         << " because there are "
14180b57cec5SDimitry Andric                         << UpperBound - LocInfo.LowerBound
14190b57cec5SDimitry Andric                         << " stores to disambiguate\n");
14200b57cec5SDimitry Andric       // Because we did not walk, LastKill is no longer valid, as this may
14210b57cec5SDimitry Andric       // have been a kill.
14220b57cec5SDimitry Andric       LocInfo.LastKillValid = false;
14230b57cec5SDimitry Andric       continue;
14240b57cec5SDimitry Andric     }
14250b57cec5SDimitry Andric     bool FoundClobberResult = false;
14260b57cec5SDimitry Andric     unsigned UpwardWalkLimit = MaxCheckLimit;
14270b57cec5SDimitry Andric     while (UpperBound > LocInfo.LowerBound) {
14280b57cec5SDimitry Andric       if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1429349cc55cSDimitry Andric         // For phis, use the walker, see where we ended up, go there.
1430349cc55cSDimitry Andric         // The invariant.group handling in MemorySSA is ad-hoc and doesn't
1431349cc55cSDimitry Andric         // support updates, so don't use it to optimize uses.
14320b57cec5SDimitry Andric         MemoryAccess *Result =
1433349cc55cSDimitry Andric             Walker->getClobberingMemoryAccessWithoutInvariantGroup(
1434bdd1243dSDimitry Andric                 MU, *AA, UpwardWalkLimit);
1435349cc55cSDimitry Andric         // We are guaranteed to find it or something is wrong.
14360b57cec5SDimitry Andric         while (VersionStack[UpperBound] != Result) {
14370b57cec5SDimitry Andric           assert(UpperBound != 0);
14380b57cec5SDimitry Andric           --UpperBound;
14390b57cec5SDimitry Andric         }
14400b57cec5SDimitry Andric         FoundClobberResult = true;
14410b57cec5SDimitry Andric         break;
14420b57cec5SDimitry Andric       }
14430b57cec5SDimitry Andric 
14440b57cec5SDimitry Andric       MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
1445bdd1243dSDimitry Andric       if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
14460b57cec5SDimitry Andric         FoundClobberResult = true;
14470b57cec5SDimitry Andric         break;
14480b57cec5SDimitry Andric       }
14490b57cec5SDimitry Andric       --UpperBound;
14500b57cec5SDimitry Andric     }
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric     // At the end of this loop, UpperBound is either a clobber, or lower bound
14530b57cec5SDimitry Andric     // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
14540b57cec5SDimitry Andric     if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1455bdd1243dSDimitry Andric       MU->setDefiningAccess(VersionStack[UpperBound], true);
14560b57cec5SDimitry Andric       LocInfo.LastKill = UpperBound;
14570b57cec5SDimitry Andric     } else {
14580b57cec5SDimitry Andric       // Otherwise, we checked all the new ones, and now we know we can get to
14590b57cec5SDimitry Andric       // LastKill.
1460bdd1243dSDimitry Andric       MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true);
14610b57cec5SDimitry Andric     }
14620b57cec5SDimitry Andric     LocInfo.LowerBound = VersionStack.size() - 1;
14630b57cec5SDimitry Andric     LocInfo.LowerBoundBlock = BB;
14640b57cec5SDimitry Andric   }
14650b57cec5SDimitry Andric }
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric /// Optimize uses to point to their actual clobbering definitions.
optimizeUses()14680b57cec5SDimitry Andric void MemorySSA::OptimizeUses::optimizeUses() {
14690b57cec5SDimitry Andric   SmallVector<MemoryAccess *, 16> VersionStack;
14700b57cec5SDimitry Andric   DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
14710b57cec5SDimitry Andric   VersionStack.push_back(MSSA->getLiveOnEntryDef());
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric   unsigned long StackEpoch = 1;
14740b57cec5SDimitry Andric   unsigned long PopEpoch = 1;
14750b57cec5SDimitry Andric   // We perform a non-recursive top-down dominator tree walk.
14760b57cec5SDimitry Andric   for (const auto *DomNode : depth_first(DT->getRootNode()))
14770b57cec5SDimitry Andric     optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
14780b57cec5SDimitry Andric                         LocStackInfo);
14790b57cec5SDimitry Andric }
14800b57cec5SDimitry Andric 
placePHINodes(const SmallPtrSetImpl<BasicBlock * > & DefiningBlocks)14810b57cec5SDimitry Andric void MemorySSA::placePHINodes(
14820b57cec5SDimitry Andric     const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
14830b57cec5SDimitry Andric   // Determine where our MemoryPhi's should go
14840b57cec5SDimitry Andric   ForwardIDFCalculator IDFs(*DT);
14850b57cec5SDimitry Andric   IDFs.setDefiningBlocks(DefiningBlocks);
14860b57cec5SDimitry Andric   SmallVector<BasicBlock *, 32> IDFBlocks;
14870b57cec5SDimitry Andric   IDFs.calculate(IDFBlocks);
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric   // Now place MemoryPhi nodes.
14900b57cec5SDimitry Andric   for (auto &BB : IDFBlocks)
14910b57cec5SDimitry Andric     createMemoryPhi(BB);
14920b57cec5SDimitry Andric }
14930b57cec5SDimitry Andric 
buildMemorySSA(BatchAAResults & BAA)14940b57cec5SDimitry Andric void MemorySSA::buildMemorySSA(BatchAAResults &BAA) {
14950b57cec5SDimitry Andric   // We create an access to represent "live on entry", for things like
14960b57cec5SDimitry Andric   // arguments or users of globals, where the memory they use is defined before
14970b57cec5SDimitry Andric   // the beginning of the function. We do not actually insert it into the IR.
14980b57cec5SDimitry Andric   // We do not define a live on exit for the immediate uses, and thus our
14990b57cec5SDimitry Andric   // semantics do *not* imply that something with no immediate uses can simply
15000b57cec5SDimitry Andric   // be removed.
15010b57cec5SDimitry Andric   BasicBlock &StartingPoint = F.getEntryBlock();
15020b57cec5SDimitry Andric   LiveOnEntryDef.reset(new MemoryDef(F.getContext(), nullptr, nullptr,
15030b57cec5SDimitry Andric                                      &StartingPoint, NextID++));
15040b57cec5SDimitry Andric 
15050b57cec5SDimitry Andric   // We maintain lists of memory accesses per-block, trading memory for time. We
15060b57cec5SDimitry Andric   // could just look up the memory access for every possible instruction in the
15070b57cec5SDimitry Andric   // stream.
15080b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
15090b57cec5SDimitry Andric   // Go through each block, figure out where defs occur, and chain together all
15100b57cec5SDimitry Andric   // the accesses.
15110b57cec5SDimitry Andric   for (BasicBlock &B : F) {
15120b57cec5SDimitry Andric     bool InsertIntoDef = false;
15130b57cec5SDimitry Andric     AccessList *Accesses = nullptr;
15140b57cec5SDimitry Andric     DefsList *Defs = nullptr;
15150b57cec5SDimitry Andric     for (Instruction &I : B) {
15160b57cec5SDimitry Andric       MemoryUseOrDef *MUD = createNewAccess(&I, &BAA);
15170b57cec5SDimitry Andric       if (!MUD)
15180b57cec5SDimitry Andric         continue;
15190b57cec5SDimitry Andric 
15200b57cec5SDimitry Andric       if (!Accesses)
15210b57cec5SDimitry Andric         Accesses = getOrCreateAccessList(&B);
15220b57cec5SDimitry Andric       Accesses->push_back(MUD);
15230b57cec5SDimitry Andric       if (isa<MemoryDef>(MUD)) {
15240b57cec5SDimitry Andric         InsertIntoDef = true;
15250b57cec5SDimitry Andric         if (!Defs)
15260b57cec5SDimitry Andric           Defs = getOrCreateDefsList(&B);
15270b57cec5SDimitry Andric         Defs->push_back(*MUD);
15280b57cec5SDimitry Andric       }
15290b57cec5SDimitry Andric     }
15300b57cec5SDimitry Andric     if (InsertIntoDef)
15310b57cec5SDimitry Andric       DefiningBlocks.insert(&B);
15320b57cec5SDimitry Andric   }
15330b57cec5SDimitry Andric   placePHINodes(DefiningBlocks);
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric   // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
15360b57cec5SDimitry Andric   // filled in with all blocks.
15370b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> Visited;
15380b57cec5SDimitry Andric   renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric   // Mark the uses in unreachable blocks as live on entry, so that they go
15410b57cec5SDimitry Andric   // somewhere.
15420b57cec5SDimitry Andric   for (auto &BB : F)
15430b57cec5SDimitry Andric     if (!Visited.count(&BB))
15440b57cec5SDimitry Andric       markUnreachableAsLiveOnEntry(&BB);
15450b57cec5SDimitry Andric }
15460b57cec5SDimitry Andric 
getWalker()15470b57cec5SDimitry Andric MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
15480b57cec5SDimitry Andric 
getWalkerImpl()1549bdd1243dSDimitry Andric MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
15500b57cec5SDimitry Andric   if (Walker)
15510b57cec5SDimitry Andric     return Walker.get();
15520b57cec5SDimitry Andric 
15530b57cec5SDimitry Andric   if (!WalkerBase)
1554bdd1243dSDimitry Andric     WalkerBase = std::make_unique<ClobberWalkerBase>(this, DT);
15550b57cec5SDimitry Andric 
1556bdd1243dSDimitry Andric   Walker = std::make_unique<CachingWalker>(this, WalkerBase.get());
15570b57cec5SDimitry Andric   return Walker.get();
15580b57cec5SDimitry Andric }
15590b57cec5SDimitry Andric 
getSkipSelfWalker()15600b57cec5SDimitry Andric MemorySSAWalker *MemorySSA::getSkipSelfWalker() {
15610b57cec5SDimitry Andric   if (SkipWalker)
15620b57cec5SDimitry Andric     return SkipWalker.get();
15630b57cec5SDimitry Andric 
15640b57cec5SDimitry Andric   if (!WalkerBase)
1565bdd1243dSDimitry Andric     WalkerBase = std::make_unique<ClobberWalkerBase>(this, DT);
15660b57cec5SDimitry Andric 
1567bdd1243dSDimitry Andric   SkipWalker = std::make_unique<SkipSelfWalker>(this, WalkerBase.get());
15680b57cec5SDimitry Andric   return SkipWalker.get();
15690b57cec5SDimitry Andric  }
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric 
15720b57cec5SDimitry Andric // This is a helper function used by the creation routines. It places NewAccess
15730b57cec5SDimitry Andric // into the access and defs lists for a given basic block, at the given
15740b57cec5SDimitry Andric // insertion point.
insertIntoListsForBlock(MemoryAccess * NewAccess,const BasicBlock * BB,InsertionPlace Point)15750b57cec5SDimitry Andric void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
15760b57cec5SDimitry Andric                                         const BasicBlock *BB,
15770b57cec5SDimitry Andric                                         InsertionPlace Point) {
15780b57cec5SDimitry Andric   auto *Accesses = getOrCreateAccessList(BB);
15790b57cec5SDimitry Andric   if (Point == Beginning) {
15800b57cec5SDimitry Andric     // If it's a phi node, it goes first, otherwise, it goes after any phi
15810b57cec5SDimitry Andric     // nodes.
15820b57cec5SDimitry Andric     if (isa<MemoryPhi>(NewAccess)) {
15830b57cec5SDimitry Andric       Accesses->push_front(NewAccess);
15840b57cec5SDimitry Andric       auto *Defs = getOrCreateDefsList(BB);
15850b57cec5SDimitry Andric       Defs->push_front(*NewAccess);
15860b57cec5SDimitry Andric     } else {
15870b57cec5SDimitry Andric       auto AI = find_if_not(
15880b57cec5SDimitry Andric           *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
15890b57cec5SDimitry Andric       Accesses->insert(AI, NewAccess);
15900b57cec5SDimitry Andric       if (!isa<MemoryUse>(NewAccess)) {
15910b57cec5SDimitry Andric         auto *Defs = getOrCreateDefsList(BB);
15920b57cec5SDimitry Andric         auto DI = find_if_not(
15930b57cec5SDimitry Andric             *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
15940b57cec5SDimitry Andric         Defs->insert(DI, *NewAccess);
15950b57cec5SDimitry Andric       }
15960b57cec5SDimitry Andric     }
15970b57cec5SDimitry Andric   } else {
15980b57cec5SDimitry Andric     Accesses->push_back(NewAccess);
15990b57cec5SDimitry Andric     if (!isa<MemoryUse>(NewAccess)) {
16000b57cec5SDimitry Andric       auto *Defs = getOrCreateDefsList(BB);
16010b57cec5SDimitry Andric       Defs->push_back(*NewAccess);
16020b57cec5SDimitry Andric     }
16030b57cec5SDimitry Andric   }
16040b57cec5SDimitry Andric   BlockNumberingValid.erase(BB);
16050b57cec5SDimitry Andric }
16060b57cec5SDimitry Andric 
insertIntoListsBefore(MemoryAccess * What,const BasicBlock * BB,AccessList::iterator InsertPt)16070b57cec5SDimitry Andric void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
16080b57cec5SDimitry Andric                                       AccessList::iterator InsertPt) {
16090b57cec5SDimitry Andric   auto *Accesses = getWritableBlockAccesses(BB);
16100b57cec5SDimitry Andric   bool WasEnd = InsertPt == Accesses->end();
16110b57cec5SDimitry Andric   Accesses->insert(AccessList::iterator(InsertPt), What);
16120b57cec5SDimitry Andric   if (!isa<MemoryUse>(What)) {
16130b57cec5SDimitry Andric     auto *Defs = getOrCreateDefsList(BB);
16140b57cec5SDimitry Andric     // If we got asked to insert at the end, we have an easy job, just shove it
16150b57cec5SDimitry Andric     // at the end. If we got asked to insert before an existing def, we also get
16160b57cec5SDimitry Andric     // an iterator. If we got asked to insert before a use, we have to hunt for
16170b57cec5SDimitry Andric     // the next def.
16180b57cec5SDimitry Andric     if (WasEnd) {
16190b57cec5SDimitry Andric       Defs->push_back(*What);
16200b57cec5SDimitry Andric     } else if (isa<MemoryDef>(InsertPt)) {
16210b57cec5SDimitry Andric       Defs->insert(InsertPt->getDefsIterator(), *What);
16220b57cec5SDimitry Andric     } else {
16230b57cec5SDimitry Andric       while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
16240b57cec5SDimitry Andric         ++InsertPt;
16250b57cec5SDimitry Andric       // Either we found a def, or we are inserting at the end
16260b57cec5SDimitry Andric       if (InsertPt == Accesses->end())
16270b57cec5SDimitry Andric         Defs->push_back(*What);
16280b57cec5SDimitry Andric       else
16290b57cec5SDimitry Andric         Defs->insert(InsertPt->getDefsIterator(), *What);
16300b57cec5SDimitry Andric     }
16310b57cec5SDimitry Andric   }
16320b57cec5SDimitry Andric   BlockNumberingValid.erase(BB);
16330b57cec5SDimitry Andric }
16340b57cec5SDimitry Andric 
prepareForMoveTo(MemoryAccess * What,BasicBlock * BB)16350b57cec5SDimitry Andric void MemorySSA::prepareForMoveTo(MemoryAccess *What, BasicBlock *BB) {
16360b57cec5SDimitry Andric   // Keep it in the lookup tables, remove from the lists
16370b57cec5SDimitry Andric   removeFromLists(What, false);
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   // Note that moving should implicitly invalidate the optimized state of a
16400b57cec5SDimitry Andric   // MemoryUse (and Phis can't be optimized). However, it doesn't do so for a
16410b57cec5SDimitry Andric   // MemoryDef.
16420b57cec5SDimitry Andric   if (auto *MD = dyn_cast<MemoryDef>(What))
16430b57cec5SDimitry Andric     MD->resetOptimized();
16440b57cec5SDimitry Andric   What->setBlock(BB);
16450b57cec5SDimitry Andric }
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric // Move What before Where in the IR.  The end result is that What will belong to
16480b57cec5SDimitry Andric // the right lists and have the right Block set, but will not otherwise be
16490b57cec5SDimitry Andric // correct. It will not have the right defining access, and if it is a def,
16500b57cec5SDimitry Andric // things below it will not properly be updated.
moveTo(MemoryUseOrDef * What,BasicBlock * BB,AccessList::iterator Where)16510b57cec5SDimitry Andric void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
16520b57cec5SDimitry Andric                        AccessList::iterator Where) {
16530b57cec5SDimitry Andric   prepareForMoveTo(What, BB);
16540b57cec5SDimitry Andric   insertIntoListsBefore(What, BB, Where);
16550b57cec5SDimitry Andric }
16560b57cec5SDimitry Andric 
moveTo(MemoryAccess * What,BasicBlock * BB,InsertionPlace Point)16570b57cec5SDimitry Andric void MemorySSA::moveTo(MemoryAccess *What, BasicBlock *BB,
16580b57cec5SDimitry Andric                        InsertionPlace Point) {
16590b57cec5SDimitry Andric   if (isa<MemoryPhi>(What)) {
16600b57cec5SDimitry Andric     assert(Point == Beginning &&
16610b57cec5SDimitry Andric            "Can only move a Phi at the beginning of the block");
16620b57cec5SDimitry Andric     // Update lookup table entry
16630b57cec5SDimitry Andric     ValueToMemoryAccess.erase(What->getBlock());
16640b57cec5SDimitry Andric     bool Inserted = ValueToMemoryAccess.insert({BB, What}).second;
16650b57cec5SDimitry Andric     (void)Inserted;
16660b57cec5SDimitry Andric     assert(Inserted && "Cannot move a Phi to a block that already has one");
16670b57cec5SDimitry Andric   }
16680b57cec5SDimitry Andric 
16690b57cec5SDimitry Andric   prepareForMoveTo(What, BB);
16700b57cec5SDimitry Andric   insertIntoListsForBlock(What, BB, Point);
16710b57cec5SDimitry Andric }
16720b57cec5SDimitry Andric 
createMemoryPhi(BasicBlock * BB)16730b57cec5SDimitry Andric MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
16740b57cec5SDimitry Andric   assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
16750b57cec5SDimitry Andric   MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
16760b57cec5SDimitry Andric   // Phi's always are placed at the front of the block.
16770b57cec5SDimitry Andric   insertIntoListsForBlock(Phi, BB, Beginning);
16780b57cec5SDimitry Andric   ValueToMemoryAccess[BB] = Phi;
16790b57cec5SDimitry Andric   return Phi;
16800b57cec5SDimitry Andric }
16810b57cec5SDimitry Andric 
createDefinedAccess(Instruction * I,MemoryAccess * Definition,const MemoryUseOrDef * Template,bool CreationMustSucceed)16820b57cec5SDimitry Andric MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
16830b57cec5SDimitry Andric                                                MemoryAccess *Definition,
16848bcb0991SDimitry Andric                                                const MemoryUseOrDef *Template,
16858bcb0991SDimitry Andric                                                bool CreationMustSucceed) {
16860b57cec5SDimitry Andric   assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
16870b57cec5SDimitry Andric   MemoryUseOrDef *NewAccess = createNewAccess(I, AA, Template);
16888bcb0991SDimitry Andric   if (CreationMustSucceed)
16898bcb0991SDimitry Andric     assert(NewAccess != nullptr && "Tried to create a memory access for a "
16908bcb0991SDimitry Andric                                    "non-memory touching instruction");
1691e8d8bef9SDimitry Andric   if (NewAccess) {
1692e8d8bef9SDimitry Andric     assert((!Definition || !isa<MemoryUse>(Definition)) &&
1693e8d8bef9SDimitry Andric            "A use cannot be a defining access");
16940b57cec5SDimitry Andric     NewAccess->setDefiningAccess(Definition);
1695e8d8bef9SDimitry Andric   }
16960b57cec5SDimitry Andric   return NewAccess;
16970b57cec5SDimitry Andric }
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric // Return true if the instruction has ordering constraints.
17000b57cec5SDimitry Andric // Note specifically that this only considers stores and loads
17010b57cec5SDimitry Andric // because others are still considered ModRef by getModRefInfo.
isOrdered(const Instruction * I)17020b57cec5SDimitry Andric static inline bool isOrdered(const Instruction *I) {
17030b57cec5SDimitry Andric   if (auto *SI = dyn_cast<StoreInst>(I)) {
17040b57cec5SDimitry Andric     if (!SI->isUnordered())
17050b57cec5SDimitry Andric       return true;
17060b57cec5SDimitry Andric   } else if (auto *LI = dyn_cast<LoadInst>(I)) {
17070b57cec5SDimitry Andric     if (!LI->isUnordered())
17080b57cec5SDimitry Andric       return true;
17090b57cec5SDimitry Andric   }
17100b57cec5SDimitry Andric   return false;
17110b57cec5SDimitry Andric }
17120b57cec5SDimitry Andric 
17130b57cec5SDimitry Andric /// Helper function to create new memory accesses
17140b57cec5SDimitry Andric template <typename AliasAnalysisType>
createNewAccess(Instruction * I,AliasAnalysisType * AAP,const MemoryUseOrDef * Template)17150b57cec5SDimitry Andric MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I,
17160b57cec5SDimitry Andric                                            AliasAnalysisType *AAP,
17170b57cec5SDimitry Andric                                            const MemoryUseOrDef *Template) {
17180b57cec5SDimitry Andric   // The assume intrinsic has a control dependency which we model by claiming
17198bcb0991SDimitry Andric   // that it writes arbitrarily. Debuginfo intrinsics may be considered
17208bcb0991SDimitry Andric   // clobbers when we have a nonstandard AA pipeline. Ignore these fake memory
17218bcb0991SDimitry Andric   // dependencies here.
17220b57cec5SDimitry Andric   // FIXME: Replace this special casing with a more accurate modelling of
17230b57cec5SDimitry Andric   // assume's control dependency.
1724e8d8bef9SDimitry Andric   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1725e8d8bef9SDimitry Andric     switch (II->getIntrinsicID()) {
1726e8d8bef9SDimitry Andric     default:
1727e8d8bef9SDimitry Andric       break;
1728e8d8bef9SDimitry Andric     case Intrinsic::assume:
1729e8d8bef9SDimitry Andric     case Intrinsic::experimental_noalias_scope_decl:
1730349cc55cSDimitry Andric     case Intrinsic::pseudoprobe:
17310b57cec5SDimitry Andric       return nullptr;
1732e8d8bef9SDimitry Andric     }
1733e8d8bef9SDimitry Andric   }
17340b57cec5SDimitry Andric 
17358bcb0991SDimitry Andric   // Using a nonstandard AA pipelines might leave us with unexpected modref
17368bcb0991SDimitry Andric   // results for I, so add a check to not model instructions that may not read
17378bcb0991SDimitry Andric   // from or write to memory. This is necessary for correctness.
17388bcb0991SDimitry Andric   if (!I->mayReadFromMemory() && !I->mayWriteToMemory())
17398bcb0991SDimitry Andric     return nullptr;
17408bcb0991SDimitry Andric 
17410b57cec5SDimitry Andric   bool Def, Use;
17420b57cec5SDimitry Andric   if (Template) {
1743e8d8bef9SDimitry Andric     Def = isa<MemoryDef>(Template);
1744e8d8bef9SDimitry Andric     Use = isa<MemoryUse>(Template);
17450b57cec5SDimitry Andric #if !defined(NDEBUG)
1746bdd1243dSDimitry Andric     ModRefInfo ModRef = AAP->getModRefInfo(I, std::nullopt);
17470b57cec5SDimitry Andric     bool DefCheck, UseCheck;
17480b57cec5SDimitry Andric     DefCheck = isModSet(ModRef) || isOrdered(I);
17490b57cec5SDimitry Andric     UseCheck = isRefSet(ModRef);
1750bdd1243dSDimitry Andric     // Memory accesses should only be reduced and can not be increased since AA
1751bdd1243dSDimitry Andric     // just might return better results as a result of some transformations.
1752bdd1243dSDimitry Andric     assert((Def == DefCheck || !DefCheck) &&
1753bdd1243dSDimitry Andric            "Memory accesses should only be reduced");
1754bdd1243dSDimitry Andric     if (!Def && Use != UseCheck) {
1755bdd1243dSDimitry Andric       // New Access should not have more power than template access
1756bdd1243dSDimitry Andric       assert(!UseCheck && "Invalid template");
1757bdd1243dSDimitry Andric     }
17580b57cec5SDimitry Andric #endif
17590b57cec5SDimitry Andric   } else {
17600b57cec5SDimitry Andric     // Find out what affect this instruction has on memory.
1761bdd1243dSDimitry Andric     ModRefInfo ModRef = AAP->getModRefInfo(I, std::nullopt);
17620b57cec5SDimitry Andric     // The isOrdered check is used to ensure that volatiles end up as defs
17630b57cec5SDimitry Andric     // (atomics end up as ModRef right now anyway).  Until we separate the
17640b57cec5SDimitry Andric     // ordering chain from the memory chain, this enables people to see at least
17650b57cec5SDimitry Andric     // some relative ordering to volatiles.  Note that getClobberingMemoryAccess
17660b57cec5SDimitry Andric     // will still give an answer that bypasses other volatile loads.  TODO:
17670b57cec5SDimitry Andric     // Separate memory aliasing and ordering into two different chains so that
17680b57cec5SDimitry Andric     // we can precisely represent both "what memory will this read/write/is
17690b57cec5SDimitry Andric     // clobbered by" and "what instructions can I move this past".
17700b57cec5SDimitry Andric     Def = isModSet(ModRef) || isOrdered(I);
17710b57cec5SDimitry Andric     Use = isRefSet(ModRef);
17720b57cec5SDimitry Andric   }
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric   // It's possible for an instruction to not modify memory at all. During
17750b57cec5SDimitry Andric   // construction, we ignore them.
17760b57cec5SDimitry Andric   if (!Def && !Use)
17770b57cec5SDimitry Andric     return nullptr;
17780b57cec5SDimitry Andric 
17790b57cec5SDimitry Andric   MemoryUseOrDef *MUD;
178006c3fb27SDimitry Andric   if (Def) {
17810b57cec5SDimitry Andric     MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
178206c3fb27SDimitry Andric   } else {
17830b57cec5SDimitry Andric     MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
178406c3fb27SDimitry Andric     if (isUseTriviallyOptimizableToLiveOnEntry(*AAP, I)) {
178506c3fb27SDimitry Andric       MemoryAccess *LiveOnEntry = getLiveOnEntryDef();
178606c3fb27SDimitry Andric       MUD->setOptimized(LiveOnEntry);
178706c3fb27SDimitry Andric     }
178806c3fb27SDimitry Andric   }
17890b57cec5SDimitry Andric   ValueToMemoryAccess[I] = MUD;
17900b57cec5SDimitry Andric   return MUD;
17910b57cec5SDimitry Andric }
17920b57cec5SDimitry Andric 
17930b57cec5SDimitry Andric /// Properly remove \p MA from all of MemorySSA's lookup tables.
removeFromLookups(MemoryAccess * MA)17940b57cec5SDimitry Andric void MemorySSA::removeFromLookups(MemoryAccess *MA) {
17950b57cec5SDimitry Andric   assert(MA->use_empty() &&
17960b57cec5SDimitry Andric          "Trying to remove memory access that still has uses");
17970b57cec5SDimitry Andric   BlockNumbering.erase(MA);
17980b57cec5SDimitry Andric   if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
17990b57cec5SDimitry Andric     MUD->setDefiningAccess(nullptr);
18000b57cec5SDimitry Andric   // Invalidate our walker's cache if necessary
18010b57cec5SDimitry Andric   if (!isa<MemoryUse>(MA))
18020b57cec5SDimitry Andric     getWalker()->invalidateInfo(MA);
18030b57cec5SDimitry Andric 
18040b57cec5SDimitry Andric   Value *MemoryInst;
18050b57cec5SDimitry Andric   if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
18060b57cec5SDimitry Andric     MemoryInst = MUD->getMemoryInst();
18070b57cec5SDimitry Andric   else
18080b57cec5SDimitry Andric     MemoryInst = MA->getBlock();
18090b57cec5SDimitry Andric 
18100b57cec5SDimitry Andric   auto VMA = ValueToMemoryAccess.find(MemoryInst);
18110b57cec5SDimitry Andric   if (VMA->second == MA)
18120b57cec5SDimitry Andric     ValueToMemoryAccess.erase(VMA);
18130b57cec5SDimitry Andric }
18140b57cec5SDimitry Andric 
18150b57cec5SDimitry Andric /// Properly remove \p MA from all of MemorySSA's lists.
18160b57cec5SDimitry Andric ///
18170b57cec5SDimitry Andric /// Because of the way the intrusive list and use lists work, it is important to
18180b57cec5SDimitry Andric /// do removal in the right order.
18190b57cec5SDimitry Andric /// ShouldDelete defaults to true, and will cause the memory access to also be
18200b57cec5SDimitry Andric /// deleted, not just removed.
removeFromLists(MemoryAccess * MA,bool ShouldDelete)18210b57cec5SDimitry Andric void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
18220b57cec5SDimitry Andric   BasicBlock *BB = MA->getBlock();
18230b57cec5SDimitry Andric   // The access list owns the reference, so we erase it from the non-owning list
18240b57cec5SDimitry Andric   // first.
18250b57cec5SDimitry Andric   if (!isa<MemoryUse>(MA)) {
18260b57cec5SDimitry Andric     auto DefsIt = PerBlockDefs.find(BB);
18270b57cec5SDimitry Andric     std::unique_ptr<DefsList> &Defs = DefsIt->second;
18280b57cec5SDimitry Andric     Defs->remove(*MA);
18290b57cec5SDimitry Andric     if (Defs->empty())
18300b57cec5SDimitry Andric       PerBlockDefs.erase(DefsIt);
18310b57cec5SDimitry Andric   }
18320b57cec5SDimitry Andric 
18330b57cec5SDimitry Andric   // The erase call here will delete it. If we don't want it deleted, we call
18340b57cec5SDimitry Andric   // remove instead.
18350b57cec5SDimitry Andric   auto AccessIt = PerBlockAccesses.find(BB);
18360b57cec5SDimitry Andric   std::unique_ptr<AccessList> &Accesses = AccessIt->second;
18370b57cec5SDimitry Andric   if (ShouldDelete)
18380b57cec5SDimitry Andric     Accesses->erase(MA);
18390b57cec5SDimitry Andric   else
18400b57cec5SDimitry Andric     Accesses->remove(MA);
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric   if (Accesses->empty()) {
18430b57cec5SDimitry Andric     PerBlockAccesses.erase(AccessIt);
18440b57cec5SDimitry Andric     BlockNumberingValid.erase(BB);
18450b57cec5SDimitry Andric   }
18460b57cec5SDimitry Andric }
18470b57cec5SDimitry Andric 
print(raw_ostream & OS) const18480b57cec5SDimitry Andric void MemorySSA::print(raw_ostream &OS) const {
18490b57cec5SDimitry Andric   MemorySSAAnnotatedWriter Writer(this);
18500b57cec5SDimitry Andric   F.print(OS, &Writer);
18510b57cec5SDimitry Andric }
18520b57cec5SDimitry Andric 
18530b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const18540b57cec5SDimitry Andric LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
18550b57cec5SDimitry Andric #endif
18560b57cec5SDimitry Andric 
verifyMemorySSA(VerificationLevel VL) const1857349cc55cSDimitry Andric void MemorySSA::verifyMemorySSA(VerificationLevel VL) const {
1858349cc55cSDimitry Andric #if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS)
1859349cc55cSDimitry Andric   VL = VerificationLevel::Full;
1860349cc55cSDimitry Andric #endif
1861349cc55cSDimitry Andric 
1862349cc55cSDimitry Andric #ifndef NDEBUG
1863349cc55cSDimitry Andric   verifyOrderingDominationAndDefUses(F, VL);
18640b57cec5SDimitry Andric   verifyDominationNumbers(F);
1865349cc55cSDimitry Andric   if (VL == VerificationLevel::Full)
18668bcb0991SDimitry Andric     verifyPrevDefInPhis(F);
1867349cc55cSDimitry Andric #endif
18680b57cec5SDimitry Andric   // Previously, the verification used to also verify that the clobberingAccess
18690b57cec5SDimitry Andric   // cached by MemorySSA is the same as the clobberingAccess found at a later
18700b57cec5SDimitry Andric   // query to AA. This does not hold true in general due to the current fragility
18710b57cec5SDimitry Andric   // of BasicAA which has arbitrary caps on the things it analyzes before giving
18720b57cec5SDimitry Andric   // up. As a result, transformations that are correct, will lead to BasicAA
18730b57cec5SDimitry Andric   // returning different Alias answers before and after that transformation.
18740b57cec5SDimitry Andric   // Invalidating MemorySSA is not an option, as the results in BasicAA can be so
18750b57cec5SDimitry Andric   // random, in the worst case we'd need to rebuild MemorySSA from scratch after
18760b57cec5SDimitry Andric   // every transformation, which defeats the purpose of using it. For such an
18770b57cec5SDimitry Andric   // example, see test4 added in D51960.
18780b57cec5SDimitry Andric }
18790b57cec5SDimitry Andric 
verifyPrevDefInPhis(Function & F) const18808bcb0991SDimitry Andric void MemorySSA::verifyPrevDefInPhis(Function &F) const {
18818bcb0991SDimitry Andric   for (const BasicBlock &BB : F) {
18828bcb0991SDimitry Andric     if (MemoryPhi *Phi = getMemoryAccess(&BB)) {
18838bcb0991SDimitry Andric       for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
18848bcb0991SDimitry Andric         auto *Pred = Phi->getIncomingBlock(I);
18858bcb0991SDimitry Andric         auto *IncAcc = Phi->getIncomingValue(I);
18868bcb0991SDimitry Andric         // If Pred has no unreachable predecessors, get last def looking at
18878bcb0991SDimitry Andric         // IDoms. If, while walkings IDoms, any of these has an unreachable
18888bcb0991SDimitry Andric         // predecessor, then the incoming def can be any access.
18898bcb0991SDimitry Andric         if (auto *DTNode = DT->getNode(Pred)) {
18908bcb0991SDimitry Andric           while (DTNode) {
18918bcb0991SDimitry Andric             if (auto *DefList = getBlockDefs(DTNode->getBlock())) {
18928bcb0991SDimitry Andric               auto *LastAcc = &*(--DefList->end());
18938bcb0991SDimitry Andric               assert(LastAcc == IncAcc &&
18948bcb0991SDimitry Andric                      "Incorrect incoming access into phi.");
1895349cc55cSDimitry Andric               (void)IncAcc;
1896349cc55cSDimitry Andric               (void)LastAcc;
18978bcb0991SDimitry Andric               break;
18988bcb0991SDimitry Andric             }
18998bcb0991SDimitry Andric             DTNode = DTNode->getIDom();
19008bcb0991SDimitry Andric           }
19018bcb0991SDimitry Andric         } else {
19028bcb0991SDimitry Andric           // If Pred has unreachable predecessors, but has at least a Def, the
19038bcb0991SDimitry Andric           // incoming access can be the last Def in Pred, or it could have been
19048bcb0991SDimitry Andric           // optimized to LoE. After an update, though, the LoE may have been
19058bcb0991SDimitry Andric           // replaced by another access, so IncAcc may be any access.
19068bcb0991SDimitry Andric           // If Pred has unreachable predecessors and no Defs, incoming access
19078bcb0991SDimitry Andric           // should be LoE; However, after an update, it may be any access.
19088bcb0991SDimitry Andric         }
19098bcb0991SDimitry Andric       }
19108bcb0991SDimitry Andric     }
19118bcb0991SDimitry Andric   }
19128bcb0991SDimitry Andric }
19138bcb0991SDimitry Andric 
19140b57cec5SDimitry Andric /// Verify that all of the blocks we believe to have valid domination numbers
19150b57cec5SDimitry Andric /// actually have valid domination numbers.
verifyDominationNumbers(const Function & F) const19160b57cec5SDimitry Andric void MemorySSA::verifyDominationNumbers(const Function &F) const {
19170b57cec5SDimitry Andric   if (BlockNumberingValid.empty())
19180b57cec5SDimitry Andric     return;
19190b57cec5SDimitry Andric 
19200b57cec5SDimitry Andric   SmallPtrSet<const BasicBlock *, 16> ValidBlocks = BlockNumberingValid;
19210b57cec5SDimitry Andric   for (const BasicBlock &BB : F) {
19220b57cec5SDimitry Andric     if (!ValidBlocks.count(&BB))
19230b57cec5SDimitry Andric       continue;
19240b57cec5SDimitry Andric 
19250b57cec5SDimitry Andric     ValidBlocks.erase(&BB);
19260b57cec5SDimitry Andric 
19270b57cec5SDimitry Andric     const AccessList *Accesses = getBlockAccesses(&BB);
19280b57cec5SDimitry Andric     // It's correct to say an empty block has valid numbering.
19290b57cec5SDimitry Andric     if (!Accesses)
19300b57cec5SDimitry Andric       continue;
19310b57cec5SDimitry Andric 
19320b57cec5SDimitry Andric     // Block numbering starts at 1.
19330b57cec5SDimitry Andric     unsigned long LastNumber = 0;
19340b57cec5SDimitry Andric     for (const MemoryAccess &MA : *Accesses) {
19350b57cec5SDimitry Andric       auto ThisNumberIter = BlockNumbering.find(&MA);
19360b57cec5SDimitry Andric       assert(ThisNumberIter != BlockNumbering.end() &&
19370b57cec5SDimitry Andric              "MemoryAccess has no domination number in a valid block!");
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric       unsigned long ThisNumber = ThisNumberIter->second;
19400b57cec5SDimitry Andric       assert(ThisNumber > LastNumber &&
19410b57cec5SDimitry Andric              "Domination numbers should be strictly increasing!");
1942349cc55cSDimitry Andric       (void)LastNumber;
19430b57cec5SDimitry Andric       LastNumber = ThisNumber;
19440b57cec5SDimitry Andric     }
19450b57cec5SDimitry Andric   }
19460b57cec5SDimitry Andric 
19470b57cec5SDimitry Andric   assert(ValidBlocks.empty() &&
19480b57cec5SDimitry Andric          "All valid BasicBlocks should exist in F -- dangling pointers?");
19490b57cec5SDimitry Andric }
19500b57cec5SDimitry Andric 
1951480093f4SDimitry Andric /// Verify ordering: the order and existence of MemoryAccesses matches the
19520b57cec5SDimitry Andric /// order and existence of memory affecting instructions.
1953480093f4SDimitry Andric /// Verify domination: each definition dominates all of its uses.
1954480093f4SDimitry Andric /// Verify def-uses: the immediate use information - walk all the memory
1955480093f4SDimitry Andric /// accesses and verifying that, for each use, it appears in the appropriate
1956480093f4SDimitry Andric /// def's use list
verifyOrderingDominationAndDefUses(Function & F,VerificationLevel VL) const1957349cc55cSDimitry Andric void MemorySSA::verifyOrderingDominationAndDefUses(Function &F,
1958349cc55cSDimitry Andric                                                    VerificationLevel VL) const {
19590b57cec5SDimitry Andric   // Walk all the blocks, comparing what the lookups think and what the access
19600b57cec5SDimitry Andric   // lists think, as well as the order in the blocks vs the order in the access
19610b57cec5SDimitry Andric   // lists.
19620b57cec5SDimitry Andric   SmallVector<MemoryAccess *, 32> ActualAccesses;
19630b57cec5SDimitry Andric   SmallVector<MemoryAccess *, 32> ActualDefs;
19640b57cec5SDimitry Andric   for (BasicBlock &B : F) {
19650b57cec5SDimitry Andric     const AccessList *AL = getBlockAccesses(&B);
19660b57cec5SDimitry Andric     const auto *DL = getBlockDefs(&B);
1967480093f4SDimitry Andric     MemoryPhi *Phi = getMemoryAccess(&B);
19680b57cec5SDimitry Andric     if (Phi) {
1969480093f4SDimitry Andric       // Verify ordering.
19700b57cec5SDimitry Andric       ActualAccesses.push_back(Phi);
19710b57cec5SDimitry Andric       ActualDefs.push_back(Phi);
1972480093f4SDimitry Andric       // Verify domination
1973349cc55cSDimitry Andric       for (const Use &U : Phi->uses()) {
1974480093f4SDimitry Andric         assert(dominates(Phi, U) && "Memory PHI does not dominate it's uses");
1975349cc55cSDimitry Andric         (void)U;
1976349cc55cSDimitry Andric       }
1977349cc55cSDimitry Andric       // Verify def-uses for full verify.
1978349cc55cSDimitry Andric       if (VL == VerificationLevel::Full) {
1979480093f4SDimitry Andric         assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1980480093f4SDimitry Andric                                             pred_begin(&B), pred_end(&B))) &&
1981480093f4SDimitry Andric                "Incomplete MemoryPhi Node");
1982480093f4SDimitry Andric         for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
1983480093f4SDimitry Andric           verifyUseInDefs(Phi->getIncomingValue(I), Phi);
1984e8d8bef9SDimitry Andric           assert(is_contained(predecessors(&B), Phi->getIncomingBlock(I)) &&
1985480093f4SDimitry Andric                  "Incoming phi block not a block predecessor");
1986480093f4SDimitry Andric         }
1987349cc55cSDimitry Andric       }
19880b57cec5SDimitry Andric     }
19890b57cec5SDimitry Andric 
19900b57cec5SDimitry Andric     for (Instruction &I : B) {
1991480093f4SDimitry Andric       MemoryUseOrDef *MA = getMemoryAccess(&I);
19920b57cec5SDimitry Andric       assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
19930b57cec5SDimitry Andric              "We have memory affecting instructions "
19940b57cec5SDimitry Andric              "in this block but they are not in the "
19950b57cec5SDimitry Andric              "access list or defs list");
19960b57cec5SDimitry Andric       if (MA) {
1997480093f4SDimitry Andric         // Verify ordering.
19980b57cec5SDimitry Andric         ActualAccesses.push_back(MA);
1999480093f4SDimitry Andric         if (MemoryAccess *MD = dyn_cast<MemoryDef>(MA)) {
2000480093f4SDimitry Andric           // Verify ordering.
20010b57cec5SDimitry Andric           ActualDefs.push_back(MA);
2002480093f4SDimitry Andric           // Verify domination.
2003349cc55cSDimitry Andric           for (const Use &U : MD->uses()) {
2004480093f4SDimitry Andric             assert(dominates(MD, U) &&
2005480093f4SDimitry Andric                    "Memory Def does not dominate it's uses");
2006349cc55cSDimitry Andric             (void)U;
2007480093f4SDimitry Andric           }
2008349cc55cSDimitry Andric         }
2009349cc55cSDimitry Andric         // Verify def-uses for full verify.
2010349cc55cSDimitry Andric         if (VL == VerificationLevel::Full)
2011480093f4SDimitry Andric           verifyUseInDefs(MA->getDefiningAccess(), MA);
20120b57cec5SDimitry Andric       }
20130b57cec5SDimitry Andric     }
20140b57cec5SDimitry Andric     // Either we hit the assert, really have no accesses, or we have both
2015480093f4SDimitry Andric     // accesses and an access list. Same with defs.
20160b57cec5SDimitry Andric     if (!AL && !DL)
20170b57cec5SDimitry Andric       continue;
2018480093f4SDimitry Andric     // Verify ordering.
20190b57cec5SDimitry Andric     assert(AL->size() == ActualAccesses.size() &&
20200b57cec5SDimitry Andric            "We don't have the same number of accesses in the block as on the "
20210b57cec5SDimitry Andric            "access list");
20220b57cec5SDimitry Andric     assert((DL || ActualDefs.size() == 0) &&
20230b57cec5SDimitry Andric            "Either we should have a defs list, or we should have no defs");
20240b57cec5SDimitry Andric     assert((!DL || DL->size() == ActualDefs.size()) &&
20250b57cec5SDimitry Andric            "We don't have the same number of defs in the block as on the "
20260b57cec5SDimitry Andric            "def list");
20270b57cec5SDimitry Andric     auto ALI = AL->begin();
20280b57cec5SDimitry Andric     auto AAI = ActualAccesses.begin();
20290b57cec5SDimitry Andric     while (ALI != AL->end() && AAI != ActualAccesses.end()) {
20300b57cec5SDimitry Andric       assert(&*ALI == *AAI && "Not the same accesses in the same order");
20310b57cec5SDimitry Andric       ++ALI;
20320b57cec5SDimitry Andric       ++AAI;
20330b57cec5SDimitry Andric     }
20340b57cec5SDimitry Andric     ActualAccesses.clear();
20350b57cec5SDimitry Andric     if (DL) {
20360b57cec5SDimitry Andric       auto DLI = DL->begin();
20370b57cec5SDimitry Andric       auto ADI = ActualDefs.begin();
20380b57cec5SDimitry Andric       while (DLI != DL->end() && ADI != ActualDefs.end()) {
20390b57cec5SDimitry Andric         assert(&*DLI == *ADI && "Not the same defs in the same order");
20400b57cec5SDimitry Andric         ++DLI;
20410b57cec5SDimitry Andric         ++ADI;
20420b57cec5SDimitry Andric       }
20430b57cec5SDimitry Andric     }
20440b57cec5SDimitry Andric     ActualDefs.clear();
20450b57cec5SDimitry Andric   }
20460b57cec5SDimitry Andric }
20470b57cec5SDimitry Andric 
20480b57cec5SDimitry Andric /// Verify the def-use lists in MemorySSA, by verifying that \p Use
20490b57cec5SDimitry Andric /// appears in the use list of \p Def.
verifyUseInDefs(MemoryAccess * Def,MemoryAccess * Use) const20500b57cec5SDimitry Andric void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
20510b57cec5SDimitry Andric   // The live on entry use may cause us to get a NULL def here
20520b57cec5SDimitry Andric   if (!Def)
20530b57cec5SDimitry Andric     assert(isLiveOnEntryDef(Use) &&
20540b57cec5SDimitry Andric            "Null def but use not point to live on entry def");
20550b57cec5SDimitry Andric   else
20560b57cec5SDimitry Andric     assert(is_contained(Def->users(), Use) &&
20570b57cec5SDimitry Andric            "Did not find use in def's use list");
20580b57cec5SDimitry Andric }
20590b57cec5SDimitry Andric 
20600b57cec5SDimitry Andric /// Perform a local numbering on blocks so that instruction ordering can be
20610b57cec5SDimitry Andric /// determined in constant time.
20620b57cec5SDimitry Andric /// TODO: We currently just number in order.  If we numbered by N, we could
20630b57cec5SDimitry Andric /// allow at least N-1 sequences of insertBefore or insertAfter (and at least
20640b57cec5SDimitry Andric /// log2(N) sequences of mixed before and after) without needing to invalidate
20650b57cec5SDimitry Andric /// the numbering.
renumberBlock(const BasicBlock * B) const20660b57cec5SDimitry Andric void MemorySSA::renumberBlock(const BasicBlock *B) const {
20670b57cec5SDimitry Andric   // The pre-increment ensures the numbers really start at 1.
20680b57cec5SDimitry Andric   unsigned long CurrentNumber = 0;
20690b57cec5SDimitry Andric   const AccessList *AL = getBlockAccesses(B);
20700b57cec5SDimitry Andric   assert(AL != nullptr && "Asking to renumber an empty block");
20710b57cec5SDimitry Andric   for (const auto &I : *AL)
20720b57cec5SDimitry Andric     BlockNumbering[&I] = ++CurrentNumber;
20730b57cec5SDimitry Andric   BlockNumberingValid.insert(B);
20740b57cec5SDimitry Andric }
20750b57cec5SDimitry Andric 
20760b57cec5SDimitry Andric /// Determine, for two memory accesses in the same block,
20770b57cec5SDimitry Andric /// whether \p Dominator dominates \p Dominatee.
20780b57cec5SDimitry Andric /// \returns True if \p Dominator dominates \p Dominatee.
locallyDominates(const MemoryAccess * Dominator,const MemoryAccess * Dominatee) const20790b57cec5SDimitry Andric bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
20800b57cec5SDimitry Andric                                  const MemoryAccess *Dominatee) const {
20810b57cec5SDimitry Andric   const BasicBlock *DominatorBlock = Dominator->getBlock();
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric   assert((DominatorBlock == Dominatee->getBlock()) &&
20840b57cec5SDimitry Andric          "Asking for local domination when accesses are in different blocks!");
20850b57cec5SDimitry Andric   // A node dominates itself.
20860b57cec5SDimitry Andric   if (Dominatee == Dominator)
20870b57cec5SDimitry Andric     return true;
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric   // When Dominatee is defined on function entry, it is not dominated by another
20900b57cec5SDimitry Andric   // memory access.
20910b57cec5SDimitry Andric   if (isLiveOnEntryDef(Dominatee))
20920b57cec5SDimitry Andric     return false;
20930b57cec5SDimitry Andric 
20940b57cec5SDimitry Andric   // When Dominator is defined on function entry, it dominates the other memory
20950b57cec5SDimitry Andric   // access.
20960b57cec5SDimitry Andric   if (isLiveOnEntryDef(Dominator))
20970b57cec5SDimitry Andric     return true;
20980b57cec5SDimitry Andric 
20990b57cec5SDimitry Andric   if (!BlockNumberingValid.count(DominatorBlock))
21000b57cec5SDimitry Andric     renumberBlock(DominatorBlock);
21010b57cec5SDimitry Andric 
21020b57cec5SDimitry Andric   unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
21030b57cec5SDimitry Andric   // All numbers start with 1
21040b57cec5SDimitry Andric   assert(DominatorNum != 0 && "Block was not numbered properly");
21050b57cec5SDimitry Andric   unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
21060b57cec5SDimitry Andric   assert(DominateeNum != 0 && "Block was not numbered properly");
21070b57cec5SDimitry Andric   return DominatorNum < DominateeNum;
21080b57cec5SDimitry Andric }
21090b57cec5SDimitry Andric 
dominates(const MemoryAccess * Dominator,const MemoryAccess * Dominatee) const21100b57cec5SDimitry Andric bool MemorySSA::dominates(const MemoryAccess *Dominator,
21110b57cec5SDimitry Andric                           const MemoryAccess *Dominatee) const {
21120b57cec5SDimitry Andric   if (Dominator == Dominatee)
21130b57cec5SDimitry Andric     return true;
21140b57cec5SDimitry Andric 
21150b57cec5SDimitry Andric   if (isLiveOnEntryDef(Dominatee))
21160b57cec5SDimitry Andric     return false;
21170b57cec5SDimitry Andric 
21180b57cec5SDimitry Andric   if (Dominator->getBlock() != Dominatee->getBlock())
21190b57cec5SDimitry Andric     return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
21200b57cec5SDimitry Andric   return locallyDominates(Dominator, Dominatee);
21210b57cec5SDimitry Andric }
21220b57cec5SDimitry Andric 
dominates(const MemoryAccess * Dominator,const Use & Dominatee) const21230b57cec5SDimitry Andric bool MemorySSA::dominates(const MemoryAccess *Dominator,
21240b57cec5SDimitry Andric                           const Use &Dominatee) const {
21250b57cec5SDimitry Andric   if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
21260b57cec5SDimitry Andric     BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
21270b57cec5SDimitry Andric     // The def must dominate the incoming block of the phi.
21280b57cec5SDimitry Andric     if (UseBB != Dominator->getBlock())
21290b57cec5SDimitry Andric       return DT->dominates(Dominator->getBlock(), UseBB);
21300b57cec5SDimitry Andric     // If the UseBB and the DefBB are the same, compare locally.
21310b57cec5SDimitry Andric     return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
21320b57cec5SDimitry Andric   }
21330b57cec5SDimitry Andric   // If it's not a PHI node use, the normal dominates can already handle it.
21340b57cec5SDimitry Andric   return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
21350b57cec5SDimitry Andric }
21360b57cec5SDimitry Andric 
ensureOptimizedUses()213781ad6265SDimitry Andric void MemorySSA::ensureOptimizedUses() {
213881ad6265SDimitry Andric   if (IsOptimized)
213981ad6265SDimitry Andric     return;
214081ad6265SDimitry Andric 
214181ad6265SDimitry Andric   BatchAAResults BatchAA(*AA);
2142bdd1243dSDimitry Andric   ClobberWalkerBase WalkerBase(this, DT);
2143bdd1243dSDimitry Andric   CachingWalker WalkerLocal(this, &WalkerBase);
214481ad6265SDimitry Andric   OptimizeUses(this, &WalkerLocal, &BatchAA, DT).optimizeUses();
214581ad6265SDimitry Andric   IsOptimized = true;
214681ad6265SDimitry Andric }
214781ad6265SDimitry Andric 
print(raw_ostream & OS) const21480b57cec5SDimitry Andric void MemoryAccess::print(raw_ostream &OS) const {
21490b57cec5SDimitry Andric   switch (getValueID()) {
21500b57cec5SDimitry Andric   case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS);
21510b57cec5SDimitry Andric   case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS);
21520b57cec5SDimitry Andric   case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS);
21530b57cec5SDimitry Andric   }
21540b57cec5SDimitry Andric   llvm_unreachable("invalid value id");
21550b57cec5SDimitry Andric }
21560b57cec5SDimitry Andric 
print(raw_ostream & OS) const21570b57cec5SDimitry Andric void MemoryDef::print(raw_ostream &OS) const {
21580b57cec5SDimitry Andric   MemoryAccess *UO = getDefiningAccess();
21590b57cec5SDimitry Andric 
21600b57cec5SDimitry Andric   auto printID = [&OS](MemoryAccess *A) {
21610b57cec5SDimitry Andric     if (A && A->getID())
21620b57cec5SDimitry Andric       OS << A->getID();
21630b57cec5SDimitry Andric     else
21640b57cec5SDimitry Andric       OS << LiveOnEntryStr;
21650b57cec5SDimitry Andric   };
21660b57cec5SDimitry Andric 
21670b57cec5SDimitry Andric   OS << getID() << " = MemoryDef(";
21680b57cec5SDimitry Andric   printID(UO);
21690b57cec5SDimitry Andric   OS << ")";
21700b57cec5SDimitry Andric 
21710b57cec5SDimitry Andric   if (isOptimized()) {
21720b57cec5SDimitry Andric     OS << "->";
21730b57cec5SDimitry Andric     printID(getOptimized());
21740b57cec5SDimitry Andric   }
21750b57cec5SDimitry Andric }
21760b57cec5SDimitry Andric 
print(raw_ostream & OS) const21770b57cec5SDimitry Andric void MemoryPhi::print(raw_ostream &OS) const {
2178fe6060f1SDimitry Andric   ListSeparator LS(",");
21790b57cec5SDimitry Andric   OS << getID() << " = MemoryPhi(";
21800b57cec5SDimitry Andric   for (const auto &Op : operands()) {
21810b57cec5SDimitry Andric     BasicBlock *BB = getIncomingBlock(Op);
21820b57cec5SDimitry Andric     MemoryAccess *MA = cast<MemoryAccess>(Op);
21830b57cec5SDimitry Andric 
2184fe6060f1SDimitry Andric     OS << LS << '{';
21850b57cec5SDimitry Andric     if (BB->hasName())
21860b57cec5SDimitry Andric       OS << BB->getName();
21870b57cec5SDimitry Andric     else
21880b57cec5SDimitry Andric       BB->printAsOperand(OS, false);
21890b57cec5SDimitry Andric     OS << ',';
21900b57cec5SDimitry Andric     if (unsigned ID = MA->getID())
21910b57cec5SDimitry Andric       OS << ID;
21920b57cec5SDimitry Andric     else
21930b57cec5SDimitry Andric       OS << LiveOnEntryStr;
21940b57cec5SDimitry Andric     OS << '}';
21950b57cec5SDimitry Andric   }
21960b57cec5SDimitry Andric   OS << ')';
21970b57cec5SDimitry Andric }
21980b57cec5SDimitry Andric 
print(raw_ostream & OS) const21990b57cec5SDimitry Andric void MemoryUse::print(raw_ostream &OS) const {
22000b57cec5SDimitry Andric   MemoryAccess *UO = getDefiningAccess();
22010b57cec5SDimitry Andric   OS << "MemoryUse(";
22020b57cec5SDimitry Andric   if (UO && UO->getID())
22030b57cec5SDimitry Andric     OS << UO->getID();
22040b57cec5SDimitry Andric   else
22050b57cec5SDimitry Andric     OS << LiveOnEntryStr;
22060b57cec5SDimitry Andric   OS << ')';
22070b57cec5SDimitry Andric }
22080b57cec5SDimitry Andric 
dump() const22090b57cec5SDimitry Andric void MemoryAccess::dump() const {
22100b57cec5SDimitry Andric // Cannot completely remove virtual function even in release mode.
22110b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
22120b57cec5SDimitry Andric   print(dbgs());
22130b57cec5SDimitry Andric   dbgs() << "\n";
22140b57cec5SDimitry Andric #endif
22150b57cec5SDimitry Andric }
22160b57cec5SDimitry Andric 
2217e8d8bef9SDimitry Andric class DOTFuncMSSAInfo {
2218e8d8bef9SDimitry Andric private:
2219e8d8bef9SDimitry Andric   const Function &F;
2220e8d8bef9SDimitry Andric   MemorySSAAnnotatedWriter MSSAWriter;
2221e8d8bef9SDimitry Andric 
2222e8d8bef9SDimitry Andric public:
DOTFuncMSSAInfo(const Function & F,MemorySSA & MSSA)2223e8d8bef9SDimitry Andric   DOTFuncMSSAInfo(const Function &F, MemorySSA &MSSA)
2224e8d8bef9SDimitry Andric       : F(F), MSSAWriter(&MSSA) {}
2225e8d8bef9SDimitry Andric 
getFunction()2226e8d8bef9SDimitry Andric   const Function *getFunction() { return &F; }
getWriter()2227e8d8bef9SDimitry Andric   MemorySSAAnnotatedWriter &getWriter() { return MSSAWriter; }
2228e8d8bef9SDimitry Andric };
2229e8d8bef9SDimitry Andric 
2230e8d8bef9SDimitry Andric namespace llvm {
2231e8d8bef9SDimitry Andric 
2232e8d8bef9SDimitry Andric template <>
2233e8d8bef9SDimitry Andric struct GraphTraits<DOTFuncMSSAInfo *> : public GraphTraits<const BasicBlock *> {
getEntryNodellvm::GraphTraits2234e8d8bef9SDimitry Andric   static NodeRef getEntryNode(DOTFuncMSSAInfo *CFGInfo) {
2235e8d8bef9SDimitry Andric     return &(CFGInfo->getFunction()->getEntryBlock());
2236e8d8bef9SDimitry Andric   }
2237e8d8bef9SDimitry Andric 
2238e8d8bef9SDimitry Andric   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
2239e8d8bef9SDimitry Andric   using nodes_iterator = pointer_iterator<Function::const_iterator>;
2240e8d8bef9SDimitry Andric 
nodes_beginllvm::GraphTraits2241e8d8bef9SDimitry Andric   static nodes_iterator nodes_begin(DOTFuncMSSAInfo *CFGInfo) {
2242e8d8bef9SDimitry Andric     return nodes_iterator(CFGInfo->getFunction()->begin());
2243e8d8bef9SDimitry Andric   }
2244e8d8bef9SDimitry Andric 
nodes_endllvm::GraphTraits2245e8d8bef9SDimitry Andric   static nodes_iterator nodes_end(DOTFuncMSSAInfo *CFGInfo) {
2246e8d8bef9SDimitry Andric     return nodes_iterator(CFGInfo->getFunction()->end());
2247e8d8bef9SDimitry Andric   }
2248e8d8bef9SDimitry Andric 
sizellvm::GraphTraits2249e8d8bef9SDimitry Andric   static size_t size(DOTFuncMSSAInfo *CFGInfo) {
2250e8d8bef9SDimitry Andric     return CFGInfo->getFunction()->size();
2251e8d8bef9SDimitry Andric   }
2252e8d8bef9SDimitry Andric };
2253e8d8bef9SDimitry Andric 
2254e8d8bef9SDimitry Andric template <>
2255e8d8bef9SDimitry Andric struct DOTGraphTraits<DOTFuncMSSAInfo *> : public DefaultDOTGraphTraits {
2256e8d8bef9SDimitry Andric 
DOTGraphTraitsllvm::DOTGraphTraits2257e8d8bef9SDimitry Andric   DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {}
2258e8d8bef9SDimitry Andric 
getGraphNamellvm::DOTGraphTraits2259e8d8bef9SDimitry Andric   static std::string getGraphName(DOTFuncMSSAInfo *CFGInfo) {
2260e8d8bef9SDimitry Andric     return "MSSA CFG for '" + CFGInfo->getFunction()->getName().str() +
2261e8d8bef9SDimitry Andric            "' function";
2262e8d8bef9SDimitry Andric   }
2263e8d8bef9SDimitry Andric 
getNodeLabelllvm::DOTGraphTraits2264e8d8bef9SDimitry Andric   std::string getNodeLabel(const BasicBlock *Node, DOTFuncMSSAInfo *CFGInfo) {
2265e8d8bef9SDimitry Andric     return DOTGraphTraits<DOTFuncInfo *>::getCompleteNodeLabel(
2266e8d8bef9SDimitry Andric         Node, nullptr,
2267e8d8bef9SDimitry Andric         [CFGInfo](raw_string_ostream &OS, const BasicBlock &BB) -> void {
2268e8d8bef9SDimitry Andric           BB.print(OS, &CFGInfo->getWriter(), true, true);
2269e8d8bef9SDimitry Andric         },
2270e8d8bef9SDimitry Andric         [](std::string &S, unsigned &I, unsigned Idx) -> void {
2271e8d8bef9SDimitry Andric           std::string Str = S.substr(I, Idx - I);
2272e8d8bef9SDimitry Andric           StringRef SR = Str;
2273e8d8bef9SDimitry Andric           if (SR.count(" = MemoryDef(") || SR.count(" = MemoryPhi(") ||
2274e8d8bef9SDimitry Andric               SR.count("MemoryUse("))
2275e8d8bef9SDimitry Andric             return;
2276e8d8bef9SDimitry Andric           DOTGraphTraits<DOTFuncInfo *>::eraseComment(S, I, Idx);
2277e8d8bef9SDimitry Andric         });
2278e8d8bef9SDimitry Andric   }
2279e8d8bef9SDimitry Andric 
getEdgeSourceLabelllvm::DOTGraphTraits2280e8d8bef9SDimitry Andric   static std::string getEdgeSourceLabel(const BasicBlock *Node,
2281e8d8bef9SDimitry Andric                                         const_succ_iterator I) {
2282e8d8bef9SDimitry Andric     return DOTGraphTraits<DOTFuncInfo *>::getEdgeSourceLabel(Node, I);
2283e8d8bef9SDimitry Andric   }
2284e8d8bef9SDimitry Andric 
2285e8d8bef9SDimitry Andric   /// Display the raw branch weights from PGO.
getEdgeAttributesllvm::DOTGraphTraits2286e8d8bef9SDimitry Andric   std::string getEdgeAttributes(const BasicBlock *Node, const_succ_iterator I,
2287e8d8bef9SDimitry Andric                                 DOTFuncMSSAInfo *CFGInfo) {
2288e8d8bef9SDimitry Andric     return "";
2289e8d8bef9SDimitry Andric   }
2290e8d8bef9SDimitry Andric 
getNodeAttributesllvm::DOTGraphTraits2291e8d8bef9SDimitry Andric   std::string getNodeAttributes(const BasicBlock *Node,
2292e8d8bef9SDimitry Andric                                 DOTFuncMSSAInfo *CFGInfo) {
2293e8d8bef9SDimitry Andric     return getNodeLabel(Node, CFGInfo).find(';') != std::string::npos
2294e8d8bef9SDimitry Andric                ? "style=filled, fillcolor=lightpink"
2295e8d8bef9SDimitry Andric                : "";
2296e8d8bef9SDimitry Andric   }
2297e8d8bef9SDimitry Andric };
2298e8d8bef9SDimitry Andric 
2299e8d8bef9SDimitry Andric } // namespace llvm
2300e8d8bef9SDimitry Andric 
23010b57cec5SDimitry Andric AnalysisKey MemorySSAAnalysis::Key;
23020b57cec5SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)23030b57cec5SDimitry Andric MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
23040b57cec5SDimitry Andric                                                  FunctionAnalysisManager &AM) {
23050b57cec5SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
23060b57cec5SDimitry Andric   auto &AA = AM.getResult<AAManager>(F);
23078bcb0991SDimitry Andric   return MemorySSAAnalysis::Result(std::make_unique<MemorySSA>(F, &AA, &DT));
23080b57cec5SDimitry Andric }
23090b57cec5SDimitry Andric 
invalidate(Function & F,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator & Inv)23100b57cec5SDimitry Andric bool MemorySSAAnalysis::Result::invalidate(
23110b57cec5SDimitry Andric     Function &F, const PreservedAnalyses &PA,
23120b57cec5SDimitry Andric     FunctionAnalysisManager::Invalidator &Inv) {
23130b57cec5SDimitry Andric   auto PAC = PA.getChecker<MemorySSAAnalysis>();
23140b57cec5SDimitry Andric   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
23150b57cec5SDimitry Andric          Inv.invalidate<AAManager>(F, PA) ||
23160b57cec5SDimitry Andric          Inv.invalidate<DominatorTreeAnalysis>(F, PA);
23170b57cec5SDimitry Andric }
23180b57cec5SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)23190b57cec5SDimitry Andric PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
23200b57cec5SDimitry Andric                                             FunctionAnalysisManager &AM) {
2321e8d8bef9SDimitry Andric   auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
232206c3fb27SDimitry Andric   if (EnsureOptimizedUses)
232381ad6265SDimitry Andric     MSSA.ensureOptimizedUses();
2324e8d8bef9SDimitry Andric   if (DotCFGMSSA != "") {
2325e8d8bef9SDimitry Andric     DOTFuncMSSAInfo CFGInfo(F, MSSA);
2326e8d8bef9SDimitry Andric     WriteGraph(&CFGInfo, "", false, "MSSA", DotCFGMSSA);
2327e8d8bef9SDimitry Andric   } else {
23280b57cec5SDimitry Andric     OS << "MemorySSA for function: " << F.getName() << "\n";
2329e8d8bef9SDimitry Andric     MSSA.print(OS);
2330e8d8bef9SDimitry Andric   }
23310b57cec5SDimitry Andric 
23320b57cec5SDimitry Andric   return PreservedAnalyses::all();
23330b57cec5SDimitry Andric }
23340b57cec5SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)2335349cc55cSDimitry Andric PreservedAnalyses MemorySSAWalkerPrinterPass::run(Function &F,
2336349cc55cSDimitry Andric                                                   FunctionAnalysisManager &AM) {
2337349cc55cSDimitry Andric   auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2338349cc55cSDimitry Andric   OS << "MemorySSA (walker) for function: " << F.getName() << "\n";
2339349cc55cSDimitry Andric   MemorySSAWalkerAnnotatedWriter Writer(&MSSA);
2340349cc55cSDimitry Andric   F.print(OS, &Writer);
2341349cc55cSDimitry Andric 
2342349cc55cSDimitry Andric   return PreservedAnalyses::all();
2343349cc55cSDimitry Andric }
2344349cc55cSDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)23450b57cec5SDimitry Andric PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
23460b57cec5SDimitry Andric                                              FunctionAnalysisManager &AM) {
23470b57cec5SDimitry Andric   AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
23480b57cec5SDimitry Andric 
23490b57cec5SDimitry Andric   return PreservedAnalyses::all();
23500b57cec5SDimitry Andric }
23510b57cec5SDimitry Andric 
23520b57cec5SDimitry Andric char MemorySSAWrapperPass::ID = 0;
23530b57cec5SDimitry Andric 
MemorySSAWrapperPass()23540b57cec5SDimitry Andric MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
23550b57cec5SDimitry Andric   initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
23560b57cec5SDimitry Andric }
23570b57cec5SDimitry Andric 
releaseMemory()23580b57cec5SDimitry Andric void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
23590b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const23600b57cec5SDimitry Andric void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
23610b57cec5SDimitry Andric   AU.setPreservesAll();
23620b57cec5SDimitry Andric   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
23630b57cec5SDimitry Andric   AU.addRequiredTransitive<AAResultsWrapperPass>();
23640b57cec5SDimitry Andric }
23650b57cec5SDimitry Andric 
runOnFunction(Function & F)23660b57cec5SDimitry Andric bool MemorySSAWrapperPass::runOnFunction(Function &F) {
23670b57cec5SDimitry Andric   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
23680b57cec5SDimitry Andric   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
23690b57cec5SDimitry Andric   MSSA.reset(new MemorySSA(F, &AA, &DT));
23700b57cec5SDimitry Andric   return false;
23710b57cec5SDimitry Andric }
23720b57cec5SDimitry Andric 
verifyAnalysis() const237347395794SDimitry Andric void MemorySSAWrapperPass::verifyAnalysis() const {
237447395794SDimitry Andric   if (VerifyMemorySSA)
237547395794SDimitry Andric     MSSA->verifyMemorySSA();
237647395794SDimitry Andric }
23770b57cec5SDimitry Andric 
print(raw_ostream & OS,const Module * M) const23780b57cec5SDimitry Andric void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
23790b57cec5SDimitry Andric   MSSA->print(OS);
23800b57cec5SDimitry Andric }
23810b57cec5SDimitry Andric 
MemorySSAWalker(MemorySSA * M)23820b57cec5SDimitry Andric MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
23830b57cec5SDimitry Andric 
23840b57cec5SDimitry Andric /// Walk the use-def chains starting at \p StartingAccess and find
23850b57cec5SDimitry Andric /// the MemoryAccess that actually clobbers Loc.
23860b57cec5SDimitry Andric ///
23870b57cec5SDimitry Andric /// \returns our clobbering memory access
getClobberingMemoryAccessBase(MemoryAccess * StartingAccess,const MemoryLocation & Loc,BatchAAResults & BAA,unsigned & UpwardWalkLimit)2388bdd1243dSDimitry Andric MemoryAccess *MemorySSA::ClobberWalkerBase::getClobberingMemoryAccessBase(
23890b57cec5SDimitry Andric     MemoryAccess *StartingAccess, const MemoryLocation &Loc,
2390bdd1243dSDimitry Andric     BatchAAResults &BAA, unsigned &UpwardWalkLimit) {
2391fe6060f1SDimitry Andric   assert(!isa<MemoryUse>(StartingAccess) && "Use cannot be defining access");
23920b57cec5SDimitry Andric 
23935f757f3fSDimitry Andric   // If location is undefined, conservatively return starting access.
23945f757f3fSDimitry Andric   if (Loc.Ptr == nullptr)
23955f757f3fSDimitry Andric     return StartingAccess;
23965f757f3fSDimitry Andric 
2397fe6060f1SDimitry Andric   Instruction *I = nullptr;
2398fe6060f1SDimitry Andric   if (auto *StartingUseOrDef = dyn_cast<MemoryUseOrDef>(StartingAccess)) {
23990b57cec5SDimitry Andric     if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
24000b57cec5SDimitry Andric       return StartingUseOrDef;
24010b57cec5SDimitry Andric 
2402fe6060f1SDimitry Andric     I = StartingUseOrDef->getMemoryInst();
24030b57cec5SDimitry Andric 
2404fe6060f1SDimitry Andric     // Conservatively, fences are always clobbers, so don't perform the walk if
2405fe6060f1SDimitry Andric     // we hit a fence.
24060b57cec5SDimitry Andric     if (!isa<CallBase>(I) && I->isFenceLike())
24070b57cec5SDimitry Andric       return StartingUseOrDef;
2408fe6060f1SDimitry Andric   }
24090b57cec5SDimitry Andric 
24100b57cec5SDimitry Andric   UpwardsMemoryQuery Q;
2411fe6060f1SDimitry Andric   Q.OriginalAccess = StartingAccess;
24120b57cec5SDimitry Andric   Q.StartingLoc = Loc;
2413e8d8bef9SDimitry Andric   Q.Inst = nullptr;
24140b57cec5SDimitry Andric   Q.IsCall = false;
24150b57cec5SDimitry Andric 
24160b57cec5SDimitry Andric   // Unlike the other function, do not walk to the def of a def, because we are
24170b57cec5SDimitry Andric   // handed something we already believe is the clobbering access.
24180b57cec5SDimitry Andric   // We never set SkipSelf to true in Q in this method.
24190b57cec5SDimitry Andric   MemoryAccess *Clobber =
2420bdd1243dSDimitry Andric       Walker.findClobber(BAA, StartingAccess, Q, UpwardWalkLimit);
2421fe6060f1SDimitry Andric   LLVM_DEBUG({
2422fe6060f1SDimitry Andric     dbgs() << "Clobber starting at access " << *StartingAccess << "\n";
2423fe6060f1SDimitry Andric     if (I)
2424fe6060f1SDimitry Andric       dbgs() << "  for instruction " << *I << "\n";
2425fe6060f1SDimitry Andric     dbgs() << "  is " << *Clobber << "\n";
2426fe6060f1SDimitry Andric   });
24270b57cec5SDimitry Andric   return Clobber;
24280b57cec5SDimitry Andric }
24290b57cec5SDimitry Andric 
2430349cc55cSDimitry Andric static const Instruction *
getInvariantGroupClobberingInstruction(Instruction & I,DominatorTree & DT)2431349cc55cSDimitry Andric getInvariantGroupClobberingInstruction(Instruction &I, DominatorTree &DT) {
2432349cc55cSDimitry Andric   if (!I.hasMetadata(LLVMContext::MD_invariant_group) || I.isVolatile())
2433349cc55cSDimitry Andric     return nullptr;
2434349cc55cSDimitry Andric 
2435349cc55cSDimitry Andric   // We consider bitcasts and zero GEPs to be the same pointer value. Start by
2436349cc55cSDimitry Andric   // stripping bitcasts and zero GEPs, then we will recursively look at loads
2437349cc55cSDimitry Andric   // and stores through bitcasts and zero GEPs.
2438349cc55cSDimitry Andric   Value *PointerOperand = getLoadStorePointerOperand(&I)->stripPointerCasts();
2439349cc55cSDimitry Andric 
2440349cc55cSDimitry Andric   // It's not safe to walk the use list of a global value because function
2441349cc55cSDimitry Andric   // passes aren't allowed to look outside their functions.
2442349cc55cSDimitry Andric   // FIXME: this could be fixed by filtering instructions from outside of
2443349cc55cSDimitry Andric   // current function.
2444349cc55cSDimitry Andric   if (isa<Constant>(PointerOperand))
2445349cc55cSDimitry Andric     return nullptr;
2446349cc55cSDimitry Andric 
2447349cc55cSDimitry Andric   // Queue to process all pointers that are equivalent to load operand.
2448349cc55cSDimitry Andric   SmallVector<const Value *, 8> PointerUsesQueue;
2449349cc55cSDimitry Andric   PointerUsesQueue.push_back(PointerOperand);
2450349cc55cSDimitry Andric 
2451349cc55cSDimitry Andric   const Instruction *MostDominatingInstruction = &I;
2452349cc55cSDimitry Andric 
2453349cc55cSDimitry Andric   // FIXME: This loop is O(n^2) because dominates can be O(n) and in worst case
2454349cc55cSDimitry Andric   // we will see all the instructions. It may not matter in practice. If it
2455349cc55cSDimitry Andric   // does, we will have to support MemorySSA construction and updates.
2456349cc55cSDimitry Andric   while (!PointerUsesQueue.empty()) {
2457349cc55cSDimitry Andric     const Value *Ptr = PointerUsesQueue.pop_back_val();
2458349cc55cSDimitry Andric     assert(Ptr && !isa<GlobalValue>(Ptr) &&
2459349cc55cSDimitry Andric            "Null or GlobalValue should not be inserted");
2460349cc55cSDimitry Andric 
2461349cc55cSDimitry Andric     for (const User *Us : Ptr->users()) {
2462349cc55cSDimitry Andric       auto *U = dyn_cast<Instruction>(Us);
2463349cc55cSDimitry Andric       if (!U || U == &I || !DT.dominates(U, MostDominatingInstruction))
2464349cc55cSDimitry Andric         continue;
2465349cc55cSDimitry Andric 
2466349cc55cSDimitry Andric       // Add bitcasts and zero GEPs to queue.
2467349cc55cSDimitry Andric       if (isa<BitCastInst>(U)) {
2468349cc55cSDimitry Andric         PointerUsesQueue.push_back(U);
2469349cc55cSDimitry Andric         continue;
2470349cc55cSDimitry Andric       }
2471349cc55cSDimitry Andric       if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
2472349cc55cSDimitry Andric         if (GEP->hasAllZeroIndices())
2473349cc55cSDimitry Andric           PointerUsesQueue.push_back(U);
2474349cc55cSDimitry Andric         continue;
2475349cc55cSDimitry Andric       }
2476349cc55cSDimitry Andric 
2477349cc55cSDimitry Andric       // If we hit a load/store with an invariant.group metadata and the same
2478349cc55cSDimitry Andric       // pointer operand, we can assume that value pointed to by the pointer
2479349cc55cSDimitry Andric       // operand didn't change.
2480349cc55cSDimitry Andric       if (U->hasMetadata(LLVMContext::MD_invariant_group) &&
2481349cc55cSDimitry Andric           getLoadStorePointerOperand(U) == Ptr && !U->isVolatile()) {
2482349cc55cSDimitry Andric         MostDominatingInstruction = U;
2483349cc55cSDimitry Andric       }
2484349cc55cSDimitry Andric     }
2485349cc55cSDimitry Andric   }
2486349cc55cSDimitry Andric   return MostDominatingInstruction == &I ? nullptr : MostDominatingInstruction;
2487349cc55cSDimitry Andric }
2488349cc55cSDimitry Andric 
getClobberingMemoryAccessBase(MemoryAccess * MA,BatchAAResults & BAA,unsigned & UpwardWalkLimit,bool SkipSelf,bool UseInvariantGroup)2489bdd1243dSDimitry Andric MemoryAccess *MemorySSA::ClobberWalkerBase::getClobberingMemoryAccessBase(
2490bdd1243dSDimitry Andric     MemoryAccess *MA, BatchAAResults &BAA, unsigned &UpwardWalkLimit,
2491bdd1243dSDimitry Andric     bool SkipSelf, bool UseInvariantGroup) {
24920b57cec5SDimitry Andric   auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
24930b57cec5SDimitry Andric   // If this is a MemoryPhi, we can't do anything.
24940b57cec5SDimitry Andric   if (!StartingAccess)
24950b57cec5SDimitry Andric     return MA;
24960b57cec5SDimitry Andric 
2497349cc55cSDimitry Andric   if (UseInvariantGroup) {
2498349cc55cSDimitry Andric     if (auto *I = getInvariantGroupClobberingInstruction(
2499349cc55cSDimitry Andric             *StartingAccess->getMemoryInst(), MSSA->getDomTree())) {
2500349cc55cSDimitry Andric       assert(isa<LoadInst>(I) || isa<StoreInst>(I));
2501349cc55cSDimitry Andric 
2502349cc55cSDimitry Andric       auto *ClobberMA = MSSA->getMemoryAccess(I);
2503349cc55cSDimitry Andric       assert(ClobberMA);
2504349cc55cSDimitry Andric       if (isa<MemoryUse>(ClobberMA))
2505349cc55cSDimitry Andric         return ClobberMA->getDefiningAccess();
2506349cc55cSDimitry Andric       return ClobberMA;
2507349cc55cSDimitry Andric     }
2508349cc55cSDimitry Andric   }
2509349cc55cSDimitry Andric 
25100b57cec5SDimitry Andric   bool IsOptimized = false;
25110b57cec5SDimitry Andric 
25120b57cec5SDimitry Andric   // If this is an already optimized use or def, return the optimized result.
25130b57cec5SDimitry Andric   // Note: Currently, we store the optimized def result in a separate field,
25140b57cec5SDimitry Andric   // since we can't use the defining access.
25150b57cec5SDimitry Andric   if (StartingAccess->isOptimized()) {
25160b57cec5SDimitry Andric     if (!SkipSelf || !isa<MemoryDef>(StartingAccess))
25170b57cec5SDimitry Andric       return StartingAccess->getOptimized();
25180b57cec5SDimitry Andric     IsOptimized = true;
25190b57cec5SDimitry Andric   }
25200b57cec5SDimitry Andric 
25210b57cec5SDimitry Andric   const Instruction *I = StartingAccess->getMemoryInst();
25220b57cec5SDimitry Andric   // We can't sanely do anything with a fence, since they conservatively clobber
25230b57cec5SDimitry Andric   // all memory, and have no locations to get pointers from to try to
25240b57cec5SDimitry Andric   // disambiguate.
25250b57cec5SDimitry Andric   if (!isa<CallBase>(I) && I->isFenceLike())
25260b57cec5SDimitry Andric     return StartingAccess;
25270b57cec5SDimitry Andric 
25280b57cec5SDimitry Andric   UpwardsMemoryQuery Q(I, StartingAccess);
25290b57cec5SDimitry Andric 
2530bdd1243dSDimitry Andric   if (isUseTriviallyOptimizableToLiveOnEntry(BAA, I)) {
25310b57cec5SDimitry Andric     MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
25320b57cec5SDimitry Andric     StartingAccess->setOptimized(LiveOnEntry);
25330b57cec5SDimitry Andric     return LiveOnEntry;
25340b57cec5SDimitry Andric   }
25350b57cec5SDimitry Andric 
25360b57cec5SDimitry Andric   MemoryAccess *OptimizedAccess;
25370b57cec5SDimitry Andric   if (!IsOptimized) {
25380b57cec5SDimitry Andric     // Start with the thing we already think clobbers this location
25390b57cec5SDimitry Andric     MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
25400b57cec5SDimitry Andric 
25410b57cec5SDimitry Andric     // At this point, DefiningAccess may be the live on entry def.
25420b57cec5SDimitry Andric     // If it is, we will not get a better result.
25430b57cec5SDimitry Andric     if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
25440b57cec5SDimitry Andric       StartingAccess->setOptimized(DefiningAccess);
25450b57cec5SDimitry Andric       return DefiningAccess;
25460b57cec5SDimitry Andric     }
25470b57cec5SDimitry Andric 
2548bdd1243dSDimitry Andric     OptimizedAccess =
2549bdd1243dSDimitry Andric         Walker.findClobber(BAA, DefiningAccess, Q, UpwardWalkLimit);
25500b57cec5SDimitry Andric     StartingAccess->setOptimized(OptimizedAccess);
25510b57cec5SDimitry Andric   } else
25520b57cec5SDimitry Andric     OptimizedAccess = StartingAccess->getOptimized();
25530b57cec5SDimitry Andric 
25540b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
25550b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << *StartingAccess << "\n");
25560b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ");
25570b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n");
25580b57cec5SDimitry Andric 
25590b57cec5SDimitry Andric   MemoryAccess *Result;
25600b57cec5SDimitry Andric   if (SkipSelf && isa<MemoryPhi>(OptimizedAccess) &&
25610b57cec5SDimitry Andric       isa<MemoryDef>(StartingAccess) && UpwardWalkLimit) {
25620b57cec5SDimitry Andric     assert(isa<MemoryDef>(Q.OriginalAccess));
25630b57cec5SDimitry Andric     Q.SkipSelfAccess = true;
2564bdd1243dSDimitry Andric     Result = Walker.findClobber(BAA, OptimizedAccess, Q, UpwardWalkLimit);
25650b57cec5SDimitry Andric   } else
25660b57cec5SDimitry Andric     Result = OptimizedAccess;
25670b57cec5SDimitry Andric 
25680b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf);
25690b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n");
25700b57cec5SDimitry Andric 
25710b57cec5SDimitry Andric   return Result;
25720b57cec5SDimitry Andric }
25730b57cec5SDimitry Andric 
25740b57cec5SDimitry Andric MemoryAccess *
getClobberingMemoryAccess(MemoryAccess * MA,BatchAAResults &)2575bdd1243dSDimitry Andric DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA,
2576bdd1243dSDimitry Andric                                                     BatchAAResults &) {
25770b57cec5SDimitry Andric   if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
25780b57cec5SDimitry Andric     return Use->getDefiningAccess();
25790b57cec5SDimitry Andric   return MA;
25800b57cec5SDimitry Andric }
25810b57cec5SDimitry Andric 
getClobberingMemoryAccess(MemoryAccess * StartingAccess,const MemoryLocation &,BatchAAResults &)25820b57cec5SDimitry Andric MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
2583bdd1243dSDimitry Andric     MemoryAccess *StartingAccess, const MemoryLocation &, BatchAAResults &) {
25840b57cec5SDimitry Andric   if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
25850b57cec5SDimitry Andric     return Use->getDefiningAccess();
25860b57cec5SDimitry Andric   return StartingAccess;
25870b57cec5SDimitry Andric }
25880b57cec5SDimitry Andric 
deleteMe(DerivedUser * Self)25890b57cec5SDimitry Andric void MemoryPhi::deleteMe(DerivedUser *Self) {
25900b57cec5SDimitry Andric   delete static_cast<MemoryPhi *>(Self);
25910b57cec5SDimitry Andric }
25920b57cec5SDimitry Andric 
deleteMe(DerivedUser * Self)25930b57cec5SDimitry Andric void MemoryDef::deleteMe(DerivedUser *Self) {
25940b57cec5SDimitry Andric   delete static_cast<MemoryDef *>(Self);
25950b57cec5SDimitry Andric }
25960b57cec5SDimitry Andric 
deleteMe(DerivedUser * Self)25970b57cec5SDimitry Andric void MemoryUse::deleteMe(DerivedUser *Self) {
25980b57cec5SDimitry Andric   delete static_cast<MemoryUse *>(Self);
25990b57cec5SDimitry Andric }
2600e8d8bef9SDimitry Andric 
IsGuaranteedLoopInvariant(const Value * Ptr) const2601bdd1243dSDimitry Andric bool upward_defs_iterator::IsGuaranteedLoopInvariant(const Value *Ptr) const {
2602bdd1243dSDimitry Andric   auto IsGuaranteedLoopInvariantBase = [](const Value *Ptr) {
2603e8d8bef9SDimitry Andric     Ptr = Ptr->stripPointerCasts();
2604e8d8bef9SDimitry Andric     if (!isa<Instruction>(Ptr))
2605e8d8bef9SDimitry Andric       return true;
2606e8d8bef9SDimitry Andric     return isa<AllocaInst>(Ptr);
2607e8d8bef9SDimitry Andric   };
2608e8d8bef9SDimitry Andric 
2609e8d8bef9SDimitry Andric   Ptr = Ptr->stripPointerCasts();
2610fe6060f1SDimitry Andric   if (auto *I = dyn_cast<Instruction>(Ptr)) {
2611fe6060f1SDimitry Andric     if (I->getParent()->isEntryBlock())
2612fe6060f1SDimitry Andric       return true;
2613fe6060f1SDimitry Andric   }
2614e8d8bef9SDimitry Andric   if (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
2615e8d8bef9SDimitry Andric     return IsGuaranteedLoopInvariantBase(GEP->getPointerOperand()) &&
2616e8d8bef9SDimitry Andric            GEP->hasAllConstantIndices();
2617e8d8bef9SDimitry Andric   }
2618e8d8bef9SDimitry Andric   return IsGuaranteedLoopInvariantBase(Ptr);
2619e8d8bef9SDimitry Andric }
2620