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