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