Metadata.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  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 "LLVMContextImpl.h"
  13. #include "MetadataImpl.h"
  14. #include "SymbolTableListTraitsImpl.h"
  15. #include "llvm/ADT/APFloat.h"
  16. #include "llvm/ADT/APInt.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/DenseSet.h"
  19. #include "llvm/ADT/None.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SetVector.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/StringMap.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/IR/Argument.h"
  29. #include "llvm/IR/BasicBlock.h"
  30. #include "llvm/IR/Constant.h"
  31. #include "llvm/IR/ConstantRange.h"
  32. #include "llvm/IR/Constants.h"
  33. #include "llvm/IR/DebugInfoMetadata.h"
  34. #include "llvm/IR/DebugLoc.h"
  35. #include "llvm/IR/Function.h"
  36. #include "llvm/IR/GlobalObject.h"
  37. #include "llvm/IR/GlobalVariable.h"
  38. #include "llvm/IR/Instruction.h"
  39. #include "llvm/IR/LLVMContext.h"
  40. #include "llvm/IR/Metadata.h"
  41. #include "llvm/IR/Module.h"
  42. #include "llvm/IR/TrackingMDRef.h"
  43. #include "llvm/IR/Type.h"
  44. #include "llvm/IR/Value.h"
  45. #include "llvm/IR/ValueHandle.h"
  46. #include "llvm/Support/Casting.h"
  47. #include "llvm/Support/ErrorHandling.h"
  48. #include "llvm/Support/MathExtras.h"
  49. #include <algorithm>
  50. #include <cassert>
  51. #include <cstddef>
  52. #include <cstdint>
  53. #include <iterator>
  54. #include <tuple>
  55. #include <type_traits>
  56. #include <utility>
  57. #include <vector>
  58. using namespace llvm;
  59. MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
  60. : Value(Ty, MetadataAsValueVal), MD(MD) {
  61. track();
  62. }
  63. MetadataAsValue::~MetadataAsValue() {
  64. getType()->getContext().pImpl->MetadataAsValues.erase(MD);
  65. untrack();
  66. }
  67. /// Canonicalize metadata arguments to intrinsics.
  68. ///
  69. /// To support bitcode upgrades (and assembly semantic sugar) for \a
  70. /// MetadataAsValue, we need to canonicalize certain metadata.
  71. ///
  72. /// - nullptr is replaced by an empty MDNode.
  73. /// - An MDNode with a single null operand is replaced by an empty MDNode.
  74. /// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
  75. ///
  76. /// This maintains readability of bitcode from when metadata was a type of
  77. /// value, and these bridges were unnecessary.
  78. static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
  79. Metadata *MD) {
  80. if (!MD)
  81. // !{}
  82. return MDNode::get(Context, None);
  83. // Return early if this isn't a single-operand MDNode.
  84. auto *N = dyn_cast<MDNode>(MD);
  85. if (!N || N->getNumOperands() != 1)
  86. return MD;
  87. if (!N->getOperand(0))
  88. // !{}
  89. return MDNode::get(Context, None);
  90. if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
  91. // Look through the MDNode.
  92. return C;
  93. return MD;
  94. }
  95. MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
  96. MD = canonicalizeMetadataForValue(Context, MD);
  97. auto *&Entry = Context.pImpl->MetadataAsValues[MD];
  98. if (!Entry)
  99. Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
  100. return Entry;
  101. }
  102. MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
  103. Metadata *MD) {
  104. MD = canonicalizeMetadataForValue(Context, MD);
  105. auto &Store = Context.pImpl->MetadataAsValues;
  106. return Store.lookup(MD);
  107. }
  108. void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
  109. LLVMContext &Context = getContext();
  110. MD = canonicalizeMetadataForValue(Context, MD);
  111. auto &Store = Context.pImpl->MetadataAsValues;
  112. // Stop tracking the old metadata.
  113. Store.erase(this->MD);
  114. untrack();
  115. this->MD = nullptr;
  116. // Start tracking MD, or RAUW if necessary.
  117. auto *&Entry = Store[MD];
  118. if (Entry) {
  119. replaceAllUsesWith(Entry);
  120. delete this;
  121. return;
  122. }
  123. this->MD = MD;
  124. track();
  125. Entry = this;
  126. }
  127. void MetadataAsValue::track() {
  128. if (MD)
  129. MetadataTracking::track(&MD, *MD, *this);
  130. }
  131. void MetadataAsValue::untrack() {
  132. if (MD)
  133. MetadataTracking::untrack(MD);
  134. }
  135. bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
  136. assert(Ref && "Expected live reference");
  137. assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
  138. "Reference without owner must be direct");
  139. if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
  140. R->addRef(Ref, Owner);
  141. return true;
  142. }
  143. if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
  144. assert(!PH->Use && "Placeholders can only be used once");
  145. assert(!Owner && "Unexpected callback to owner");
  146. PH->Use = static_cast<Metadata **>(Ref);
  147. return true;
  148. }
  149. return false;
  150. }
  151. void MetadataTracking::untrack(void *Ref, Metadata &MD) {
  152. assert(Ref && "Expected live reference");
  153. if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
  154. R->dropRef(Ref);
  155. else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
  156. PH->Use = nullptr;
  157. }
  158. bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
  159. assert(Ref && "Expected live reference");
  160. assert(New && "Expected live reference");
  161. assert(Ref != New && "Expected change");
  162. if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
  163. R->moveRef(Ref, New, MD);
  164. return true;
  165. }
  166. assert(!isa<DistinctMDOperandPlaceholder>(MD) &&
  167. "Unexpected move of an MDOperand");
  168. assert(!isReplaceable(MD) &&
  169. "Expected un-replaceable metadata, since we didn't move a reference");
  170. return false;
  171. }
  172. bool MetadataTracking::isReplaceable(const Metadata &MD) {
  173. return ReplaceableMetadataImpl::isReplaceable(MD);
  174. }
  175. void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
  176. bool WasInserted =
  177. UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
  178. .second;
  179. (void)WasInserted;
  180. assert(WasInserted && "Expected to add a reference");
  181. ++NextIndex;
  182. assert(NextIndex != 0 && "Unexpected overflow");
  183. }
  184. void ReplaceableMetadataImpl::dropRef(void *Ref) {
  185. bool WasErased = UseMap.erase(Ref);
  186. (void)WasErased;
  187. assert(WasErased && "Expected to drop a reference");
  188. }
  189. void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
  190. const Metadata &MD) {
  191. auto I = UseMap.find(Ref);
  192. assert(I != UseMap.end() && "Expected to move a reference");
  193. auto OwnerAndIndex = I->second;
  194. UseMap.erase(I);
  195. bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
  196. (void)WasInserted;
  197. assert(WasInserted && "Expected to add a reference");
  198. // Check that the references are direct if there's no owner.
  199. (void)MD;
  200. assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
  201. "Reference without owner must be direct");
  202. assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
  203. "Reference without owner must be direct");
  204. }
  205. void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
  206. if (UseMap.empty())
  207. return;
  208. // Copy out uses since UseMap will get touched below.
  209. using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
  210. SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
  211. llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
  212. return L.second.second < R.second.second;
  213. });
  214. for (const auto &Pair : Uses) {
  215. // Check that this Ref hasn't disappeared after RAUW (when updating a
  216. // previous Ref).
  217. if (!UseMap.count(Pair.first))
  218. continue;
  219. OwnerTy Owner = Pair.second.first;
  220. if (!Owner) {
  221. // Update unowned tracking references directly.
  222. Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
  223. Ref = MD;
  224. if (MD)
  225. MetadataTracking::track(Ref);
  226. UseMap.erase(Pair.first);
  227. continue;
  228. }
  229. // Check for MetadataAsValue.
  230. if (Owner.is<MetadataAsValue *>()) {
  231. Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
  232. continue;
  233. }
  234. // There's a Metadata owner -- dispatch.
  235. Metadata *OwnerMD = Owner.get<Metadata *>();
  236. switch (OwnerMD->getMetadataID()) {
  237. #define HANDLE_METADATA_LEAF(CLASS) \
  238. case Metadata::CLASS##Kind: \
  239. cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
  240. continue;
  241. #include "llvm/IR/Metadata.def"
  242. default:
  243. llvm_unreachable("Invalid metadata subclass");
  244. }
  245. }
  246. assert(UseMap.empty() && "Expected all uses to be replaced");
  247. }
  248. void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
  249. if (UseMap.empty())
  250. return;
  251. if (!ResolveUsers) {
  252. UseMap.clear();
  253. return;
  254. }
  255. // Copy out uses since UseMap could get touched below.
  256. using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
  257. SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
  258. llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
  259. return L.second.second < R.second.second;
  260. });
  261. UseMap.clear();
  262. for (const auto &Pair : Uses) {
  263. auto Owner = Pair.second.first;
  264. if (!Owner)
  265. continue;
  266. if (Owner.is<MetadataAsValue *>())
  267. continue;
  268. // Resolve MDNodes that point at this.
  269. auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
  270. if (!OwnerMD)
  271. continue;
  272. if (OwnerMD->isResolved())
  273. continue;
  274. OwnerMD->decrementUnresolvedOperandCount();
  275. }
  276. }
  277. ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
  278. if (auto *N = dyn_cast<MDNode>(&MD))
  279. return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
  280. return dyn_cast<ValueAsMetadata>(&MD);
  281. }
  282. ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
  283. if (auto *N = dyn_cast<MDNode>(&MD))
  284. return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
  285. return dyn_cast<ValueAsMetadata>(&MD);
  286. }
  287. bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
  288. if (auto *N = dyn_cast<MDNode>(&MD))
  289. return !N->isResolved();
  290. return dyn_cast<ValueAsMetadata>(&MD);
  291. }
  292. static DISubprogram *getLocalFunctionMetadata(Value *V) {
  293. assert(V && "Expected value");
  294. if (auto *A = dyn_cast<Argument>(V)) {
  295. if (auto *Fn = A->getParent())
  296. return Fn->getSubprogram();
  297. return nullptr;
  298. }
  299. if (BasicBlock *BB = cast<Instruction>(V)->getParent()) {
  300. if (auto *Fn = BB->getParent())
  301. return Fn->getSubprogram();
  302. return nullptr;
  303. }
  304. return nullptr;
  305. }
  306. ValueAsMetadata *ValueAsMetadata::get(Value *V) {
  307. assert(V && "Unexpected null Value");
  308. auto &Context = V->getContext();
  309. auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
  310. if (!Entry) {
  311. assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
  312. "Expected constant or function-local value");
  313. assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
  314. V->IsUsedByMD = true;
  315. if (auto *C = dyn_cast<Constant>(V))
  316. Entry = new ConstantAsMetadata(C);
  317. else
  318. Entry = new LocalAsMetadata(V);
  319. }
  320. return Entry;
  321. }
  322. ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
  323. assert(V && "Unexpected null Value");
  324. return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
  325. }
  326. void ValueAsMetadata::handleDeletion(Value *V) {
  327. assert(V && "Expected valid value");
  328. auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
  329. auto I = Store.find(V);
  330. if (I == Store.end())
  331. return;
  332. // Remove old entry from the map.
  333. ValueAsMetadata *MD = I->second;
  334. assert(MD && "Expected valid metadata");
  335. assert(MD->getValue() == V && "Expected valid mapping");
  336. Store.erase(I);
  337. // Delete the metadata.
  338. MD->replaceAllUsesWith(nullptr);
  339. delete MD;
  340. }
  341. void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
  342. assert(From && "Expected valid value");
  343. assert(To && "Expected valid value");
  344. assert(From != To && "Expected changed value");
  345. assert(From->getType() == To->getType() && "Unexpected type change");
  346. LLVMContext &Context = From->getType()->getContext();
  347. auto &Store = Context.pImpl->ValuesAsMetadata;
  348. auto I = Store.find(From);
  349. if (I == Store.end()) {
  350. assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
  351. return;
  352. }
  353. // Remove old entry from the map.
  354. assert(From->IsUsedByMD && "Expected From to be used by metadata");
  355. From->IsUsedByMD = false;
  356. ValueAsMetadata *MD = I->second;
  357. assert(MD && "Expected valid metadata");
  358. assert(MD->getValue() == From && "Expected valid mapping");
  359. Store.erase(I);
  360. if (isa<LocalAsMetadata>(MD)) {
  361. if (auto *C = dyn_cast<Constant>(To)) {
  362. // Local became a constant.
  363. MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
  364. delete MD;
  365. return;
  366. }
  367. if (getLocalFunctionMetadata(From) && getLocalFunctionMetadata(To) &&
  368. getLocalFunctionMetadata(From) != getLocalFunctionMetadata(To)) {
  369. // DISubprogram changed.
  370. MD->replaceAllUsesWith(nullptr);
  371. delete MD;
  372. return;
  373. }
  374. } else if (!isa<Constant>(To)) {
  375. // Changed to function-local value.
  376. MD->replaceAllUsesWith(nullptr);
  377. delete MD;
  378. return;
  379. }
  380. auto *&Entry = Store[To];
  381. if (Entry) {
  382. // The target already exists.
  383. MD->replaceAllUsesWith(Entry);
  384. delete MD;
  385. return;
  386. }
  387. // Update MD in place (and update the map entry).
  388. assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
  389. To->IsUsedByMD = true;
  390. MD->V = To;
  391. Entry = MD;
  392. }
  393. //===----------------------------------------------------------------------===//
  394. // MDString implementation.
  395. //
  396. MDString *MDString::get(LLVMContext &Context, StringRef Str) {
  397. auto &Store = Context.pImpl->MDStringCache;
  398. auto I = Store.try_emplace(Str);
  399. auto &MapEntry = I.first->getValue();
  400. if (!I.second)
  401. return &MapEntry;
  402. MapEntry.Entry = &*I.first;
  403. return &MapEntry;
  404. }
  405. StringRef MDString::getString() const {
  406. assert(Entry && "Expected to find string map entry");
  407. return Entry->first();
  408. }
  409. //===----------------------------------------------------------------------===//
  410. // MDNode implementation.
  411. //
  412. // Assert that the MDNode types will not be unaligned by the objects
  413. // prepended to them.
  414. #define HANDLE_MDNODE_LEAF(CLASS) \
  415. static_assert( \
  416. alignof(uint64_t) >= alignof(CLASS), \
  417. "Alignment is insufficient after objects prepended to " #CLASS);
  418. #include "llvm/IR/Metadata.def"
  419. void *MDNode::operator new(size_t Size, unsigned NumOps) {
  420. size_t OpSize = NumOps * sizeof(MDOperand);
  421. // uint64_t is the most aligned type we need support (ensured by static_assert
  422. // above)
  423. OpSize = alignTo(OpSize, alignof(uint64_t));
  424. void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
  425. MDOperand *O = static_cast<MDOperand *>(Ptr);
  426. for (MDOperand *E = O - NumOps; O != E; --O)
  427. (void)new (O - 1) MDOperand;
  428. return Ptr;
  429. }
  430. void MDNode::operator delete(void *Mem) {
  431. MDNode *N = static_cast<MDNode *>(Mem);
  432. size_t OpSize = N->NumOperands * sizeof(MDOperand);
  433. OpSize = alignTo(OpSize, alignof(uint64_t));
  434. MDOperand *O = static_cast<MDOperand *>(Mem);
  435. for (MDOperand *E = O - N->NumOperands; O != E; --O)
  436. (O - 1)->~MDOperand();
  437. ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
  438. }
  439. MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
  440. ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
  441. : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
  442. NumUnresolved(0), Context(Context) {
  443. unsigned Op = 0;
  444. for (Metadata *MD : Ops1)
  445. setOperand(Op++, MD);
  446. for (Metadata *MD : Ops2)
  447. setOperand(Op++, MD);
  448. if (!isUniqued())
  449. return;
  450. // Count the unresolved operands. If there are any, RAUW support will be
  451. // added lazily on first reference.
  452. countUnresolvedOperands();
  453. }
  454. TempMDNode MDNode::clone() const {
  455. switch (getMetadataID()) {
  456. default:
  457. llvm_unreachable("Invalid MDNode subclass");
  458. #define HANDLE_MDNODE_LEAF(CLASS) \
  459. case CLASS##Kind: \
  460. return cast<CLASS>(this)->cloneImpl();
  461. #include "llvm/IR/Metadata.def"
  462. }
  463. }
  464. static bool isOperandUnresolved(Metadata *Op) {
  465. if (auto *N = dyn_cast_or_null<MDNode>(Op))
  466. return !N->isResolved();
  467. return false;
  468. }
  469. void MDNode::countUnresolvedOperands() {
  470. assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
  471. assert(isUniqued() && "Expected this to be uniqued");
  472. NumUnresolved = count_if(operands(), isOperandUnresolved);
  473. }
  474. void MDNode::makeUniqued() {
  475. assert(isTemporary() && "Expected this to be temporary");
  476. assert(!isResolved() && "Expected this to be unresolved");
  477. // Enable uniquing callbacks.
  478. for (auto &Op : mutable_operands())
  479. Op.reset(Op.get(), this);
  480. // Make this 'uniqued'.
  481. Storage = Uniqued;
  482. countUnresolvedOperands();
  483. if (!NumUnresolved) {
  484. dropReplaceableUses();
  485. assert(isResolved() && "Expected this to be resolved");
  486. }
  487. assert(isUniqued() && "Expected this to be uniqued");
  488. }
  489. void MDNode::makeDistinct() {
  490. assert(isTemporary() && "Expected this to be temporary");
  491. assert(!isResolved() && "Expected this to be unresolved");
  492. // Drop RAUW support and store as a distinct node.
  493. dropReplaceableUses();
  494. storeDistinctInContext();
  495. assert(isDistinct() && "Expected this to be distinct");
  496. assert(isResolved() && "Expected this to be resolved");
  497. }
  498. void MDNode::resolve() {
  499. assert(isUniqued() && "Expected this to be uniqued");
  500. assert(!isResolved() && "Expected this to be unresolved");
  501. NumUnresolved = 0;
  502. dropReplaceableUses();
  503. assert(isResolved() && "Expected this to be resolved");
  504. }
  505. void MDNode::dropReplaceableUses() {
  506. assert(!NumUnresolved && "Unexpected unresolved operand");
  507. // Drop any RAUW support.
  508. if (Context.hasReplaceableUses())
  509. Context.takeReplaceableUses()->resolveAllUses();
  510. }
  511. void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
  512. assert(isUniqued() && "Expected this to be uniqued");
  513. assert(NumUnresolved != 0 && "Expected unresolved operands");
  514. // Check if an operand was resolved.
  515. if (!isOperandUnresolved(Old)) {
  516. if (isOperandUnresolved(New))
  517. // An operand was un-resolved!
  518. ++NumUnresolved;
  519. } else if (!isOperandUnresolved(New))
  520. decrementUnresolvedOperandCount();
  521. }
  522. void MDNode::decrementUnresolvedOperandCount() {
  523. assert(!isResolved() && "Expected this to be unresolved");
  524. if (isTemporary())
  525. return;
  526. assert(isUniqued() && "Expected this to be uniqued");
  527. if (--NumUnresolved)
  528. return;
  529. // Last unresolved operand has just been resolved.
  530. dropReplaceableUses();
  531. assert(isResolved() && "Expected this to become resolved");
  532. }
  533. void MDNode::resolveCycles() {
  534. if (isResolved())
  535. return;
  536. // Resolve this node immediately.
  537. resolve();
  538. // Resolve all operands.
  539. for (const auto &Op : operands()) {
  540. auto *N = dyn_cast_or_null<MDNode>(Op);
  541. if (!N)
  542. continue;
  543. assert(!N->isTemporary() &&
  544. "Expected all forward declarations to be resolved");
  545. if (!N->isResolved())
  546. N->resolveCycles();
  547. }
  548. }
  549. static bool hasSelfReference(MDNode *N) {
  550. for (Metadata *MD : N->operands())
  551. if (MD == N)
  552. return true;
  553. return false;
  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 !is_contained(BSet, 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. return concatenate(A, B);
  790. }
  791. MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
  792. if (!A || !B)
  793. return nullptr;
  794. APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
  795. APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
  796. if (AVal.compare(BVal) == APFloat::cmpLessThan)
  797. return A;
  798. return B;
  799. }
  800. static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
  801. return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
  802. }
  803. static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
  804. return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
  805. }
  806. static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
  807. ConstantInt *Low, ConstantInt *High) {
  808. ConstantRange NewRange(Low->getValue(), High->getValue());
  809. unsigned Size = EndPoints.size();
  810. APInt LB = EndPoints[Size - 2]->getValue();
  811. APInt LE = EndPoints[Size - 1]->getValue();
  812. ConstantRange LastRange(LB, LE);
  813. if (canBeMerged(NewRange, LastRange)) {
  814. ConstantRange Union = LastRange.unionWith(NewRange);
  815. Type *Ty = High->getType();
  816. EndPoints[Size - 2] =
  817. cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
  818. EndPoints[Size - 1] =
  819. cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
  820. return true;
  821. }
  822. return false;
  823. }
  824. static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
  825. ConstantInt *Low, ConstantInt *High) {
  826. if (!EndPoints.empty())
  827. if (tryMergeRange(EndPoints, Low, High))
  828. return;
  829. EndPoints.push_back(Low);
  830. EndPoints.push_back(High);
  831. }
  832. MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
  833. // Given two ranges, we want to compute the union of the ranges. This
  834. // is slightly complicated by having to combine the intervals and merge
  835. // the ones that overlap.
  836. if (!A || !B)
  837. return nullptr;
  838. if (A == B)
  839. return A;
  840. // First, walk both lists in order of the lower boundary of each interval.
  841. // At each step, try to merge the new interval to the last one we adedd.
  842. SmallVector<ConstantInt *, 4> EndPoints;
  843. int AI = 0;
  844. int BI = 0;
  845. int AN = A->getNumOperands() / 2;
  846. int BN = B->getNumOperands() / 2;
  847. while (AI < AN && BI < BN) {
  848. ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
  849. ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
  850. if (ALow->getValue().slt(BLow->getValue())) {
  851. addRange(EndPoints, ALow,
  852. mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
  853. ++AI;
  854. } else {
  855. addRange(EndPoints, BLow,
  856. mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
  857. ++BI;
  858. }
  859. }
  860. while (AI < AN) {
  861. addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
  862. mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
  863. ++AI;
  864. }
  865. while (BI < BN) {
  866. addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
  867. mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
  868. ++BI;
  869. }
  870. // If we have more than 2 ranges (4 endpoints) we have to try to merge
  871. // the last and first ones.
  872. unsigned Size = EndPoints.size();
  873. if (Size > 4) {
  874. ConstantInt *FB = EndPoints[0];
  875. ConstantInt *FE = EndPoints[1];
  876. if (tryMergeRange(EndPoints, FB, FE)) {
  877. for (unsigned i = 0; i < Size - 2; ++i) {
  878. EndPoints[i] = EndPoints[i + 2];
  879. }
  880. EndPoints.resize(Size - 2);
  881. }
  882. }
  883. // If in the end we have a single range, it is possible that it is now the
  884. // full range. Just drop the metadata in that case.
  885. if (EndPoints.size() == 2) {
  886. ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
  887. if (Range.isFullSet())
  888. return nullptr;
  889. }
  890. SmallVector<Metadata *, 4> MDs;
  891. MDs.reserve(EndPoints.size());
  892. for (auto *I : EndPoints)
  893. MDs.push_back(ConstantAsMetadata::get(I));
  894. return MDNode::get(A->getContext(), MDs);
  895. }
  896. MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
  897. if (!A || !B)
  898. return nullptr;
  899. ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
  900. ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
  901. if (AVal->getZExtValue() < BVal->getZExtValue())
  902. return A;
  903. return B;
  904. }
  905. //===----------------------------------------------------------------------===//
  906. // NamedMDNode implementation.
  907. //
  908. static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
  909. return *(SmallVector<TrackingMDRef, 4> *)Operands;
  910. }
  911. NamedMDNode::NamedMDNode(const Twine &N)
  912. : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
  913. NamedMDNode::~NamedMDNode() {
  914. dropAllReferences();
  915. delete &getNMDOps(Operands);
  916. }
  917. unsigned NamedMDNode::getNumOperands() const {
  918. return (unsigned)getNMDOps(Operands).size();
  919. }
  920. MDNode *NamedMDNode::getOperand(unsigned i) const {
  921. assert(i < getNumOperands() && "Invalid Operand number!");
  922. auto *N = getNMDOps(Operands)[i].get();
  923. return cast_or_null<MDNode>(N);
  924. }
  925. void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
  926. void NamedMDNode::setOperand(unsigned I, MDNode *New) {
  927. assert(I < getNumOperands() && "Invalid operand number");
  928. getNMDOps(Operands)[I].reset(New);
  929. }
  930. void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
  931. void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
  932. StringRef NamedMDNode::getName() const { return StringRef(Name); }
  933. //===----------------------------------------------------------------------===//
  934. // Instruction Metadata method implementations.
  935. //
  936. void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
  937. for (auto &I : Attachments)
  938. if (I.first == ID) {
  939. I.second.reset(&MD);
  940. return;
  941. }
  942. Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
  943. std::make_tuple(&MD));
  944. }
  945. bool MDAttachmentMap::erase(unsigned ID) {
  946. if (empty())
  947. return false;
  948. // Common case is one/last value.
  949. if (Attachments.back().first == ID) {
  950. Attachments.pop_back();
  951. return true;
  952. }
  953. for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
  954. ++I)
  955. if (I->first == ID) {
  956. *I = std::move(Attachments.back());
  957. Attachments.pop_back();
  958. return true;
  959. }
  960. return false;
  961. }
  962. MDNode *MDAttachmentMap::lookup(unsigned ID) const {
  963. for (const auto &I : Attachments)
  964. if (I.first == ID)
  965. return I.second;
  966. return nullptr;
  967. }
  968. void MDAttachmentMap::getAll(
  969. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  970. Result.append(Attachments.begin(), Attachments.end());
  971. // Sort the resulting array so it is stable.
  972. if (Result.size() > 1)
  973. array_pod_sort(Result.begin(), Result.end());
  974. }
  975. void MDGlobalAttachmentMap::insert(unsigned ID, MDNode &MD) {
  976. Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
  977. }
  978. MDNode *MDGlobalAttachmentMap::lookup(unsigned ID) const {
  979. for (const auto &A : Attachments)
  980. if (A.MDKind == ID)
  981. return A.Node;
  982. return nullptr;
  983. }
  984. void MDGlobalAttachmentMap::get(unsigned ID,
  985. SmallVectorImpl<MDNode *> &Result) const {
  986. for (const auto &A : Attachments)
  987. if (A.MDKind == ID)
  988. Result.push_back(A.Node);
  989. }
  990. bool MDGlobalAttachmentMap::erase(unsigned ID) {
  991. auto I = std::remove_if(Attachments.begin(), Attachments.end(),
  992. [ID](const Attachment &A) { return A.MDKind == ID; });
  993. bool Changed = I != Attachments.end();
  994. Attachments.erase(I, Attachments.end());
  995. return Changed;
  996. }
  997. void MDGlobalAttachmentMap::getAll(
  998. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  999. for (const auto &A : Attachments)
  1000. Result.emplace_back(A.MDKind, A.Node);
  1001. // Sort the resulting array so it is stable with respect to metadata IDs. We
  1002. // need to preserve the original insertion order though.
  1003. llvm::stable_sort(Result, less_first());
  1004. }
  1005. void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
  1006. if (!Node && !hasMetadata())
  1007. return;
  1008. setMetadata(getContext().getMDKindID(Kind), Node);
  1009. }
  1010. MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
  1011. return getMetadataImpl(getContext().getMDKindID(Kind));
  1012. }
  1013. void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
  1014. if (!hasMetadataHashEntry())
  1015. return; // Nothing to remove!
  1016. auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
  1017. SmallSet<unsigned, 4> KnownSet;
  1018. KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
  1019. if (KnownSet.empty()) {
  1020. // Just drop our entry at the store.
  1021. InstructionMetadata.erase(this);
  1022. setHasMetadataHashEntry(false);
  1023. return;
  1024. }
  1025. auto &Info = InstructionMetadata[this];
  1026. Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
  1027. return !KnownSet.count(I.first);
  1028. });
  1029. if (Info.empty()) {
  1030. // Drop our entry at the store.
  1031. InstructionMetadata.erase(this);
  1032. setHasMetadataHashEntry(false);
  1033. }
  1034. }
  1035. void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
  1036. if (!Node && !hasMetadata())
  1037. return;
  1038. // Handle 'dbg' as a special case since it is not stored in the hash table.
  1039. if (KindID == LLVMContext::MD_dbg) {
  1040. DbgLoc = DebugLoc(Node);
  1041. return;
  1042. }
  1043. // Handle the case when we're adding/updating metadata on an instruction.
  1044. if (Node) {
  1045. auto &Info = getContext().pImpl->InstructionMetadata[this];
  1046. assert(!Info.empty() == hasMetadataHashEntry() &&
  1047. "HasMetadata bit is wonked");
  1048. if (Info.empty())
  1049. setHasMetadataHashEntry(true);
  1050. Info.set(KindID, *Node);
  1051. return;
  1052. }
  1053. // Otherwise, we're removing metadata from an instruction.
  1054. assert((hasMetadataHashEntry() ==
  1055. (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
  1056. "HasMetadata bit out of date!");
  1057. if (!hasMetadataHashEntry())
  1058. return; // Nothing to remove!
  1059. auto &Info = getContext().pImpl->InstructionMetadata[this];
  1060. // Handle removal of an existing value.
  1061. Info.erase(KindID);
  1062. if (!Info.empty())
  1063. return;
  1064. getContext().pImpl->InstructionMetadata.erase(this);
  1065. setHasMetadataHashEntry(false);
  1066. }
  1067. void Instruction::setAAMetadata(const AAMDNodes &N) {
  1068. setMetadata(LLVMContext::MD_tbaa, N.TBAA);
  1069. setMetadata(LLVMContext::MD_alias_scope, N.Scope);
  1070. setMetadata(LLVMContext::MD_noalias, N.NoAlias);
  1071. }
  1072. MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
  1073. // Handle 'dbg' as a special case since it is not stored in the hash table.
  1074. if (KindID == LLVMContext::MD_dbg)
  1075. return DbgLoc.getAsMDNode();
  1076. if (!hasMetadataHashEntry())
  1077. return nullptr;
  1078. auto &Info = getContext().pImpl->InstructionMetadata[this];
  1079. assert(!Info.empty() && "bit out of sync with hash table");
  1080. return Info.lookup(KindID);
  1081. }
  1082. void Instruction::getAllMetadataImpl(
  1083. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  1084. Result.clear();
  1085. // Handle 'dbg' as a special case since it is not stored in the hash table.
  1086. if (DbgLoc) {
  1087. Result.push_back(
  1088. std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
  1089. if (!hasMetadataHashEntry())
  1090. return;
  1091. }
  1092. assert(hasMetadataHashEntry() &&
  1093. getContext().pImpl->InstructionMetadata.count(this) &&
  1094. "Shouldn't have called this");
  1095. const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
  1096. assert(!Info.empty() && "Shouldn't have called this");
  1097. Info.getAll(Result);
  1098. }
  1099. void Instruction::getAllMetadataOtherThanDebugLocImpl(
  1100. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  1101. Result.clear();
  1102. assert(hasMetadataHashEntry() &&
  1103. getContext().pImpl->InstructionMetadata.count(this) &&
  1104. "Shouldn't have called this");
  1105. const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
  1106. assert(!Info.empty() && "Shouldn't have called this");
  1107. Info.getAll(Result);
  1108. }
  1109. bool Instruction::extractProfMetadata(uint64_t &TrueVal,
  1110. uint64_t &FalseVal) const {
  1111. assert(
  1112. (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select) &&
  1113. "Looking for branch weights on something besides branch or select");
  1114. auto *ProfileData = getMetadata(LLVMContext::MD_prof);
  1115. if (!ProfileData || ProfileData->getNumOperands() != 3)
  1116. return false;
  1117. auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
  1118. if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
  1119. return false;
  1120. auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
  1121. auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
  1122. if (!CITrue || !CIFalse)
  1123. return false;
  1124. TrueVal = CITrue->getValue().getZExtValue();
  1125. FalseVal = CIFalse->getValue().getZExtValue();
  1126. return true;
  1127. }
  1128. bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
  1129. assert((getOpcode() == Instruction::Br ||
  1130. getOpcode() == Instruction::Select ||
  1131. getOpcode() == Instruction::Call ||
  1132. getOpcode() == Instruction::Invoke ||
  1133. getOpcode() == Instruction::Switch) &&
  1134. "Looking for branch weights on something besides branch");
  1135. TotalVal = 0;
  1136. auto *ProfileData = getMetadata(LLVMContext::MD_prof);
  1137. if (!ProfileData)
  1138. return false;
  1139. auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
  1140. if (!ProfDataName)
  1141. return false;
  1142. if (ProfDataName->getString().equals("branch_weights")) {
  1143. TotalVal = 0;
  1144. for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
  1145. auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
  1146. if (!V)
  1147. return false;
  1148. TotalVal += V->getValue().getZExtValue();
  1149. }
  1150. return true;
  1151. } else if (ProfDataName->getString().equals("VP") &&
  1152. ProfileData->getNumOperands() > 3) {
  1153. TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
  1154. ->getValue()
  1155. .getZExtValue();
  1156. return true;
  1157. }
  1158. return false;
  1159. }
  1160. void Instruction::clearMetadataHashEntries() {
  1161. assert(hasMetadataHashEntry() && "Caller should check");
  1162. getContext().pImpl->InstructionMetadata.erase(this);
  1163. setHasMetadataHashEntry(false);
  1164. }
  1165. void GlobalObject::getMetadata(unsigned KindID,
  1166. SmallVectorImpl<MDNode *> &MDs) const {
  1167. if (hasMetadata())
  1168. getContext().pImpl->GlobalObjectMetadata[this].get(KindID, MDs);
  1169. }
  1170. void GlobalObject::getMetadata(StringRef Kind,
  1171. SmallVectorImpl<MDNode *> &MDs) const {
  1172. if (hasMetadata())
  1173. getMetadata(getContext().getMDKindID(Kind), MDs);
  1174. }
  1175. void GlobalObject::addMetadata(unsigned KindID, MDNode &MD) {
  1176. if (!hasMetadata())
  1177. setHasMetadataHashEntry(true);
  1178. getContext().pImpl->GlobalObjectMetadata[this].insert(KindID, MD);
  1179. }
  1180. void GlobalObject::addMetadata(StringRef Kind, MDNode &MD) {
  1181. addMetadata(getContext().getMDKindID(Kind), MD);
  1182. }
  1183. bool GlobalObject::eraseMetadata(unsigned KindID) {
  1184. // Nothing to unset.
  1185. if (!hasMetadata())
  1186. return false;
  1187. auto &Store = getContext().pImpl->GlobalObjectMetadata[this];
  1188. bool Changed = Store.erase(KindID);
  1189. if (Store.empty())
  1190. clearMetadata();
  1191. return Changed;
  1192. }
  1193. void GlobalObject::getAllMetadata(
  1194. SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
  1195. MDs.clear();
  1196. if (!hasMetadata())
  1197. return;
  1198. getContext().pImpl->GlobalObjectMetadata[this].getAll(MDs);
  1199. }
  1200. void GlobalObject::clearMetadata() {
  1201. if (!hasMetadata())
  1202. return;
  1203. getContext().pImpl->GlobalObjectMetadata.erase(this);
  1204. setHasMetadataHashEntry(false);
  1205. }
  1206. void GlobalObject::setMetadata(unsigned KindID, MDNode *N) {
  1207. eraseMetadata(KindID);
  1208. if (N)
  1209. addMetadata(KindID, *N);
  1210. }
  1211. void GlobalObject::setMetadata(StringRef Kind, MDNode *N) {
  1212. setMetadata(getContext().getMDKindID(Kind), N);
  1213. }
  1214. MDNode *GlobalObject::getMetadata(unsigned KindID) const {
  1215. if (hasMetadata())
  1216. return getContext().pImpl->GlobalObjectMetadata[this].lookup(KindID);
  1217. return nullptr;
  1218. }
  1219. MDNode *GlobalObject::getMetadata(StringRef Kind) const {
  1220. return getMetadata(getContext().getMDKindID(Kind));
  1221. }
  1222. void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
  1223. SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
  1224. Other->getAllMetadata(MDs);
  1225. for (auto &MD : MDs) {
  1226. // We need to adjust the type metadata offset.
  1227. if (Offset != 0 && MD.first == LLVMContext::MD_type) {
  1228. auto *OffsetConst = cast<ConstantInt>(
  1229. cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
  1230. Metadata *TypeId = MD.second->getOperand(1);
  1231. auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
  1232. OffsetConst->getType(), OffsetConst->getValue() + Offset));
  1233. addMetadata(LLVMContext::MD_type,
  1234. *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
  1235. continue;
  1236. }
  1237. // If an offset adjustment was specified we need to modify the DIExpression
  1238. // to prepend the adjustment:
  1239. // !DIExpression(DW_OP_plus, Offset, [original expr])
  1240. auto *Attachment = MD.second;
  1241. if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
  1242. DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
  1243. DIExpression *E = nullptr;
  1244. if (!GV) {
  1245. auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
  1246. GV = GVE->getVariable();
  1247. E = GVE->getExpression();
  1248. }
  1249. ArrayRef<uint64_t> OrigElements;
  1250. if (E)
  1251. OrigElements = E->getElements();
  1252. std::vector<uint64_t> Elements(OrigElements.size() + 2);
  1253. Elements[0] = dwarf::DW_OP_plus_uconst;
  1254. Elements[1] = Offset;
  1255. llvm::copy(OrigElements, Elements.begin() + 2);
  1256. E = DIExpression::get(getContext(), Elements);
  1257. Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
  1258. }
  1259. addMetadata(MD.first, *Attachment);
  1260. }
  1261. }
  1262. void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {
  1263. addMetadata(
  1264. LLVMContext::MD_type,
  1265. *MDTuple::get(getContext(),
  1266. {ConstantAsMetadata::get(ConstantInt::get(
  1267. Type::getInt64Ty(getContext()), Offset)),
  1268. TypeID}));
  1269. }
  1270. void Function::setSubprogram(DISubprogram *SP) {
  1271. setMetadata(LLVMContext::MD_dbg, SP);
  1272. }
  1273. DISubprogram *Function::getSubprogram() const {
  1274. return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
  1275. }
  1276. bool Function::isDebugInfoForProfiling() const {
  1277. if (DISubprogram *SP = getSubprogram()) {
  1278. if (DICompileUnit *CU = SP->getUnit()) {
  1279. return CU->getDebugInfoForProfiling();
  1280. }
  1281. }
  1282. return false;
  1283. }
  1284. void GlobalVariable::addDebugInfo(DIGlobalVariableExpression *GV) {
  1285. addMetadata(LLVMContext::MD_dbg, *GV);
  1286. }
  1287. void GlobalVariable::getDebugInfo(
  1288. SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const {
  1289. SmallVector<MDNode *, 1> MDs;
  1290. getMetadata(LLVMContext::MD_dbg, MDs);
  1291. for (MDNode *MD : MDs)
  1292. GVs.push_back(cast<DIGlobalVariableExpression>(MD));
  1293. }