MemorySSA.h 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- MemorySSA.h - Build Memory SSA ---------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. /// \file
  15. /// This file exposes an interface to building/using memory SSA to
  16. /// walk memory instructions using a use/def graph.
  17. ///
  18. /// Memory SSA class builds an SSA form that links together memory access
  19. /// instructions such as loads, stores, atomics, and calls. Additionally, it
  20. /// does a trivial form of "heap versioning" Every time the memory state changes
  21. /// in the program, we generate a new heap version. It generates
  22. /// MemoryDef/Uses/Phis that are overlayed on top of the existing instructions.
  23. ///
  24. /// As a trivial example,
  25. /// define i32 @main() #0 {
  26. /// entry:
  27. /// %call = call noalias i8* @_Znwm(i64 4) #2
  28. /// %0 = bitcast i8* %call to i32*
  29. /// %call1 = call noalias i8* @_Znwm(i64 4) #2
  30. /// %1 = bitcast i8* %call1 to i32*
  31. /// store i32 5, i32* %0, align 4
  32. /// store i32 7, i32* %1, align 4
  33. /// %2 = load i32* %0, align 4
  34. /// %3 = load i32* %1, align 4
  35. /// %add = add nsw i32 %2, %3
  36. /// ret i32 %add
  37. /// }
  38. ///
  39. /// Will become
  40. /// define i32 @main() #0 {
  41. /// entry:
  42. /// ; 1 = MemoryDef(0)
  43. /// %call = call noalias i8* @_Znwm(i64 4) #3
  44. /// %2 = bitcast i8* %call to i32*
  45. /// ; 2 = MemoryDef(1)
  46. /// %call1 = call noalias i8* @_Znwm(i64 4) #3
  47. /// %4 = bitcast i8* %call1 to i32*
  48. /// ; 3 = MemoryDef(2)
  49. /// store i32 5, i32* %2, align 4
  50. /// ; 4 = MemoryDef(3)
  51. /// store i32 7, i32* %4, align 4
  52. /// ; MemoryUse(3)
  53. /// %7 = load i32* %2, align 4
  54. /// ; MemoryUse(4)
  55. /// %8 = load i32* %4, align 4
  56. /// %add = add nsw i32 %7, %8
  57. /// ret i32 %add
  58. /// }
  59. ///
  60. /// Given this form, all the stores that could ever effect the load at %8 can be
  61. /// gotten by using the MemoryUse associated with it, and walking from use to
  62. /// def until you hit the top of the function.
  63. ///
  64. /// Each def also has a list of users associated with it, so you can walk from
  65. /// both def to users, and users to defs. Note that we disambiguate MemoryUses,
  66. /// but not the RHS of MemoryDefs. You can see this above at %7, which would
  67. /// otherwise be a MemoryUse(4). Being disambiguated means that for a given
  68. /// store, all the MemoryUses on its use lists are may-aliases of that store
  69. /// (but the MemoryDefs on its use list may not be).
  70. ///
  71. /// MemoryDefs are not disambiguated because it would require multiple reaching
  72. /// definitions, which would require multiple phis, and multiple memoryaccesses
  73. /// per instruction.
  74. //
  75. //===----------------------------------------------------------------------===//
  76. #ifndef LLVM_ANALYSIS_MEMORYSSA_H
  77. #define LLVM_ANALYSIS_MEMORYSSA_H
  78. #include "llvm/ADT/DenseMap.h"
  79. #include "llvm/ADT/GraphTraits.h"
  80. #include "llvm/ADT/SmallPtrSet.h"
  81. #include "llvm/ADT/SmallVector.h"
  82. #include "llvm/ADT/ilist.h"
  83. #include "llvm/ADT/ilist_node.h"
  84. #include "llvm/ADT/iterator.h"
  85. #include "llvm/ADT/iterator_range.h"
  86. #include "llvm/ADT/simple_ilist.h"
  87. #include "llvm/Analysis/AliasAnalysis.h"
  88. #include "llvm/Analysis/MemoryLocation.h"
  89. #include "llvm/Analysis/PHITransAddr.h"
  90. #include "llvm/IR/BasicBlock.h"
  91. #include "llvm/IR/DerivedUser.h"
  92. #include "llvm/IR/Dominators.h"
  93. #include "llvm/IR/Module.h"
  94. #include "llvm/IR/Operator.h"
  95. #include "llvm/IR/Type.h"
  96. #include "llvm/IR/Use.h"
  97. #include "llvm/IR/User.h"
  98. #include "llvm/IR/Value.h"
  99. #include "llvm/IR/ValueHandle.h"
  100. #include "llvm/Pass.h"
  101. #include "llvm/Support/Casting.h"
  102. #include "llvm/Support/CommandLine.h"
  103. #include <algorithm>
  104. #include <cassert>
  105. #include <cstddef>
  106. #include <iterator>
  107. #include <memory>
  108. #include <utility>
  109. namespace llvm {
  110. /// Enables memory ssa as a dependency for loop passes.
  111. extern cl::opt<bool> EnableMSSALoopDependency;
  112. class AllocaInst;
  113. class Function;
  114. class Instruction;
  115. class MemoryAccess;
  116. class MemorySSAWalker;
  117. class LLVMContext;
  118. class raw_ostream;
  119. namespace MSSAHelpers {
  120. struct AllAccessTag {};
  121. struct DefsOnlyTag {};
  122. } // end namespace MSSAHelpers
  123. enum : unsigned {
  124. // Used to signify what the default invalid ID is for MemoryAccess's
  125. // getID()
  126. INVALID_MEMORYACCESS_ID = -1U
  127. };
  128. template <class T> class memoryaccess_def_iterator_base;
  129. using memoryaccess_def_iterator = memoryaccess_def_iterator_base<MemoryAccess>;
  130. using const_memoryaccess_def_iterator =
  131. memoryaccess_def_iterator_base<const MemoryAccess>;
  132. // The base for all memory accesses. All memory accesses in a block are
  133. // linked together using an intrusive list.
  134. class MemoryAccess
  135. : public DerivedUser,
  136. public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>,
  137. public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>> {
  138. public:
  139. using AllAccessType =
  140. ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
  141. using DefsOnlyType =
  142. ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
  143. MemoryAccess(const MemoryAccess &) = delete;
  144. MemoryAccess &operator=(const MemoryAccess &) = delete;
  145. void *operator new(size_t) = delete;
  146. // Methods for support type inquiry through isa, cast, and
  147. // dyn_cast
  148. static bool classof(const Value *V) {
  149. unsigned ID = V->getValueID();
  150. return ID == MemoryUseVal || ID == MemoryPhiVal || ID == MemoryDefVal;
  151. }
  152. BasicBlock *getBlock() const { return Block; }
  153. void print(raw_ostream &OS) const;
  154. void dump() const;
  155. /// The user iterators for a memory access
  156. using iterator = user_iterator;
  157. using const_iterator = const_user_iterator;
  158. /// This iterator walks over all of the defs in a given
  159. /// MemoryAccess. For MemoryPhi nodes, this walks arguments. For
  160. /// MemoryUse/MemoryDef, this walks the defining access.
  161. memoryaccess_def_iterator defs_begin();
  162. const_memoryaccess_def_iterator defs_begin() const;
  163. memoryaccess_def_iterator defs_end();
  164. const_memoryaccess_def_iterator defs_end() const;
  165. /// Get the iterators for the all access list and the defs only list
  166. /// We default to the all access list.
  167. AllAccessType::self_iterator getIterator() {
  168. return this->AllAccessType::getIterator();
  169. }
  170. AllAccessType::const_self_iterator getIterator() const {
  171. return this->AllAccessType::getIterator();
  172. }
  173. AllAccessType::reverse_self_iterator getReverseIterator() {
  174. return this->AllAccessType::getReverseIterator();
  175. }
  176. AllAccessType::const_reverse_self_iterator getReverseIterator() const {
  177. return this->AllAccessType::getReverseIterator();
  178. }
  179. DefsOnlyType::self_iterator getDefsIterator() {
  180. return this->DefsOnlyType::getIterator();
  181. }
  182. DefsOnlyType::const_self_iterator getDefsIterator() const {
  183. return this->DefsOnlyType::getIterator();
  184. }
  185. DefsOnlyType::reverse_self_iterator getReverseDefsIterator() {
  186. return this->DefsOnlyType::getReverseIterator();
  187. }
  188. DefsOnlyType::const_reverse_self_iterator getReverseDefsIterator() const {
  189. return this->DefsOnlyType::getReverseIterator();
  190. }
  191. protected:
  192. friend class MemoryDef;
  193. friend class MemoryPhi;
  194. friend class MemorySSA;
  195. friend class MemoryUse;
  196. friend class MemoryUseOrDef;
  197. /// Used by MemorySSA to change the block of a MemoryAccess when it is
  198. /// moved.
  199. void setBlock(BasicBlock *BB) { Block = BB; }
  200. /// Used for debugging and tracking things about MemoryAccesses.
  201. /// Guaranteed unique among MemoryAccesses, no guarantees otherwise.
  202. inline unsigned getID() const;
  203. MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue,
  204. BasicBlock *BB, unsigned NumOperands)
  205. : DerivedUser(Type::getVoidTy(C), Vty, nullptr, NumOperands, DeleteValue),
  206. Block(BB) {}
  207. // Use deleteValue() to delete a generic MemoryAccess.
  208. ~MemoryAccess() = default;
  209. private:
  210. BasicBlock *Block;
  211. };
  212. template <>
  213. struct ilist_alloc_traits<MemoryAccess> {
  214. static void deleteNode(MemoryAccess *MA) { MA->deleteValue(); }
  215. };
  216. inline raw_ostream &operator<<(raw_ostream &OS, const MemoryAccess &MA) {
  217. MA.print(OS);
  218. return OS;
  219. }
  220. /// Class that has the common methods + fields of memory uses/defs. It's
  221. /// a little awkward to have, but there are many cases where we want either a
  222. /// use or def, and there are many cases where uses are needed (defs aren't
  223. /// acceptable), and vice-versa.
  224. ///
  225. /// This class should never be instantiated directly; make a MemoryUse or
  226. /// MemoryDef instead.
  227. class MemoryUseOrDef : public MemoryAccess {
  228. public:
  229. void *operator new(size_t) = delete;
  230. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
  231. /// Get the instruction that this MemoryUse represents.
  232. Instruction *getMemoryInst() const { return MemoryInstruction; }
  233. /// Get the access that produces the memory state used by this Use.
  234. MemoryAccess *getDefiningAccess() const { return getOperand(0); }
  235. static bool classof(const Value *MA) {
  236. return MA->getValueID() == MemoryUseVal || MA->getValueID() == MemoryDefVal;
  237. }
  238. // Sadly, these have to be public because they are needed in some of the
  239. // iterators.
  240. inline bool isOptimized() const;
  241. inline MemoryAccess *getOptimized() const;
  242. inline void setOptimized(MemoryAccess *);
  243. // Retrieve AliasResult type of the optimized access. Ideally this would be
  244. // returned by the caching walker and may go away in the future.
  245. Optional<AliasResult> getOptimizedAccessType() const {
  246. return isOptimized() ? OptimizedAccessAlias : None;
  247. }
  248. /// Reset the ID of what this MemoryUse was optimized to, causing it to
  249. /// be rewalked by the walker if necessary.
  250. /// This really should only be called by tests.
  251. inline void resetOptimized();
  252. protected:
  253. friend class MemorySSA;
  254. friend class MemorySSAUpdater;
  255. MemoryUseOrDef(LLVMContext &C, MemoryAccess *DMA, unsigned Vty,
  256. DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB,
  257. unsigned NumOperands)
  258. : MemoryAccess(C, Vty, DeleteValue, BB, NumOperands),
  259. MemoryInstruction(MI), OptimizedAccessAlias(MayAlias) {
  260. setDefiningAccess(DMA);
  261. }
  262. // Use deleteValue() to delete a generic MemoryUseOrDef.
  263. ~MemoryUseOrDef() = default;
  264. void setOptimizedAccessType(Optional<AliasResult> AR) {
  265. OptimizedAccessAlias = AR;
  266. }
  267. void setDefiningAccess(MemoryAccess *DMA, bool Optimized = false,
  268. Optional<AliasResult> AR = MayAlias) {
  269. if (!Optimized) {
  270. setOperand(0, DMA);
  271. return;
  272. }
  273. setOptimized(DMA);
  274. setOptimizedAccessType(AR);
  275. }
  276. private:
  277. Instruction *MemoryInstruction;
  278. Optional<AliasResult> OptimizedAccessAlias;
  279. };
  280. /// Represents read-only accesses to memory
  281. ///
  282. /// In particular, the set of Instructions that will be represented by
  283. /// MemoryUse's is exactly the set of Instructions for which
  284. /// AliasAnalysis::getModRefInfo returns "Ref".
  285. class MemoryUse final : public MemoryUseOrDef {
  286. public:
  287. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
  288. MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB)
  289. : MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB,
  290. /*NumOperands=*/1) {}
  291. // allocate space for exactly one operand
  292. void *operator new(size_t s) { return User::operator new(s, 1); }
  293. static bool classof(const Value *MA) {
  294. return MA->getValueID() == MemoryUseVal;
  295. }
  296. void print(raw_ostream &OS) const;
  297. void setOptimized(MemoryAccess *DMA) {
  298. OptimizedID = DMA->getID();
  299. setOperand(0, DMA);
  300. }
  301. bool isOptimized() const {
  302. return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID();
  303. }
  304. MemoryAccess *getOptimized() const {
  305. return getDefiningAccess();
  306. }
  307. void resetOptimized() {
  308. OptimizedID = INVALID_MEMORYACCESS_ID;
  309. }
  310. protected:
  311. friend class MemorySSA;
  312. private:
  313. static void deleteMe(DerivedUser *Self);
  314. unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
  315. };
  316. template <>
  317. struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {};
  318. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUse, MemoryAccess)
  319. /// Represents a read-write access to memory, whether it is a must-alias,
  320. /// or a may-alias.
  321. ///
  322. /// In particular, the set of Instructions that will be represented by
  323. /// MemoryDef's is exactly the set of Instructions for which
  324. /// AliasAnalysis::getModRefInfo returns "Mod" or "ModRef".
  325. /// Note that, in order to provide def-def chains, all defs also have a use
  326. /// associated with them. This use points to the nearest reaching
  327. /// MemoryDef/MemoryPhi.
  328. class MemoryDef final : public MemoryUseOrDef {
  329. public:
  330. friend class MemorySSA;
  331. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
  332. MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB,
  333. unsigned Ver)
  334. : MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB,
  335. /*NumOperands=*/2),
  336. ID(Ver) {}
  337. // allocate space for exactly two operands
  338. void *operator new(size_t s) { return User::operator new(s, 2); }
  339. static bool classof(const Value *MA) {
  340. return MA->getValueID() == MemoryDefVal;
  341. }
  342. void setOptimized(MemoryAccess *MA) {
  343. setOperand(1, MA);
  344. OptimizedID = MA->getID();
  345. }
  346. MemoryAccess *getOptimized() const {
  347. return cast_or_null<MemoryAccess>(getOperand(1));
  348. }
  349. bool isOptimized() const {
  350. return getOptimized() && OptimizedID == getOptimized()->getID();
  351. }
  352. void resetOptimized() {
  353. OptimizedID = INVALID_MEMORYACCESS_ID;
  354. setOperand(1, nullptr);
  355. }
  356. void print(raw_ostream &OS) const;
  357. unsigned getID() const { return ID; }
  358. private:
  359. static void deleteMe(DerivedUser *Self);
  360. const unsigned ID;
  361. unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
  362. };
  363. template <>
  364. struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 2> {};
  365. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryDef, MemoryAccess)
  366. template <>
  367. struct OperandTraits<MemoryUseOrDef> {
  368. static Use *op_begin(MemoryUseOrDef *MUD) {
  369. if (auto *MU = dyn_cast<MemoryUse>(MUD))
  370. return OperandTraits<MemoryUse>::op_begin(MU);
  371. return OperandTraits<MemoryDef>::op_begin(cast<MemoryDef>(MUD));
  372. }
  373. static Use *op_end(MemoryUseOrDef *MUD) {
  374. if (auto *MU = dyn_cast<MemoryUse>(MUD))
  375. return OperandTraits<MemoryUse>::op_end(MU);
  376. return OperandTraits<MemoryDef>::op_end(cast<MemoryDef>(MUD));
  377. }
  378. static unsigned operands(const MemoryUseOrDef *MUD) {
  379. if (const auto *MU = dyn_cast<MemoryUse>(MUD))
  380. return OperandTraits<MemoryUse>::operands(MU);
  381. return OperandTraits<MemoryDef>::operands(cast<MemoryDef>(MUD));
  382. }
  383. };
  384. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUseOrDef, MemoryAccess)
  385. /// Represents phi nodes for memory accesses.
  386. ///
  387. /// These have the same semantic as regular phi nodes, with the exception that
  388. /// only one phi will ever exist in a given basic block.
  389. /// Guaranteeing one phi per block means guaranteeing there is only ever one
  390. /// valid reaching MemoryDef/MemoryPHI along each path to the phi node.
  391. /// This is ensured by not allowing disambiguation of the RHS of a MemoryDef or
  392. /// a MemoryPhi's operands.
  393. /// That is, given
  394. /// if (a) {
  395. /// store %a
  396. /// store %b
  397. /// }
  398. /// it *must* be transformed into
  399. /// if (a) {
  400. /// 1 = MemoryDef(liveOnEntry)
  401. /// store %a
  402. /// 2 = MemoryDef(1)
  403. /// store %b
  404. /// }
  405. /// and *not*
  406. /// if (a) {
  407. /// 1 = MemoryDef(liveOnEntry)
  408. /// store %a
  409. /// 2 = MemoryDef(liveOnEntry)
  410. /// store %b
  411. /// }
  412. /// even if the two stores do not conflict. Otherwise, both 1 and 2 reach the
  413. /// end of the branch, and if there are not two phi nodes, one will be
  414. /// disconnected completely from the SSA graph below that point.
  415. /// Because MemoryUse's do not generate new definitions, they do not have this
  416. /// issue.
  417. class MemoryPhi final : public MemoryAccess {
  418. // allocate space for exactly zero operands
  419. void *operator new(size_t s) { return User::operator new(s); }
  420. public:
  421. /// Provide fast operand accessors
  422. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
  423. MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0)
  424. : MemoryAccess(C, MemoryPhiVal, deleteMe, BB, 0), ID(Ver),
  425. ReservedSpace(NumPreds) {
  426. allocHungoffUses(ReservedSpace);
  427. }
  428. // Block iterator interface. This provides access to the list of incoming
  429. // basic blocks, which parallels the list of incoming values.
  430. using block_iterator = BasicBlock **;
  431. using const_block_iterator = BasicBlock *const *;
  432. block_iterator block_begin() {
  433. return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
  434. }
  435. const_block_iterator block_begin() const {
  436. return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
  437. }
  438. block_iterator block_end() { return block_begin() + getNumOperands(); }
  439. const_block_iterator block_end() const {
  440. return block_begin() + getNumOperands();
  441. }
  442. iterator_range<block_iterator> blocks() {
  443. return make_range(block_begin(), block_end());
  444. }
  445. iterator_range<const_block_iterator> blocks() const {
  446. return make_range(block_begin(), block_end());
  447. }
  448. op_range incoming_values() { return operands(); }
  449. const_op_range incoming_values() const { return operands(); }
  450. /// Return the number of incoming edges
  451. unsigned getNumIncomingValues() const { return getNumOperands(); }
  452. /// Return incoming value number x
  453. MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); }
  454. void setIncomingValue(unsigned I, MemoryAccess *V) {
  455. assert(V && "PHI node got a null value!");
  456. setOperand(I, V);
  457. }
  458. static unsigned getOperandNumForIncomingValue(unsigned I) { return I; }
  459. static unsigned getIncomingValueNumForOperand(unsigned I) { return I; }
  460. /// Return incoming basic block number @p i.
  461. BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; }
  462. /// Return incoming basic block corresponding
  463. /// to an operand of the PHI.
  464. BasicBlock *getIncomingBlock(const Use &U) const {
  465. assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
  466. return getIncomingBlock(unsigned(&U - op_begin()));
  467. }
  468. /// Return incoming basic block corresponding
  469. /// to value use iterator.
  470. BasicBlock *getIncomingBlock(MemoryAccess::const_user_iterator I) const {
  471. return getIncomingBlock(I.getUse());
  472. }
  473. void setIncomingBlock(unsigned I, BasicBlock *BB) {
  474. assert(BB && "PHI node got a null basic block!");
  475. block_begin()[I] = BB;
  476. }
  477. /// Add an incoming value to the end of the PHI list
  478. void addIncoming(MemoryAccess *V, BasicBlock *BB) {
  479. if (getNumOperands() == ReservedSpace)
  480. growOperands(); // Get more space!
  481. // Initialize some new operands.
  482. setNumHungOffUseOperands(getNumOperands() + 1);
  483. setIncomingValue(getNumOperands() - 1, V);
  484. setIncomingBlock(getNumOperands() - 1, BB);
  485. }
  486. /// Return the first index of the specified basic
  487. /// block in the value list for this PHI. Returns -1 if no instance.
  488. int getBasicBlockIndex(const BasicBlock *BB) const {
  489. for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
  490. if (block_begin()[I] == BB)
  491. return I;
  492. return -1;
  493. }
  494. MemoryAccess *getIncomingValueForBlock(const BasicBlock *BB) const {
  495. int Idx = getBasicBlockIndex(BB);
  496. assert(Idx >= 0 && "Invalid basic block argument!");
  497. return getIncomingValue(Idx);
  498. }
  499. // After deleting incoming position I, the order of incoming may be changed.
  500. void unorderedDeleteIncoming(unsigned I) {
  501. unsigned E = getNumOperands();
  502. assert(I < E && "Cannot remove out of bounds Phi entry.");
  503. // MemoryPhi must have at least two incoming values, otherwise the MemoryPhi
  504. // itself should be deleted.
  505. assert(E >= 2 && "Cannot only remove incoming values in MemoryPhis with "
  506. "at least 2 values.");
  507. setIncomingValue(I, getIncomingValue(E - 1));
  508. setIncomingBlock(I, block_begin()[E - 1]);
  509. setOperand(E - 1, nullptr);
  510. block_begin()[E - 1] = nullptr;
  511. setNumHungOffUseOperands(getNumOperands() - 1);
  512. }
  513. // After deleting entries that satisfy Pred, remaining entries may have
  514. // changed order.
  515. template <typename Fn> void unorderedDeleteIncomingIf(Fn &&Pred) {
  516. for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
  517. if (Pred(getIncomingValue(I), getIncomingBlock(I))) {
  518. unorderedDeleteIncoming(I);
  519. E = getNumOperands();
  520. --I;
  521. }
  522. assert(getNumOperands() >= 1 &&
  523. "Cannot remove all incoming blocks in a MemoryPhi.");
  524. }
  525. // After deleting incoming block BB, the incoming blocks order may be changed.
  526. void unorderedDeleteIncomingBlock(const BasicBlock *BB) {
  527. unorderedDeleteIncomingIf(
  528. [&](const MemoryAccess *, const BasicBlock *B) { return BB == B; });
  529. }
  530. // After deleting incoming memory access MA, the incoming accesses order may
  531. // be changed.
  532. void unorderedDeleteIncomingValue(const MemoryAccess *MA) {
  533. unorderedDeleteIncomingIf(
  534. [&](const MemoryAccess *M, const BasicBlock *) { return MA == M; });
  535. }
  536. static bool classof(const Value *V) {
  537. return V->getValueID() == MemoryPhiVal;
  538. }
  539. void print(raw_ostream &OS) const;
  540. unsigned getID() const { return ID; }
  541. protected:
  542. friend class MemorySSA;
  543. /// this is more complicated than the generic
  544. /// User::allocHungoffUses, because we have to allocate Uses for the incoming
  545. /// values and pointers to the incoming blocks, all in one allocation.
  546. void allocHungoffUses(unsigned N) {
  547. User::allocHungoffUses(N, /* IsPhi */ true);
  548. }
  549. private:
  550. // For debugging only
  551. const unsigned ID;
  552. unsigned ReservedSpace;
  553. /// This grows the operand list in response to a push_back style of
  554. /// operation. This grows the number of ops by 1.5 times.
  555. void growOperands() {
  556. unsigned E = getNumOperands();
  557. // 2 op PHI nodes are VERY common, so reserve at least enough for that.
  558. ReservedSpace = std::max(E + E / 2, 2u);
  559. growHungoffUses(ReservedSpace, /* IsPhi */ true);
  560. }
  561. static void deleteMe(DerivedUser *Self);
  562. };
  563. inline unsigned MemoryAccess::getID() const {
  564. assert((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) &&
  565. "only memory defs and phis have ids");
  566. if (const auto *MD = dyn_cast<MemoryDef>(this))
  567. return MD->getID();
  568. return cast<MemoryPhi>(this)->getID();
  569. }
  570. inline bool MemoryUseOrDef::isOptimized() const {
  571. if (const auto *MD = dyn_cast<MemoryDef>(this))
  572. return MD->isOptimized();
  573. return cast<MemoryUse>(this)->isOptimized();
  574. }
  575. inline MemoryAccess *MemoryUseOrDef::getOptimized() const {
  576. if (const auto *MD = dyn_cast<MemoryDef>(this))
  577. return MD->getOptimized();
  578. return cast<MemoryUse>(this)->getOptimized();
  579. }
  580. inline void MemoryUseOrDef::setOptimized(MemoryAccess *MA) {
  581. if (auto *MD = dyn_cast<MemoryDef>(this))
  582. MD->setOptimized(MA);
  583. else
  584. cast<MemoryUse>(this)->setOptimized(MA);
  585. }
  586. inline void MemoryUseOrDef::resetOptimized() {
  587. if (auto *MD = dyn_cast<MemoryDef>(this))
  588. MD->resetOptimized();
  589. else
  590. cast<MemoryUse>(this)->resetOptimized();
  591. }
  592. template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits<2> {};
  593. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryPhi, MemoryAccess)
  594. /// Encapsulates MemorySSA, including all data associated with memory
  595. /// accesses.
  596. class MemorySSA {
  597. public:
  598. MemorySSA(Function &, AliasAnalysis *, DominatorTree *);
  599. // MemorySSA must remain where it's constructed; Walkers it creates store
  600. // pointers to it.
  601. MemorySSA(MemorySSA &&) = delete;
  602. ~MemorySSA();
  603. MemorySSAWalker *getWalker();
  604. MemorySSAWalker *getSkipSelfWalker();
  605. /// Given a memory Mod/Ref'ing instruction, get the MemorySSA
  606. /// access associated with it. If passed a basic block gets the memory phi
  607. /// node that exists for that block, if there is one. Otherwise, this will get
  608. /// a MemoryUseOrDef.
  609. MemoryUseOrDef *getMemoryAccess(const Instruction *I) const {
  610. return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
  611. }
  612. MemoryPhi *getMemoryAccess(const BasicBlock *BB) const {
  613. return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
  614. }
  615. DominatorTree &getDomTree() const { return *DT; }
  616. void dump() const;
  617. void print(raw_ostream &) const;
  618. /// Return true if \p MA represents the live on entry value
  619. ///
  620. /// Loads and stores from pointer arguments and other global values may be
  621. /// defined by memory operations that do not occur in the current function, so
  622. /// they may be live on entry to the function. MemorySSA represents such
  623. /// memory state by the live on entry definition, which is guaranteed to occur
  624. /// before any other memory access in the function.
  625. inline bool isLiveOnEntryDef(const MemoryAccess *MA) const {
  626. return MA == LiveOnEntryDef.get();
  627. }
  628. inline MemoryAccess *getLiveOnEntryDef() const {
  629. return LiveOnEntryDef.get();
  630. }
  631. // Sadly, iplists, by default, owns and deletes pointers added to the
  632. // list. It's not currently possible to have two iplists for the same type,
  633. // where one owns the pointers, and one does not. This is because the traits
  634. // are per-type, not per-tag. If this ever changes, we should make the
  635. // DefList an iplist.
  636. using AccessList = iplist<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
  637. using DefsList =
  638. simple_ilist<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
  639. /// Return the list of MemoryAccess's for a given basic block.
  640. ///
  641. /// This list is not modifiable by the user.
  642. const AccessList *getBlockAccesses(const BasicBlock *BB) const {
  643. return getWritableBlockAccesses(BB);
  644. }
  645. /// Return the list of MemoryDef's and MemoryPhi's for a given basic
  646. /// block.
  647. ///
  648. /// This list is not modifiable by the user.
  649. const DefsList *getBlockDefs(const BasicBlock *BB) const {
  650. return getWritableBlockDefs(BB);
  651. }
  652. /// Given two memory accesses in the same basic block, determine
  653. /// whether MemoryAccess \p A dominates MemoryAccess \p B.
  654. bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const;
  655. /// Given two memory accesses in potentially different blocks,
  656. /// determine whether MemoryAccess \p A dominates MemoryAccess \p B.
  657. bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;
  658. /// Given a MemoryAccess and a Use, determine whether MemoryAccess \p A
  659. /// dominates Use \p B.
  660. bool dominates(const MemoryAccess *A, const Use &B) const;
  661. /// Verify that MemorySSA is self consistent (IE definitions dominate
  662. /// all uses, uses appear in the right places). This is used by unit tests.
  663. void verifyMemorySSA() const;
  664. /// Used in various insertion functions to specify whether we are talking
  665. /// about the beginning or end of a block.
  666. enum InsertionPlace { Beginning, End, BeforeTerminator };
  667. protected:
  668. // Used by Memory SSA annotater, dumpers, and wrapper pass
  669. friend class MemorySSAAnnotatedWriter;
  670. friend class MemorySSAPrinterLegacyPass;
  671. friend class MemorySSAUpdater;
  672. void verifyOrderingDominationAndDefUses(Function &F) const;
  673. void verifyDominationNumbers(const Function &F) const;
  674. void verifyPrevDefInPhis(Function &F) const;
  675. // This is used by the use optimizer and updater.
  676. AccessList *getWritableBlockAccesses(const BasicBlock *BB) const {
  677. auto It = PerBlockAccesses.find(BB);
  678. return It == PerBlockAccesses.end() ? nullptr : It->second.get();
  679. }
  680. // This is used by the use optimizer and updater.
  681. DefsList *getWritableBlockDefs(const BasicBlock *BB) const {
  682. auto It = PerBlockDefs.find(BB);
  683. return It == PerBlockDefs.end() ? nullptr : It->second.get();
  684. }
  685. // These is used by the updater to perform various internal MemorySSA
  686. // machinsations. They do not always leave the IR in a correct state, and
  687. // relies on the updater to fixup what it breaks, so it is not public.
  688. void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where);
  689. void moveTo(MemoryAccess *What, BasicBlock *BB, InsertionPlace Point);
  690. // Rename the dominator tree branch rooted at BB.
  691. void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal,
  692. SmallPtrSetImpl<BasicBlock *> &Visited) {
  693. renamePass(DT->getNode(BB), IncomingVal, Visited, true, true);
  694. }
  695. void removeFromLookups(MemoryAccess *);
  696. void removeFromLists(MemoryAccess *, bool ShouldDelete = true);
  697. void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *,
  698. InsertionPlace);
  699. void insertIntoListsBefore(MemoryAccess *, const BasicBlock *,
  700. AccessList::iterator);
  701. MemoryUseOrDef *createDefinedAccess(Instruction *, MemoryAccess *,
  702. const MemoryUseOrDef *Template = nullptr,
  703. bool CreationMustSucceed = true);
  704. private:
  705. template <class AliasAnalysisType> class ClobberWalkerBase;
  706. template <class AliasAnalysisType> class CachingWalker;
  707. template <class AliasAnalysisType> class SkipSelfWalker;
  708. class OptimizeUses;
  709. CachingWalker<AliasAnalysis> *getWalkerImpl();
  710. void buildMemorySSA(BatchAAResults &BAA);
  711. void prepareForMoveTo(MemoryAccess *, BasicBlock *);
  712. void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;
  713. using AccessMap = DenseMap<const BasicBlock *, std::unique_ptr<AccessList>>;
  714. using DefsMap = DenseMap<const BasicBlock *, std::unique_ptr<DefsList>>;
  715. void markUnreachableAsLiveOnEntry(BasicBlock *BB);
  716. MemoryPhi *createMemoryPhi(BasicBlock *BB);
  717. template <typename AliasAnalysisType>
  718. MemoryUseOrDef *createNewAccess(Instruction *, AliasAnalysisType *,
  719. const MemoryUseOrDef *Template = nullptr);
  720. void placePHINodes(const SmallPtrSetImpl<BasicBlock *> &);
  721. MemoryAccess *renameBlock(BasicBlock *, MemoryAccess *, bool);
  722. void renameSuccessorPhis(BasicBlock *, MemoryAccess *, bool);
  723. void renamePass(DomTreeNode *, MemoryAccess *IncomingVal,
  724. SmallPtrSetImpl<BasicBlock *> &Visited,
  725. bool SkipVisited = false, bool RenameAllUses = false);
  726. AccessList *getOrCreateAccessList(const BasicBlock *);
  727. DefsList *getOrCreateDefsList(const BasicBlock *);
  728. void renumberBlock(const BasicBlock *) const;
  729. AliasAnalysis *AA;
  730. DominatorTree *DT;
  731. Function &F;
  732. // Memory SSA mappings
  733. DenseMap<const Value *, MemoryAccess *> ValueToMemoryAccess;
  734. // These two mappings contain the main block to access/def mappings for
  735. // MemorySSA. The list contained in PerBlockAccesses really owns all the
  736. // MemoryAccesses.
  737. // Both maps maintain the invariant that if a block is found in them, the
  738. // corresponding list is not empty, and if a block is not found in them, the
  739. // corresponding list is empty.
  740. AccessMap PerBlockAccesses;
  741. DefsMap PerBlockDefs;
  742. std::unique_ptr<MemoryAccess, ValueDeleter> LiveOnEntryDef;
  743. // Domination mappings
  744. // Note that the numbering is local to a block, even though the map is
  745. // global.
  746. mutable SmallPtrSet<const BasicBlock *, 16> BlockNumberingValid;
  747. mutable DenseMap<const MemoryAccess *, unsigned long> BlockNumbering;
  748. // Memory SSA building info
  749. std::unique_ptr<ClobberWalkerBase<AliasAnalysis>> WalkerBase;
  750. std::unique_ptr<CachingWalker<AliasAnalysis>> Walker;
  751. std::unique_ptr<SkipSelfWalker<AliasAnalysis>> SkipWalker;
  752. unsigned NextID;
  753. };
  754. // Internal MemorySSA utils, for use by MemorySSA classes and walkers
  755. class MemorySSAUtil {
  756. protected:
  757. friend class GVNHoist;
  758. friend class MemorySSAWalker;
  759. // This function should not be used by new passes.
  760. static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
  761. AliasAnalysis &AA);
  762. };
  763. // This pass does eager building and then printing of MemorySSA. It is used by
  764. // the tests to be able to build, dump, and verify Memory SSA.
  765. class MemorySSAPrinterLegacyPass : public FunctionPass {
  766. public:
  767. MemorySSAPrinterLegacyPass();
  768. bool runOnFunction(Function &) override;
  769. void getAnalysisUsage(AnalysisUsage &AU) const override;
  770. static char ID;
  771. };
  772. /// An analysis that produces \c MemorySSA for a function.
  773. ///
  774. class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> {
  775. friend AnalysisInfoMixin<MemorySSAAnalysis>;
  776. static AnalysisKey Key;
  777. public:
  778. // Wrap MemorySSA result to ensure address stability of internal MemorySSA
  779. // pointers after construction. Use a wrapper class instead of plain
  780. // unique_ptr<MemorySSA> to avoid build breakage on MSVC.
  781. struct Result {
  782. Result(std::unique_ptr<MemorySSA> &&MSSA) : MSSA(std::move(MSSA)) {}
  783. MemorySSA &getMSSA() { return *MSSA.get(); }
  784. std::unique_ptr<MemorySSA> MSSA;
  785. bool invalidate(Function &F, const PreservedAnalyses &PA,
  786. FunctionAnalysisManager::Invalidator &Inv);
  787. };
  788. Result run(Function &F, FunctionAnalysisManager &AM);
  789. };
  790. /// Printer pass for \c MemorySSA.
  791. class MemorySSAPrinterPass : public PassInfoMixin<MemorySSAPrinterPass> {
  792. raw_ostream &OS;
  793. public:
  794. explicit MemorySSAPrinterPass(raw_ostream &OS) : OS(OS) {}
  795. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  796. };
  797. /// Verifier pass for \c MemorySSA.
  798. struct MemorySSAVerifierPass : PassInfoMixin<MemorySSAVerifierPass> {
  799. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  800. };
  801. /// Legacy analysis pass which computes \c MemorySSA.
  802. class MemorySSAWrapperPass : public FunctionPass {
  803. public:
  804. MemorySSAWrapperPass();
  805. static char ID;
  806. bool runOnFunction(Function &) override;
  807. void releaseMemory() override;
  808. MemorySSA &getMSSA() { return *MSSA; }
  809. const MemorySSA &getMSSA() const { return *MSSA; }
  810. void getAnalysisUsage(AnalysisUsage &AU) const override;
  811. void verifyAnalysis() const override;
  812. void print(raw_ostream &OS, const Module *M = nullptr) const override;
  813. private:
  814. std::unique_ptr<MemorySSA> MSSA;
  815. };
  816. /// This is the generic walker interface for walkers of MemorySSA.
  817. /// Walkers are used to be able to further disambiguate the def-use chains
  818. /// MemorySSA gives you, or otherwise produce better info than MemorySSA gives
  819. /// you.
  820. /// In particular, while the def-use chains provide basic information, and are
  821. /// guaranteed to give, for example, the nearest may-aliasing MemoryDef for a
  822. /// MemoryUse as AliasAnalysis considers it, a user mant want better or other
  823. /// information. In particular, they may want to use SCEV info to further
  824. /// disambiguate memory accesses, or they may want the nearest dominating
  825. /// may-aliasing MemoryDef for a call or a store. This API enables a
  826. /// standardized interface to getting and using that info.
  827. class MemorySSAWalker {
  828. public:
  829. MemorySSAWalker(MemorySSA *);
  830. virtual ~MemorySSAWalker() = default;
  831. using MemoryAccessSet = SmallVector<MemoryAccess *, 8>;
  832. /// Given a memory Mod/Ref/ModRef'ing instruction, calling this
  833. /// will give you the nearest dominating MemoryAccess that Mod's the location
  834. /// the instruction accesses (by skipping any def which AA can prove does not
  835. /// alias the location(s) accessed by the instruction given).
  836. ///
  837. /// Note that this will return a single access, and it must dominate the
  838. /// Instruction, so if an operand of a MemoryPhi node Mod's the instruction,
  839. /// this will return the MemoryPhi, not the operand. This means that
  840. /// given:
  841. /// if (a) {
  842. /// 1 = MemoryDef(liveOnEntry)
  843. /// store %a
  844. /// } else {
  845. /// 2 = MemoryDef(liveOnEntry)
  846. /// store %b
  847. /// }
  848. /// 3 = MemoryPhi(2, 1)
  849. /// MemoryUse(3)
  850. /// load %a
  851. ///
  852. /// calling this API on load(%a) will return the MemoryPhi, not the MemoryDef
  853. /// in the if (a) branch.
  854. MemoryAccess *getClobberingMemoryAccess(const Instruction *I) {
  855. MemoryAccess *MA = MSSA->getMemoryAccess(I);
  856. assert(MA && "Handed an instruction that MemorySSA doesn't recognize?");
  857. return getClobberingMemoryAccess(MA);
  858. }
  859. /// Does the same thing as getClobberingMemoryAccess(const Instruction *I),
  860. /// but takes a MemoryAccess instead of an Instruction.
  861. virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) = 0;
  862. /// Given a potentially clobbering memory access and a new location,
  863. /// calling this will give you the nearest dominating clobbering MemoryAccess
  864. /// (by skipping non-aliasing def links).
  865. ///
  866. /// This version of the function is mainly used to disambiguate phi translated
  867. /// pointers, where the value of a pointer may have changed from the initial
  868. /// memory access. Note that this expects to be handed either a MemoryUse,
  869. /// or an already potentially clobbering access. Unlike the above API, if
  870. /// given a MemoryDef that clobbers the pointer as the starting access, it
  871. /// will return that MemoryDef, whereas the above would return the clobber
  872. /// starting from the use side of the memory def.
  873. virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
  874. const MemoryLocation &) = 0;
  875. /// Given a memory access, invalidate anything this walker knows about
  876. /// that access.
  877. /// This API is used by walkers that store information to perform basic cache
  878. /// invalidation. This will be called by MemorySSA at appropriate times for
  879. /// the walker it uses or returns.
  880. virtual void invalidateInfo(MemoryAccess *) {}
  881. protected:
  882. friend class MemorySSA; // For updating MSSA pointer in MemorySSA move
  883. // constructor.
  884. MemorySSA *MSSA;
  885. };
  886. /// A MemorySSAWalker that does no alias queries, or anything else. It
  887. /// simply returns the links as they were constructed by the builder.
  888. class DoNothingMemorySSAWalker final : public MemorySSAWalker {
  889. public:
  890. // Keep the overrides below from hiding the Instruction overload of
  891. // getClobberingMemoryAccess.
  892. using MemorySSAWalker::getClobberingMemoryAccess;
  893. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
  894. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
  895. const MemoryLocation &) override;
  896. };
  897. using MemoryAccessPair = std::pair<MemoryAccess *, MemoryLocation>;
  898. using ConstMemoryAccessPair = std::pair<const MemoryAccess *, MemoryLocation>;
  899. /// Iterator base class used to implement const and non-const iterators
  900. /// over the defining accesses of a MemoryAccess.
  901. template <class T>
  902. class memoryaccess_def_iterator_base
  903. : public iterator_facade_base<memoryaccess_def_iterator_base<T>,
  904. std::forward_iterator_tag, T, ptrdiff_t, T *,
  905. T *> {
  906. using BaseT = typename memoryaccess_def_iterator_base::iterator_facade_base;
  907. public:
  908. memoryaccess_def_iterator_base(T *Start) : Access(Start) {}
  909. memoryaccess_def_iterator_base() = default;
  910. bool operator==(const memoryaccess_def_iterator_base &Other) const {
  911. return Access == Other.Access && (!Access || ArgNo == Other.ArgNo);
  912. }
  913. // This is a bit ugly, but for MemoryPHI's, unlike PHINodes, you can't get the
  914. // block from the operand in constant time (In a PHINode, the uselist has
  915. // both, so it's just subtraction). We provide it as part of the
  916. // iterator to avoid callers having to linear walk to get the block.
  917. // If the operation becomes constant time on MemoryPHI's, this bit of
  918. // abstraction breaking should be removed.
  919. BasicBlock *getPhiArgBlock() const {
  920. MemoryPhi *MP = dyn_cast<MemoryPhi>(Access);
  921. assert(MP && "Tried to get phi arg block when not iterating over a PHI");
  922. return MP->getIncomingBlock(ArgNo);
  923. }
  924. typename BaseT::iterator::pointer operator*() const {
  925. assert(Access && "Tried to access past the end of our iterator");
  926. // Go to the first argument for phis, and the defining access for everything
  927. // else.
  928. if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access))
  929. return MP->getIncomingValue(ArgNo);
  930. return cast<MemoryUseOrDef>(Access)->getDefiningAccess();
  931. }
  932. using BaseT::operator++;
  933. memoryaccess_def_iterator_base &operator++() {
  934. assert(Access && "Hit end of iterator");
  935. if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) {
  936. if (++ArgNo >= MP->getNumIncomingValues()) {
  937. ArgNo = 0;
  938. Access = nullptr;
  939. }
  940. } else {
  941. Access = nullptr;
  942. }
  943. return *this;
  944. }
  945. private:
  946. T *Access = nullptr;
  947. unsigned ArgNo = 0;
  948. };
  949. inline memoryaccess_def_iterator MemoryAccess::defs_begin() {
  950. return memoryaccess_def_iterator(this);
  951. }
  952. inline const_memoryaccess_def_iterator MemoryAccess::defs_begin() const {
  953. return const_memoryaccess_def_iterator(this);
  954. }
  955. inline memoryaccess_def_iterator MemoryAccess::defs_end() {
  956. return memoryaccess_def_iterator();
  957. }
  958. inline const_memoryaccess_def_iterator MemoryAccess::defs_end() const {
  959. return const_memoryaccess_def_iterator();
  960. }
  961. /// GraphTraits for a MemoryAccess, which walks defs in the normal case,
  962. /// and uses in the inverse case.
  963. template <> struct GraphTraits<MemoryAccess *> {
  964. using NodeRef = MemoryAccess *;
  965. using ChildIteratorType = memoryaccess_def_iterator;
  966. static NodeRef getEntryNode(NodeRef N) { return N; }
  967. static ChildIteratorType child_begin(NodeRef N) { return N->defs_begin(); }
  968. static ChildIteratorType child_end(NodeRef N) { return N->defs_end(); }
  969. };
  970. template <> struct GraphTraits<Inverse<MemoryAccess *>> {
  971. using NodeRef = MemoryAccess *;
  972. using ChildIteratorType = MemoryAccess::iterator;
  973. static NodeRef getEntryNode(NodeRef N) { return N; }
  974. static ChildIteratorType child_begin(NodeRef N) { return N->user_begin(); }
  975. static ChildIteratorType child_end(NodeRef N) { return N->user_end(); }
  976. };
  977. /// Provide an iterator that walks defs, giving both the memory access,
  978. /// and the current pointer location, updating the pointer location as it
  979. /// changes due to phi node translation.
  980. ///
  981. /// This iterator, while somewhat specialized, is what most clients actually
  982. /// want when walking upwards through MemorySSA def chains. It takes a pair of
  983. /// <MemoryAccess,MemoryLocation>, and walks defs, properly translating the
  984. /// memory location through phi nodes for the user.
  985. class upward_defs_iterator
  986. : public iterator_facade_base<upward_defs_iterator,
  987. std::forward_iterator_tag,
  988. const MemoryAccessPair> {
  989. using BaseT = upward_defs_iterator::iterator_facade_base;
  990. public:
  991. upward_defs_iterator(const MemoryAccessPair &Info, DominatorTree *DT,
  992. bool *PerformedPhiTranslation = nullptr)
  993. : DefIterator(Info.first), Location(Info.second),
  994. OriginalAccess(Info.first), DT(DT),
  995. PerformedPhiTranslation(PerformedPhiTranslation) {
  996. CurrentPair.first = nullptr;
  997. WalkingPhi = Info.first && isa<MemoryPhi>(Info.first);
  998. fillInCurrentPair();
  999. }
  1000. upward_defs_iterator() { CurrentPair.first = nullptr; }
  1001. bool operator==(const upward_defs_iterator &Other) const {
  1002. return DefIterator == Other.DefIterator;
  1003. }
  1004. BaseT::iterator::reference operator*() const {
  1005. assert(DefIterator != OriginalAccess->defs_end() &&
  1006. "Tried to access past the end of our iterator");
  1007. return CurrentPair;
  1008. }
  1009. using BaseT::operator++;
  1010. upward_defs_iterator &operator++() {
  1011. assert(DefIterator != OriginalAccess->defs_end() &&
  1012. "Tried to access past the end of the iterator");
  1013. ++DefIterator;
  1014. if (DefIterator != OriginalAccess->defs_end())
  1015. fillInCurrentPair();
  1016. return *this;
  1017. }
  1018. BasicBlock *getPhiArgBlock() const { return DefIterator.getPhiArgBlock(); }
  1019. private:
  1020. /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible
  1021. /// loop. In particular, this guarantees that it only references a single
  1022. /// MemoryLocation during execution of the containing function.
  1023. bool IsGuaranteedLoopInvariant(Value *Ptr) const;
  1024. void fillInCurrentPair() {
  1025. CurrentPair.first = *DefIterator;
  1026. CurrentPair.second = Location;
  1027. if (WalkingPhi && Location.Ptr) {
  1028. // Mark size as unknown, if the location is not guaranteed to be
  1029. // loop-invariant for any possible loop in the function. Setting the size
  1030. // to unknown guarantees that any memory accesses that access locations
  1031. // after the pointer are considered as clobbers, which is important to
  1032. // catch loop carried dependences.
  1033. if (Location.Ptr &&
  1034. !IsGuaranteedLoopInvariant(const_cast<Value *>(Location.Ptr)))
  1035. CurrentPair.second =
  1036. Location.getWithNewSize(LocationSize::beforeOrAfterPointer());
  1037. PHITransAddr Translator(
  1038. const_cast<Value *>(Location.Ptr),
  1039. OriginalAccess->getBlock()->getModule()->getDataLayout(), nullptr);
  1040. if (!Translator.PHITranslateValue(OriginalAccess->getBlock(),
  1041. DefIterator.getPhiArgBlock(), DT,
  1042. true)) {
  1043. Value *TransAddr = Translator.getAddr();
  1044. if (TransAddr != Location.Ptr) {
  1045. CurrentPair.second = CurrentPair.second.getWithNewPtr(TransAddr);
  1046. if (TransAddr &&
  1047. !IsGuaranteedLoopInvariant(const_cast<Value *>(TransAddr)))
  1048. CurrentPair.second = CurrentPair.second.getWithNewSize(
  1049. LocationSize::beforeOrAfterPointer());
  1050. if (PerformedPhiTranslation)
  1051. *PerformedPhiTranslation = true;
  1052. }
  1053. }
  1054. }
  1055. }
  1056. MemoryAccessPair CurrentPair;
  1057. memoryaccess_def_iterator DefIterator;
  1058. MemoryLocation Location;
  1059. MemoryAccess *OriginalAccess = nullptr;
  1060. DominatorTree *DT = nullptr;
  1061. bool WalkingPhi = false;
  1062. bool *PerformedPhiTranslation = nullptr;
  1063. };
  1064. inline upward_defs_iterator
  1065. upward_defs_begin(const MemoryAccessPair &Pair, DominatorTree &DT,
  1066. bool *PerformedPhiTranslation = nullptr) {
  1067. return upward_defs_iterator(Pair, &DT, PerformedPhiTranslation);
  1068. }
  1069. inline upward_defs_iterator upward_defs_end() { return upward_defs_iterator(); }
  1070. inline iterator_range<upward_defs_iterator>
  1071. upward_defs(const MemoryAccessPair &Pair, DominatorTree &DT) {
  1072. return make_range(upward_defs_begin(Pair, DT), upward_defs_end());
  1073. }
  1074. /// Walks the defining accesses of MemoryDefs. Stops after we hit something that
  1075. /// has no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when
  1076. /// comparing against a null def_chain_iterator, this will compare equal only
  1077. /// after walking said Phi/liveOnEntry.
  1078. ///
  1079. /// The UseOptimizedChain flag specifies whether to walk the clobbering
  1080. /// access chain, or all the accesses.
  1081. ///
  1082. /// Normally, MemoryDef are all just def/use linked together, so a def_chain on
  1083. /// a MemoryDef will walk all MemoryDefs above it in the program until it hits
  1084. /// a phi node. The optimized chain walks the clobbering access of a store.
  1085. /// So if you are just trying to find, given a store, what the next
  1086. /// thing that would clobber the same memory is, you want the optimized chain.
  1087. template <class T, bool UseOptimizedChain = false>
  1088. struct def_chain_iterator
  1089. : public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>,
  1090. std::forward_iterator_tag, MemoryAccess *> {
  1091. def_chain_iterator() : MA(nullptr) {}
  1092. def_chain_iterator(T MA) : MA(MA) {}
  1093. T operator*() const { return MA; }
  1094. def_chain_iterator &operator++() {
  1095. // N.B. liveOnEntry has a null defining access.
  1096. if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
  1097. if (UseOptimizedChain && MUD->isOptimized())
  1098. MA = MUD->getOptimized();
  1099. else
  1100. MA = MUD->getDefiningAccess();
  1101. } else {
  1102. MA = nullptr;
  1103. }
  1104. return *this;
  1105. }
  1106. bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
  1107. private:
  1108. T MA;
  1109. };
  1110. template <class T>
  1111. inline iterator_range<def_chain_iterator<T>>
  1112. def_chain(T MA, MemoryAccess *UpTo = nullptr) {
  1113. #ifdef EXPENSIVE_CHECKS
  1114. assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) &&
  1115. "UpTo isn't in the def chain!");
  1116. #endif
  1117. return make_range(def_chain_iterator<T>(MA), def_chain_iterator<T>(UpTo));
  1118. }
  1119. template <class T>
  1120. inline iterator_range<def_chain_iterator<T, true>> optimized_def_chain(T MA) {
  1121. return make_range(def_chain_iterator<T, true>(MA),
  1122. def_chain_iterator<T, true>(nullptr));
  1123. }
  1124. } // end namespace llvm
  1125. #endif // LLVM_ANALYSIS_MEMORYSSA_H
  1126. #ifdef __GNUC__
  1127. #pragma GCC diagnostic pop
  1128. #endif