Metadata.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. //===- Metadata.cpp - Implement Metadata classes --------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Metadata classes.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/IR/Metadata.h"
  14. #include "LLVMContextImpl.h"
  15. #include "MetadataImpl.h"
  16. #include "SymbolTableListTraitsImpl.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallSet.h"
  20. #include "llvm/ADT/SmallString.h"
  21. #include "llvm/ADT/StringMap.h"
  22. #include "llvm/IR/ConstantRange.h"
  23. #include "llvm/IR/DebugInfoMetadata.h"
  24. #include "llvm/IR/Instruction.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/IR/ValueHandle.h"
  28. using namespace llvm;
  29. MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
  30. : Value(Ty, MetadataAsValueVal), MD(MD) {
  31. track();
  32. }
  33. MetadataAsValue::~MetadataAsValue() {
  34. getType()->getContext().pImpl->MetadataAsValues.erase(MD);
  35. untrack();
  36. }
  37. /// \brief Canonicalize metadata arguments to intrinsics.
  38. ///
  39. /// To support bitcode upgrades (and assembly semantic sugar) for \a
  40. /// MetadataAsValue, we need to canonicalize certain metadata.
  41. ///
  42. /// - nullptr is replaced by an empty MDNode.
  43. /// - An MDNode with a single null operand is replaced by an empty MDNode.
  44. /// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
  45. ///
  46. /// This maintains readability of bitcode from when metadata was a type of
  47. /// value, and these bridges were unnecessary.
  48. static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
  49. Metadata *MD) {
  50. if (!MD)
  51. // !{}
  52. return MDNode::get(Context, None);
  53. // Return early if this isn't a single-operand MDNode.
  54. auto *N = dyn_cast<MDNode>(MD);
  55. if (!N || N->getNumOperands() != 1)
  56. return MD;
  57. if (!N->getOperand(0))
  58. // !{}
  59. return MDNode::get(Context, None);
  60. if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
  61. // Look through the MDNode.
  62. return C;
  63. return MD;
  64. }
  65. MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
  66. MD = canonicalizeMetadataForValue(Context, MD);
  67. auto *&Entry = Context.pImpl->MetadataAsValues[MD];
  68. if (!Entry)
  69. Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
  70. return Entry;
  71. }
  72. MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
  73. Metadata *MD) {
  74. MD = canonicalizeMetadataForValue(Context, MD);
  75. auto &Store = Context.pImpl->MetadataAsValues;
  76. return Store.lookup(MD);
  77. }
  78. void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
  79. LLVMContext &Context = getContext();
  80. MD = canonicalizeMetadataForValue(Context, MD);
  81. auto &Store = Context.pImpl->MetadataAsValues;
  82. // Stop tracking the old metadata.
  83. Store.erase(this->MD);
  84. untrack();
  85. this->MD = nullptr;
  86. // Start tracking MD, or RAUW if necessary.
  87. auto *&Entry = Store[MD];
  88. if (Entry) {
  89. replaceAllUsesWith(Entry);
  90. delete this;
  91. return;
  92. }
  93. this->MD = MD;
  94. track();
  95. Entry = this;
  96. }
  97. void MetadataAsValue::track() {
  98. if (MD)
  99. MetadataTracking::track(&MD, *MD, *this);
  100. }
  101. void MetadataAsValue::untrack() {
  102. if (MD)
  103. MetadataTracking::untrack(MD);
  104. }
  105. void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
  106. bool WasInserted =
  107. UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
  108. .second;
  109. (void)WasInserted;
  110. assert(WasInserted && "Expected to add a reference");
  111. ++NextIndex;
  112. assert(NextIndex != 0 && "Unexpected overflow");
  113. }
  114. void ReplaceableMetadataImpl::dropRef(void *Ref) {
  115. bool WasErased = UseMap.erase(Ref);
  116. (void)WasErased;
  117. // assert(WasErased && "Expected to drop a reference"); // HLSL Change - not while cleaning up OOM
  118. }
  119. void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
  120. const Metadata &MD) {
  121. auto I = UseMap.find(Ref);
  122. assert(I != UseMap.end() && "Expected to move a reference");
  123. auto OwnerAndIndex = I->second;
  124. UseMap.erase(I);
  125. bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
  126. (void)WasInserted;
  127. assert(WasInserted && "Expected to add a reference");
  128. // Check that the references are direct if there's no owner.
  129. (void)MD;
  130. assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
  131. "Reference without owner must be direct");
  132. assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
  133. "Reference without owner must be direct");
  134. }
  135. void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
  136. assert(!(MD && isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary()) &&
  137. "Expected non-temp node");
  138. if (UseMap.empty())
  139. return;
  140. // Copy out uses since UseMap will get touched below.
  141. typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
  142. SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
  143. std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
  144. return L.second.second < R.second.second;
  145. });
  146. for (const auto &Pair : Uses) {
  147. // Check that this Ref hasn't disappeared after RAUW (when updating a
  148. // previous Ref).
  149. if (!UseMap.count(Pair.first))
  150. continue;
  151. OwnerTy Owner = Pair.second.first;
  152. if (!Owner) {
  153. // Update unowned tracking references directly.
  154. Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
  155. Ref = MD;
  156. if (MD)
  157. MetadataTracking::track(Ref);
  158. UseMap.erase(Pair.first);
  159. continue;
  160. }
  161. // Check for MetadataAsValue.
  162. if (Owner.is<MetadataAsValue *>()) {
  163. Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
  164. continue;
  165. }
  166. // There's a Metadata owner -- dispatch.
  167. Metadata *OwnerMD = Owner.get<Metadata *>();
  168. switch (OwnerMD->getMetadataID()) {
  169. #define HANDLE_METADATA_LEAF(CLASS) \
  170. case Metadata::CLASS##Kind: \
  171. cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
  172. continue;
  173. #include "llvm/IR/Metadata.def"
  174. default:
  175. llvm_unreachable("Invalid metadata subclass");
  176. }
  177. }
  178. assert(UseMap.empty() && "Expected all uses to be replaced");
  179. }
  180. void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
  181. if (UseMap.empty())
  182. return;
  183. if (!ResolveUsers) {
  184. UseMap.clear();
  185. return;
  186. }
  187. // Copy out uses since UseMap could get touched below.
  188. typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
  189. SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
  190. std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
  191. return L.second.second < R.second.second;
  192. });
  193. UseMap.clear();
  194. for (const auto &Pair : Uses) {
  195. auto Owner = Pair.second.first;
  196. if (!Owner)
  197. continue;
  198. if (Owner.is<MetadataAsValue *>())
  199. continue;
  200. // Resolve MDNodes that point at this.
  201. auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
  202. if (!OwnerMD)
  203. continue;
  204. if (OwnerMD->isResolved())
  205. continue;
  206. OwnerMD->decrementUnresolvedOperandCount();
  207. }
  208. }
  209. static Function *getLocalFunction(Value *V) {
  210. assert(V && "Expected value");
  211. if (auto *A = dyn_cast<Argument>(V))
  212. return A->getParent();
  213. if (BasicBlock *BB = cast<Instruction>(V)->getParent())
  214. return BB->getParent();
  215. return nullptr;
  216. }
  217. ValueAsMetadata *ValueAsMetadata::get(Value *V) {
  218. assert(V && "Unexpected null Value");
  219. auto &Context = V->getContext();
  220. auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
  221. if (!Entry) {
  222. assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
  223. "Expected constant or function-local value");
  224. assert(!V->IsUsedByMD &&
  225. "Expected this to be the only metadata use");
  226. V->IsUsedByMD = true;
  227. if (auto *C = dyn_cast<Constant>(V))
  228. Entry = new ConstantAsMetadata(C);
  229. else
  230. Entry = new LocalAsMetadata(V);
  231. }
  232. return Entry;
  233. }
  234. ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
  235. assert(V && "Unexpected null Value");
  236. return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
  237. }
  238. void ValueAsMetadata::handleDeletion(Value *V) {
  239. assert(V && "Expected valid value");
  240. auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
  241. auto I = Store.find(V);
  242. if (I == Store.end())
  243. return;
  244. // Remove old entry from the map.
  245. ValueAsMetadata *MD = I->second;
  246. // assert(MD && "Expected valid metadata"); // HLSL Change - MD might be nullptr under OOM
  247. // assert(MD->getValue() == V && "Expected valid mapping"); // HLSL Change - MD might be nullptr under OOM
  248. Store.erase(I);
  249. // Delete the metadata.
  250. if (MD) MD->replaceAllUsesWith(nullptr); // HLSL Change - MD might be nullptr under OOM
  251. delete MD;
  252. }
  253. void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
  254. assert(From && "Expected valid value");
  255. assert(To && "Expected valid value");
  256. assert(From != To && "Expected changed value");
  257. assert(From->getType() == To->getType() && "Unexpected type change");
  258. LLVMContext &Context = From->getType()->getContext();
  259. auto &Store = Context.pImpl->ValuesAsMetadata;
  260. auto I = Store.find(From);
  261. if (I == Store.end()) {
  262. assert(!From->IsUsedByMD &&
  263. "Expected From not to be used by metadata");
  264. return;
  265. }
  266. // Remove old entry from the map.
  267. assert(From->IsUsedByMD &&
  268. "Expected From to be used by metadata");
  269. From->IsUsedByMD = false;
  270. ValueAsMetadata *MD = I->second;
  271. assert(MD && "Expected valid metadata");
  272. assert(MD->getValue() == From && "Expected valid mapping");
  273. Store.erase(I);
  274. if (isa<LocalAsMetadata>(MD)) {
  275. if (auto *C = dyn_cast<Constant>(To)) {
  276. // Local became a constant.
  277. MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
  278. delete MD;
  279. return;
  280. }
  281. if (getLocalFunction(From) && getLocalFunction(To) &&
  282. getLocalFunction(From) != getLocalFunction(To)) {
  283. // Function changed.
  284. MD->replaceAllUsesWith(nullptr);
  285. delete MD;
  286. return;
  287. }
  288. } else if (!isa<Constant>(To)) {
  289. // Changed to function-local value.
  290. MD->replaceAllUsesWith(nullptr);
  291. delete MD;
  292. return;
  293. }
  294. auto *&Entry = Store[To];
  295. if (Entry) {
  296. // The target already exists.
  297. MD->replaceAllUsesWith(Entry);
  298. delete MD;
  299. return;
  300. }
  301. // Update MD in place (and update the map entry).
  302. assert(!To->IsUsedByMD &&
  303. "Expected this to be the only metadata use");
  304. To->IsUsedByMD = true;
  305. MD->V = To;
  306. Entry = MD;
  307. }
  308. //===----------------------------------------------------------------------===//
  309. // MDString implementation.
  310. //
  311. MDString *MDString::get(LLVMContext &Context, StringRef Str) {
  312. auto &Store = Context.pImpl->MDStringCache;
  313. auto I = Store.find(Str);
  314. if (I != Store.end())
  315. return &I->second;
  316. auto *Entry =
  317. StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
  318. bool WasInserted = Store.insert(Entry);
  319. (void)WasInserted;
  320. assert(WasInserted && "Expected entry to be inserted");
  321. Entry->second.Entry = Entry;
  322. return &Entry->second;
  323. }
  324. StringRef MDString::getString() const {
  325. assert(Entry && "Expected to find string map entry");
  326. return Entry->first();
  327. }
  328. //===----------------------------------------------------------------------===//
  329. // MDNode implementation.
  330. //
  331. // Assert that the MDNode types will not be unaligned by the objects
  332. // prepended to them.
  333. #define HANDLE_MDNODE_LEAF(CLASS) \
  334. static_assert( \
  335. llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment, \
  336. "Alignment is insufficient after objects prepended to " #CLASS);
  337. #include "llvm/IR/Metadata.def"
  338. void *MDNode::operator new(size_t Size, unsigned NumOps) {
  339. size_t OpSize = NumOps * sizeof(MDOperand);
  340. // uint64_t is the most aligned type we need support (ensured by static_assert
  341. // above)
  342. OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
  343. void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
  344. MDOperand *O = static_cast<MDOperand *>(Ptr);
  345. for (MDOperand *E = O - NumOps; O != E; --O)
  346. (void)new (O - 1) MDOperand;
  347. return Ptr;
  348. }
  349. void MDNode::operator delete(void *Mem) {
  350. MDNode *N = static_cast<MDNode *>(Mem);
  351. size_t OpSize = N->NumOperands * sizeof(MDOperand);
  352. OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
  353. MDOperand *O = static_cast<MDOperand *>(Mem);
  354. for (MDOperand *E = O - N->NumOperands; O != E; --O)
  355. (O - 1)->~MDOperand();
  356. ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
  357. }
  358. MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
  359. ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
  360. : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
  361. NumUnresolved(0), Context(Context) {
  362. unsigned Op = 0;
  363. for (Metadata *MD : Ops1)
  364. setOperand(Op++, MD);
  365. for (Metadata *MD : Ops2)
  366. setOperand(Op++, MD);
  367. if (isDistinct())
  368. return;
  369. if (isUniqued())
  370. // Check whether any operands are unresolved, requiring re-uniquing. If
  371. // not, don't support RAUW.
  372. if (!countUnresolvedOperands())
  373. return;
  374. this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
  375. }
  376. TempMDNode MDNode::clone() const {
  377. switch (getMetadataID()) {
  378. default:
  379. llvm_unreachable("Invalid MDNode subclass");
  380. #define HANDLE_MDNODE_LEAF(CLASS) \
  381. case CLASS##Kind: \
  382. return cast<CLASS>(this)->cloneImpl();
  383. #include "llvm/IR/Metadata.def"
  384. }
  385. }
  386. static bool isOperandUnresolved(Metadata *Op) {
  387. if (auto *N = dyn_cast_or_null<MDNode>(Op))
  388. return !N->isResolved();
  389. return false;
  390. }
  391. unsigned MDNode::countUnresolvedOperands() {
  392. assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
  393. NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
  394. return NumUnresolved;
  395. }
  396. void MDNode::makeUniqued() {
  397. assert(isTemporary() && "Expected this to be temporary");
  398. assert(!isResolved() && "Expected this to be unresolved");
  399. // Enable uniquing callbacks.
  400. for (auto &Op : mutable_operands())
  401. Op.reset(Op.get(), this);
  402. // Make this 'uniqued'.
  403. Storage = Uniqued;
  404. if (!countUnresolvedOperands())
  405. resolve();
  406. assert(isUniqued() && "Expected this to be uniqued");
  407. }
  408. void MDNode::makeDistinct() {
  409. assert(isTemporary() && "Expected this to be temporary");
  410. assert(!isResolved() && "Expected this to be unresolved");
  411. // Pretend to be uniqued, resolve the node, and then store in distinct table.
  412. Storage = Uniqued;
  413. resolve();
  414. storeDistinctInContext();
  415. assert(isDistinct() && "Expected this to be distinct");
  416. assert(isResolved() && "Expected this to be resolved");
  417. }
  418. void MDNode::resolve() {
  419. assert(isUniqued() && "Expected this to be uniqued");
  420. assert(!isResolved() && "Expected this to be unresolved");
  421. // Move the map, so that this immediately looks resolved.
  422. auto Uses = Context.takeReplaceableUses();
  423. NumUnresolved = 0;
  424. assert(isResolved() && "Expected this to be resolved");
  425. // Drop RAUW support.
  426. Uses->resolveAllUses();
  427. }
  428. void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
  429. assert(NumUnresolved != 0 && "Expected unresolved operands");
  430. // Check if an operand was resolved.
  431. if (!isOperandUnresolved(Old)) {
  432. if (isOperandUnresolved(New))
  433. // An operand was un-resolved!
  434. ++NumUnresolved;
  435. } else if (!isOperandUnresolved(New))
  436. decrementUnresolvedOperandCount();
  437. }
  438. void MDNode::decrementUnresolvedOperandCount() {
  439. if (!--NumUnresolved)
  440. // Last unresolved operand has just been resolved.
  441. resolve();
  442. }
  443. void MDNode::resolveCycles() {
  444. if (isResolved())
  445. return;
  446. // Resolve this node immediately.
  447. resolve();
  448. // Resolve all operands.
  449. for (const auto &Op : operands()) {
  450. auto *N = dyn_cast_or_null<MDNode>(Op);
  451. if (!N)
  452. continue;
  453. assert(!N->isTemporary() &&
  454. "Expected all forward declarations to be resolved");
  455. if (!N->isResolved())
  456. N->resolveCycles();
  457. }
  458. }
  459. static bool hasSelfReference(MDNode *N) {
  460. for (Metadata *MD : N->operands())
  461. if (MD == N)
  462. return true;
  463. return false;
  464. }
  465. MDNode *MDNode::replaceWithPermanentImpl() {
  466. if (hasSelfReference(this))
  467. return replaceWithDistinctImpl();
  468. return replaceWithUniquedImpl();
  469. }
  470. MDNode *MDNode::replaceWithUniquedImpl() {
  471. // Try to uniquify in place.
  472. MDNode *UniquedNode = uniquify();
  473. if (UniquedNode == this) {
  474. makeUniqued();
  475. return this;
  476. }
  477. // Collision, so RAUW instead.
  478. replaceAllUsesWith(UniquedNode);
  479. deleteAsSubclass();
  480. return UniquedNode;
  481. }
  482. MDNode *MDNode::replaceWithDistinctImpl() {
  483. makeDistinct();
  484. return this;
  485. }
  486. void MDTuple::recalculateHash() {
  487. setHash(MDTupleInfo::KeyTy::calculateHash(this));
  488. }
  489. void MDNode::dropAllReferences() {
  490. for (unsigned I = 0, E = NumOperands; I != E; ++I)
  491. setOperand(I, nullptr);
  492. if (!isResolved()) {
  493. Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
  494. (void)Context.takeReplaceableUses();
  495. }
  496. }
  497. void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
  498. unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
  499. assert(Op < getNumOperands() && "Expected valid operand");
  500. if (!isUniqued()) {
  501. // This node is not uniqued. Just set the operand and be done with it.
  502. setOperand(Op, New);
  503. return;
  504. }
  505. // This node is uniqued.
  506. eraseFromStore();
  507. Metadata *Old = getOperand(Op);
  508. setOperand(Op, New);
  509. // Drop uniquing for self-reference cycles.
  510. if (New == this) {
  511. if (!isResolved())
  512. resolve();
  513. storeDistinctInContext();
  514. return;
  515. }
  516. // Re-unique the node.
  517. auto *Uniqued = uniquify();
  518. if (Uniqued == this) {
  519. if (!isResolved())
  520. resolveAfterOperandChange(Old, New);
  521. return;
  522. }
  523. // Collision.
  524. if (!isResolved()) {
  525. // Still unresolved, so RAUW.
  526. //
  527. // First, clear out all operands to prevent any recursion (similar to
  528. // dropAllReferences(), but we still need the use-list).
  529. for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
  530. setOperand(O, nullptr);
  531. Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
  532. deleteAsSubclass();
  533. return;
  534. }
  535. // Store in non-uniqued form if RAUW isn't possible.
  536. storeDistinctInContext();
  537. }
  538. void MDNode::deleteAsSubclass() {
  539. switch (getMetadataID()) {
  540. default:
  541. llvm_unreachable("Invalid subclass of MDNode");
  542. #define HANDLE_MDNODE_LEAF(CLASS) \
  543. case CLASS##Kind: \
  544. delete cast<CLASS>(this); \
  545. break;
  546. #include "llvm/IR/Metadata.def"
  547. }
  548. }
  549. template <class T, class InfoT>
  550. static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
  551. if (T *U = getUniqued(Store, N))
  552. return U;
  553. Store.insert(N);
  554. return N;
  555. }
  556. template <class NodeTy> struct MDNode::HasCachedHash {
  557. typedef char Yes[1];
  558. typedef char No[2];
  559. template <class U, U Val> struct SFINAE {};
  560. template <class U>
  561. static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
  562. template <class U> static No &check(...);
  563. static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
  564. };
  565. MDNode *MDNode::uniquify() {
  566. assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
  567. // Try to insert into uniquing store.
  568. switch (getMetadataID()) {
  569. default:
  570. llvm_unreachable("Invalid subclass of MDNode");
  571. #define HANDLE_MDNODE_LEAF(CLASS) \
  572. case CLASS##Kind: { \
  573. CLASS *SubclassThis = cast<CLASS>(this); \
  574. std::integral_constant<bool, HasCachedHash<CLASS>::value> \
  575. ShouldRecalculateHash; \
  576. dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
  577. return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
  578. }
  579. #include "llvm/IR/Metadata.def"
  580. }
  581. }
  582. void MDNode::eraseFromStore() {
  583. switch (getMetadataID()) {
  584. default:
  585. llvm_unreachable("Invalid subclass of MDNode");
  586. #define HANDLE_MDNODE_LEAF(CLASS) \
  587. case CLASS##Kind: \
  588. getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
  589. break;
  590. #include "llvm/IR/Metadata.def"
  591. }
  592. }
  593. MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
  594. StorageType Storage, bool ShouldCreate) {
  595. unsigned Hash = 0;
  596. if (Storage == Uniqued) {
  597. MDTupleInfo::KeyTy Key(MDs);
  598. if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
  599. return N;
  600. if (!ShouldCreate)
  601. return nullptr;
  602. Hash = Key.getHash();
  603. } else {
  604. assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
  605. }
  606. // HLSL Change - guard with try/catch
  607. MDTuple *MDTuplePtr(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs));
  608. MDTuple *Result;
  609. try {
  610. Result = storeImpl(MDTuplePtr, Storage, Context.pImpl->MDTuples);
  611. } catch (...) {
  612. MDTuplePtr->deleteAsSubclass();
  613. throw;
  614. }
  615. return Result;
  616. }
  617. void MDNode::deleteTemporary(MDNode *N) {
  618. assert(N->isTemporary() && "Expected temporary node");
  619. N->replaceAllUsesWith(nullptr);
  620. N->deleteAsSubclass();
  621. }
  622. void MDNode::storeDistinctInContext() {
  623. assert(isResolved() && "Expected resolved nodes");
  624. Storage = Distinct;
  625. // Reset the hash.
  626. switch (getMetadataID()) {
  627. default:
  628. llvm_unreachable("Invalid subclass of MDNode");
  629. #define HANDLE_MDNODE_LEAF(CLASS) \
  630. case CLASS##Kind: { \
  631. std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
  632. dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
  633. break; \
  634. }
  635. #include "llvm/IR/Metadata.def"
  636. }
  637. getContext().pImpl->DistinctMDNodes.insert(this);
  638. }
  639. void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
  640. if (getOperand(I) == New)
  641. return;
  642. if (!isUniqued()) {
  643. setOperand(I, New);
  644. return;
  645. }
  646. handleChangedOperand(mutable_begin() + I, New);
  647. }
  648. void MDNode::setOperand(unsigned I, Metadata *New) {
  649. assert(I < NumOperands);
  650. mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
  651. }
  652. /// \brief Get a node, or a self-reference that looks like it.
  653. ///
  654. /// Special handling for finding self-references, for use by \a
  655. /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
  656. /// when self-referencing nodes were still uniqued. If the first operand has
  657. /// the same operands as \c Ops, return the first operand instead.
  658. static MDNode *getOrSelfReference(LLVMContext &Context,
  659. ArrayRef<Metadata *> Ops) {
  660. if (!Ops.empty())
  661. if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
  662. if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
  663. for (unsigned I = 1, E = Ops.size(); I != E; ++I)
  664. if (Ops[I] != N->getOperand(I))
  665. return MDNode::get(Context, Ops);
  666. return N;
  667. }
  668. return MDNode::get(Context, Ops);
  669. }
  670. MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
  671. if (!A)
  672. return B;
  673. if (!B)
  674. return A;
  675. SmallVector<Metadata *, 4> MDs;
  676. MDs.reserve(A->getNumOperands() + B->getNumOperands());
  677. MDs.append(A->op_begin(), A->op_end());
  678. MDs.append(B->op_begin(), B->op_end());
  679. // FIXME: This preserves long-standing behaviour, but is it really the right
  680. // behaviour? Or was that an unintended side-effect of node uniquing?
  681. return getOrSelfReference(A->getContext(), MDs);
  682. }
  683. MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
  684. if (!A || !B)
  685. return nullptr;
  686. SmallVector<Metadata *, 4> MDs;
  687. for (Metadata *MD : A->operands())
  688. if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
  689. MDs.push_back(MD);
  690. // FIXME: This preserves long-standing behaviour, but is it really the right
  691. // behaviour? Or was that an unintended side-effect of node uniquing?
  692. return getOrSelfReference(A->getContext(), MDs);
  693. }
  694. MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
  695. if (!A || !B)
  696. return nullptr;
  697. SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
  698. for (Metadata *MD : A->operands())
  699. if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
  700. MDs.push_back(MD);
  701. // FIXME: This preserves long-standing behaviour, but is it really the right
  702. // behaviour? Or was that an unintended side-effect of node uniquing?
  703. return getOrSelfReference(A->getContext(), MDs);
  704. }
  705. MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
  706. if (!A || !B)
  707. return nullptr;
  708. APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
  709. APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
  710. if (AVal.compare(BVal) == APFloat::cmpLessThan)
  711. return A;
  712. return B;
  713. }
  714. static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
  715. return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
  716. }
  717. static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
  718. return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
  719. }
  720. static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
  721. ConstantInt *Low, ConstantInt *High) {
  722. ConstantRange NewRange(Low->getValue(), High->getValue());
  723. unsigned Size = EndPoints.size();
  724. APInt LB = EndPoints[Size - 2]->getValue();
  725. APInt LE = EndPoints[Size - 1]->getValue();
  726. ConstantRange LastRange(LB, LE);
  727. if (canBeMerged(NewRange, LastRange)) {
  728. ConstantRange Union = LastRange.unionWith(NewRange);
  729. Type *Ty = High->getType();
  730. EndPoints[Size - 2] =
  731. cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
  732. EndPoints[Size - 1] =
  733. cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
  734. return true;
  735. }
  736. return false;
  737. }
  738. static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
  739. ConstantInt *Low, ConstantInt *High) {
  740. if (!EndPoints.empty())
  741. if (tryMergeRange(EndPoints, Low, High))
  742. return;
  743. EndPoints.push_back(Low);
  744. EndPoints.push_back(High);
  745. }
  746. MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
  747. // Given two ranges, we want to compute the union of the ranges. This
  748. // is slightly complitade by having to combine the intervals and merge
  749. // the ones that overlap.
  750. if (!A || !B)
  751. return nullptr;
  752. if (A == B)
  753. return A;
  754. // First, walk both lists in older of the lower boundary of each interval.
  755. // At each step, try to merge the new interval to the last one we adedd.
  756. SmallVector<ConstantInt *, 4> EndPoints;
  757. int AI = 0;
  758. int BI = 0;
  759. int AN = A->getNumOperands() / 2;
  760. int BN = B->getNumOperands() / 2;
  761. while (AI < AN && BI < BN) {
  762. ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
  763. ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
  764. if (ALow->getValue().slt(BLow->getValue())) {
  765. addRange(EndPoints, ALow,
  766. mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
  767. ++AI;
  768. } else {
  769. addRange(EndPoints, BLow,
  770. mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
  771. ++BI;
  772. }
  773. }
  774. while (AI < AN) {
  775. addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
  776. mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
  777. ++AI;
  778. }
  779. while (BI < BN) {
  780. addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
  781. mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
  782. ++BI;
  783. }
  784. // If we have more than 2 ranges (4 endpoints) we have to try to merge
  785. // the last and first ones.
  786. unsigned Size = EndPoints.size();
  787. if (Size > 4) {
  788. ConstantInt *FB = EndPoints[0];
  789. ConstantInt *FE = EndPoints[1];
  790. if (tryMergeRange(EndPoints, FB, FE)) {
  791. for (unsigned i = 0; i < Size - 2; ++i) {
  792. EndPoints[i] = EndPoints[i + 2];
  793. }
  794. EndPoints.resize(Size - 2);
  795. }
  796. }
  797. // If in the end we have a single range, it is possible that it is now the
  798. // full range. Just drop the metadata in that case.
  799. if (EndPoints.size() == 2) {
  800. ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
  801. if (Range.isFullSet())
  802. return nullptr;
  803. }
  804. SmallVector<Metadata *, 4> MDs;
  805. MDs.reserve(EndPoints.size());
  806. for (auto *I : EndPoints)
  807. MDs.push_back(ConstantAsMetadata::get(I));
  808. return MDNode::get(A->getContext(), MDs);
  809. }
  810. //===----------------------------------------------------------------------===//
  811. // NamedMDNode implementation.
  812. //
  813. static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
  814. return *(SmallVector<TrackingMDRef, 4> *)Operands;
  815. }
  816. NamedMDNode::NamedMDNode(const Twine &N)
  817. : Name(N.str()), Parent(nullptr),
  818. Operands(new SmallVector<TrackingMDRef, 4>()) {}
  819. NamedMDNode::~NamedMDNode() {
  820. dropAllReferences();
  821. delete &getNMDOps(Operands);
  822. }
  823. unsigned NamedMDNode::getNumOperands() const {
  824. return (unsigned)getNMDOps(Operands).size();
  825. }
  826. MDNode *NamedMDNode::getOperand(unsigned i) const {
  827. assert(i < getNumOperands() && "Invalid Operand number!");
  828. auto *N = getNMDOps(Operands)[i].get();
  829. return cast_or_null<MDNode>(N);
  830. }
  831. void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
  832. void NamedMDNode::setOperand(unsigned I, MDNode *New) {
  833. assert(I < getNumOperands() && "Invalid operand number");
  834. getNMDOps(Operands)[I].reset(New);
  835. }
  836. void NamedMDNode::eraseFromParent() {
  837. getParent()->eraseNamedMetadata(this);
  838. }
  839. void NamedMDNode::dropAllReferences() {
  840. getNMDOps(Operands).clear();
  841. }
  842. StringRef NamedMDNode::getName() const {
  843. return StringRef(Name);
  844. }
  845. //===----------------------------------------------------------------------===//
  846. // Instruction Metadata method implementations.
  847. //
  848. void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
  849. for (auto &I : Attachments)
  850. if (I.first == ID) {
  851. I.second.reset(&MD);
  852. return;
  853. }
  854. Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
  855. std::make_tuple(&MD));
  856. }
  857. void MDAttachmentMap::erase(unsigned ID) {
  858. if (empty())
  859. return;
  860. // Common case is one/last value.
  861. if (Attachments.back().first == ID) {
  862. Attachments.pop_back();
  863. return;
  864. }
  865. for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
  866. ++I)
  867. if (I->first == ID) {
  868. *I = std::move(Attachments.back());
  869. Attachments.pop_back();
  870. return;
  871. }
  872. }
  873. MDNode *MDAttachmentMap::lookup(unsigned ID) const {
  874. for (const auto &I : Attachments)
  875. if (I.first == ID)
  876. return I.second;
  877. return nullptr;
  878. }
  879. void MDAttachmentMap::getAll(
  880. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  881. Result.append(Attachments.begin(), Attachments.end());
  882. // Sort the resulting array so it is stable.
  883. if (Result.size() > 1)
  884. array_pod_sort(Result.begin(), Result.end());
  885. }
  886. void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
  887. if (!Node && !hasMetadata())
  888. return;
  889. setMetadata(getContext().getMDKindID(Kind), Node);
  890. }
  891. MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
  892. return getMetadataImpl(getContext().getMDKindID(Kind));
  893. }
  894. void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
  895. SmallSet<unsigned, 5> KnownSet;
  896. KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
  897. // Drop debug if needed
  898. if (KnownSet.erase(LLVMContext::MD_dbg))
  899. DbgLoc = DebugLoc();
  900. if (!hasMetadataHashEntry())
  901. return; // Nothing to remove!
  902. auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
  903. if (KnownSet.empty()) {
  904. // Just drop our entry at the store.
  905. InstructionMetadata.erase(this);
  906. setHasMetadataHashEntry(false);
  907. return;
  908. }
  909. auto &Info = InstructionMetadata[this];
  910. Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
  911. return !KnownSet.count(I.first);
  912. });
  913. if (Info.empty()) {
  914. // Drop our entry at the store.
  915. InstructionMetadata.erase(this);
  916. setHasMetadataHashEntry(false);
  917. }
  918. }
  919. /// setMetadata - Set the metadata of of the specified kind to the specified
  920. /// node. This updates/replaces metadata if already present, or removes it if
  921. /// Node is null.
  922. void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
  923. if (!Node && !hasMetadata())
  924. return;
  925. // Handle 'dbg' as a special case since it is not stored in the hash table.
  926. if (KindID == LLVMContext::MD_dbg) {
  927. DbgLoc = DebugLoc(Node);
  928. return;
  929. }
  930. // Handle the case when we're adding/updating metadata on an instruction.
  931. if (Node) {
  932. auto &Info = getContext().pImpl->InstructionMetadata[this];
  933. assert(!Info.empty() == hasMetadataHashEntry() &&
  934. "HasMetadata bit is wonked");
  935. if (Info.empty())
  936. setHasMetadataHashEntry(true);
  937. Info.set(KindID, *Node);
  938. return;
  939. }
  940. // Otherwise, we're removing metadata from an instruction.
  941. assert((hasMetadataHashEntry() ==
  942. (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
  943. "HasMetadata bit out of date!");
  944. if (!hasMetadataHashEntry())
  945. return; // Nothing to remove!
  946. auto &Info = getContext().pImpl->InstructionMetadata[this];
  947. // Handle removal of an existing value.
  948. Info.erase(KindID);
  949. if (!Info.empty())
  950. return;
  951. getContext().pImpl->InstructionMetadata.erase(this);
  952. setHasMetadataHashEntry(false);
  953. }
  954. void Instruction::setAAMetadata(const AAMDNodes &N) {
  955. setMetadata(LLVMContext::MD_tbaa, N.TBAA);
  956. setMetadata(LLVMContext::MD_alias_scope, N.Scope);
  957. setMetadata(LLVMContext::MD_noalias, N.NoAlias);
  958. }
  959. MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
  960. // Handle 'dbg' as a special case since it is not stored in the hash table.
  961. if (KindID == LLVMContext::MD_dbg)
  962. return DbgLoc.getAsMDNode();
  963. if (!hasMetadataHashEntry())
  964. return nullptr;
  965. auto &Info = getContext().pImpl->InstructionMetadata[this];
  966. assert(!Info.empty() && "bit out of sync with hash table");
  967. return Info.lookup(KindID);
  968. }
  969. void Instruction::getAllMetadataImpl(
  970. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  971. Result.clear();
  972. // Handle 'dbg' as a special case since it is not stored in the hash table.
  973. if (DbgLoc) {
  974. Result.push_back(
  975. std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
  976. if (!hasMetadataHashEntry()) return;
  977. }
  978. assert(hasMetadataHashEntry() &&
  979. getContext().pImpl->InstructionMetadata.count(this) &&
  980. "Shouldn't have called this");
  981. const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
  982. assert(!Info.empty() && "Shouldn't have called this");
  983. Info.getAll(Result);
  984. }
  985. void Instruction::getAllMetadataOtherThanDebugLocImpl(
  986. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  987. Result.clear();
  988. assert(hasMetadataHashEntry() &&
  989. getContext().pImpl->InstructionMetadata.count(this) &&
  990. "Shouldn't have called this");
  991. const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
  992. assert(!Info.empty() && "Shouldn't have called this");
  993. Info.getAll(Result);
  994. }
  995. /// clearMetadataHashEntries - Clear all hashtable-based metadata from
  996. /// this instruction.
  997. void Instruction::clearMetadataHashEntries() {
  998. assert(hasMetadataHashEntry() && "Caller should check");
  999. getContext().pImpl->InstructionMetadata.erase(this);
  1000. setHasMetadataHashEntry(false);
  1001. }
  1002. MDNode *Function::getMetadata(unsigned KindID) const {
  1003. if (!hasMetadata())
  1004. return nullptr;
  1005. return getContext().pImpl->FunctionMetadata[this].lookup(KindID);
  1006. }
  1007. MDNode *Function::getMetadata(StringRef Kind) const {
  1008. if (!hasMetadata())
  1009. return nullptr;
  1010. return getMetadata(getContext().getMDKindID(Kind));
  1011. }
  1012. void Function::setMetadata(unsigned KindID, MDNode *MD) {
  1013. if (MD) {
  1014. if (!hasMetadata())
  1015. setHasMetadataHashEntry(true);
  1016. getContext().pImpl->FunctionMetadata[this].set(KindID, *MD);
  1017. return;
  1018. }
  1019. // Nothing to unset.
  1020. if (!hasMetadata())
  1021. return;
  1022. auto &Store = getContext().pImpl->FunctionMetadata[this];
  1023. Store.erase(KindID);
  1024. if (Store.empty())
  1025. clearMetadata();
  1026. }
  1027. void Function::setMetadata(StringRef Kind, MDNode *MD) {
  1028. if (!MD && !hasMetadata())
  1029. return;
  1030. setMetadata(getContext().getMDKindID(Kind), MD);
  1031. }
  1032. void Function::getAllMetadata(
  1033. SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
  1034. MDs.clear();
  1035. if (!hasMetadata())
  1036. return;
  1037. getContext().pImpl->FunctionMetadata[this].getAll(MDs);
  1038. }
  1039. void Function::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
  1040. if (!hasMetadata())
  1041. return;
  1042. if (KnownIDs.empty()) {
  1043. clearMetadata();
  1044. return;
  1045. }
  1046. SmallSet<unsigned, 5> KnownSet;
  1047. KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
  1048. auto &Store = getContext().pImpl->FunctionMetadata[this];
  1049. assert(!Store.empty());
  1050. Store.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
  1051. return !KnownSet.count(I.first);
  1052. });
  1053. if (Store.empty())
  1054. clearMetadata();
  1055. }
  1056. void Function::clearMetadata() {
  1057. if (!hasMetadata())
  1058. return;
  1059. getContext().pImpl->FunctionMetadata.erase(this);
  1060. setHasMetadataHashEntry(false);
  1061. }