Metadata.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  1. //===- Metadata.cpp - Implement Metadata classes --------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Metadata classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/Metadata.h"
  13. #include "LLVMContextImpl.h"
  14. #include "MetadataImpl.h"
  15. #include "SymbolTableListTraitsImpl.h"
  16. #include "llvm/ADT/APFloat.h"
  17. #include "llvm/ADT/APInt.h"
  18. #include "llvm/ADT/ArrayRef.h"
  19. #include "llvm/ADT/DenseSet.h"
  20. #include "llvm/ADT/None.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SetVector.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/SmallSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringMap.h"
  27. #include "llvm/ADT/StringRef.h"
  28. #include "llvm/ADT/Twine.h"
  29. #include "llvm/IR/Argument.h"
  30. #include "llvm/IR/BasicBlock.h"
  31. #include "llvm/IR/Constant.h"
  32. #include "llvm/IR/ConstantRange.h"
  33. #include "llvm/IR/Constants.h"
  34. #include "llvm/IR/DebugInfoMetadata.h"
  35. #include "llvm/IR/DebugLoc.h"
  36. #include "llvm/IR/Function.h"
  37. #include "llvm/IR/GlobalObject.h"
  38. #include "llvm/IR/GlobalVariable.h"
  39. #include "llvm/IR/Instruction.h"
  40. #include "llvm/IR/LLVMContext.h"
  41. #include "llvm/IR/MDBuilder.h"
  42. #include "llvm/IR/Module.h"
  43. #include "llvm/IR/TrackingMDRef.h"
  44. #include "llvm/IR/Type.h"
  45. #include "llvm/IR/Value.h"
  46. #include "llvm/IR/ValueHandle.h"
  47. #include "llvm/Support/Casting.h"
  48. #include "llvm/Support/ErrorHandling.h"
  49. #include "llvm/Support/MathExtras.h"
  50. #include <algorithm>
  51. #include <cassert>
  52. #include <cstddef>
  53. #include <cstdint>
  54. #include <iterator>
  55. #include <tuple>
  56. #include <type_traits>
  57. #include <utility>
  58. #include <vector>
  59. using namespace llvm;
  60. MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
  61. : Value(Ty, MetadataAsValueVal), MD(MD) {
  62. track();
  63. }
  64. MetadataAsValue::~MetadataAsValue() {
  65. getType()->getContext().pImpl->MetadataAsValues.erase(MD);
  66. untrack();
  67. }
  68. /// Canonicalize metadata arguments to intrinsics.
  69. ///
  70. /// To support bitcode upgrades (and assembly semantic sugar) for \a
  71. /// MetadataAsValue, we need to canonicalize certain metadata.
  72. ///
  73. /// - nullptr is replaced by an empty MDNode.
  74. /// - An MDNode with a single null operand is replaced by an empty MDNode.
  75. /// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
  76. ///
  77. /// This maintains readability of bitcode from when metadata was a type of
  78. /// value, and these bridges were unnecessary.
  79. static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
  80. Metadata *MD) {
  81. if (!MD)
  82. // !{}
  83. return MDNode::get(Context, None);
  84. // Return early if this isn't a single-operand MDNode.
  85. auto *N = dyn_cast<MDNode>(MD);
  86. if (!N || N->getNumOperands() != 1)
  87. return MD;
  88. if (!N->getOperand(0))
  89. // !{}
  90. return MDNode::get(Context, None);
  91. if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
  92. // Look through the MDNode.
  93. return C;
  94. return MD;
  95. }
  96. MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
  97. MD = canonicalizeMetadataForValue(Context, MD);
  98. auto *&Entry = Context.pImpl->MetadataAsValues[MD];
  99. if (!Entry)
  100. Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
  101. return Entry;
  102. }
  103. MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
  104. Metadata *MD) {
  105. MD = canonicalizeMetadataForValue(Context, MD);
  106. auto &Store = Context.pImpl->MetadataAsValues;
  107. return Store.lookup(MD);
  108. }
  109. void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
  110. LLVMContext &Context = getContext();
  111. MD = canonicalizeMetadataForValue(Context, MD);
  112. auto &Store = Context.pImpl->MetadataAsValues;
  113. // Stop tracking the old metadata.
  114. Store.erase(this->MD);
  115. untrack();
  116. this->MD = nullptr;
  117. // Start tracking MD, or RAUW if necessary.
  118. auto *&Entry = Store[MD];
  119. if (Entry) {
  120. replaceAllUsesWith(Entry);
  121. delete this;
  122. return;
  123. }
  124. this->MD = MD;
  125. track();
  126. Entry = this;
  127. }
  128. void MetadataAsValue::track() {
  129. if (MD)
  130. MetadataTracking::track(&MD, *MD, *this);
  131. }
  132. void MetadataAsValue::untrack() {
  133. if (MD)
  134. MetadataTracking::untrack(MD);
  135. }
  136. bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
  137. assert(Ref && "Expected live reference");
  138. assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
  139. "Reference without owner must be direct");
  140. if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
  141. R->addRef(Ref, Owner);
  142. return true;
  143. }
  144. if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
  145. assert(!PH->Use && "Placeholders can only be used once");
  146. assert(!Owner && "Unexpected callback to owner");
  147. PH->Use = static_cast<Metadata **>(Ref);
  148. return true;
  149. }
  150. return false;
  151. }
  152. void MetadataTracking::untrack(void *Ref, Metadata &MD) {
  153. assert(Ref && "Expected live reference");
  154. if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
  155. R->dropRef(Ref);
  156. else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
  157. PH->Use = nullptr;
  158. }
  159. bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
  160. assert(Ref && "Expected live reference");
  161. assert(New && "Expected live reference");
  162. assert(Ref != New && "Expected change");
  163. if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
  164. R->moveRef(Ref, New, MD);
  165. return true;
  166. }
  167. assert(!isa<DistinctMDOperandPlaceholder>(MD) &&
  168. "Unexpected move of an MDOperand");
  169. assert(!isReplaceable(MD) &&
  170. "Expected un-replaceable metadata, since we didn't move a reference");
  171. return false;
  172. }
  173. bool MetadataTracking::isReplaceable(const Metadata &MD) {
  174. return ReplaceableMetadataImpl::isReplaceable(MD);
  175. }
  176. void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
  177. bool WasInserted =
  178. UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
  179. .second;
  180. (void)WasInserted;
  181. assert(WasInserted && "Expected to add a reference");
  182. ++NextIndex;
  183. assert(NextIndex != 0 && "Unexpected overflow");
  184. }
  185. void ReplaceableMetadataImpl::dropRef(void *Ref) {
  186. bool WasErased = UseMap.erase(Ref);
  187. (void)WasErased;
  188. assert(WasErased && "Expected to drop a reference");
  189. }
  190. void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
  191. const Metadata &MD) {
  192. auto I = UseMap.find(Ref);
  193. assert(I != UseMap.end() && "Expected to move a reference");
  194. auto OwnerAndIndex = I->second;
  195. UseMap.erase(I);
  196. bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
  197. (void)WasInserted;
  198. assert(WasInserted && "Expected to add a reference");
  199. // Check that the references are direct if there's no owner.
  200. (void)MD;
  201. assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
  202. "Reference without owner must be direct");
  203. assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
  204. "Reference without owner must be direct");
  205. }
  206. void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
  207. if (UseMap.empty())
  208. return;
  209. // Copy out uses since UseMap will get touched below.
  210. using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
  211. SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
  212. llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
  213. return L.second.second < R.second.second;
  214. });
  215. for (const auto &Pair : Uses) {
  216. // Check that this Ref hasn't disappeared after RAUW (when updating a
  217. // previous Ref).
  218. if (!UseMap.count(Pair.first))
  219. continue;
  220. OwnerTy Owner = Pair.second.first;
  221. if (!Owner) {
  222. // Update unowned tracking references directly.
  223. Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
  224. Ref = MD;
  225. if (MD)
  226. MetadataTracking::track(Ref);
  227. UseMap.erase(Pair.first);
  228. continue;
  229. }
  230. // Check for MetadataAsValue.
  231. if (Owner.is<MetadataAsValue *>()) {
  232. Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
  233. continue;
  234. }
  235. // There's a Metadata owner -- dispatch.
  236. Metadata *OwnerMD = Owner.get<Metadata *>();
  237. switch (OwnerMD->getMetadataID()) {
  238. #define HANDLE_METADATA_LEAF(CLASS) \
  239. case Metadata::CLASS##Kind: \
  240. cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
  241. continue;
  242. #include "llvm/IR/Metadata.def"
  243. default:
  244. llvm_unreachable("Invalid metadata subclass");
  245. }
  246. }
  247. assert(UseMap.empty() && "Expected all uses to be replaced");
  248. }
  249. void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
  250. if (UseMap.empty())
  251. return;
  252. if (!ResolveUsers) {
  253. UseMap.clear();
  254. return;
  255. }
  256. // Copy out uses since UseMap could get touched below.
  257. using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
  258. SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
  259. llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
  260. return L.second.second < R.second.second;
  261. });
  262. UseMap.clear();
  263. for (const auto &Pair : Uses) {
  264. auto Owner = Pair.second.first;
  265. if (!Owner)
  266. continue;
  267. if (Owner.is<MetadataAsValue *>())
  268. continue;
  269. // Resolve MDNodes that point at this.
  270. auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
  271. if (!OwnerMD)
  272. continue;
  273. if (OwnerMD->isResolved())
  274. continue;
  275. OwnerMD->decrementUnresolvedOperandCount();
  276. }
  277. }
  278. ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
  279. if (auto *N = dyn_cast<MDNode>(&MD))
  280. return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
  281. return dyn_cast<ValueAsMetadata>(&MD);
  282. }
  283. ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
  284. if (auto *N = dyn_cast<MDNode>(&MD))
  285. return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
  286. return dyn_cast<ValueAsMetadata>(&MD);
  287. }
  288. bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
  289. if (auto *N = dyn_cast<MDNode>(&MD))
  290. return !N->isResolved();
  291. return dyn_cast<ValueAsMetadata>(&MD);
  292. }
  293. static DISubprogram *getLocalFunctionMetadata(Value *V) {
  294. assert(V && "Expected value");
  295. if (auto *A = dyn_cast<Argument>(V)) {
  296. if (auto *Fn = A->getParent())
  297. return Fn->getSubprogram();
  298. return nullptr;
  299. }
  300. if (BasicBlock *BB = cast<Instruction>(V)->getParent()) {
  301. if (auto *Fn = BB->getParent())
  302. return Fn->getSubprogram();
  303. return nullptr;
  304. }
  305. return nullptr;
  306. }
  307. ValueAsMetadata *ValueAsMetadata::get(Value *V) {
  308. assert(V && "Unexpected null Value");
  309. auto &Context = V->getContext();
  310. auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
  311. if (!Entry) {
  312. assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
  313. "Expected constant or function-local value");
  314. assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
  315. V->IsUsedByMD = true;
  316. if (auto *C = dyn_cast<Constant>(V))
  317. Entry = new ConstantAsMetadata(C);
  318. else
  319. Entry = new LocalAsMetadata(V);
  320. }
  321. return Entry;
  322. }
  323. ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
  324. assert(V && "Unexpected null Value");
  325. return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
  326. }
  327. void ValueAsMetadata::handleDeletion(Value *V) {
  328. assert(V && "Expected valid value");
  329. auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
  330. auto I = Store.find(V);
  331. if (I == Store.end())
  332. return;
  333. // Remove old entry from the map.
  334. ValueAsMetadata *MD = I->second;
  335. assert(MD && "Expected valid metadata");
  336. assert(MD->getValue() == V && "Expected valid mapping");
  337. Store.erase(I);
  338. // Delete the metadata.
  339. MD->replaceAllUsesWith(nullptr);
  340. delete MD;
  341. }
  342. void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
  343. assert(From && "Expected valid value");
  344. assert(To && "Expected valid value");
  345. assert(From != To && "Expected changed value");
  346. assert(From->getType() == To->getType() && "Unexpected type change");
  347. LLVMContext &Context = From->getType()->getContext();
  348. auto &Store = Context.pImpl->ValuesAsMetadata;
  349. auto I = Store.find(From);
  350. if (I == Store.end()) {
  351. assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
  352. return;
  353. }
  354. // Remove old entry from the map.
  355. assert(From->IsUsedByMD && "Expected From to be used by metadata");
  356. From->IsUsedByMD = false;
  357. ValueAsMetadata *MD = I->second;
  358. assert(MD && "Expected valid metadata");
  359. assert(MD->getValue() == From && "Expected valid mapping");
  360. Store.erase(I);
  361. if (isa<LocalAsMetadata>(MD)) {
  362. if (auto *C = dyn_cast<Constant>(To)) {
  363. // Local became a constant.
  364. MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
  365. delete MD;
  366. return;
  367. }
  368. if (getLocalFunctionMetadata(From) && getLocalFunctionMetadata(To) &&
  369. getLocalFunctionMetadata(From) != getLocalFunctionMetadata(To)) {
  370. // DISubprogram changed.
  371. MD->replaceAllUsesWith(nullptr);
  372. delete MD;
  373. return;
  374. }
  375. } else if (!isa<Constant>(To)) {
  376. // Changed to function-local value.
  377. MD->replaceAllUsesWith(nullptr);
  378. delete MD;
  379. return;
  380. }
  381. auto *&Entry = Store[To];
  382. if (Entry) {
  383. // The target already exists.
  384. MD->replaceAllUsesWith(Entry);
  385. delete MD;
  386. return;
  387. }
  388. // Update MD in place (and update the map entry).
  389. assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
  390. To->IsUsedByMD = true;
  391. MD->V = To;
  392. Entry = MD;
  393. }
  394. //===----------------------------------------------------------------------===//
  395. // MDString implementation.
  396. //
  397. MDString *MDString::get(LLVMContext &Context, StringRef Str) {
  398. auto &Store = Context.pImpl->MDStringCache;
  399. auto I = Store.try_emplace(Str);
  400. auto &MapEntry = I.first->getValue();
  401. if (!I.second)
  402. return &MapEntry;
  403. MapEntry.Entry = &*I.first;
  404. return &MapEntry;
  405. }
  406. StringRef MDString::getString() const {
  407. assert(Entry && "Expected to find string map entry");
  408. return Entry->first();
  409. }
  410. //===----------------------------------------------------------------------===//
  411. // MDNode implementation.
  412. //
  413. // Assert that the MDNode types will not be unaligned by the objects
  414. // prepended to them.
  415. #define HANDLE_MDNODE_LEAF(CLASS) \
  416. static_assert( \
  417. alignof(uint64_t) >= alignof(CLASS), \
  418. "Alignment is insufficient after objects prepended to " #CLASS);
  419. #include "llvm/IR/Metadata.def"
  420. void *MDNode::operator new(size_t Size, unsigned NumOps) {
  421. size_t OpSize = NumOps * sizeof(MDOperand);
  422. // uint64_t is the most aligned type we need support (ensured by static_assert
  423. // above)
  424. OpSize = alignTo(OpSize, alignof(uint64_t));
  425. void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
  426. MDOperand *O = static_cast<MDOperand *>(Ptr);
  427. for (MDOperand *E = O - NumOps; O != E; --O)
  428. (void)new (O - 1) MDOperand;
  429. return Ptr;
  430. }
  431. // Repress memory sanitization, due to use-after-destroy by operator
  432. // delete. Bug report 24578 identifies this issue.
  433. LLVM_NO_SANITIZE_MEMORY_ATTRIBUTE void MDNode::operator delete(void *Mem) {
  434. MDNode *N = static_cast<MDNode *>(Mem);
  435. size_t OpSize = N->NumOperands * sizeof(MDOperand);
  436. OpSize = alignTo(OpSize, alignof(uint64_t));
  437. MDOperand *O = static_cast<MDOperand *>(Mem);
  438. for (MDOperand *E = O - N->NumOperands; O != E; --O)
  439. (O - 1)->~MDOperand();
  440. ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
  441. }
  442. MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
  443. ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
  444. : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
  445. NumUnresolved(0), Context(Context) {
  446. unsigned Op = 0;
  447. for (Metadata *MD : Ops1)
  448. setOperand(Op++, MD);
  449. for (Metadata *MD : Ops2)
  450. setOperand(Op++, MD);
  451. if (!isUniqued())
  452. return;
  453. // Count the unresolved operands. If there are any, RAUW support will be
  454. // added lazily on first reference.
  455. countUnresolvedOperands();
  456. }
  457. TempMDNode MDNode::clone() const {
  458. switch (getMetadataID()) {
  459. default:
  460. llvm_unreachable("Invalid MDNode subclass");
  461. #define HANDLE_MDNODE_LEAF(CLASS) \
  462. case CLASS##Kind: \
  463. return cast<CLASS>(this)->cloneImpl();
  464. #include "llvm/IR/Metadata.def"
  465. }
  466. }
  467. static bool isOperandUnresolved(Metadata *Op) {
  468. if (auto *N = dyn_cast_or_null<MDNode>(Op))
  469. return !N->isResolved();
  470. return false;
  471. }
  472. void MDNode::countUnresolvedOperands() {
  473. assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
  474. assert(isUniqued() && "Expected this to be uniqued");
  475. NumUnresolved = count_if(operands(), isOperandUnresolved);
  476. }
  477. void MDNode::makeUniqued() {
  478. assert(isTemporary() && "Expected this to be temporary");
  479. assert(!isResolved() && "Expected this to be unresolved");
  480. // Enable uniquing callbacks.
  481. for (auto &Op : mutable_operands())
  482. Op.reset(Op.get(), this);
  483. // Make this 'uniqued'.
  484. Storage = Uniqued;
  485. countUnresolvedOperands();
  486. if (!NumUnresolved) {
  487. dropReplaceableUses();
  488. assert(isResolved() && "Expected this to be resolved");
  489. }
  490. assert(isUniqued() && "Expected this to be uniqued");
  491. }
  492. void MDNode::makeDistinct() {
  493. assert(isTemporary() && "Expected this to be temporary");
  494. assert(!isResolved() && "Expected this to be unresolved");
  495. // Drop RAUW support and store as a distinct node.
  496. dropReplaceableUses();
  497. storeDistinctInContext();
  498. assert(isDistinct() && "Expected this to be distinct");
  499. assert(isResolved() && "Expected this to be resolved");
  500. }
  501. void MDNode::resolve() {
  502. assert(isUniqued() && "Expected this to be uniqued");
  503. assert(!isResolved() && "Expected this to be unresolved");
  504. NumUnresolved = 0;
  505. dropReplaceableUses();
  506. assert(isResolved() && "Expected this to be resolved");
  507. }
  508. void MDNode::dropReplaceableUses() {
  509. assert(!NumUnresolved && "Unexpected unresolved operand");
  510. // Drop any RAUW support.
  511. if (Context.hasReplaceableUses())
  512. Context.takeReplaceableUses()->resolveAllUses();
  513. }
  514. void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
  515. assert(isUniqued() && "Expected this to be uniqued");
  516. assert(NumUnresolved != 0 && "Expected unresolved operands");
  517. // Check if an operand was resolved.
  518. if (!isOperandUnresolved(Old)) {
  519. if (isOperandUnresolved(New))
  520. // An operand was un-resolved!
  521. ++NumUnresolved;
  522. } else if (!isOperandUnresolved(New))
  523. decrementUnresolvedOperandCount();
  524. }
  525. void MDNode::decrementUnresolvedOperandCount() {
  526. assert(!isResolved() && "Expected this to be unresolved");
  527. if (isTemporary())
  528. return;
  529. assert(isUniqued() && "Expected this to be uniqued");
  530. if (--NumUnresolved)
  531. return;
  532. // Last unresolved operand has just been resolved.
  533. dropReplaceableUses();
  534. assert(isResolved() && "Expected this to become resolved");
  535. }
  536. void MDNode::resolveCycles() {
  537. if (isResolved())
  538. return;
  539. // Resolve this node immediately.
  540. resolve();
  541. // Resolve all operands.
  542. for (const auto &Op : operands()) {
  543. auto *N = dyn_cast_or_null<MDNode>(Op);
  544. if (!N)
  545. continue;
  546. assert(!N->isTemporary() &&
  547. "Expected all forward declarations to be resolved");
  548. if (!N->isResolved())
  549. N->resolveCycles();
  550. }
  551. }
  552. static bool hasSelfReference(MDNode *N) {
  553. return llvm::is_contained(N->operands(), N);
  554. }
  555. MDNode *MDNode::replaceWithPermanentImpl() {
  556. switch (getMetadataID()) {
  557. default:
  558. // If this type isn't uniquable, replace with a distinct node.
  559. return replaceWithDistinctImpl();
  560. #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
  561. case CLASS##Kind: \
  562. break;
  563. #include "llvm/IR/Metadata.def"
  564. }
  565. // Even if this type is uniquable, self-references have to be distinct.
  566. if (hasSelfReference(this))
  567. return replaceWithDistinctImpl();
  568. return replaceWithUniquedImpl();
  569. }
  570. MDNode *MDNode::replaceWithUniquedImpl() {
  571. // Try to uniquify in place.
  572. MDNode *UniquedNode = uniquify();
  573. if (UniquedNode == this) {
  574. makeUniqued();
  575. return this;
  576. }
  577. // Collision, so RAUW instead.
  578. replaceAllUsesWith(UniquedNode);
  579. deleteAsSubclass();
  580. return UniquedNode;
  581. }
  582. MDNode *MDNode::replaceWithDistinctImpl() {
  583. makeDistinct();
  584. return this;
  585. }
  586. void MDTuple::recalculateHash() {
  587. setHash(MDTupleInfo::KeyTy::calculateHash(this));
  588. }
  589. void MDNode::dropAllReferences() {
  590. for (unsigned I = 0, E = NumOperands; I != E; ++I)
  591. setOperand(I, nullptr);
  592. if (Context.hasReplaceableUses()) {
  593. Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
  594. (void)Context.takeReplaceableUses();
  595. }
  596. }
  597. void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
  598. unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
  599. assert(Op < getNumOperands() && "Expected valid operand");
  600. if (!isUniqued()) {
  601. // This node is not uniqued. Just set the operand and be done with it.
  602. setOperand(Op, New);
  603. return;
  604. }
  605. // This node is uniqued.
  606. eraseFromStore();
  607. Metadata *Old = getOperand(Op);
  608. setOperand(Op, New);
  609. // Drop uniquing for self-reference cycles and deleted constants.
  610. if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
  611. if (!isResolved())
  612. resolve();
  613. storeDistinctInContext();
  614. return;
  615. }
  616. // Re-unique the node.
  617. auto *Uniqued = uniquify();
  618. if (Uniqued == this) {
  619. if (!isResolved())
  620. resolveAfterOperandChange(Old, New);
  621. return;
  622. }
  623. // Collision.
  624. if (!isResolved()) {
  625. // Still unresolved, so RAUW.
  626. //
  627. // First, clear out all operands to prevent any recursion (similar to
  628. // dropAllReferences(), but we still need the use-list).
  629. for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
  630. setOperand(O, nullptr);
  631. if (Context.hasReplaceableUses())
  632. Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
  633. deleteAsSubclass();
  634. return;
  635. }
  636. // Store in non-uniqued form if RAUW isn't possible.
  637. storeDistinctInContext();
  638. }
  639. void MDNode::deleteAsSubclass() {
  640. switch (getMetadataID()) {
  641. default:
  642. llvm_unreachable("Invalid subclass of MDNode");
  643. #define HANDLE_MDNODE_LEAF(CLASS) \
  644. case CLASS##Kind: \
  645. delete cast<CLASS>(this); \
  646. break;
  647. #include "llvm/IR/Metadata.def"
  648. }
  649. }
  650. template <class T, class InfoT>
  651. static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
  652. if (T *U = getUniqued(Store, N))
  653. return U;
  654. Store.insert(N);
  655. return N;
  656. }
  657. template <class NodeTy> struct MDNode::HasCachedHash {
  658. using Yes = char[1];
  659. using No = char[2];
  660. template <class U, U Val> struct SFINAE {};
  661. template <class U>
  662. static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
  663. template <class U> static No &check(...);
  664. static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
  665. };
  666. MDNode *MDNode::uniquify() {
  667. assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
  668. // Try to insert into uniquing store.
  669. switch (getMetadataID()) {
  670. default:
  671. llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
  672. #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
  673. case CLASS##Kind: { \
  674. CLASS *SubclassThis = cast<CLASS>(this); \
  675. std::integral_constant<bool, HasCachedHash<CLASS>::value> \
  676. ShouldRecalculateHash; \
  677. dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
  678. return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
  679. }
  680. #include "llvm/IR/Metadata.def"
  681. }
  682. }
  683. void MDNode::eraseFromStore() {
  684. switch (getMetadataID()) {
  685. default:
  686. llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
  687. #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
  688. case CLASS##Kind: \
  689. getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
  690. break;
  691. #include "llvm/IR/Metadata.def"
  692. }
  693. }
  694. MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
  695. StorageType Storage, bool ShouldCreate) {
  696. unsigned Hash = 0;
  697. if (Storage == Uniqued) {
  698. MDTupleInfo::KeyTy Key(MDs);
  699. if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
  700. return N;
  701. if (!ShouldCreate)
  702. return nullptr;
  703. Hash = Key.getHash();
  704. } else {
  705. assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
  706. }
  707. return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
  708. Storage, Context.pImpl->MDTuples);
  709. }
  710. void MDNode::deleteTemporary(MDNode *N) {
  711. assert(N->isTemporary() && "Expected temporary node");
  712. N->replaceAllUsesWith(nullptr);
  713. N->deleteAsSubclass();
  714. }
  715. void MDNode::storeDistinctInContext() {
  716. assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
  717. assert(!NumUnresolved && "Unexpected unresolved nodes");
  718. Storage = Distinct;
  719. assert(isResolved() && "Expected this to be resolved");
  720. // Reset the hash.
  721. switch (getMetadataID()) {
  722. default:
  723. llvm_unreachable("Invalid subclass of MDNode");
  724. #define HANDLE_MDNODE_LEAF(CLASS) \
  725. case CLASS##Kind: { \
  726. std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
  727. dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
  728. break; \
  729. }
  730. #include "llvm/IR/Metadata.def"
  731. }
  732. getContext().pImpl->DistinctMDNodes.push_back(this);
  733. }
  734. void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
  735. if (getOperand(I) == New)
  736. return;
  737. if (!isUniqued()) {
  738. setOperand(I, New);
  739. return;
  740. }
  741. handleChangedOperand(mutable_begin() + I, New);
  742. }
  743. void MDNode::setOperand(unsigned I, Metadata *New) {
  744. assert(I < NumOperands);
  745. mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
  746. }
  747. /// Get a node or a self-reference that looks like it.
  748. ///
  749. /// Special handling for finding self-references, for use by \a
  750. /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
  751. /// when self-referencing nodes were still uniqued. If the first operand has
  752. /// the same operands as \c Ops, return the first operand instead.
  753. static MDNode *getOrSelfReference(LLVMContext &Context,
  754. ArrayRef<Metadata *> Ops) {
  755. if (!Ops.empty())
  756. if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
  757. if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
  758. for (unsigned I = 1, E = Ops.size(); I != E; ++I)
  759. if (Ops[I] != N->getOperand(I))
  760. return MDNode::get(Context, Ops);
  761. return N;
  762. }
  763. return MDNode::get(Context, Ops);
  764. }
  765. MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
  766. if (!A)
  767. return B;
  768. if (!B)
  769. return A;
  770. SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
  771. MDs.insert(B->op_begin(), B->op_end());
  772. // FIXME: This preserves long-standing behaviour, but is it really the right
  773. // behaviour? Or was that an unintended side-effect of node uniquing?
  774. return getOrSelfReference(A->getContext(), MDs.getArrayRef());
  775. }
  776. MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
  777. if (!A || !B)
  778. return nullptr;
  779. SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
  780. SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
  781. MDs.remove_if([&](Metadata *MD) { return !BSet.count(MD); });
  782. // FIXME: This preserves long-standing behaviour, but is it really the right
  783. // behaviour? Or was that an unintended side-effect of node uniquing?
  784. return getOrSelfReference(A->getContext(), MDs.getArrayRef());
  785. }
  786. MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
  787. if (!A || !B)
  788. return nullptr;
  789. // Take the intersection of domains then union the scopes
  790. // within those domains
  791. SmallPtrSet<const MDNode *, 16> ADomains;
  792. SmallPtrSet<const MDNode *, 16> IntersectDomains;
  793. SmallSetVector<Metadata *, 4> MDs;
  794. for (const MDOperand &MDOp : A->operands())
  795. if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
  796. if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
  797. ADomains.insert(Domain);
  798. for (const MDOperand &MDOp : B->operands())
  799. if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
  800. if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
  801. if (ADomains.contains(Domain)) {
  802. IntersectDomains.insert(Domain);
  803. MDs.insert(MDOp);
  804. }
  805. for (const MDOperand &MDOp : A->operands())
  806. if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
  807. if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
  808. if (IntersectDomains.contains(Domain))
  809. MDs.insert(MDOp);
  810. return MDs.empty() ? nullptr
  811. : getOrSelfReference(A->getContext(), MDs.getArrayRef());
  812. }
  813. MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
  814. if (!A || !B)
  815. return nullptr;
  816. APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
  817. APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
  818. if (AVal < BVal)
  819. return A;
  820. return B;
  821. }
  822. static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
  823. return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
  824. }
  825. static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
  826. return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
  827. }
  828. static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
  829. ConstantInt *Low, ConstantInt *High) {
  830. ConstantRange NewRange(Low->getValue(), High->getValue());
  831. unsigned Size = EndPoints.size();
  832. APInt LB = EndPoints[Size - 2]->getValue();
  833. APInt LE = EndPoints[Size - 1]->getValue();
  834. ConstantRange LastRange(LB, LE);
  835. if (canBeMerged(NewRange, LastRange)) {
  836. ConstantRange Union = LastRange.unionWith(NewRange);
  837. Type *Ty = High->getType();
  838. EndPoints[Size - 2] =
  839. cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
  840. EndPoints[Size - 1] =
  841. cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
  842. return true;
  843. }
  844. return false;
  845. }
  846. static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
  847. ConstantInt *Low, ConstantInt *High) {
  848. if (!EndPoints.empty())
  849. if (tryMergeRange(EndPoints, Low, High))
  850. return;
  851. EndPoints.push_back(Low);
  852. EndPoints.push_back(High);
  853. }
  854. MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
  855. // Given two ranges, we want to compute the union of the ranges. This
  856. // is slightly complicated by having to combine the intervals and merge
  857. // the ones that overlap.
  858. if (!A || !B)
  859. return nullptr;
  860. if (A == B)
  861. return A;
  862. // First, walk both lists in order of the lower boundary of each interval.
  863. // At each step, try to merge the new interval to the last one we adedd.
  864. SmallVector<ConstantInt *, 4> EndPoints;
  865. int AI = 0;
  866. int BI = 0;
  867. int AN = A->getNumOperands() / 2;
  868. int BN = B->getNumOperands() / 2;
  869. while (AI < AN && BI < BN) {
  870. ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
  871. ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
  872. if (ALow->getValue().slt(BLow->getValue())) {
  873. addRange(EndPoints, ALow,
  874. mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
  875. ++AI;
  876. } else {
  877. addRange(EndPoints, BLow,
  878. mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
  879. ++BI;
  880. }
  881. }
  882. while (AI < AN) {
  883. addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
  884. mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
  885. ++AI;
  886. }
  887. while (BI < BN) {
  888. addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
  889. mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
  890. ++BI;
  891. }
  892. // If we have more than 2 ranges (4 endpoints) we have to try to merge
  893. // the last and first ones.
  894. unsigned Size = EndPoints.size();
  895. if (Size > 4) {
  896. ConstantInt *FB = EndPoints[0];
  897. ConstantInt *FE = EndPoints[1];
  898. if (tryMergeRange(EndPoints, FB, FE)) {
  899. for (unsigned i = 0; i < Size - 2; ++i) {
  900. EndPoints[i] = EndPoints[i + 2];
  901. }
  902. EndPoints.resize(Size - 2);
  903. }
  904. }
  905. // If in the end we have a single range, it is possible that it is now the
  906. // full range. Just drop the metadata in that case.
  907. if (EndPoints.size() == 2) {
  908. ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
  909. if (Range.isFullSet())
  910. return nullptr;
  911. }
  912. SmallVector<Metadata *, 4> MDs;
  913. MDs.reserve(EndPoints.size());
  914. for (auto *I : EndPoints)
  915. MDs.push_back(ConstantAsMetadata::get(I));
  916. return MDNode::get(A->getContext(), MDs);
  917. }
  918. MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
  919. if (!A || !B)
  920. return nullptr;
  921. ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
  922. ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
  923. if (AVal->getZExtValue() < BVal->getZExtValue())
  924. return A;
  925. return B;
  926. }
  927. //===----------------------------------------------------------------------===//
  928. // NamedMDNode implementation.
  929. //
  930. static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
  931. return *(SmallVector<TrackingMDRef, 4> *)Operands;
  932. }
  933. NamedMDNode::NamedMDNode(const Twine &N)
  934. : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
  935. NamedMDNode::~NamedMDNode() {
  936. dropAllReferences();
  937. delete &getNMDOps(Operands);
  938. }
  939. unsigned NamedMDNode::getNumOperands() const {
  940. return (unsigned)getNMDOps(Operands).size();
  941. }
  942. MDNode *NamedMDNode::getOperand(unsigned i) const {
  943. assert(i < getNumOperands() && "Invalid Operand number!");
  944. auto *N = getNMDOps(Operands)[i].get();
  945. return cast_or_null<MDNode>(N);
  946. }
  947. void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
  948. void NamedMDNode::setOperand(unsigned I, MDNode *New) {
  949. assert(I < getNumOperands() && "Invalid operand number");
  950. getNMDOps(Operands)[I].reset(New);
  951. }
  952. void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
  953. void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
  954. StringRef NamedMDNode::getName() const { return StringRef(Name); }
  955. //===----------------------------------------------------------------------===//
  956. // Instruction Metadata method implementations.
  957. //
  958. MDNode *MDAttachments::lookup(unsigned ID) const {
  959. for (const auto &A : Attachments)
  960. if (A.MDKind == ID)
  961. return A.Node;
  962. return nullptr;
  963. }
  964. void MDAttachments::get(unsigned ID, SmallVectorImpl<MDNode *> &Result) const {
  965. for (const auto &A : Attachments)
  966. if (A.MDKind == ID)
  967. Result.push_back(A.Node);
  968. }
  969. void MDAttachments::getAll(
  970. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  971. for (const auto &A : Attachments)
  972. Result.emplace_back(A.MDKind, A.Node);
  973. // Sort the resulting array so it is stable with respect to metadata IDs. We
  974. // need to preserve the original insertion order though.
  975. if (Result.size() > 1)
  976. llvm::stable_sort(Result, less_first());
  977. }
  978. void MDAttachments::set(unsigned ID, MDNode *MD) {
  979. erase(ID);
  980. if (MD)
  981. insert(ID, *MD);
  982. }
  983. void MDAttachments::insert(unsigned ID, MDNode &MD) {
  984. Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
  985. }
  986. bool MDAttachments::erase(unsigned ID) {
  987. if (empty())
  988. return false;
  989. // Common case is one value.
  990. if (Attachments.size() == 1 && Attachments.back().MDKind == ID) {
  991. Attachments.pop_back();
  992. return true;
  993. }
  994. auto OldSize = Attachments.size();
  995. llvm::erase_if(Attachments,
  996. [ID](const Attachment &A) { return A.MDKind == ID; });
  997. return OldSize != Attachments.size();
  998. }
  999. MDNode *Value::getMetadata(unsigned KindID) const {
  1000. if (!hasMetadata())
  1001. return nullptr;
  1002. const auto &Info = getContext().pImpl->ValueMetadata[this];
  1003. assert(!Info.empty() && "bit out of sync with hash table");
  1004. return Info.lookup(KindID);
  1005. }
  1006. MDNode *Value::getMetadata(StringRef Kind) const {
  1007. if (!hasMetadata())
  1008. return nullptr;
  1009. const auto &Info = getContext().pImpl->ValueMetadata[this];
  1010. assert(!Info.empty() && "bit out of sync with hash table");
  1011. return Info.lookup(getContext().getMDKindID(Kind));
  1012. }
  1013. void Value::getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const {
  1014. if (hasMetadata())
  1015. getContext().pImpl->ValueMetadata[this].get(KindID, MDs);
  1016. }
  1017. void Value::getMetadata(StringRef Kind, SmallVectorImpl<MDNode *> &MDs) const {
  1018. if (hasMetadata())
  1019. getMetadata(getContext().getMDKindID(Kind), MDs);
  1020. }
  1021. void Value::getAllMetadata(
  1022. SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
  1023. if (hasMetadata()) {
  1024. assert(getContext().pImpl->ValueMetadata.count(this) &&
  1025. "bit out of sync with hash table");
  1026. const auto &Info = getContext().pImpl->ValueMetadata.find(this)->second;
  1027. assert(!Info.empty() && "Shouldn't have called this");
  1028. Info.getAll(MDs);
  1029. }
  1030. }
  1031. void Value::setMetadata(unsigned KindID, MDNode *Node) {
  1032. assert(isa<Instruction>(this) || isa<GlobalObject>(this));
  1033. // Handle the case when we're adding/updating metadata on a value.
  1034. if (Node) {
  1035. auto &Info = getContext().pImpl->ValueMetadata[this];
  1036. assert(!Info.empty() == HasMetadata && "bit out of sync with hash table");
  1037. if (Info.empty())
  1038. HasMetadata = true;
  1039. Info.set(KindID, Node);
  1040. return;
  1041. }
  1042. // Otherwise, we're removing metadata from an instruction.
  1043. assert((HasMetadata == (getContext().pImpl->ValueMetadata.count(this) > 0)) &&
  1044. "bit out of sync with hash table");
  1045. if (!HasMetadata)
  1046. return; // Nothing to remove!
  1047. auto &Info = getContext().pImpl->ValueMetadata[this];
  1048. // Handle removal of an existing value.
  1049. Info.erase(KindID);
  1050. if (!Info.empty())
  1051. return;
  1052. getContext().pImpl->ValueMetadata.erase(this);
  1053. HasMetadata = false;
  1054. }
  1055. void Value::setMetadata(StringRef Kind, MDNode *Node) {
  1056. if (!Node && !HasMetadata)
  1057. return;
  1058. setMetadata(getContext().getMDKindID(Kind), Node);
  1059. }
  1060. void Value::addMetadata(unsigned KindID, MDNode &MD) {
  1061. assert(isa<Instruction>(this) || isa<GlobalObject>(this));
  1062. if (!HasMetadata)
  1063. HasMetadata = true;
  1064. getContext().pImpl->ValueMetadata[this].insert(KindID, MD);
  1065. }
  1066. void Value::addMetadata(StringRef Kind, MDNode &MD) {
  1067. addMetadata(getContext().getMDKindID(Kind), MD);
  1068. }
  1069. bool Value::eraseMetadata(unsigned KindID) {
  1070. // Nothing to unset.
  1071. if (!HasMetadata)
  1072. return false;
  1073. auto &Store = getContext().pImpl->ValueMetadata[this];
  1074. bool Changed = Store.erase(KindID);
  1075. if (Store.empty())
  1076. clearMetadata();
  1077. return Changed;
  1078. }
  1079. void Value::clearMetadata() {
  1080. if (!HasMetadata)
  1081. return;
  1082. assert(getContext().pImpl->ValueMetadata.count(this) &&
  1083. "bit out of sync with hash table");
  1084. getContext().pImpl->ValueMetadata.erase(this);
  1085. HasMetadata = false;
  1086. }
  1087. void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
  1088. if (!Node && !hasMetadata())
  1089. return;
  1090. setMetadata(getContext().getMDKindID(Kind), Node);
  1091. }
  1092. MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
  1093. return getMetadataImpl(getContext().getMDKindID(Kind));
  1094. }
  1095. void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
  1096. if (!Value::hasMetadata())
  1097. return; // Nothing to remove!
  1098. if (KnownIDs.empty()) {
  1099. // Just drop our entry at the store.
  1100. clearMetadata();
  1101. return;
  1102. }
  1103. SmallSet<unsigned, 4> KnownSet;
  1104. KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
  1105. auto &MetadataStore = getContext().pImpl->ValueMetadata;
  1106. auto &Info = MetadataStore[this];
  1107. assert(!Info.empty() && "bit out of sync with hash table");
  1108. Info.remove_if([&KnownSet](const MDAttachments::Attachment &I) {
  1109. return !KnownSet.count(I.MDKind);
  1110. });
  1111. if (Info.empty()) {
  1112. // Drop our entry at the store.
  1113. clearMetadata();
  1114. }
  1115. }
  1116. void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
  1117. if (!Node && !hasMetadata())
  1118. return;
  1119. // Handle 'dbg' as a special case since it is not stored in the hash table.
  1120. if (KindID == LLVMContext::MD_dbg) {
  1121. DbgLoc = DebugLoc(Node);
  1122. return;
  1123. }
  1124. Value::setMetadata(KindID, Node);
  1125. }
  1126. void Instruction::addAnnotationMetadata(StringRef Name) {
  1127. MDBuilder MDB(getContext());
  1128. auto *Existing = getMetadata(LLVMContext::MD_annotation);
  1129. SmallVector<Metadata *, 4> Names;
  1130. bool AppendName = true;
  1131. if (Existing) {
  1132. auto *Tuple = cast<MDTuple>(Existing);
  1133. for (auto &N : Tuple->operands()) {
  1134. if (cast<MDString>(N.get())->getString() == Name)
  1135. AppendName = false;
  1136. Names.push_back(N.get());
  1137. }
  1138. }
  1139. if (AppendName)
  1140. Names.push_back(MDB.createString(Name));
  1141. MDNode *MD = MDTuple::get(getContext(), Names);
  1142. setMetadata(LLVMContext::MD_annotation, MD);
  1143. }
  1144. void Instruction::setAAMetadata(const AAMDNodes &N) {
  1145. setMetadata(LLVMContext::MD_tbaa, N.TBAA);
  1146. setMetadata(LLVMContext::MD_tbaa_struct, N.TBAAStruct);
  1147. setMetadata(LLVMContext::MD_alias_scope, N.Scope);
  1148. setMetadata(LLVMContext::MD_noalias, N.NoAlias);
  1149. }
  1150. MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
  1151. // Handle 'dbg' as a special case since it is not stored in the hash table.
  1152. if (KindID == LLVMContext::MD_dbg)
  1153. return DbgLoc.getAsMDNode();
  1154. return Value::getMetadata(KindID);
  1155. }
  1156. void Instruction::getAllMetadataImpl(
  1157. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  1158. Result.clear();
  1159. // Handle 'dbg' as a special case since it is not stored in the hash table.
  1160. if (DbgLoc) {
  1161. Result.push_back(
  1162. std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
  1163. }
  1164. Value::getAllMetadata(Result);
  1165. }
  1166. bool Instruction::extractProfMetadata(uint64_t &TrueVal,
  1167. uint64_t &FalseVal) const {
  1168. assert(
  1169. (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select) &&
  1170. "Looking for branch weights on something besides branch or select");
  1171. auto *ProfileData = getMetadata(LLVMContext::MD_prof);
  1172. if (!ProfileData || ProfileData->getNumOperands() != 3)
  1173. return false;
  1174. auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
  1175. if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
  1176. return false;
  1177. auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
  1178. auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
  1179. if (!CITrue || !CIFalse)
  1180. return false;
  1181. TrueVal = CITrue->getValue().getZExtValue();
  1182. FalseVal = CIFalse->getValue().getZExtValue();
  1183. return true;
  1184. }
  1185. bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
  1186. assert((getOpcode() == Instruction::Br ||
  1187. getOpcode() == Instruction::Select ||
  1188. getOpcode() == Instruction::Call ||
  1189. getOpcode() == Instruction::Invoke ||
  1190. getOpcode() == Instruction::Switch) &&
  1191. "Looking for branch weights on something besides branch");
  1192. TotalVal = 0;
  1193. auto *ProfileData = getMetadata(LLVMContext::MD_prof);
  1194. if (!ProfileData)
  1195. return false;
  1196. auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
  1197. if (!ProfDataName)
  1198. return false;
  1199. if (ProfDataName->getString().equals("branch_weights")) {
  1200. TotalVal = 0;
  1201. for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
  1202. auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
  1203. if (!V)
  1204. return false;
  1205. TotalVal += V->getValue().getZExtValue();
  1206. }
  1207. return true;
  1208. } else if (ProfDataName->getString().equals("VP") &&
  1209. ProfileData->getNumOperands() > 3) {
  1210. TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
  1211. ->getValue()
  1212. .getZExtValue();
  1213. return true;
  1214. }
  1215. return false;
  1216. }
  1217. void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
  1218. SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
  1219. Other->getAllMetadata(MDs);
  1220. for (auto &MD : MDs) {
  1221. // We need to adjust the type metadata offset.
  1222. if (Offset != 0 && MD.first == LLVMContext::MD_type) {
  1223. auto *OffsetConst = cast<ConstantInt>(
  1224. cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
  1225. Metadata *TypeId = MD.second->getOperand(1);
  1226. auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
  1227. OffsetConst->getType(), OffsetConst->getValue() + Offset));
  1228. addMetadata(LLVMContext::MD_type,
  1229. *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
  1230. continue;
  1231. }
  1232. // If an offset adjustment was specified we need to modify the DIExpression
  1233. // to prepend the adjustment:
  1234. // !DIExpression(DW_OP_plus, Offset, [original expr])
  1235. auto *Attachment = MD.second;
  1236. if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
  1237. DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
  1238. DIExpression *E = nullptr;
  1239. if (!GV) {
  1240. auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
  1241. GV = GVE->getVariable();
  1242. E = GVE->getExpression();
  1243. }
  1244. ArrayRef<uint64_t> OrigElements;
  1245. if (E)
  1246. OrigElements = E->getElements();
  1247. std::vector<uint64_t> Elements(OrigElements.size() + 2);
  1248. Elements[0] = dwarf::DW_OP_plus_uconst;
  1249. Elements[1] = Offset;
  1250. llvm::copy(OrigElements, Elements.begin() + 2);
  1251. E = DIExpression::get(getContext(), Elements);
  1252. Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
  1253. }
  1254. addMetadata(MD.first, *Attachment);
  1255. }
  1256. }
  1257. void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {
  1258. addMetadata(
  1259. LLVMContext::MD_type,
  1260. *MDTuple::get(getContext(),
  1261. {ConstantAsMetadata::get(ConstantInt::get(
  1262. Type::getInt64Ty(getContext()), Offset)),
  1263. TypeID}));
  1264. }
  1265. void GlobalObject::setVCallVisibilityMetadata(VCallVisibility Visibility) {
  1266. // Remove any existing vcall visibility metadata first in case we are
  1267. // updating.
  1268. eraseMetadata(LLVMContext::MD_vcall_visibility);
  1269. addMetadata(LLVMContext::MD_vcall_visibility,
  1270. *MDNode::get(getContext(),
  1271. {ConstantAsMetadata::get(ConstantInt::get(
  1272. Type::getInt64Ty(getContext()), Visibility))}));
  1273. }
  1274. GlobalObject::VCallVisibility GlobalObject::getVCallVisibility() const {
  1275. if (MDNode *MD = getMetadata(LLVMContext::MD_vcall_visibility)) {
  1276. uint64_t Val = cast<ConstantInt>(
  1277. cast<ConstantAsMetadata>(MD->getOperand(0))->getValue())
  1278. ->getZExtValue();
  1279. assert(Val <= 2 && "unknown vcall visibility!");
  1280. return (VCallVisibility)Val;
  1281. }
  1282. return VCallVisibility::VCallVisibilityPublic;
  1283. }
  1284. void Function::setSubprogram(DISubprogram *SP) {
  1285. setMetadata(LLVMContext::MD_dbg, SP);
  1286. }
  1287. DISubprogram *Function::getSubprogram() const {
  1288. return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
  1289. }
  1290. bool Function::isDebugInfoForProfiling() const {
  1291. if (DISubprogram *SP = getSubprogram()) {
  1292. if (DICompileUnit *CU = SP->getUnit()) {
  1293. return CU->getDebugInfoForProfiling();
  1294. }
  1295. }
  1296. return false;
  1297. }
  1298. void GlobalVariable::addDebugInfo(DIGlobalVariableExpression *GV) {
  1299. addMetadata(LLVMContext::MD_dbg, *GV);
  1300. }
  1301. void GlobalVariable::getDebugInfo(
  1302. SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const {
  1303. SmallVector<MDNode *, 1> MDs;
  1304. getMetadata(LLVMContext::MD_dbg, MDs);
  1305. for (MDNode *MD : MDs)
  1306. GVs.push_back(cast<DIGlobalVariableExpression>(MD));
  1307. }