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