TypeBasedAliasAnalysis.cpp 22 KB

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