MemoryDependenceAnalysis.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. //===- llvm/Analysis/MemoryDependenceAnalysis.h - Memory Deps --*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the MemoryDependenceAnalysis analysis pass.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_ANALYSIS_MEMORYDEPENDENCEANALYSIS_H
  14. #define LLVM_ANALYSIS_MEMORYDEPENDENCEANALYSIS_H
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/PointerIntPair.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/Analysis/AliasAnalysis.h"
  19. #include "llvm/IR/BasicBlock.h"
  20. #include "llvm/IR/PredIteratorCache.h"
  21. #include "llvm/IR/ValueHandle.h"
  22. #include "llvm/Pass.h"
  23. namespace llvm {
  24. class Function;
  25. class FunctionPass;
  26. class Instruction;
  27. class CallSite;
  28. class AliasAnalysis;
  29. class AssumptionCache;
  30. class MemoryDependenceAnalysis;
  31. class PredIteratorCache;
  32. class DominatorTree;
  33. class PHITransAddr;
  34. /// MemDepResult - A memory dependence query can return one of three different
  35. /// answers, described below.
  36. class MemDepResult {
  37. enum DepType {
  38. /// Invalid - Clients of MemDep never see this.
  39. Invalid = 0,
  40. /// Clobber - This is a dependence on the specified instruction which
  41. /// clobbers the desired value. The pointer member of the MemDepResult
  42. /// pair holds the instruction that clobbers the memory. For example,
  43. /// this occurs when we see a may-aliased store to the memory location we
  44. /// care about.
  45. ///
  46. /// There are several cases that may be interesting here:
  47. /// 1. Loads are clobbered by may-alias stores.
  48. /// 2. Loads are considered clobbered by partially-aliased loads. The
  49. /// client may choose to analyze deeper into these cases.
  50. Clobber,
  51. /// Def - This is a dependence on the specified instruction which
  52. /// defines/produces the desired memory location. The pointer member of
  53. /// the MemDepResult pair holds the instruction that defines the memory.
  54. /// Cases of interest:
  55. /// 1. This could be a load or store for dependence queries on
  56. /// load/store. The value loaded or stored is the produced value.
  57. /// Note that the pointer operand may be different than that of the
  58. /// queried pointer due to must aliases and phi translation. Note
  59. /// that the def may not be the same type as the query, the pointers
  60. /// may just be must aliases.
  61. /// 2. For loads and stores, this could be an allocation instruction. In
  62. /// this case, the load is loading an undef value or a store is the
  63. /// first store to (that part of) the allocation.
  64. /// 3. Dependence queries on calls return Def only when they are
  65. /// readonly calls or memory use intrinsics with identical callees
  66. /// and no intervening clobbers. No validation is done that the
  67. /// operands to the calls are the same.
  68. Def,
  69. /// Other - This marker indicates that the query has no known dependency
  70. /// in the specified block. More detailed state info is encoded in the
  71. /// upper part of the pair (i.e. the Instruction*)
  72. Other
  73. };
  74. /// If DepType is "Other", the upper part of the pair
  75. /// (i.e. the Instruction* part) is instead used to encode more detailed
  76. /// type information as follows
  77. enum OtherType {
  78. /// NonLocal - This marker indicates that the query has no dependency in
  79. /// the specified block. To find out more, the client should query other
  80. /// predecessor blocks.
  81. NonLocal = 0x4,
  82. /// NonFuncLocal - This marker indicates that the query has no
  83. /// dependency in the specified function.
  84. NonFuncLocal = 0x8,
  85. /// Unknown - This marker indicates that the query dependency
  86. /// is unknown.
  87. Unknown = 0xc
  88. };
  89. typedef PointerIntPair<Instruction*, 2, DepType> PairTy;
  90. PairTy Value;
  91. explicit MemDepResult(PairTy V) : Value(V) {}
  92. public:
  93. MemDepResult() : Value(nullptr, Invalid) {}
  94. /// get methods: These are static ctor methods for creating various
  95. /// MemDepResult kinds.
  96. static MemDepResult getDef(Instruction *Inst) {
  97. assert(Inst && "Def requires inst");
  98. return MemDepResult(PairTy(Inst, Def));
  99. }
  100. static MemDepResult getClobber(Instruction *Inst) {
  101. assert(Inst && "Clobber requires inst");
  102. return MemDepResult(PairTy(Inst, Clobber));
  103. }
  104. static MemDepResult getNonLocal() {
  105. return MemDepResult(
  106. PairTy(reinterpret_cast<Instruction*>(NonLocal), Other));
  107. }
  108. static MemDepResult getNonFuncLocal() {
  109. return MemDepResult(
  110. PairTy(reinterpret_cast<Instruction*>(NonFuncLocal), Other));
  111. }
  112. static MemDepResult getUnknown() {
  113. return MemDepResult(
  114. PairTy(reinterpret_cast<Instruction*>(Unknown), Other));
  115. }
  116. /// isClobber - Return true if this MemDepResult represents a query that is
  117. /// an instruction clobber dependency.
  118. bool isClobber() const { return Value.getInt() == Clobber; }
  119. /// isDef - Return true if this MemDepResult represents a query that is
  120. /// an instruction definition dependency.
  121. bool isDef() const { return Value.getInt() == Def; }
  122. /// isNonLocal - Return true if this MemDepResult represents a query that
  123. /// is transparent to the start of the block, but where a non-local hasn't
  124. /// been done.
  125. bool isNonLocal() const {
  126. return Value.getInt() == Other
  127. && Value.getPointer() == reinterpret_cast<Instruction*>(NonLocal);
  128. }
  129. /// isNonFuncLocal - Return true if this MemDepResult represents a query
  130. /// that is transparent to the start of the function.
  131. bool isNonFuncLocal() const {
  132. return Value.getInt() == Other
  133. && Value.getPointer() == reinterpret_cast<Instruction*>(NonFuncLocal);
  134. }
  135. /// isUnknown - Return true if this MemDepResult represents a query which
  136. /// cannot and/or will not be computed.
  137. bool isUnknown() const {
  138. return Value.getInt() == Other
  139. && Value.getPointer() == reinterpret_cast<Instruction*>(Unknown);
  140. }
  141. /// getInst() - If this is a normal dependency, return the instruction that
  142. /// is depended on. Otherwise, return null.
  143. Instruction *getInst() const {
  144. if (Value.getInt() == Other) return nullptr;
  145. return Value.getPointer();
  146. }
  147. bool operator==(const MemDepResult &M) const { return Value == M.Value; }
  148. bool operator!=(const MemDepResult &M) const { return Value != M.Value; }
  149. bool operator<(const MemDepResult &M) const { return Value < M.Value; }
  150. bool operator>(const MemDepResult &M) const { return Value > M.Value; }
  151. private:
  152. friend class MemoryDependenceAnalysis;
  153. /// Dirty - Entries with this marker occur in a LocalDeps map or
  154. /// NonLocalDeps map when the instruction they previously referenced was
  155. /// removed from MemDep. In either case, the entry may include an
  156. /// instruction pointer. If so, the pointer is an instruction in the
  157. /// block where scanning can start from, saving some work.
  158. ///
  159. /// In a default-constructed MemDepResult object, the type will be Dirty
  160. /// and the instruction pointer will be null.
  161. ///
  162. /// isDirty - Return true if this is a MemDepResult in its dirty/invalid.
  163. /// state.
  164. bool isDirty() const { return Value.getInt() == Invalid; }
  165. static MemDepResult getDirty(Instruction *Inst) {
  166. return MemDepResult(PairTy(Inst, Invalid));
  167. }
  168. };
  169. /// NonLocalDepEntry - This is an entry in the NonLocalDepInfo cache. For
  170. /// each BasicBlock (the BB entry) it keeps a MemDepResult.
  171. class NonLocalDepEntry {
  172. BasicBlock *BB;
  173. MemDepResult Result;
  174. public:
  175. NonLocalDepEntry(BasicBlock *bb, MemDepResult result)
  176. : BB(bb), Result(result) {}
  177. // This is used for searches.
  178. NonLocalDepEntry(BasicBlock *bb) : BB(bb) {}
  179. // BB is the sort key, it can't be changed.
  180. BasicBlock *getBB() const { return BB; }
  181. void setResult(const MemDepResult &R) { Result = R; }
  182. const MemDepResult &getResult() const { return Result; }
  183. bool operator<(const NonLocalDepEntry &RHS) const {
  184. return BB < RHS.BB;
  185. }
  186. };
  187. /// NonLocalDepResult - This is a result from a NonLocal dependence query.
  188. /// For each BasicBlock (the BB entry) it keeps a MemDepResult and the
  189. /// (potentially phi translated) address that was live in the block.
  190. class NonLocalDepResult {
  191. NonLocalDepEntry Entry;
  192. Value *Address;
  193. public:
  194. NonLocalDepResult(BasicBlock *bb, MemDepResult result, Value *address)
  195. : Entry(bb, result), Address(address) {}
  196. // BB is the sort key, it can't be changed.
  197. BasicBlock *getBB() const { return Entry.getBB(); }
  198. void setResult(const MemDepResult &R, Value *Addr) {
  199. Entry.setResult(R);
  200. Address = Addr;
  201. }
  202. const MemDepResult &getResult() const { return Entry.getResult(); }
  203. /// getAddress - Return the address of this pointer in this block. This can
  204. /// be different than the address queried for the non-local result because
  205. /// of phi translation. This returns null if the address was not available
  206. /// in a block (i.e. because phi translation failed) or if this is a cached
  207. /// result and that address was deleted.
  208. ///
  209. /// The address is always null for a non-local 'call' dependence.
  210. Value *getAddress() const { return Address; }
  211. };
  212. /// MemoryDependenceAnalysis - This is an analysis that determines, for a
  213. /// given memory operation, what preceding memory operations it depends on.
  214. /// It builds on alias analysis information, and tries to provide a lazy,
  215. /// caching interface to a common kind of alias information query.
  216. ///
  217. /// The dependency information returned is somewhat unusual, but is pragmatic.
  218. /// If queried about a store or call that might modify memory, the analysis
  219. /// will return the instruction[s] that may either load from that memory or
  220. /// store to it. If queried with a load or call that can never modify memory,
  221. /// the analysis will return calls and stores that might modify the pointer,
  222. /// but generally does not return loads unless a) they are volatile, or
  223. /// b) they load from *must-aliased* pointers. Returning a dependence on
  224. /// must-alias'd pointers instead of all pointers interacts well with the
  225. /// internal caching mechanism.
  226. ///
  227. class MemoryDependenceAnalysis : public FunctionPass {
  228. // A map from instructions to their dependency.
  229. typedef DenseMap<Instruction*, MemDepResult> LocalDepMapType;
  230. LocalDepMapType LocalDeps;
  231. public:
  232. typedef std::vector<NonLocalDepEntry> NonLocalDepInfo;
  233. private:
  234. /// ValueIsLoadPair - This is a pair<Value*, bool> where the bool is true if
  235. /// the dependence is a read only dependence, false if read/write.
  236. typedef PointerIntPair<const Value*, 1, bool> ValueIsLoadPair;
  237. /// BBSkipFirstBlockPair - This pair is used when caching information for a
  238. /// block. If the pointer is null, the cache value is not a full query that
  239. /// starts at the specified block. If non-null, the bool indicates whether
  240. /// or not the contents of the block was skipped.
  241. typedef PointerIntPair<BasicBlock*, 1, bool> BBSkipFirstBlockPair;
  242. /// NonLocalPointerInfo - This record is the information kept for each
  243. /// (value, is load) pair.
  244. struct NonLocalPointerInfo {
  245. /// Pair - The pair of the block and the skip-first-block flag.
  246. BBSkipFirstBlockPair Pair;
  247. /// NonLocalDeps - The results of the query for each relevant block.
  248. NonLocalDepInfo NonLocalDeps;
  249. /// Size - The maximum size of the dereferences of the
  250. /// pointer. May be UnknownSize if the sizes are unknown.
  251. uint64_t Size;
  252. /// AATags - The AA tags associated with dereferences of the
  253. /// pointer. The members may be null if there are no tags or
  254. /// conflicting tags.
  255. AAMDNodes AATags;
  256. NonLocalPointerInfo() : Size(MemoryLocation::UnknownSize) {}
  257. };
  258. /// CachedNonLocalPointerInfo - This map stores the cached results of doing
  259. /// a pointer lookup at the bottom of a block. The key of this map is the
  260. /// pointer+isload bit, the value is a list of <bb->result> mappings.
  261. typedef DenseMap<ValueIsLoadPair,
  262. NonLocalPointerInfo> CachedNonLocalPointerInfo;
  263. CachedNonLocalPointerInfo NonLocalPointerDeps;
  264. // A map from instructions to their non-local pointer dependencies.
  265. typedef DenseMap<Instruction*,
  266. SmallPtrSet<ValueIsLoadPair, 4> > ReverseNonLocalPtrDepTy;
  267. ReverseNonLocalPtrDepTy ReverseNonLocalPtrDeps;
  268. /// PerInstNLInfo - This is the instruction we keep for each cached access
  269. /// that we have for an instruction. The pointer is an owning pointer and
  270. /// the bool indicates whether we have any dirty bits in the set.
  271. typedef std::pair<NonLocalDepInfo, bool> PerInstNLInfo;
  272. // A map from instructions to their non-local dependencies.
  273. typedef DenseMap<Instruction*, PerInstNLInfo> NonLocalDepMapType;
  274. NonLocalDepMapType NonLocalDeps;
  275. // A reverse mapping from dependencies to the dependees. This is
  276. // used when removing instructions to keep the cache coherent.
  277. typedef DenseMap<Instruction*,
  278. SmallPtrSet<Instruction*, 4> > ReverseDepMapType;
  279. ReverseDepMapType ReverseLocalDeps;
  280. // A reverse mapping from dependencies to the non-local dependees.
  281. ReverseDepMapType ReverseNonLocalDeps;
  282. /// Current AA implementation, just a cache.
  283. AliasAnalysis *AA;
  284. DominatorTree *DT;
  285. AssumptionCache *AC;
  286. PredIteratorCache PredCache;
  287. public:
  288. MemoryDependenceAnalysis();
  289. ~MemoryDependenceAnalysis() override;
  290. static char ID;
  291. /// Pass Implementation stuff. This doesn't do any analysis eagerly.
  292. bool runOnFunction(Function &) override;
  293. /// Clean up memory in between runs
  294. void releaseMemory() override;
  295. /// getAnalysisUsage - Does not modify anything. It uses Value Numbering
  296. /// and Alias Analysis.
  297. ///
  298. void getAnalysisUsage(AnalysisUsage &AU) const override;
  299. /// getDependency - Return the instruction on which a memory operation
  300. /// depends. See the class comment for more details. It is illegal to call
  301. /// this on non-memory instructions.
  302. MemDepResult getDependency(Instruction *QueryInst);
  303. /// getNonLocalCallDependency - Perform a full dependency query for the
  304. /// specified call, returning the set of blocks that the value is
  305. /// potentially live across. The returned set of results will include a
  306. /// "NonLocal" result for all blocks where the value is live across.
  307. ///
  308. /// This method assumes the instruction returns a "NonLocal" dependency
  309. /// within its own block.
  310. ///
  311. /// This returns a reference to an internal data structure that may be
  312. /// invalidated on the next non-local query or when an instruction is
  313. /// removed. Clients must copy this data if they want it around longer than
  314. /// that.
  315. const NonLocalDepInfo &getNonLocalCallDependency(CallSite QueryCS);
  316. /// getNonLocalPointerDependency - Perform a full dependency query for an
  317. /// access to the QueryInst's specified memory location, returning the set
  318. /// of instructions that either define or clobber the value.
  319. ///
  320. /// Warning: For a volatile query instruction, the dependencies will be
  321. /// accurate, and thus usable for reordering, but it is never legal to
  322. /// remove the query instruction.
  323. ///
  324. /// This method assumes the pointer has a "NonLocal" dependency within
  325. /// QueryInst's parent basic block.
  326. void getNonLocalPointerDependency(Instruction *QueryInst,
  327. SmallVectorImpl<NonLocalDepResult> &Result);
  328. /// removeInstruction - Remove an instruction from the dependence analysis,
  329. /// updating the dependence of instructions that previously depended on it.
  330. void removeInstruction(Instruction *InstToRemove);
  331. /// invalidateCachedPointerInfo - This method is used to invalidate cached
  332. /// information about the specified pointer, because it may be too
  333. /// conservative in memdep. This is an optional call that can be used when
  334. /// the client detects an equivalence between the pointer and some other
  335. /// value and replaces the other value with ptr. This can make Ptr available
  336. /// in more places that cached info does not necessarily keep.
  337. void invalidateCachedPointerInfo(Value *Ptr);
  338. /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
  339. /// This needs to be done when the CFG changes, e.g., due to splitting
  340. /// critical edges.
  341. void invalidateCachedPredecessors();
  342. /// getPointerDependencyFrom - Return the instruction on which a memory
  343. /// location depends. If isLoad is true, this routine ignores may-aliases
  344. /// with read-only operations. If isLoad is false, this routine ignores
  345. /// may-aliases with reads from read-only locations. If possible, pass
  346. /// the query instruction as well; this function may take advantage of
  347. /// the metadata annotated to the query instruction to refine the result.
  348. ///
  349. /// Note that this is an uncached query, and thus may be inefficient.
  350. ///
  351. MemDepResult getPointerDependencyFrom(const MemoryLocation &Loc,
  352. bool isLoad,
  353. BasicBlock::iterator ScanIt,
  354. BasicBlock *BB,
  355. Instruction *QueryInst = nullptr);
  356. /// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that
  357. /// looks at a memory location for a load (specified by MemLocBase, Offs,
  358. /// and Size) and compares it against a load. If the specified load could
  359. /// be safely widened to a larger integer load that is 1) still efficient,
  360. /// 2) safe for the target, and 3) would provide the specified memory
  361. /// location value, then this function returns the size in bytes of the
  362. /// load width to use. If not, this returns zero.
  363. static unsigned getLoadLoadClobberFullWidthSize(const Value *MemLocBase,
  364. int64_t MemLocOffs,
  365. unsigned MemLocSize,
  366. const LoadInst *LI);
  367. private:
  368. MemDepResult getCallSiteDependencyFrom(CallSite C, bool isReadOnlyCall,
  369. BasicBlock::iterator ScanIt,
  370. BasicBlock *BB);
  371. bool getNonLocalPointerDepFromBB(Instruction *QueryInst,
  372. const PHITransAddr &Pointer,
  373. const MemoryLocation &Loc, bool isLoad,
  374. BasicBlock *BB,
  375. SmallVectorImpl<NonLocalDepResult> &Result,
  376. DenseMap<BasicBlock *, Value *> &Visited,
  377. bool SkipFirstBlock = false);
  378. MemDepResult GetNonLocalInfoForBlock(Instruction *QueryInst,
  379. const MemoryLocation &Loc, bool isLoad,
  380. BasicBlock *BB, NonLocalDepInfo *Cache,
  381. unsigned NumSortedEntries);
  382. void RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P);
  383. /// verifyRemoved - Verify that the specified instruction does not occur
  384. /// in our internal data structures.
  385. void verifyRemoved(Instruction *Inst) const;
  386. };
  387. } // End llvm namespace
  388. #endif