Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:15

0001 //===- MemorySSA.h - Build Memory SSA ---------------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 /// \file
0010 /// This file exposes an interface to building/using memory SSA to
0011 /// walk memory instructions using a use/def graph.
0012 ///
0013 /// Memory SSA class builds an SSA form that links together memory access
0014 /// instructions such as loads, stores, atomics, and calls. Additionally, it
0015 /// does a trivial form of "heap versioning" Every time the memory state changes
0016 /// in the program, we generate a new heap version. It generates
0017 /// MemoryDef/Uses/Phis that are overlayed on top of the existing instructions.
0018 ///
0019 /// As a trivial example,
0020 /// define i32 @main() #0 {
0021 /// entry:
0022 ///   %call = call noalias i8* @_Znwm(i64 4) #2
0023 ///   %0 = bitcast i8* %call to i32*
0024 ///   %call1 = call noalias i8* @_Znwm(i64 4) #2
0025 ///   %1 = bitcast i8* %call1 to i32*
0026 ///   store i32 5, i32* %0, align 4
0027 ///   store i32 7, i32* %1, align 4
0028 ///   %2 = load i32* %0, align 4
0029 ///   %3 = load i32* %1, align 4
0030 ///   %add = add nsw i32 %2, %3
0031 ///   ret i32 %add
0032 /// }
0033 ///
0034 /// Will become
0035 /// define i32 @main() #0 {
0036 /// entry:
0037 ///   ; 1 = MemoryDef(0)
0038 ///   %call = call noalias i8* @_Znwm(i64 4) #3
0039 ///   %2 = bitcast i8* %call to i32*
0040 ///   ; 2 = MemoryDef(1)
0041 ///   %call1 = call noalias i8* @_Znwm(i64 4) #3
0042 ///   %4 = bitcast i8* %call1 to i32*
0043 ///   ; 3 = MemoryDef(2)
0044 ///   store i32 5, i32* %2, align 4
0045 ///   ; 4 = MemoryDef(3)
0046 ///   store i32 7, i32* %4, align 4
0047 ///   ; MemoryUse(3)
0048 ///   %7 = load i32* %2, align 4
0049 ///   ; MemoryUse(4)
0050 ///   %8 = load i32* %4, align 4
0051 ///   %add = add nsw i32 %7, %8
0052 ///   ret i32 %add
0053 /// }
0054 ///
0055 /// Given this form, all the stores that could ever effect the load at %8 can be
0056 /// gotten by using the MemoryUse associated with it, and walking from use to
0057 /// def until you hit the top of the function.
0058 ///
0059 /// Each def also has a list of users associated with it, so you can walk from
0060 /// both def to users, and users to defs. Note that we disambiguate MemoryUses,
0061 /// but not the RHS of MemoryDefs. You can see this above at %7, which would
0062 /// otherwise be a MemoryUse(4). Being disambiguated means that for a given
0063 /// store, all the MemoryUses on its use lists are may-aliases of that store
0064 /// (but the MemoryDefs on its use list may not be).
0065 ///
0066 /// MemoryDefs are not disambiguated because it would require multiple reaching
0067 /// definitions, which would require multiple phis, and multiple memoryaccesses
0068 /// per instruction.
0069 ///
0070 /// In addition to the def/use graph described above, MemoryDefs also contain
0071 /// an "optimized" definition use.  The "optimized" use points to some def
0072 /// reachable through the memory def chain.  The optimized def *may* (but is
0073 /// not required to) alias the original MemoryDef, but no def *closer* to the
0074 /// source def may alias it.  As the name implies, the purpose of the optimized
0075 /// use is to allow caching of clobber searches for memory defs.  The optimized
0076 /// def may be nullptr, in which case clients must walk the defining access
0077 /// chain.
0078 ///
0079 /// When iterating the uses of a MemoryDef, both defining uses and optimized
0080 /// uses will be encountered.  If only one type is needed, the client must
0081 /// filter the use walk.
0082 //
0083 //===----------------------------------------------------------------------===//
0084 
0085 #ifndef LLVM_ANALYSIS_MEMORYSSA_H
0086 #define LLVM_ANALYSIS_MEMORYSSA_H
0087 
0088 #include "llvm/ADT/DenseMap.h"
0089 #include "llvm/ADT/SmallPtrSet.h"
0090 #include "llvm/ADT/SmallVector.h"
0091 #include "llvm/ADT/ilist_node.h"
0092 #include "llvm/ADT/iterator_range.h"
0093 #include "llvm/Analysis/AliasAnalysis.h"
0094 #include "llvm/Analysis/MemoryLocation.h"
0095 #include "llvm/Analysis/PHITransAddr.h"
0096 #include "llvm/IR/DerivedUser.h"
0097 #include "llvm/IR/Dominators.h"
0098 #include "llvm/IR/Type.h"
0099 #include "llvm/IR/User.h"
0100 #include "llvm/Pass.h"
0101 #include <algorithm>
0102 #include <cassert>
0103 #include <cstddef>
0104 #include <iterator>
0105 #include <memory>
0106 #include <utility>
0107 
0108 namespace llvm {
0109 
0110 template <class GraphType> struct GraphTraits;
0111 class Function;
0112 class Loop;
0113 class LLVMContext;
0114 class MemoryAccess;
0115 class MemorySSAWalker;
0116 class Module;
0117 class raw_ostream;
0118 
0119 namespace MSSAHelpers {
0120 
0121 struct AllAccessTag {};
0122 struct DefsOnlyTag {};
0123 
0124 } // end namespace MSSAHelpers
0125 
0126 enum : unsigned {
0127   // Used to signify what the default invalid ID is for MemoryAccess's
0128   // getID()
0129   INVALID_MEMORYACCESS_ID = -1U
0130 };
0131 
0132 template <class T> class memoryaccess_def_iterator_base;
0133 using memoryaccess_def_iterator = memoryaccess_def_iterator_base<MemoryAccess>;
0134 using const_memoryaccess_def_iterator =
0135     memoryaccess_def_iterator_base<const MemoryAccess>;
0136 
0137 // The base for all memory accesses. All memory accesses in a block are
0138 // linked together using an intrusive list.
0139 class MemoryAccess
0140     : public DerivedUser,
0141       public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>,
0142       public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>> {
0143 public:
0144   using AllAccessType =
0145       ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
0146   using DefsOnlyType =
0147       ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
0148 
0149   MemoryAccess(const MemoryAccess &) = delete;
0150   MemoryAccess &operator=(const MemoryAccess &) = delete;
0151 
0152   void *operator new(size_t) = delete;
0153 
0154   // Methods for support type inquiry through isa, cast, and
0155   // dyn_cast
0156   static bool classof(const Value *V) {
0157     unsigned ID = V->getValueID();
0158     return ID == MemoryUseVal || ID == MemoryPhiVal || ID == MemoryDefVal;
0159   }
0160 
0161   BasicBlock *getBlock() const { return Block; }
0162 
0163   void print(raw_ostream &OS) const;
0164   void dump() const;
0165 
0166   /// The user iterators for a memory access
0167   using iterator = user_iterator;
0168   using const_iterator = const_user_iterator;
0169 
0170   /// This iterator walks over all of the defs in a given
0171   /// MemoryAccess. For MemoryPhi nodes, this walks arguments. For
0172   /// MemoryUse/MemoryDef, this walks the defining access.
0173   memoryaccess_def_iterator defs_begin();
0174   const_memoryaccess_def_iterator defs_begin() const;
0175   memoryaccess_def_iterator defs_end();
0176   const_memoryaccess_def_iterator defs_end() const;
0177 
0178   /// Get the iterators for the all access list and the defs only list
0179   /// We default to the all access list.
0180   AllAccessType::self_iterator getIterator() {
0181     return this->AllAccessType::getIterator();
0182   }
0183   AllAccessType::const_self_iterator getIterator() const {
0184     return this->AllAccessType::getIterator();
0185   }
0186   AllAccessType::reverse_self_iterator getReverseIterator() {
0187     return this->AllAccessType::getReverseIterator();
0188   }
0189   AllAccessType::const_reverse_self_iterator getReverseIterator() const {
0190     return this->AllAccessType::getReverseIterator();
0191   }
0192   DefsOnlyType::self_iterator getDefsIterator() {
0193     return this->DefsOnlyType::getIterator();
0194   }
0195   DefsOnlyType::const_self_iterator getDefsIterator() const {
0196     return this->DefsOnlyType::getIterator();
0197   }
0198   DefsOnlyType::reverse_self_iterator getReverseDefsIterator() {
0199     return this->DefsOnlyType::getReverseIterator();
0200   }
0201   DefsOnlyType::const_reverse_self_iterator getReverseDefsIterator() const {
0202     return this->DefsOnlyType::getReverseIterator();
0203   }
0204 
0205 protected:
0206   friend class MemoryDef;
0207   friend class MemoryPhi;
0208   friend class MemorySSA;
0209   friend class MemoryUse;
0210   friend class MemoryUseOrDef;
0211 
0212   /// Used by MemorySSA to change the block of a MemoryAccess when it is
0213   /// moved.
0214   void setBlock(BasicBlock *BB) { Block = BB; }
0215 
0216   /// Used for debugging and tracking things about MemoryAccesses.
0217   /// Guaranteed unique among MemoryAccesses, no guarantees otherwise.
0218   inline unsigned getID() const;
0219 
0220   MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue,
0221                BasicBlock *BB, AllocInfo AllocInfo)
0222       : DerivedUser(Type::getVoidTy(C), Vty, AllocInfo, DeleteValue),
0223         Block(BB) {}
0224 
0225   // Use deleteValue() to delete a generic MemoryAccess.
0226   ~MemoryAccess() = default;
0227 
0228 private:
0229   BasicBlock *Block;
0230 };
0231 
0232 template <>
0233 struct ilist_alloc_traits<MemoryAccess> {
0234   static void deleteNode(MemoryAccess *MA) { MA->deleteValue(); }
0235 };
0236 
0237 inline raw_ostream &operator<<(raw_ostream &OS, const MemoryAccess &MA) {
0238   MA.print(OS);
0239   return OS;
0240 }
0241 
0242 /// Class that has the common methods + fields of memory uses/defs. It's
0243 /// a little awkward to have, but there are many cases where we want either a
0244 /// use or def, and there are many cases where uses are needed (defs aren't
0245 /// acceptable), and vice-versa.
0246 ///
0247 /// This class should never be instantiated directly; make a MemoryUse or
0248 /// MemoryDef instead.
0249 class MemoryUseOrDef : public MemoryAccess {
0250 public:
0251   void *operator new(size_t) = delete;
0252 
0253   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
0254 
0255   /// Get the instruction that this MemoryUse represents.
0256   Instruction *getMemoryInst() const { return MemoryInstruction; }
0257 
0258   /// Get the access that produces the memory state used by this Use.
0259   MemoryAccess *getDefiningAccess() const { return getOperand(0); }
0260 
0261   static bool classof(const Value *MA) {
0262     return MA->getValueID() == MemoryUseVal || MA->getValueID() == MemoryDefVal;
0263   }
0264 
0265   /// Do we have an optimized use?
0266   inline bool isOptimized() const;
0267   /// Return the MemoryAccess associated with the optimized use, or nullptr.
0268   inline MemoryAccess *getOptimized() const;
0269   /// Sets the optimized use for a MemoryDef.
0270   inline void setOptimized(MemoryAccess *);
0271 
0272   /// Reset the ID of what this MemoryUse was optimized to, causing it to
0273   /// be rewalked by the walker if necessary.
0274   /// This really should only be called by tests.
0275   inline void resetOptimized();
0276 
0277 protected:
0278   friend class MemorySSA;
0279   friend class MemorySSAUpdater;
0280 
0281   MemoryUseOrDef(LLVMContext &C, MemoryAccess *DMA, unsigned Vty,
0282                  DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB,
0283                  AllocInfo AllocInfo)
0284       : MemoryAccess(C, Vty, DeleteValue, BB, AllocInfo),
0285         MemoryInstruction(MI) {
0286     setDefiningAccess(DMA);
0287   }
0288 
0289   // Use deleteValue() to delete a generic MemoryUseOrDef.
0290   ~MemoryUseOrDef() = default;
0291 
0292   void setDefiningAccess(MemoryAccess *DMA, bool Optimized = false) {
0293     if (!Optimized) {
0294       setOperand(0, DMA);
0295       return;
0296     }
0297     setOptimized(DMA);
0298   }
0299 
0300 private:
0301   Instruction *MemoryInstruction;
0302 };
0303 
0304 /// Represents read-only accesses to memory
0305 ///
0306 /// In particular, the set of Instructions that will be represented by
0307 /// MemoryUse's is exactly the set of Instructions for which
0308 /// AliasAnalysis::getModRefInfo returns "Ref".
0309 class MemoryUse final : public MemoryUseOrDef {
0310   constexpr static IntrusiveOperandsAllocMarker AllocMarker{1};
0311 
0312 public:
0313   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
0314 
0315   MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB)
0316       : MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB, AllocMarker) {}
0317 
0318   // allocate space for exactly one operand
0319   void *operator new(size_t S) { return User::operator new(S, AllocMarker); }
0320   void operator delete(void *Ptr) { User::operator delete(Ptr); }
0321 
0322   static bool classof(const Value *MA) {
0323     return MA->getValueID() == MemoryUseVal;
0324   }
0325 
0326   void print(raw_ostream &OS) const;
0327 
0328   void setOptimized(MemoryAccess *DMA) {
0329     OptimizedID = DMA->getID();
0330     setOperand(0, DMA);
0331   }
0332 
0333   /// Whether the MemoryUse is optimized. If ensureOptimizedUses() was called,
0334   /// uses will usually be optimized, but this is not guaranteed (e.g. due to
0335   /// invalidation and optimization limits.)
0336   bool isOptimized() const {
0337     return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID();
0338   }
0339 
0340   MemoryAccess *getOptimized() const {
0341     return getDefiningAccess();
0342   }
0343 
0344   void resetOptimized() {
0345     OptimizedID = INVALID_MEMORYACCESS_ID;
0346   }
0347 
0348 protected:
0349   friend class MemorySSA;
0350 
0351 private:
0352   static void deleteMe(DerivedUser *Self);
0353 
0354   unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
0355 };
0356 
0357 template <>
0358 struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {};
0359 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUse, MemoryAccess)
0360 
0361 /// Represents a read-write access to memory, whether it is a must-alias,
0362 /// or a may-alias.
0363 ///
0364 /// In particular, the set of Instructions that will be represented by
0365 /// MemoryDef's is exactly the set of Instructions for which
0366 /// AliasAnalysis::getModRefInfo returns "Mod" or "ModRef".
0367 /// Note that, in order to provide def-def chains, all defs also have a use
0368 /// associated with them. This use points to the nearest reaching
0369 /// MemoryDef/MemoryPhi.
0370 class MemoryDef final : public MemoryUseOrDef {
0371   constexpr static IntrusiveOperandsAllocMarker AllocMarker{2};
0372 
0373 public:
0374   friend class MemorySSA;
0375 
0376   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
0377 
0378   MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB,
0379             unsigned Ver)
0380       : MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB, AllocMarker),
0381         ID(Ver) {}
0382 
0383   // allocate space for exactly two operands
0384   void *operator new(size_t S) { return User::operator new(S, AllocMarker); }
0385   void operator delete(void *Ptr) { User::operator delete(Ptr); }
0386 
0387   static bool classof(const Value *MA) {
0388     return MA->getValueID() == MemoryDefVal;
0389   }
0390 
0391   void setOptimized(MemoryAccess *MA) {
0392     setOperand(1, MA);
0393     OptimizedID = MA->getID();
0394   }
0395 
0396   MemoryAccess *getOptimized() const {
0397     return cast_or_null<MemoryAccess>(getOperand(1));
0398   }
0399 
0400   bool isOptimized() const {
0401     return getOptimized() && OptimizedID == getOptimized()->getID();
0402   }
0403 
0404   void resetOptimized() {
0405     OptimizedID = INVALID_MEMORYACCESS_ID;
0406     setOperand(1, nullptr);
0407   }
0408 
0409   void print(raw_ostream &OS) const;
0410 
0411   unsigned getID() const { return ID; }
0412 
0413 private:
0414   static void deleteMe(DerivedUser *Self);
0415 
0416   const unsigned ID;
0417   unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
0418 };
0419 
0420 template <>
0421 struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 2> {};
0422 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryDef, MemoryAccess)
0423 
0424 template <>
0425 struct OperandTraits<MemoryUseOrDef> {
0426   static Use *op_begin(MemoryUseOrDef *MUD) {
0427     if (auto *MU = dyn_cast<MemoryUse>(MUD))
0428       return OperandTraits<MemoryUse>::op_begin(MU);
0429     return OperandTraits<MemoryDef>::op_begin(cast<MemoryDef>(MUD));
0430   }
0431 
0432   static Use *op_end(MemoryUseOrDef *MUD) {
0433     if (auto *MU = dyn_cast<MemoryUse>(MUD))
0434       return OperandTraits<MemoryUse>::op_end(MU);
0435     return OperandTraits<MemoryDef>::op_end(cast<MemoryDef>(MUD));
0436   }
0437 
0438   static unsigned operands(const MemoryUseOrDef *MUD) {
0439     if (const auto *MU = dyn_cast<MemoryUse>(MUD))
0440       return OperandTraits<MemoryUse>::operands(MU);
0441     return OperandTraits<MemoryDef>::operands(cast<MemoryDef>(MUD));
0442   }
0443 };
0444 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUseOrDef, MemoryAccess)
0445 
0446 /// Represents phi nodes for memory accesses.
0447 ///
0448 /// These have the same semantic as regular phi nodes, with the exception that
0449 /// only one phi will ever exist in a given basic block.
0450 /// Guaranteeing one phi per block means guaranteeing there is only ever one
0451 /// valid reaching MemoryDef/MemoryPHI along each path to the phi node.
0452 /// This is ensured by not allowing disambiguation of the RHS of a MemoryDef or
0453 /// a MemoryPhi's operands.
0454 /// That is, given
0455 /// if (a) {
0456 ///   store %a
0457 ///   store %b
0458 /// }
0459 /// it *must* be transformed into
0460 /// if (a) {
0461 ///    1 = MemoryDef(liveOnEntry)
0462 ///    store %a
0463 ///    2 = MemoryDef(1)
0464 ///    store %b
0465 /// }
0466 /// and *not*
0467 /// if (a) {
0468 ///    1 = MemoryDef(liveOnEntry)
0469 ///    store %a
0470 ///    2 = MemoryDef(liveOnEntry)
0471 ///    store %b
0472 /// }
0473 /// even if the two stores do not conflict. Otherwise, both 1 and 2 reach the
0474 /// end of the branch, and if there are not two phi nodes, one will be
0475 /// disconnected completely from the SSA graph below that point.
0476 /// Because MemoryUse's do not generate new definitions, they do not have this
0477 /// issue.
0478 class MemoryPhi final : public MemoryAccess {
0479   constexpr static HungOffOperandsAllocMarker AllocMarker{};
0480 
0481   // allocate space for exactly zero operands
0482   void *operator new(size_t S) { return User::operator new(S, AllocMarker); }
0483 
0484 public:
0485   void operator delete(void *Ptr) { User::operator delete(Ptr); }
0486 
0487   /// Provide fast operand accessors
0488   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
0489 
0490   MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0)
0491       : MemoryAccess(C, MemoryPhiVal, deleteMe, BB, AllocMarker), ID(Ver),
0492         ReservedSpace(NumPreds) {
0493     allocHungoffUses(ReservedSpace);
0494   }
0495 
0496   // Block iterator interface. This provides access to the list of incoming
0497   // basic blocks, which parallels the list of incoming values.
0498   using block_iterator = BasicBlock **;
0499   using const_block_iterator = BasicBlock *const *;
0500 
0501   block_iterator block_begin() {
0502     return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
0503   }
0504 
0505   const_block_iterator block_begin() const {
0506     return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
0507   }
0508 
0509   block_iterator block_end() { return block_begin() + getNumOperands(); }
0510 
0511   const_block_iterator block_end() const {
0512     return block_begin() + getNumOperands();
0513   }
0514 
0515   iterator_range<block_iterator> blocks() {
0516     return make_range(block_begin(), block_end());
0517   }
0518 
0519   iterator_range<const_block_iterator> blocks() const {
0520     return make_range(block_begin(), block_end());
0521   }
0522 
0523   op_range incoming_values() { return operands(); }
0524 
0525   const_op_range incoming_values() const { return operands(); }
0526 
0527   /// Return the number of incoming edges
0528   unsigned getNumIncomingValues() const { return getNumOperands(); }
0529 
0530   /// Return incoming value number x
0531   MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); }
0532   void setIncomingValue(unsigned I, MemoryAccess *V) {
0533     assert(V && "PHI node got a null value!");
0534     setOperand(I, V);
0535   }
0536 
0537   static unsigned getOperandNumForIncomingValue(unsigned I) { return I; }
0538   static unsigned getIncomingValueNumForOperand(unsigned I) { return I; }
0539 
0540   /// Return incoming basic block number @p i.
0541   BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; }
0542 
0543   /// Return incoming basic block corresponding
0544   /// to an operand of the PHI.
0545   BasicBlock *getIncomingBlock(const Use &U) const {
0546     assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
0547     return getIncomingBlock(unsigned(&U - op_begin()));
0548   }
0549 
0550   /// Return incoming basic block corresponding
0551   /// to value use iterator.
0552   BasicBlock *getIncomingBlock(MemoryAccess::const_user_iterator I) const {
0553     return getIncomingBlock(I.getUse());
0554   }
0555 
0556   void setIncomingBlock(unsigned I, BasicBlock *BB) {
0557     assert(BB && "PHI node got a null basic block!");
0558     block_begin()[I] = BB;
0559   }
0560 
0561   /// Add an incoming value to the end of the PHI list
0562   void addIncoming(MemoryAccess *V, BasicBlock *BB) {
0563     if (getNumOperands() == ReservedSpace)
0564       growOperands(); // Get more space!
0565     // Initialize some new operands.
0566     setNumHungOffUseOperands(getNumOperands() + 1);
0567     setIncomingValue(getNumOperands() - 1, V);
0568     setIncomingBlock(getNumOperands() - 1, BB);
0569   }
0570 
0571   /// Return the first index of the specified basic
0572   /// block in the value list for this PHI.  Returns -1 if no instance.
0573   int getBasicBlockIndex(const BasicBlock *BB) const {
0574     for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
0575       if (block_begin()[I] == BB)
0576         return I;
0577     return -1;
0578   }
0579 
0580   MemoryAccess *getIncomingValueForBlock(const BasicBlock *BB) const {
0581     int Idx = getBasicBlockIndex(BB);
0582     assert(Idx >= 0 && "Invalid basic block argument!");
0583     return getIncomingValue(Idx);
0584   }
0585 
0586   // After deleting incoming position I, the order of incoming may be changed.
0587   void unorderedDeleteIncoming(unsigned I) {
0588     unsigned E = getNumOperands();
0589     assert(I < E && "Cannot remove out of bounds Phi entry.");
0590     // MemoryPhi must have at least two incoming values, otherwise the MemoryPhi
0591     // itself should be deleted.
0592     assert(E >= 2 && "Cannot only remove incoming values in MemoryPhis with "
0593                      "at least 2 values.");
0594     setIncomingValue(I, getIncomingValue(E - 1));
0595     setIncomingBlock(I, block_begin()[E - 1]);
0596     setOperand(E - 1, nullptr);
0597     block_begin()[E - 1] = nullptr;
0598     setNumHungOffUseOperands(getNumOperands() - 1);
0599   }
0600 
0601   // After deleting entries that satisfy Pred, remaining entries may have
0602   // changed order.
0603   template <typename Fn> void unorderedDeleteIncomingIf(Fn &&Pred) {
0604     for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
0605       if (Pred(getIncomingValue(I), getIncomingBlock(I))) {
0606         unorderedDeleteIncoming(I);
0607         E = getNumOperands();
0608         --I;
0609       }
0610     assert(getNumOperands() >= 1 &&
0611            "Cannot remove all incoming blocks in a MemoryPhi.");
0612   }
0613 
0614   // After deleting incoming block BB, the incoming blocks order may be changed.
0615   void unorderedDeleteIncomingBlock(const BasicBlock *BB) {
0616     unorderedDeleteIncomingIf(
0617         [&](const MemoryAccess *, const BasicBlock *B) { return BB == B; });
0618   }
0619 
0620   // After deleting incoming memory access MA, the incoming accesses order may
0621   // be changed.
0622   void unorderedDeleteIncomingValue(const MemoryAccess *MA) {
0623     unorderedDeleteIncomingIf(
0624         [&](const MemoryAccess *M, const BasicBlock *) { return MA == M; });
0625   }
0626 
0627   static bool classof(const Value *V) {
0628     return V->getValueID() == MemoryPhiVal;
0629   }
0630 
0631   void print(raw_ostream &OS) const;
0632 
0633   unsigned getID() const { return ID; }
0634 
0635 protected:
0636   friend class MemorySSA;
0637 
0638   /// this is more complicated than the generic
0639   /// User::allocHungoffUses, because we have to allocate Uses for the incoming
0640   /// values and pointers to the incoming blocks, all in one allocation.
0641   void allocHungoffUses(unsigned N) {
0642     User::allocHungoffUses(N, /* IsPhi */ true);
0643   }
0644 
0645 private:
0646   // For debugging only
0647   const unsigned ID;
0648   unsigned ReservedSpace;
0649 
0650   /// This grows the operand list in response to a push_back style of
0651   /// operation.  This grows the number of ops by 1.5 times.
0652   void growOperands() {
0653     unsigned E = getNumOperands();
0654     // 2 op PHI nodes are VERY common, so reserve at least enough for that.
0655     ReservedSpace = std::max(E + E / 2, 2u);
0656     growHungoffUses(ReservedSpace, /* IsPhi */ true);
0657   }
0658 
0659   static void deleteMe(DerivedUser *Self);
0660 };
0661 
0662 inline unsigned MemoryAccess::getID() const {
0663   assert((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) &&
0664          "only memory defs and phis have ids");
0665   if (const auto *MD = dyn_cast<MemoryDef>(this))
0666     return MD->getID();
0667   return cast<MemoryPhi>(this)->getID();
0668 }
0669 
0670 inline bool MemoryUseOrDef::isOptimized() const {
0671   if (const auto *MD = dyn_cast<MemoryDef>(this))
0672     return MD->isOptimized();
0673   return cast<MemoryUse>(this)->isOptimized();
0674 }
0675 
0676 inline MemoryAccess *MemoryUseOrDef::getOptimized() const {
0677   if (const auto *MD = dyn_cast<MemoryDef>(this))
0678     return MD->getOptimized();
0679   return cast<MemoryUse>(this)->getOptimized();
0680 }
0681 
0682 inline void MemoryUseOrDef::setOptimized(MemoryAccess *MA) {
0683   if (auto *MD = dyn_cast<MemoryDef>(this))
0684     MD->setOptimized(MA);
0685   else
0686     cast<MemoryUse>(this)->setOptimized(MA);
0687 }
0688 
0689 inline void MemoryUseOrDef::resetOptimized() {
0690   if (auto *MD = dyn_cast<MemoryDef>(this))
0691     MD->resetOptimized();
0692   else
0693     cast<MemoryUse>(this)->resetOptimized();
0694 }
0695 
0696 template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits {};
0697 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryPhi, MemoryAccess)
0698 
0699 /// Encapsulates MemorySSA, including all data associated with memory
0700 /// accesses.
0701 class MemorySSA {
0702 public:
0703   MemorySSA(Function &, AliasAnalysis *, DominatorTree *);
0704   MemorySSA(Loop &, AliasAnalysis *, DominatorTree *);
0705 
0706   // MemorySSA must remain where it's constructed; Walkers it creates store
0707   // pointers to it.
0708   MemorySSA(MemorySSA &&) = delete;
0709 
0710   ~MemorySSA();
0711 
0712   MemorySSAWalker *getWalker();
0713   MemorySSAWalker *getSkipSelfWalker();
0714 
0715   /// Given a memory Mod/Ref'ing instruction, get the MemorySSA
0716   /// access associated with it. If passed a basic block gets the memory phi
0717   /// node that exists for that block, if there is one. Otherwise, this will get
0718   /// a MemoryUseOrDef.
0719   MemoryUseOrDef *getMemoryAccess(const Instruction *I) const {
0720     return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
0721   }
0722 
0723   MemoryPhi *getMemoryAccess(const BasicBlock *BB) const {
0724     return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
0725   }
0726 
0727   DominatorTree &getDomTree() const { return *DT; }
0728 
0729   void dump() const;
0730   void print(raw_ostream &) const;
0731 
0732   /// Return true if \p MA represents the live on entry value
0733   ///
0734   /// Loads and stores from pointer arguments and other global values may be
0735   /// defined by memory operations that do not occur in the current function, so
0736   /// they may be live on entry to the function. MemorySSA represents such
0737   /// memory state by the live on entry definition, which is guaranteed to occur
0738   /// before any other memory access in the function.
0739   inline bool isLiveOnEntryDef(const MemoryAccess *MA) const {
0740     return MA == LiveOnEntryDef.get();
0741   }
0742 
0743   inline MemoryAccess *getLiveOnEntryDef() const {
0744     return LiveOnEntryDef.get();
0745   }
0746 
0747   // Sadly, iplists, by default, owns and deletes pointers added to the
0748   // list. It's not currently possible to have two iplists for the same type,
0749   // where one owns the pointers, and one does not. This is because the traits
0750   // are per-type, not per-tag.  If this ever changes, we should make the
0751   // DefList an iplist.
0752   using AccessList = iplist<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
0753   using DefsList =
0754       simple_ilist<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
0755 
0756   /// Return the list of MemoryAccess's for a given basic block.
0757   ///
0758   /// This list is not modifiable by the user.
0759   const AccessList *getBlockAccesses(const BasicBlock *BB) const {
0760     return getWritableBlockAccesses(BB);
0761   }
0762 
0763   /// Return the list of MemoryDef's and MemoryPhi's for a given basic
0764   /// block.
0765   ///
0766   /// This list is not modifiable by the user.
0767   const DefsList *getBlockDefs(const BasicBlock *BB) const {
0768     return getWritableBlockDefs(BB);
0769   }
0770 
0771   /// Given two memory accesses in the same basic block, determine
0772   /// whether MemoryAccess \p A dominates MemoryAccess \p B.
0773   bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const;
0774 
0775   /// Given two memory accesses in potentially different blocks,
0776   /// determine whether MemoryAccess \p A dominates MemoryAccess \p B.
0777   bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;
0778 
0779   /// Given a MemoryAccess and a Use, determine whether MemoryAccess \p A
0780   /// dominates Use \p B.
0781   bool dominates(const MemoryAccess *A, const Use &B) const;
0782 
0783   enum class VerificationLevel { Fast, Full };
0784   /// Verify that MemorySSA is self consistent (IE definitions dominate
0785   /// all uses, uses appear in the right places).  This is used by unit tests.
0786   void verifyMemorySSA(VerificationLevel = VerificationLevel::Fast) const;
0787 
0788   /// Used in various insertion functions to specify whether we are talking
0789   /// about the beginning or end of a block.
0790   enum InsertionPlace { Beginning, End, BeforeTerminator };
0791 
0792   /// By default, uses are *not* optimized during MemorySSA construction.
0793   /// Calling this method will attempt to optimize all MemoryUses, if this has
0794   /// not happened yet for this MemorySSA instance. This should be done if you
0795   /// plan to query the clobbering access for most uses, or if you walk the
0796   /// def-use chain of uses.
0797   void ensureOptimizedUses();
0798 
0799   AliasAnalysis &getAA() { return *AA; }
0800 
0801 protected:
0802   // Used by Memory SSA dumpers and wrapper pass
0803   friend class MemorySSAUpdater;
0804 
0805   template <typename IterT>
0806   void verifyOrderingDominationAndDefUses(
0807       IterT Blocks, VerificationLevel = VerificationLevel::Fast) const;
0808   template <typename IterT> void verifyDominationNumbers(IterT Blocks) const;
0809   template <typename IterT> void verifyPrevDefInPhis(IterT Blocks) const;
0810 
0811   // This is used by the use optimizer and updater.
0812   AccessList *getWritableBlockAccesses(const BasicBlock *BB) const {
0813     auto It = PerBlockAccesses.find(BB);
0814     return It == PerBlockAccesses.end() ? nullptr : It->second.get();
0815   }
0816 
0817   // This is used by the use optimizer and updater.
0818   DefsList *getWritableBlockDefs(const BasicBlock *BB) const {
0819     auto It = PerBlockDefs.find(BB);
0820     return It == PerBlockDefs.end() ? nullptr : It->second.get();
0821   }
0822 
0823   // These is used by the updater to perform various internal MemorySSA
0824   // machinsations.  They do not always leave the IR in a correct state, and
0825   // relies on the updater to fixup what it breaks, so it is not public.
0826 
0827   void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where);
0828   void moveTo(MemoryAccess *What, BasicBlock *BB, InsertionPlace Point);
0829 
0830   // Rename the dominator tree branch rooted at BB.
0831   void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal,
0832                   SmallPtrSetImpl<BasicBlock *> &Visited) {
0833     renamePass(DT->getNode(BB), IncomingVal, Visited, true, true);
0834   }
0835 
0836   void removeFromLookups(MemoryAccess *);
0837   void removeFromLists(MemoryAccess *, bool ShouldDelete = true);
0838   void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *,
0839                                InsertionPlace);
0840   void insertIntoListsBefore(MemoryAccess *, const BasicBlock *,
0841                              AccessList::iterator);
0842   MemoryUseOrDef *createDefinedAccess(Instruction *, MemoryAccess *,
0843                                       const MemoryUseOrDef *Template = nullptr,
0844                                       bool CreationMustSucceed = true);
0845 
0846 private:
0847   class ClobberWalkerBase;
0848   class CachingWalker;
0849   class SkipSelfWalker;
0850   class OptimizeUses;
0851 
0852   CachingWalker *getWalkerImpl();
0853   template <typename IterT>
0854   void buildMemorySSA(BatchAAResults &BAA, IterT Blocks);
0855 
0856   void prepareForMoveTo(MemoryAccess *, BasicBlock *);
0857   void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;
0858 
0859   using AccessMap = DenseMap<const BasicBlock *, std::unique_ptr<AccessList>>;
0860   using DefsMap = DenseMap<const BasicBlock *, std::unique_ptr<DefsList>>;
0861 
0862   void markUnreachableAsLiveOnEntry(BasicBlock *BB);
0863   MemoryPhi *createMemoryPhi(BasicBlock *BB);
0864   template <typename AliasAnalysisType>
0865   MemoryUseOrDef *createNewAccess(Instruction *, AliasAnalysisType *,
0866                                   const MemoryUseOrDef *Template = nullptr);
0867   void placePHINodes(const SmallPtrSetImpl<BasicBlock *> &);
0868   MemoryAccess *renameBlock(BasicBlock *, MemoryAccess *, bool);
0869   void renameSuccessorPhis(BasicBlock *, MemoryAccess *, bool);
0870   void renamePass(DomTreeNode *, MemoryAccess *IncomingVal,
0871                   SmallPtrSetImpl<BasicBlock *> &Visited,
0872                   bool SkipVisited = false, bool RenameAllUses = false);
0873   AccessList *getOrCreateAccessList(const BasicBlock *);
0874   DefsList *getOrCreateDefsList(const BasicBlock *);
0875   void renumberBlock(const BasicBlock *) const;
0876   AliasAnalysis *AA = nullptr;
0877   DominatorTree *DT;
0878   Function *F = nullptr;
0879   Loop *L = nullptr;
0880 
0881   // Memory SSA mappings
0882   DenseMap<const Value *, MemoryAccess *> ValueToMemoryAccess;
0883 
0884   // These two mappings contain the main block to access/def mappings for
0885   // MemorySSA. The list contained in PerBlockAccesses really owns all the
0886   // MemoryAccesses.
0887   // Both maps maintain the invariant that if a block is found in them, the
0888   // corresponding list is not empty, and if a block is not found in them, the
0889   // corresponding list is empty.
0890   AccessMap PerBlockAccesses;
0891   DefsMap PerBlockDefs;
0892   std::unique_ptr<MemoryAccess, ValueDeleter> LiveOnEntryDef;
0893 
0894   // Domination mappings
0895   // Note that the numbering is local to a block, even though the map is
0896   // global.
0897   mutable SmallPtrSet<const BasicBlock *, 16> BlockNumberingValid;
0898   mutable DenseMap<const MemoryAccess *, unsigned long> BlockNumbering;
0899 
0900   // Memory SSA building info
0901   std::unique_ptr<ClobberWalkerBase> WalkerBase;
0902   std::unique_ptr<CachingWalker> Walker;
0903   std::unique_ptr<SkipSelfWalker> SkipWalker;
0904   unsigned NextID = 0;
0905   bool IsOptimized = false;
0906 };
0907 
0908 /// Enables verification of MemorySSA.
0909 ///
0910 /// The checks which this flag enables is exensive and disabled by default
0911 /// unless `EXPENSIVE_CHECKS` is defined.  The flag `-verify-memoryssa` can be
0912 /// used to selectively enable the verification without re-compilation.
0913 extern bool VerifyMemorySSA;
0914 
0915 // Internal MemorySSA utils, for use by MemorySSA classes and walkers
0916 class MemorySSAUtil {
0917 protected:
0918   friend class GVNHoist;
0919   friend class MemorySSAWalker;
0920 
0921   // This function should not be used by new passes.
0922   static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
0923                                   AliasAnalysis &AA);
0924 };
0925 
0926 /// An analysis that produces \c MemorySSA for a function.
0927 ///
0928 class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> {
0929   friend AnalysisInfoMixin<MemorySSAAnalysis>;
0930 
0931   static AnalysisKey Key;
0932 
0933 public:
0934   // Wrap MemorySSA result to ensure address stability of internal MemorySSA
0935   // pointers after construction.  Use a wrapper class instead of plain
0936   // unique_ptr<MemorySSA> to avoid build breakage on MSVC.
0937   struct Result {
0938     Result(std::unique_ptr<MemorySSA> &&MSSA) : MSSA(std::move(MSSA)) {}
0939 
0940     MemorySSA &getMSSA() { return *MSSA; }
0941 
0942     std::unique_ptr<MemorySSA> MSSA;
0943 
0944     bool invalidate(Function &F, const PreservedAnalyses &PA,
0945                     FunctionAnalysisManager::Invalidator &Inv);
0946   };
0947 
0948   Result run(Function &F, FunctionAnalysisManager &AM);
0949 };
0950 
0951 /// Printer pass for \c MemorySSA.
0952 class MemorySSAPrinterPass : public PassInfoMixin<MemorySSAPrinterPass> {
0953   raw_ostream &OS;
0954   bool EnsureOptimizedUses;
0955 
0956 public:
0957   explicit MemorySSAPrinterPass(raw_ostream &OS, bool EnsureOptimizedUses)
0958       : OS(OS), EnsureOptimizedUses(EnsureOptimizedUses) {}
0959 
0960   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
0961 
0962   static bool isRequired() { return true; }
0963 };
0964 
0965 /// Printer pass for \c MemorySSA via the walker.
0966 class MemorySSAWalkerPrinterPass
0967     : public PassInfoMixin<MemorySSAWalkerPrinterPass> {
0968   raw_ostream &OS;
0969 
0970 public:
0971   explicit MemorySSAWalkerPrinterPass(raw_ostream &OS) : OS(OS) {}
0972 
0973   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
0974 
0975   static bool isRequired() { return true; }
0976 };
0977 
0978 /// Verifier pass for \c MemorySSA.
0979 struct MemorySSAVerifierPass : PassInfoMixin<MemorySSAVerifierPass> {
0980   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
0981   static bool isRequired() { return true; }
0982 };
0983 
0984 /// Legacy analysis pass which computes \c MemorySSA.
0985 class MemorySSAWrapperPass : public FunctionPass {
0986 public:
0987   MemorySSAWrapperPass();
0988 
0989   static char ID;
0990 
0991   bool runOnFunction(Function &) override;
0992   void releaseMemory() override;
0993   MemorySSA &getMSSA() { return *MSSA; }
0994   const MemorySSA &getMSSA() const { return *MSSA; }
0995 
0996   void getAnalysisUsage(AnalysisUsage &AU) const override;
0997 
0998   void verifyAnalysis() const override;
0999   void print(raw_ostream &OS, const Module *M = nullptr) const override;
1000 
1001 private:
1002   std::unique_ptr<MemorySSA> MSSA;
1003 };
1004 
1005 /// This is the generic walker interface for walkers of MemorySSA.
1006 /// Walkers are used to be able to further disambiguate the def-use chains
1007 /// MemorySSA gives you, or otherwise produce better info than MemorySSA gives
1008 /// you.
1009 /// In particular, while the def-use chains provide basic information, and are
1010 /// guaranteed to give, for example, the nearest may-aliasing MemoryDef for a
1011 /// MemoryUse as AliasAnalysis considers it, a user mant want better or other
1012 /// information. In particular, they may want to use SCEV info to further
1013 /// disambiguate memory accesses, or they may want the nearest dominating
1014 /// may-aliasing MemoryDef for a call or a store. This API enables a
1015 /// standardized interface to getting and using that info.
1016 class MemorySSAWalker {
1017 public:
1018   MemorySSAWalker(MemorySSA *);
1019   virtual ~MemorySSAWalker() = default;
1020 
1021   using MemoryAccessSet = SmallVector<MemoryAccess *, 8>;
1022 
1023   /// Given a memory Mod/Ref/ModRef'ing instruction, calling this
1024   /// will give you the nearest dominating MemoryAccess that Mod's the location
1025   /// the instruction accesses (by skipping any def which AA can prove does not
1026   /// alias the location(s) accessed by the instruction given).
1027   ///
1028   /// Note that this will return a single access, and it must dominate the
1029   /// Instruction, so if an operand of a MemoryPhi node Mod's the instruction,
1030   /// this will return the MemoryPhi, not the operand. This means that
1031   /// given:
1032   /// if (a) {
1033   ///   1 = MemoryDef(liveOnEntry)
1034   ///   store %a
1035   /// } else {
1036   ///   2 = MemoryDef(liveOnEntry)
1037   ///   store %b
1038   /// }
1039   /// 3 = MemoryPhi(2, 1)
1040   /// MemoryUse(3)
1041   /// load %a
1042   ///
1043   /// calling this API on load(%a) will return the MemoryPhi, not the MemoryDef
1044   /// in the if (a) branch.
1045   MemoryAccess *getClobberingMemoryAccess(const Instruction *I,
1046                                           BatchAAResults &AA) {
1047     MemoryAccess *MA = MSSA->getMemoryAccess(I);
1048     assert(MA && "Handed an instruction that MemorySSA doesn't recognize?");
1049     return getClobberingMemoryAccess(MA, AA);
1050   }
1051 
1052   /// Does the same thing as getClobberingMemoryAccess(const Instruction *I),
1053   /// but takes a MemoryAccess instead of an Instruction.
1054   virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1055                                                   BatchAAResults &AA) = 0;
1056 
1057   /// Given a potentially clobbering memory access and a new location,
1058   /// calling this will give you the nearest dominating clobbering MemoryAccess
1059   /// (by skipping non-aliasing def links).
1060   ///
1061   /// This version of the function is mainly used to disambiguate phi translated
1062   /// pointers, where the value of a pointer may have changed from the initial
1063   /// memory access. Note that this expects to be handed either a MemoryUse,
1064   /// or an already potentially clobbering access. Unlike the above API, if
1065   /// given a MemoryDef that clobbers the pointer as the starting access, it
1066   /// will return that MemoryDef, whereas the above would return the clobber
1067   /// starting from the use side of  the memory def.
1068   virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1069                                                   const MemoryLocation &,
1070                                                   BatchAAResults &AA) = 0;
1071 
1072   MemoryAccess *getClobberingMemoryAccess(const Instruction *I) {
1073     BatchAAResults BAA(MSSA->getAA());
1074     return getClobberingMemoryAccess(I, BAA);
1075   }
1076 
1077   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) {
1078     BatchAAResults BAA(MSSA->getAA());
1079     return getClobberingMemoryAccess(MA, BAA);
1080   }
1081 
1082   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1083                                           const MemoryLocation &Loc) {
1084     BatchAAResults BAA(MSSA->getAA());
1085     return getClobberingMemoryAccess(MA, Loc, BAA);
1086   }
1087 
1088   /// Given a memory access, invalidate anything this walker knows about
1089   /// that access.
1090   /// This API is used by walkers that store information to perform basic cache
1091   /// invalidation.  This will be called by MemorySSA at appropriate times for
1092   /// the walker it uses or returns.
1093   virtual void invalidateInfo(MemoryAccess *) {}
1094 
1095 protected:
1096   friend class MemorySSA; // For updating MSSA pointer in MemorySSA move
1097                           // constructor.
1098   MemorySSA *MSSA;
1099 };
1100 
1101 /// A MemorySSAWalker that does no alias queries, or anything else. It
1102 /// simply returns the links as they were constructed by the builder.
1103 class DoNothingMemorySSAWalker final : public MemorySSAWalker {
1104 public:
1105   // Keep the overrides below from hiding the Instruction overload of
1106   // getClobberingMemoryAccess.
1107   using MemorySSAWalker::getClobberingMemoryAccess;
1108 
1109   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1110                                           BatchAAResults &) override;
1111   MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1112                                           const MemoryLocation &,
1113                                           BatchAAResults &) override;
1114 };
1115 
1116 using MemoryAccessPair = std::pair<MemoryAccess *, MemoryLocation>;
1117 using ConstMemoryAccessPair = std::pair<const MemoryAccess *, MemoryLocation>;
1118 
1119 /// Iterator base class used to implement const and non-const iterators
1120 /// over the defining accesses of a MemoryAccess.
1121 template <class T>
1122 class memoryaccess_def_iterator_base
1123     : public iterator_facade_base<memoryaccess_def_iterator_base<T>,
1124                                   std::forward_iterator_tag, T, ptrdiff_t, T *,
1125                                   T *> {
1126   using BaseT = typename memoryaccess_def_iterator_base::iterator_facade_base;
1127 
1128 public:
1129   memoryaccess_def_iterator_base(T *Start) : Access(Start) {}
1130   memoryaccess_def_iterator_base() = default;
1131 
1132   bool operator==(const memoryaccess_def_iterator_base &Other) const {
1133     return Access == Other.Access && (!Access || ArgNo == Other.ArgNo);
1134   }
1135 
1136   // This is a bit ugly, but for MemoryPHI's, unlike PHINodes, you can't get the
1137   // block from the operand in constant time (In a PHINode, the uselist has
1138   // both, so it's just subtraction). We provide it as part of the
1139   // iterator to avoid callers having to linear walk to get the block.
1140   // If the operation becomes constant time on MemoryPHI's, this bit of
1141   // abstraction breaking should be removed.
1142   BasicBlock *getPhiArgBlock() const {
1143     MemoryPhi *MP = dyn_cast<MemoryPhi>(Access);
1144     assert(MP && "Tried to get phi arg block when not iterating over a PHI");
1145     return MP->getIncomingBlock(ArgNo);
1146   }
1147 
1148   typename std::iterator_traits<BaseT>::pointer operator*() const {
1149     assert(Access && "Tried to access past the end of our iterator");
1150     // Go to the first argument for phis, and the defining access for everything
1151     // else.
1152     if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access))
1153       return MP->getIncomingValue(ArgNo);
1154     return cast<MemoryUseOrDef>(Access)->getDefiningAccess();
1155   }
1156 
1157   using BaseT::operator++;
1158   memoryaccess_def_iterator_base &operator++() {
1159     assert(Access && "Hit end of iterator");
1160     if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) {
1161       if (++ArgNo >= MP->getNumIncomingValues()) {
1162         ArgNo = 0;
1163         Access = nullptr;
1164       }
1165     } else {
1166       Access = nullptr;
1167     }
1168     return *this;
1169   }
1170 
1171 private:
1172   T *Access = nullptr;
1173   unsigned ArgNo = 0;
1174 };
1175 
1176 inline memoryaccess_def_iterator MemoryAccess::defs_begin() {
1177   return memoryaccess_def_iterator(this);
1178 }
1179 
1180 inline const_memoryaccess_def_iterator MemoryAccess::defs_begin() const {
1181   return const_memoryaccess_def_iterator(this);
1182 }
1183 
1184 inline memoryaccess_def_iterator MemoryAccess::defs_end() {
1185   return memoryaccess_def_iterator();
1186 }
1187 
1188 inline const_memoryaccess_def_iterator MemoryAccess::defs_end() const {
1189   return const_memoryaccess_def_iterator();
1190 }
1191 
1192 /// GraphTraits for a MemoryAccess, which walks defs in the normal case,
1193 /// and uses in the inverse case.
1194 template <> struct GraphTraits<MemoryAccess *> {
1195   using NodeRef = MemoryAccess *;
1196   using ChildIteratorType = memoryaccess_def_iterator;
1197 
1198   static NodeRef getEntryNode(NodeRef N) { return N; }
1199   static ChildIteratorType child_begin(NodeRef N) { return N->defs_begin(); }
1200   static ChildIteratorType child_end(NodeRef N) { return N->defs_end(); }
1201 };
1202 
1203 template <> struct GraphTraits<Inverse<MemoryAccess *>> {
1204   using NodeRef = MemoryAccess *;
1205   using ChildIteratorType = MemoryAccess::iterator;
1206 
1207   static NodeRef getEntryNode(NodeRef N) { return N; }
1208   static ChildIteratorType child_begin(NodeRef N) { return N->user_begin(); }
1209   static ChildIteratorType child_end(NodeRef N) { return N->user_end(); }
1210 };
1211 
1212 /// Provide an iterator that walks defs, giving both the memory access,
1213 /// and the current pointer location, updating the pointer location as it
1214 /// changes due to phi node translation.
1215 ///
1216 /// This iterator, while somewhat specialized, is what most clients actually
1217 /// want when walking upwards through MemorySSA def chains. It takes a pair of
1218 /// <MemoryAccess,MemoryLocation>, and walks defs, properly translating the
1219 /// memory location through phi nodes for the user.
1220 class upward_defs_iterator
1221     : public iterator_facade_base<upward_defs_iterator,
1222                                   std::forward_iterator_tag,
1223                                   const MemoryAccessPair> {
1224   using BaseT = upward_defs_iterator::iterator_facade_base;
1225 
1226 public:
1227   upward_defs_iterator(const MemoryAccessPair &Info, DominatorTree *DT)
1228       : DefIterator(Info.first), Location(Info.second),
1229         OriginalAccess(Info.first), DT(DT) {
1230     CurrentPair.first = nullptr;
1231 
1232     WalkingPhi = Info.first && isa<MemoryPhi>(Info.first);
1233     fillInCurrentPair();
1234   }
1235 
1236   upward_defs_iterator() { CurrentPair.first = nullptr; }
1237 
1238   bool operator==(const upward_defs_iterator &Other) const {
1239     return DefIterator == Other.DefIterator;
1240   }
1241 
1242   typename std::iterator_traits<BaseT>::reference operator*() const {
1243     assert(DefIterator != OriginalAccess->defs_end() &&
1244            "Tried to access past the end of our iterator");
1245     return CurrentPair;
1246   }
1247 
1248   using BaseT::operator++;
1249   upward_defs_iterator &operator++() {
1250     assert(DefIterator != OriginalAccess->defs_end() &&
1251            "Tried to access past the end of the iterator");
1252     ++DefIterator;
1253     if (DefIterator != OriginalAccess->defs_end())
1254       fillInCurrentPair();
1255     return *this;
1256   }
1257 
1258   BasicBlock *getPhiArgBlock() const { return DefIterator.getPhiArgBlock(); }
1259 
1260 private:
1261   /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible
1262   /// loop. In particular, this guarantees that it only references a single
1263   /// MemoryLocation during execution of the containing function.
1264   bool IsGuaranteedLoopInvariant(const Value *Ptr) const;
1265 
1266   void fillInCurrentPair() {
1267     CurrentPair.first = *DefIterator;
1268     CurrentPair.second = Location;
1269     if (WalkingPhi && Location.Ptr) {
1270       PHITransAddr Translator(
1271           const_cast<Value *>(Location.Ptr),
1272           OriginalAccess->getBlock()->getDataLayout(), nullptr);
1273 
1274       if (Value *Addr =
1275               Translator.translateValue(OriginalAccess->getBlock(),
1276                                         DefIterator.getPhiArgBlock(), DT, true))
1277         if (Addr != CurrentPair.second.Ptr)
1278           CurrentPair.second = CurrentPair.second.getWithNewPtr(Addr);
1279 
1280       // Mark size as unknown, if the location is not guaranteed to be
1281       // loop-invariant for any possible loop in the function. Setting the size
1282       // to unknown guarantees that any memory accesses that access locations
1283       // after the pointer are considered as clobbers, which is important to
1284       // catch loop carried dependences.
1285       if (!IsGuaranteedLoopInvariant(CurrentPair.second.Ptr))
1286         CurrentPair.second = CurrentPair.second.getWithNewSize(
1287             LocationSize::beforeOrAfterPointer());
1288     }
1289   }
1290 
1291   MemoryAccessPair CurrentPair;
1292   memoryaccess_def_iterator DefIterator;
1293   MemoryLocation Location;
1294   MemoryAccess *OriginalAccess = nullptr;
1295   DominatorTree *DT = nullptr;
1296   bool WalkingPhi = false;
1297 };
1298 
1299 inline upward_defs_iterator
1300 upward_defs_begin(const MemoryAccessPair &Pair, DominatorTree &DT) {
1301   return upward_defs_iterator(Pair, &DT);
1302 }
1303 
1304 inline upward_defs_iterator upward_defs_end() { return upward_defs_iterator(); }
1305 
1306 inline iterator_range<upward_defs_iterator>
1307 upward_defs(const MemoryAccessPair &Pair, DominatorTree &DT) {
1308   return make_range(upward_defs_begin(Pair, DT), upward_defs_end());
1309 }
1310 
1311 /// Walks the defining accesses of MemoryDefs. Stops after we hit something that
1312 /// has no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when
1313 /// comparing against a null def_chain_iterator, this will compare equal only
1314 /// after walking said Phi/liveOnEntry.
1315 ///
1316 /// The UseOptimizedChain flag specifies whether to walk the clobbering
1317 /// access chain, or all the accesses.
1318 ///
1319 /// Normally, MemoryDef are all just def/use linked together, so a def_chain on
1320 /// a MemoryDef will walk all MemoryDefs above it in the program until it hits
1321 /// a phi node.  The optimized chain walks the clobbering access of a store.
1322 /// So if you are just trying to find, given a store, what the next
1323 /// thing that would clobber the same memory is, you want the optimized chain.
1324 template <class T, bool UseOptimizedChain = false>
1325 struct def_chain_iterator
1326     : public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>,
1327                                   std::forward_iterator_tag, MemoryAccess *> {
1328   def_chain_iterator() : MA(nullptr) {}
1329   def_chain_iterator(T MA) : MA(MA) {}
1330 
1331   T operator*() const { return MA; }
1332 
1333   def_chain_iterator &operator++() {
1334     // N.B. liveOnEntry has a null defining access.
1335     if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1336       if (UseOptimizedChain && MUD->isOptimized())
1337         MA = MUD->getOptimized();
1338       else
1339         MA = MUD->getDefiningAccess();
1340     } else {
1341       MA = nullptr;
1342     }
1343 
1344     return *this;
1345   }
1346 
1347   bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
1348 
1349 private:
1350   T MA;
1351 };
1352 
1353 template <class T>
1354 inline iterator_range<def_chain_iterator<T>>
1355 def_chain(T MA, MemoryAccess *UpTo = nullptr) {
1356 #ifdef EXPENSIVE_CHECKS
1357   assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) &&
1358          "UpTo isn't in the def chain!");
1359 #endif
1360   return make_range(def_chain_iterator<T>(MA), def_chain_iterator<T>(UpTo));
1361 }
1362 
1363 template <class T>
1364 inline iterator_range<def_chain_iterator<T, true>> optimized_def_chain(T MA) {
1365   return make_range(def_chain_iterator<T, true>(MA),
1366                     def_chain_iterator<T, true>(nullptr));
1367 }
1368 
1369 } // end namespace llvm
1370 
1371 #endif // LLVM_ANALYSIS_MEMORYSSA_H