TypeBasedAliasAnalysis.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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. static cl::opt<bool> EnableTBAA("enable-tbaa", cl::init(true));
  137. namespace {
  138. /// TBAANode - This is a simple wrapper around an MDNode which provides a
  139. /// higher-level interface by hiding the details of how alias analysis
  140. /// information is encoded in its operands.
  141. class TBAANode {
  142. const MDNode *Node;
  143. public:
  144. TBAANode() : Node(nullptr) {}
  145. explicit TBAANode(const MDNode *N) : Node(N) {}
  146. /// getNode - Get the MDNode for this TBAANode.
  147. const MDNode *getNode() const { return Node; }
  148. /// getParent - Get this TBAANode's Alias tree parent.
  149. TBAANode getParent() const {
  150. if (Node->getNumOperands() < 2)
  151. return TBAANode();
  152. MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1));
  153. if (!P)
  154. return TBAANode();
  155. // Ok, this node has a valid parent. Return it.
  156. return TBAANode(P);
  157. }
  158. /// TypeIsImmutable - Test if this TBAANode represents a type for objects
  159. /// which are not modified (by any means) in the context where this
  160. /// AliasAnalysis is relevant.
  161. bool TypeIsImmutable() const {
  162. if (Node->getNumOperands() < 3)
  163. return false;
  164. ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Node->getOperand(2));
  165. if (!CI)
  166. return false;
  167. return CI->getValue()[0];
  168. }
  169. };
  170. /// This is a simple wrapper around an MDNode which provides a
  171. /// higher-level interface by hiding the details of how alias analysis
  172. /// information is encoded in its operands.
  173. class TBAAStructTagNode {
  174. /// This node should be created with createTBAAStructTagNode.
  175. const MDNode *Node;
  176. public:
  177. explicit TBAAStructTagNode(const MDNode *N) : Node(N) {}
  178. /// Get the MDNode for this TBAAStructTagNode.
  179. const MDNode *getNode() const { return Node; }
  180. const MDNode *getBaseType() const {
  181. return dyn_cast_or_null<MDNode>(Node->getOperand(0));
  182. }
  183. const MDNode *getAccessType() const {
  184. return dyn_cast_or_null<MDNode>(Node->getOperand(1));
  185. }
  186. uint64_t getOffset() const {
  187. return mdconst::extract<ConstantInt>(Node->getOperand(2))->getZExtValue();
  188. }
  189. /// TypeIsImmutable - Test if this TBAAStructTagNode represents a type for
  190. /// objects which are not modified (by any means) in the context where this
  191. /// AliasAnalysis is relevant.
  192. bool TypeIsImmutable() const {
  193. if (Node->getNumOperands() < 4)
  194. return false;
  195. ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Node->getOperand(3));
  196. if (!CI)
  197. return false;
  198. return CI->getValue()[0];
  199. }
  200. };
  201. /// This is a simple wrapper around an MDNode which provides a
  202. /// higher-level interface by hiding the details of how alias analysis
  203. /// information is encoded in its operands.
  204. class TBAAStructTypeNode {
  205. /// This node should be created with createTBAAStructTypeNode.
  206. const MDNode *Node;
  207. public:
  208. TBAAStructTypeNode() : Node(nullptr) {}
  209. explicit TBAAStructTypeNode(const MDNode *N) : Node(N) {}
  210. /// Get the MDNode for this TBAAStructTypeNode.
  211. const MDNode *getNode() const { return Node; }
  212. /// Get this TBAAStructTypeNode's field in the type DAG with
  213. /// given offset. Update the offset to be relative to the field type.
  214. TBAAStructTypeNode getParent(uint64_t &Offset) const {
  215. // Parent can be omitted for the root node.
  216. if (Node->getNumOperands() < 2)
  217. return TBAAStructTypeNode();
  218. // Fast path for a scalar type node and a struct type node with a single
  219. // field.
  220. if (Node->getNumOperands() <= 3) {
  221. uint64_t Cur = Node->getNumOperands() == 2
  222. ? 0
  223. : mdconst::extract<ConstantInt>(Node->getOperand(2))
  224. ->getZExtValue();
  225. Offset -= Cur;
  226. MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1));
  227. if (!P)
  228. return TBAAStructTypeNode();
  229. return TBAAStructTypeNode(P);
  230. }
  231. // Assume the offsets are in order. We return the previous field if
  232. // the current offset is bigger than the given offset.
  233. unsigned TheIdx = 0;
  234. for (unsigned Idx = 1; Idx < Node->getNumOperands(); Idx += 2) {
  235. uint64_t Cur = mdconst::extract<ConstantInt>(Node->getOperand(Idx + 1))
  236. ->getZExtValue();
  237. if (Cur > Offset) {
  238. assert(Idx >= 3 &&
  239. "TBAAStructTypeNode::getParent should have an offset match!");
  240. TheIdx = Idx - 2;
  241. break;
  242. }
  243. }
  244. // Move along the last field.
  245. if (TheIdx == 0)
  246. TheIdx = Node->getNumOperands() - 2;
  247. uint64_t Cur = mdconst::extract<ConstantInt>(Node->getOperand(TheIdx + 1))
  248. ->getZExtValue();
  249. Offset -= Cur;
  250. MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(TheIdx));
  251. if (!P)
  252. return TBAAStructTypeNode();
  253. return TBAAStructTypeNode(P);
  254. }
  255. };
  256. }
  257. namespace {
  258. /// TypeBasedAliasAnalysis - This is a simple alias analysis
  259. /// implementation that uses TypeBased to answer queries.
  260. class TypeBasedAliasAnalysis : public ImmutablePass,
  261. public AliasAnalysis {
  262. public:
  263. static char ID; // Class identification, replacement for typeinfo
  264. TypeBasedAliasAnalysis() : ImmutablePass(ID) {
  265. initializeTypeBasedAliasAnalysisPass(*PassRegistry::getPassRegistry());
  266. }
  267. bool doInitialization(Module &M) override;
  268. /// getAdjustedAnalysisPointer - This method is used when a pass implements
  269. /// an analysis interface through multiple inheritance. If needed, it
  270. /// should override this to adjust the this pointer as needed for the
  271. /// specified pass info.
  272. void *getAdjustedAnalysisPointer(const void *PI) override {
  273. if (PI == &AliasAnalysis::ID)
  274. return (AliasAnalysis*)this;
  275. return this;
  276. }
  277. bool Aliases(const MDNode *A, const MDNode *B) const;
  278. bool PathAliases(const MDNode *A, const MDNode *B) const;
  279. private:
  280. void getAnalysisUsage(AnalysisUsage &AU) const override;
  281. AliasResult alias(const MemoryLocation &LocA,
  282. const MemoryLocation &LocB) override;
  283. bool pointsToConstantMemory(const MemoryLocation &Loc,
  284. bool OrLocal) override;
  285. ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
  286. ModRefBehavior getModRefBehavior(const Function *F) override;
  287. ModRefResult getModRefInfo(ImmutableCallSite CS,
  288. const MemoryLocation &Loc) override;
  289. ModRefResult getModRefInfo(ImmutableCallSite CS1,
  290. ImmutableCallSite CS2) override;
  291. };
  292. } // End of anonymous namespace
  293. // Register this pass...
  294. char TypeBasedAliasAnalysis::ID = 0;
  295. INITIALIZE_AG_PASS(TypeBasedAliasAnalysis, AliasAnalysis, "tbaa",
  296. "Type-Based Alias Analysis", false, true, false)
  297. ImmutablePass *llvm::createTypeBasedAliasAnalysisPass() {
  298. return new TypeBasedAliasAnalysis();
  299. }
  300. bool TypeBasedAliasAnalysis::doInitialization(Module &M) {
  301. InitializeAliasAnalysis(this, &M.getDataLayout());
  302. return true;
  303. }
  304. void
  305. TypeBasedAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  306. AU.setPreservesAll();
  307. AliasAnalysis::getAnalysisUsage(AU);
  308. }
  309. /// Check the first operand of the tbaa tag node, if it is a MDNode, we treat
  310. /// it as struct-path aware TBAA format, otherwise, we treat it as scalar TBAA
  311. /// format.
  312. static bool isStructPathTBAA(const MDNode *MD) {
  313. // Anonymous TBAA root starts with a MDNode and dragonegg uses it as
  314. // a TBAA tag.
  315. return isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
  316. }
  317. /// Aliases - Test whether the type represented by A may alias the
  318. /// type represented by B.
  319. bool
  320. TypeBasedAliasAnalysis::Aliases(const MDNode *A,
  321. const MDNode *B) const {
  322. // Make sure that both MDNodes are struct-path aware.
  323. if (isStructPathTBAA(A) && isStructPathTBAA(B))
  324. return PathAliases(A, B);
  325. // Keep track of the root node for A and B.
  326. TBAANode RootA, RootB;
  327. // Climb the tree from A to see if we reach B.
  328. for (TBAANode T(A); ; ) {
  329. if (T.getNode() == B)
  330. // B is an ancestor of A.
  331. return true;
  332. RootA = T;
  333. T = T.getParent();
  334. if (!T.getNode())
  335. break;
  336. }
  337. // Climb the tree from B to see if we reach A.
  338. for (TBAANode T(B); ; ) {
  339. if (T.getNode() == A)
  340. // A is an ancestor of B.
  341. return true;
  342. RootB = T;
  343. T = T.getParent();
  344. if (!T.getNode())
  345. break;
  346. }
  347. // Neither node is an ancestor of the other.
  348. // If they have different roots, they're part of different potentially
  349. // unrelated type systems, so we must be conservative.
  350. if (RootA.getNode() != RootB.getNode())
  351. return true;
  352. // If they have the same root, then we've proved there's no alias.
  353. return false;
  354. }
  355. /// Test whether the struct-path tag represented by A may alias the
  356. /// struct-path tag represented by B.
  357. bool
  358. TypeBasedAliasAnalysis::PathAliases(const MDNode *A,
  359. const MDNode *B) const {
  360. // Verify that both input nodes are struct-path aware.
  361. assert(isStructPathTBAA(A) && "MDNode A is not struct-path aware.");
  362. assert(isStructPathTBAA(B) && "MDNode B is not struct-path aware.");
  363. // Keep track of the root node for A and B.
  364. TBAAStructTypeNode RootA, RootB;
  365. TBAAStructTagNode TagA(A), TagB(B);
  366. // TODO: We need to check if AccessType of TagA encloses AccessType of
  367. // TagB to support aggregate AccessType. If yes, return true.
  368. // Start from the base type of A, follow the edge with the correct offset in
  369. // the type DAG and adjust the offset until we reach the base type of B or
  370. // until we reach the Root node.
  371. // Compare the adjusted offset once we have the same base.
  372. // Climb the type DAG from base type of A to see if we reach base type of B.
  373. const MDNode *BaseA = TagA.getBaseType();
  374. const MDNode *BaseB = TagB.getBaseType();
  375. uint64_t OffsetA = TagA.getOffset(), OffsetB = TagB.getOffset();
  376. for (TBAAStructTypeNode T(BaseA); ; ) {
  377. if (T.getNode() == BaseB)
  378. // Base type of A encloses base type of B, check if the offsets match.
  379. return OffsetA == OffsetB;
  380. RootA = T;
  381. // Follow the edge with the correct offset, OffsetA will be adjusted to
  382. // be relative to the field type.
  383. T = T.getParent(OffsetA);
  384. if (!T.getNode())
  385. break;
  386. }
  387. // Reset OffsetA and climb the type DAG from base type of B to see if we reach
  388. // base type of A.
  389. OffsetA = TagA.getOffset();
  390. for (TBAAStructTypeNode T(BaseB); ; ) {
  391. if (T.getNode() == BaseA)
  392. // Base type of B encloses base type of A, check if the offsets match.
  393. return OffsetA == OffsetB;
  394. RootB = T;
  395. // Follow the edge with the correct offset, OffsetB will be adjusted to
  396. // be relative to the field type.
  397. T = T.getParent(OffsetB);
  398. if (!T.getNode())
  399. break;
  400. }
  401. // Neither node is an ancestor of the other.
  402. // If they have different roots, they're part of different potentially
  403. // unrelated type systems, so we must be conservative.
  404. if (RootA.getNode() != RootB.getNode())
  405. return true;
  406. // If they have the same root, then we've proved there's no alias.
  407. return false;
  408. }
  409. AliasResult TypeBasedAliasAnalysis::alias(const MemoryLocation &LocA,
  410. const MemoryLocation &LocB) {
  411. if (!EnableTBAA)
  412. return AliasAnalysis::alias(LocA, LocB);
  413. // Get the attached MDNodes. If either value lacks a tbaa MDNode, we must
  414. // be conservative.
  415. const MDNode *AM = LocA.AATags.TBAA;
  416. if (!AM) return AliasAnalysis::alias(LocA, LocB);
  417. const MDNode *BM = LocB.AATags.TBAA;
  418. if (!BM) return AliasAnalysis::alias(LocA, LocB);
  419. // If they may alias, chain to the next AliasAnalysis.
  420. if (Aliases(AM, BM))
  421. return AliasAnalysis::alias(LocA, LocB);
  422. // Otherwise return a definitive result.
  423. return NoAlias;
  424. }
  425. bool TypeBasedAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
  426. bool OrLocal) {
  427. if (!EnableTBAA)
  428. return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
  429. const MDNode *M = Loc.AATags.TBAA;
  430. if (!M) return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
  431. // If this is an "immutable" type, we can assume the pointer is pointing
  432. // to constant memory.
  433. if ((!isStructPathTBAA(M) && TBAANode(M).TypeIsImmutable()) ||
  434. (isStructPathTBAA(M) && TBAAStructTagNode(M).TypeIsImmutable()))
  435. return true;
  436. return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
  437. }
  438. AliasAnalysis::ModRefBehavior
  439. TypeBasedAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
  440. if (!EnableTBAA)
  441. return AliasAnalysis::getModRefBehavior(CS);
  442. ModRefBehavior Min = UnknownModRefBehavior;
  443. // If this is an "immutable" type, we can assume the call doesn't write
  444. // to memory.
  445. if (const MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
  446. if ((!isStructPathTBAA(M) && TBAANode(M).TypeIsImmutable()) ||
  447. (isStructPathTBAA(M) && TBAAStructTagNode(M).TypeIsImmutable()))
  448. Min = OnlyReadsMemory;
  449. return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
  450. }
  451. AliasAnalysis::ModRefBehavior
  452. TypeBasedAliasAnalysis::getModRefBehavior(const Function *F) {
  453. // Functions don't have metadata. Just chain to the next implementation.
  454. return AliasAnalysis::getModRefBehavior(F);
  455. }
  456. AliasAnalysis::ModRefResult
  457. TypeBasedAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
  458. const MemoryLocation &Loc) {
  459. if (!EnableTBAA)
  460. return AliasAnalysis::getModRefInfo(CS, Loc);
  461. if (const MDNode *L = Loc.AATags.TBAA)
  462. if (const MDNode *M =
  463. CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
  464. if (!Aliases(L, M))
  465. return NoModRef;
  466. return AliasAnalysis::getModRefInfo(CS, Loc);
  467. }
  468. AliasAnalysis::ModRefResult
  469. TypeBasedAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
  470. ImmutableCallSite CS2) {
  471. if (!EnableTBAA)
  472. return AliasAnalysis::getModRefInfo(CS1, CS2);
  473. if (const MDNode *M1 =
  474. CS1.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
  475. if (const MDNode *M2 =
  476. CS2.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
  477. if (!Aliases(M1, M2))
  478. return NoModRef;
  479. return AliasAnalysis::getModRefInfo(CS1, CS2);
  480. }
  481. bool MDNode::isTBAAVtableAccess() const {
  482. if (!isStructPathTBAA(this)) {
  483. if (getNumOperands() < 1) return false;
  484. if (MDString *Tag1 = dyn_cast<MDString>(getOperand(0))) {
  485. if (Tag1->getString() == "vtable pointer") return true;
  486. }
  487. return false;
  488. }
  489. // For struct-path aware TBAA, we use the access type of the tag.
  490. if (getNumOperands() < 2) return false;
  491. MDNode *Tag = cast_or_null<MDNode>(getOperand(1));
  492. if (!Tag) return false;
  493. if (MDString *Tag1 = dyn_cast<MDString>(Tag->getOperand(0))) {
  494. if (Tag1->getString() == "vtable pointer") return true;
  495. }
  496. return false;
  497. }
  498. MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) {
  499. if (!A || !B)
  500. return nullptr;
  501. if (A == B)
  502. return A;
  503. // For struct-path aware TBAA, we use the access type of the tag.
  504. bool StructPath = isStructPathTBAA(A) && isStructPathTBAA(B);
  505. if (StructPath) {
  506. A = cast_or_null<MDNode>(A->getOperand(1));
  507. if (!A) return nullptr;
  508. B = cast_or_null<MDNode>(B->getOperand(1));
  509. if (!B) return nullptr;
  510. }
  511. SmallSetVector<MDNode *, 4> PathA;
  512. MDNode *T = A;
  513. while (T) {
  514. if (PathA.count(T))
  515. report_fatal_error("Cycle found in TBAA metadata.");
  516. PathA.insert(T);
  517. T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1))
  518. : nullptr;
  519. }
  520. SmallSetVector<MDNode *, 4> PathB;
  521. T = B;
  522. while (T) {
  523. if (PathB.count(T))
  524. report_fatal_error("Cycle found in TBAA metadata.");
  525. PathB.insert(T);
  526. T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1))
  527. : nullptr;
  528. }
  529. int IA = PathA.size() - 1;
  530. int IB = PathB.size() - 1;
  531. MDNode *Ret = nullptr;
  532. while (IA >= 0 && IB >=0) {
  533. if (PathA[IA] == PathB[IB])
  534. Ret = PathA[IA];
  535. else
  536. break;
  537. --IA;
  538. --IB;
  539. }
  540. if (!StructPath)
  541. return Ret;
  542. if (!Ret)
  543. return nullptr;
  544. // We need to convert from a type node to a tag node.
  545. Type *Int64 = IntegerType::get(A->getContext(), 64);
  546. Metadata *Ops[3] = {Ret, Ret,
  547. ConstantAsMetadata::get(ConstantInt::get(Int64, 0))};
  548. return MDNode::get(A->getContext(), Ops);
  549. }
  550. void Instruction::getAAMetadata(AAMDNodes &N, bool Merge) const {
  551. if (Merge)
  552. N.TBAA =
  553. MDNode::getMostGenericTBAA(N.TBAA, getMetadata(LLVMContext::MD_tbaa));
  554. else
  555. N.TBAA = getMetadata(LLVMContext::MD_tbaa);
  556. if (Merge)
  557. N.Scope = MDNode::getMostGenericAliasScope(
  558. N.Scope, getMetadata(LLVMContext::MD_alias_scope));
  559. else
  560. N.Scope = getMetadata(LLVMContext::MD_alias_scope);
  561. if (Merge)
  562. N.NoAlias =
  563. MDNode::intersect(N.NoAlias, getMetadata(LLVMContext::MD_noalias));
  564. else
  565. N.NoAlias = getMetadata(LLVMContext::MD_noalias);
  566. }