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