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