TypeBasedAliasAnalysis.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. //===- TypeBasedAliasAnalysis.cpp - Type-Based Alias Analysis -------------===//
  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 TypeBasedAliasAnalysis pass, which implements
  11. // metadata-based TBAA.
  12. //
  13. // In LLVM IR, memory does not have types, so LLVM's own type system is not
  14. // suitable for doing TBAA. Instead, metadata is added to the IR to describe
  15. // a type system of a higher level language. This can be used to implement
  16. // typical C/C++ TBAA, but it can also be used to implement custom alias
  17. // analysis behavior for other languages.
  18. //
  19. // We now support two types of metadata format: scalar TBAA and struct-path
  20. // aware TBAA. After all testing cases are upgraded to use struct-path aware
  21. // TBAA and we can auto-upgrade existing bc files, the support for scalar TBAA
  22. // can be dropped.
  23. //
  24. // The scalar TBAA metadata format is very simple. TBAA MDNodes have up to
  25. // three fields, e.g.:
  26. // !0 = metadata !{ metadata !"an example type tree" }
  27. // !1 = metadata !{ metadata !"int", metadata !0 }
  28. // !2 = metadata !{ metadata !"float", metadata !0 }
  29. // !3 = metadata !{ metadata !"const float", metadata !2, i64 1 }
  30. //
  31. // The first field is an identity field. It can be any value, usually
  32. // an MDString, which uniquely identifies the type. The most important
  33. // name in the tree is the name of the root node. Two trees with
  34. // different root node names are entirely disjoint, even if they
  35. // have leaves with common names.
  36. //
  37. // The second field identifies the type's parent node in the tree, or
  38. // is null or omitted for a root node. A type is considered to alias
  39. // all of its descendants and all of its ancestors in the tree. Also,
  40. // a type is considered to alias all types in other trees, so that
  41. // bitcode produced from multiple front-ends is handled conservatively.
  42. //
  43. // If the third field is present, it's an integer which if equal to 1
  44. // indicates that the type is "constant" (meaning pointsToConstantMemory
  45. // should return true; see
  46. // http://llvm.org/docs/AliasAnalysis.html#OtherItfs).
  47. //
  48. // With struct-path aware TBAA, the MDNodes attached to an instruction using
  49. // "!tbaa" are called path tag nodes.
  50. //
  51. // The path tag node has 4 fields with the last field being optional.
  52. //
  53. // The first field is the base type node, it can be a struct type node
  54. // or a scalar type node. The second field is the access type node, it
  55. // must be a scalar type node. The third field is the offset into the base type.
  56. // The last field has the same meaning as the last field of our scalar TBAA:
  57. // it's an integer which if equal to 1 indicates that the access is "constant".
  58. //
  59. // The struct type node has a name and a list of pairs, one pair for each member
  60. // of the struct. The first element of each pair is a type node (a struct type
  61. // node or a sclar type node), specifying the type of the member, the second
  62. // element of each pair is the offset of the member.
  63. //
  64. // Given an example
  65. // typedef struct {
  66. // short s;
  67. // } A;
  68. // typedef struct {
  69. // uint16_t s;
  70. // A a;
  71. // } B;
  72. //
  73. // For an acess to B.a.s, we attach !5 (a path tag node) to the load/store
  74. // instruction. The base type is !4 (struct B), the access type is !2 (scalar
  75. // type short) and the offset is 4.
  76. //
  77. // !0 = metadata !{metadata !"Simple C/C++ TBAA"}
  78. // !1 = metadata !{metadata !"omnipotent char", metadata !0} // Scalar type node
  79. // !2 = metadata !{metadata !"short", metadata !1} // Scalar type node
  80. // !3 = metadata !{metadata !"A", metadata !2, i64 0} // Struct type node
  81. // !4 = metadata !{metadata !"B", metadata !2, i64 0, metadata !3, i64 4}
  82. // // Struct type node
  83. // !5 = metadata !{metadata !4, metadata !2, i64 4} // Path tag node
  84. //
  85. // The struct type nodes and the scalar type nodes form a type DAG.
  86. // Root (!0)
  87. // char (!1) -- edge to Root
  88. // short (!2) -- edge to char
  89. // A (!3) -- edge with offset 0 to short
  90. // B (!4) -- edge with offset 0 to short and edge with offset 4 to A
  91. //
  92. // To check if two tags (tagX and tagY) can alias, we start from the base type
  93. // of tagX, follow the edge with the correct offset in the type DAG and adjust
  94. // the offset until we reach the base type of tagY or until we reach the Root
  95. // node.
  96. // If we reach the base type of tagY, compare the adjusted offset with
  97. // offset of tagY, return Alias if the offsets are the same, return NoAlias
  98. // otherwise.
  99. // If we reach the Root node, perform the above starting from base type of tagY
  100. // to see if we reach base type of tagX.
  101. //
  102. // If they have different roots, they're part of different potentially
  103. // unrelated type systems, so we return Alias to be conservative.
  104. // If neither node is an ancestor of the other and they have the same root,
  105. // then we say NoAlias.
  106. //
  107. // TODO: The current metadata format doesn't support struct
  108. // fields. For example:
  109. // struct X {
  110. // double d;
  111. // int i;
  112. // };
  113. // void foo(struct X *x, struct X *y, double *p) {
  114. // *x = *y;
  115. // *p = 0.0;
  116. // }
  117. // Struct X has a double member, so the store to *x can alias the store to *p.
  118. // Currently it's not possible to precisely describe all the things struct X
  119. // aliases, so struct assignments must use conservative TBAA nodes. There's
  120. // no scheme for attaching metadata to @llvm.memcpy yet either.
  121. //
  122. //===----------------------------------------------------------------------===//
  123. #include "llvm/Analysis/Passes.h"
  124. #include "llvm/Analysis/AliasAnalysis.h"
  125. #include "llvm/IR/Constants.h"
  126. #include "llvm/IR/LLVMContext.h"
  127. #include "llvm/IR/Metadata.h"
  128. #include "llvm/IR/Module.h"
  129. #include "llvm/Pass.h"
  130. #include "llvm/Support/CommandLine.h"
  131. #include "llvm/ADT/SetVector.h"
  132. using namespace llvm;
  133. // A handy option for disabling TBAA functionality. The same effect can also be
  134. // achieved by stripping the !tbaa tags from IR, but this option is sometimes
  135. // more convenient.
  136. #if 0 // HLSL Change Starts - option pending
  137. static cl::opt<bool> EnableTBAA("enable-tbaa", cl::init(true));
  138. #else
  139. static const bool EnableTBAA = true;
  140. #endif // HLSL Change Ends
  141. namespace {
  142. /// TBAANode - This is a simple wrapper around an MDNode which provides a
  143. /// higher-level interface by hiding the details of how alias analysis
  144. /// information is encoded in its operands.
  145. class TBAANode {
  146. const MDNode *Node;
  147. public:
  148. TBAANode() : Node(nullptr) {}
  149. explicit TBAANode(const MDNode *N) : Node(N) {}
  150. /// getNode - Get the MDNode for this TBAANode.
  151. const MDNode *getNode() const { return Node; }
  152. /// getParent - Get this TBAANode's Alias tree parent.
  153. TBAANode getParent() const {
  154. if (Node->getNumOperands() < 2)
  155. return TBAANode();
  156. MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1));
  157. if (!P)
  158. return TBAANode();
  159. // Ok, this node has a valid parent. Return it.
  160. return TBAANode(P);
  161. }
  162. /// TypeIsImmutable - Test if this TBAANode represents a type for objects
  163. /// which are not modified (by any means) in the context where this
  164. /// AliasAnalysis is relevant.
  165. bool TypeIsImmutable() const {
  166. if (Node->getNumOperands() < 3)
  167. return false;
  168. ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Node->getOperand(2));
  169. if (!CI)
  170. return false;
  171. return CI->getValue()[0];
  172. }
  173. };
  174. /// This is a simple wrapper around an MDNode which provides a
  175. /// higher-level interface by hiding the details of how alias analysis
  176. /// information is encoded in its operands.
  177. class TBAAStructTagNode {
  178. /// This node should be created with createTBAAStructTagNode.
  179. const MDNode *Node;
  180. public:
  181. explicit TBAAStructTagNode(const MDNode *N) : Node(N) {}
  182. /// Get the MDNode for this TBAAStructTagNode.
  183. const MDNode *getNode() const { return Node; }
  184. const MDNode *getBaseType() const {
  185. return dyn_cast_or_null<MDNode>(Node->getOperand(0));
  186. }
  187. const MDNode *getAccessType() const {
  188. return dyn_cast_or_null<MDNode>(Node->getOperand(1));
  189. }
  190. uint64_t getOffset() const {
  191. return mdconst::extract<ConstantInt>(Node->getOperand(2))->getZExtValue();
  192. }
  193. /// TypeIsImmutable - Test if this TBAAStructTagNode represents a type for
  194. /// objects which are not modified (by any means) in the context where this
  195. /// AliasAnalysis is relevant.
  196. bool TypeIsImmutable() const {
  197. if (Node->getNumOperands() < 4)
  198. return false;
  199. ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Node->getOperand(3));
  200. if (!CI)
  201. return false;
  202. return CI->getValue()[0];
  203. }
  204. };
  205. /// This is a simple wrapper around an MDNode which provides a
  206. /// higher-level interface by hiding the details of how alias analysis
  207. /// information is encoded in its operands.
  208. class TBAAStructTypeNode {
  209. /// This node should be created with createTBAAStructTypeNode.
  210. const MDNode *Node;
  211. public:
  212. TBAAStructTypeNode() : Node(nullptr) {}
  213. explicit TBAAStructTypeNode(const MDNode *N) : Node(N) {}
  214. /// Get the MDNode for this TBAAStructTypeNode.
  215. const MDNode *getNode() const { return Node; }
  216. /// Get this TBAAStructTypeNode's field in the type DAG with
  217. /// given offset. Update the offset to be relative to the field type.
  218. TBAAStructTypeNode getParent(uint64_t &Offset) const {
  219. // Parent can be omitted for the root node.
  220. if (Node->getNumOperands() < 2)
  221. return TBAAStructTypeNode();
  222. // Fast path for a scalar type node and a struct type node with a single
  223. // field.
  224. if (Node->getNumOperands() <= 3) {
  225. uint64_t Cur = Node->getNumOperands() == 2
  226. ? 0
  227. : mdconst::extract<ConstantInt>(Node->getOperand(2))
  228. ->getZExtValue();
  229. Offset -= Cur;
  230. MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1));
  231. if (!P)
  232. return TBAAStructTypeNode();
  233. return TBAAStructTypeNode(P);
  234. }
  235. // Assume the offsets are in order. We return the previous field if
  236. // the current offset is bigger than the given offset.
  237. unsigned TheIdx = 0;
  238. for (unsigned Idx = 1; Idx < Node->getNumOperands(); Idx += 2) {
  239. uint64_t Cur = mdconst::extract<ConstantInt>(Node->getOperand(Idx + 1))
  240. ->getZExtValue();
  241. if (Cur > Offset) {
  242. assert(Idx >= 3 &&
  243. "TBAAStructTypeNode::getParent should have an offset match!");
  244. TheIdx = Idx - 2;
  245. break;
  246. }
  247. }
  248. // Move along the last field.
  249. if (TheIdx == 0)
  250. TheIdx = Node->getNumOperands() - 2;
  251. uint64_t Cur = mdconst::extract<ConstantInt>(Node->getOperand(TheIdx + 1))
  252. ->getZExtValue();
  253. Offset -= Cur;
  254. MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(TheIdx));
  255. if (!P)
  256. return TBAAStructTypeNode();
  257. return TBAAStructTypeNode(P);
  258. }
  259. };
  260. }
  261. namespace {
  262. /// TypeBasedAliasAnalysis - This is a simple alias analysis
  263. /// implementation that uses TypeBased to answer queries.
  264. class TypeBasedAliasAnalysis : public ImmutablePass,
  265. public AliasAnalysis {
  266. public:
  267. static char ID; // Class identification, replacement for typeinfo
  268. TypeBasedAliasAnalysis() : ImmutablePass(ID) {
  269. initializeTypeBasedAliasAnalysisPass(*PassRegistry::getPassRegistry());
  270. }
  271. bool doInitialization(Module &M) override;
  272. /// getAdjustedAnalysisPointer - This method is used when a pass implements
  273. /// an analysis interface through multiple inheritance. If needed, it
  274. /// should override this to adjust the this pointer as needed for the
  275. /// specified pass info.
  276. void *getAdjustedAnalysisPointer(const void *PI) override {
  277. if (PI == &AliasAnalysis::ID)
  278. return (AliasAnalysis*)this;
  279. return this;
  280. }
  281. bool Aliases(const MDNode *A, const MDNode *B) const;
  282. bool PathAliases(const MDNode *A, const MDNode *B) const;
  283. private:
  284. void getAnalysisUsage(AnalysisUsage &AU) const override;
  285. AliasResult alias(const MemoryLocation &LocA,
  286. const MemoryLocation &LocB) override;
  287. bool pointsToConstantMemory(const MemoryLocation &Loc,
  288. bool OrLocal) override;
  289. ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
  290. ModRefBehavior getModRefBehavior(const Function *F) override;
  291. ModRefResult getModRefInfo(ImmutableCallSite CS,
  292. const MemoryLocation &Loc) override;
  293. ModRefResult getModRefInfo(ImmutableCallSite CS1,
  294. ImmutableCallSite CS2) override;
  295. };
  296. } // End of anonymous namespace
  297. // Register this pass...
  298. char TypeBasedAliasAnalysis::ID = 0;
  299. INITIALIZE_AG_PASS(TypeBasedAliasAnalysis, AliasAnalysis, "tbaa",
  300. "Type-Based Alias Analysis", false, true, false)
  301. ImmutablePass *llvm::createTypeBasedAliasAnalysisPass() {
  302. return new TypeBasedAliasAnalysis();
  303. }
  304. bool TypeBasedAliasAnalysis::doInitialization(Module &M) {
  305. InitializeAliasAnalysis(this, &M.getDataLayout());
  306. return true;
  307. }
  308. void
  309. TypeBasedAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  310. AU.setPreservesAll();
  311. AliasAnalysis::getAnalysisUsage(AU);
  312. }
  313. /// Check the first operand of the tbaa tag node, if it is a MDNode, we treat
  314. /// it as struct-path aware TBAA format, otherwise, we treat it as scalar TBAA
  315. /// format.
  316. static bool isStructPathTBAA(const MDNode *MD) {
  317. // Anonymous TBAA root starts with a MDNode and dragonegg uses it as
  318. // a TBAA tag.
  319. return isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
  320. }
  321. /// Aliases - Test whether the type represented by A may alias the
  322. /// type represented by B.
  323. bool
  324. TypeBasedAliasAnalysis::Aliases(const MDNode *A,
  325. const MDNode *B) const {
  326. // Make sure that both MDNodes are struct-path aware.
  327. if (isStructPathTBAA(A) && isStructPathTBAA(B))
  328. return PathAliases(A, B);
  329. // Keep track of the root node for A and B.
  330. TBAANode RootA, RootB;
  331. // Climb the tree from A to see if we reach B.
  332. for (TBAANode T(A); ; ) {
  333. if (T.getNode() == B)
  334. // B is an ancestor of A.
  335. return true;
  336. RootA = T;
  337. T = T.getParent();
  338. if (!T.getNode())
  339. break;
  340. }
  341. // Climb the tree from B to see if we reach A.
  342. for (TBAANode T(B); ; ) {
  343. if (T.getNode() == A)
  344. // A is an ancestor of B.
  345. return true;
  346. RootB = T;
  347. T = T.getParent();
  348. if (!T.getNode())
  349. break;
  350. }
  351. // Neither node is an ancestor of the other.
  352. // If they have different roots, they're part of different potentially
  353. // unrelated type systems, so we must be conservative.
  354. if (RootA.getNode() != RootB.getNode())
  355. return true;
  356. // If they have the same root, then we've proved there's no alias.
  357. return false;
  358. }
  359. /// Test whether the struct-path tag represented by A may alias the
  360. /// struct-path tag represented by B.
  361. bool
  362. TypeBasedAliasAnalysis::PathAliases(const MDNode *A,
  363. const MDNode *B) const {
  364. // Verify that both input nodes are struct-path aware.
  365. assert(isStructPathTBAA(A) && "MDNode A is not struct-path aware.");
  366. assert(isStructPathTBAA(B) && "MDNode B is not struct-path aware.");
  367. // Keep track of the root node for A and B.
  368. TBAAStructTypeNode RootA, RootB;
  369. TBAAStructTagNode TagA(A), TagB(B);
  370. // TODO: We need to check if AccessType of TagA encloses AccessType of
  371. // TagB to support aggregate AccessType. If yes, return true.
  372. // Start from the base type of A, follow the edge with the correct offset in
  373. // the type DAG and adjust the offset until we reach the base type of B or
  374. // until we reach the Root node.
  375. // Compare the adjusted offset once we have the same base.
  376. // Climb the type DAG from base type of A to see if we reach base type of B.
  377. const MDNode *BaseA = TagA.getBaseType();
  378. const MDNode *BaseB = TagB.getBaseType();
  379. uint64_t OffsetA = TagA.getOffset(), OffsetB = TagB.getOffset();
  380. for (TBAAStructTypeNode T(BaseA); ; ) {
  381. if (T.getNode() == BaseB)
  382. // Base type of A encloses base type of B, check if the offsets match.
  383. return OffsetA == OffsetB;
  384. RootA = T;
  385. // Follow the edge with the correct offset, OffsetA will be adjusted to
  386. // be relative to the field type.
  387. T = T.getParent(OffsetA);
  388. if (!T.getNode())
  389. break;
  390. }
  391. // Reset OffsetA and climb the type DAG from base type of B to see if we reach
  392. // base type of A.
  393. OffsetA = TagA.getOffset();
  394. for (TBAAStructTypeNode T(BaseB); ; ) {
  395. if (T.getNode() == BaseA)
  396. // Base type of B encloses base type of A, check if the offsets match.
  397. return OffsetA == OffsetB;
  398. RootB = T;
  399. // Follow the edge with the correct offset, OffsetB will be adjusted to
  400. // be relative to the field type.
  401. T = T.getParent(OffsetB);
  402. if (!T.getNode())
  403. break;
  404. }
  405. // Neither node is an ancestor of the other.
  406. // If they have different roots, they're part of different potentially
  407. // unrelated type systems, so we must be conservative.
  408. if (RootA.getNode() != RootB.getNode())
  409. return true;
  410. // If they have the same root, then we've proved there's no alias.
  411. return false;
  412. }
  413. AliasResult TypeBasedAliasAnalysis::alias(const MemoryLocation &LocA,
  414. const MemoryLocation &LocB) {
  415. if (!EnableTBAA)
  416. return AliasAnalysis::alias(LocA, LocB);
  417. // Get the attached MDNodes. If either value lacks a tbaa MDNode, we must
  418. // be conservative.
  419. const MDNode *AM = LocA.AATags.TBAA;
  420. if (!AM) return AliasAnalysis::alias(LocA, LocB);
  421. const MDNode *BM = LocB.AATags.TBAA;
  422. if (!BM) return AliasAnalysis::alias(LocA, LocB);
  423. // If they may alias, chain to the next AliasAnalysis.
  424. if (Aliases(AM, BM))
  425. return AliasAnalysis::alias(LocA, LocB);
  426. // Otherwise return a definitive result.
  427. return NoAlias;
  428. }
  429. bool TypeBasedAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
  430. bool OrLocal) {
  431. if (!EnableTBAA)
  432. return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
  433. const MDNode *M = Loc.AATags.TBAA;
  434. if (!M) return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
  435. // If this is an "immutable" type, we can assume the pointer is pointing
  436. // to constant memory.
  437. if ((!isStructPathTBAA(M) && TBAANode(M).TypeIsImmutable()) ||
  438. (isStructPathTBAA(M) && TBAAStructTagNode(M).TypeIsImmutable()))
  439. return true;
  440. return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
  441. }
  442. AliasAnalysis::ModRefBehavior
  443. TypeBasedAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
  444. if (!EnableTBAA)
  445. return AliasAnalysis::getModRefBehavior(CS);
  446. ModRefBehavior Min = UnknownModRefBehavior;
  447. // If this is an "immutable" type, we can assume the call doesn't write
  448. // to memory.
  449. if (const MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
  450. if ((!isStructPathTBAA(M) && TBAANode(M).TypeIsImmutable()) ||
  451. (isStructPathTBAA(M) && TBAAStructTagNode(M).TypeIsImmutable()))
  452. Min = OnlyReadsMemory;
  453. return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
  454. }
  455. AliasAnalysis::ModRefBehavior
  456. TypeBasedAliasAnalysis::getModRefBehavior(const Function *F) {
  457. // Functions don't have metadata. Just chain to the next implementation.
  458. return AliasAnalysis::getModRefBehavior(F);
  459. }
  460. AliasAnalysis::ModRefResult
  461. TypeBasedAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
  462. const MemoryLocation &Loc) {
  463. if (!EnableTBAA)
  464. return AliasAnalysis::getModRefInfo(CS, Loc);
  465. if (const MDNode *L = Loc.AATags.TBAA)
  466. if (const MDNode *M =
  467. CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
  468. if (!Aliases(L, M))
  469. return NoModRef;
  470. return AliasAnalysis::getModRefInfo(CS, Loc);
  471. }
  472. AliasAnalysis::ModRefResult
  473. TypeBasedAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
  474. ImmutableCallSite CS2) {
  475. if (!EnableTBAA)
  476. return AliasAnalysis::getModRefInfo(CS1, CS2);
  477. if (const MDNode *M1 =
  478. CS1.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
  479. if (const MDNode *M2 =
  480. CS2.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
  481. if (!Aliases(M1, M2))
  482. return NoModRef;
  483. return AliasAnalysis::getModRefInfo(CS1, CS2);
  484. }
  485. bool MDNode::isTBAAVtableAccess() const {
  486. if (!isStructPathTBAA(this)) {
  487. if (getNumOperands() < 1) return false;
  488. if (MDString *Tag1 = dyn_cast<MDString>(getOperand(0))) {
  489. if (Tag1->getString() == "vtable pointer") return true;
  490. }
  491. return false;
  492. }
  493. // For struct-path aware TBAA, we use the access type of the tag.
  494. if (getNumOperands() < 2) return false;
  495. MDNode *Tag = cast_or_null<MDNode>(getOperand(1));
  496. if (!Tag) return false;
  497. if (MDString *Tag1 = dyn_cast<MDString>(Tag->getOperand(0))) {
  498. if (Tag1->getString() == "vtable pointer") return true;
  499. }
  500. return false;
  501. }
  502. MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) {
  503. if (!A || !B)
  504. return nullptr;
  505. if (A == B)
  506. return A;
  507. // For struct-path aware TBAA, we use the access type of the tag.
  508. bool StructPath = isStructPathTBAA(A) && isStructPathTBAA(B);
  509. if (StructPath) {
  510. A = cast_or_null<MDNode>(A->getOperand(1));
  511. if (!A) return nullptr;
  512. B = cast_or_null<MDNode>(B->getOperand(1));
  513. if (!B) return nullptr;
  514. }
  515. SmallSetVector<MDNode *, 4> PathA;
  516. MDNode *T = A;
  517. while (T) {
  518. if (PathA.count(T))
  519. report_fatal_error("Cycle found in TBAA metadata.");
  520. PathA.insert(T);
  521. T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1))
  522. : nullptr;
  523. }
  524. SmallSetVector<MDNode *, 4> PathB;
  525. T = B;
  526. while (T) {
  527. if (PathB.count(T))
  528. report_fatal_error("Cycle found in TBAA metadata.");
  529. PathB.insert(T);
  530. T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1))
  531. : nullptr;
  532. }
  533. int IA = PathA.size() - 1;
  534. int IB = PathB.size() - 1;
  535. MDNode *Ret = nullptr;
  536. while (IA >= 0 && IB >=0) {
  537. if (PathA[IA] == PathB[IB])
  538. Ret = PathA[IA];
  539. else
  540. break;
  541. --IA;
  542. --IB;
  543. }
  544. if (!StructPath)
  545. return Ret;
  546. if (!Ret)
  547. return nullptr;
  548. // We need to convert from a type node to a tag node.
  549. Type *Int64 = IntegerType::get(A->getContext(), 64);
  550. Metadata *Ops[3] = {Ret, Ret,
  551. ConstantAsMetadata::get(ConstantInt::get(Int64, 0))};
  552. return MDNode::get(A->getContext(), Ops);
  553. }
  554. void Instruction::getAAMetadata(AAMDNodes &N, bool Merge) const {
  555. if (Merge)
  556. N.TBAA =
  557. MDNode::getMostGenericTBAA(N.TBAA, getMetadata(LLVMContext::MD_tbaa));
  558. else
  559. N.TBAA = getMetadata(LLVMContext::MD_tbaa);
  560. if (Merge)
  561. N.Scope = MDNode::getMostGenericAliasScope(
  562. N.Scope, getMetadata(LLVMContext::MD_alias_scope));
  563. else
  564. N.Scope = getMetadata(LLVMContext::MD_alias_scope);
  565. if (Merge)
  566. N.NoAlias =
  567. MDNode::intersect(N.NoAlias, getMetadata(LLVMContext::MD_noalias));
  568. else
  569. N.NoAlias = getMetadata(LLVMContext::MD_noalias);
  570. }