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