IR: Metadata: Detect an RAUW recursion
[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 "SymbolTableListTraitsImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/IR/ConstantRange.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/LeakDetector.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/ValueHandle.h"
28
29 using namespace llvm;
30
31 MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
32     : Value(Ty, MetadataAsValueVal), MD(MD) {
33   track();
34 }
35
36 MetadataAsValue::~MetadataAsValue() {
37   getType()->getContext().pImpl->MetadataAsValues.erase(MD);
38   untrack();
39 }
40
41 /// \brief Canonicalize metadata arguments to intrinsics.
42 ///
43 /// To support bitcode upgrades (and assembly semantic sugar) for \a
44 /// MetadataAsValue, we need to canonicalize certain metadata.
45 ///
46 ///   - nullptr is replaced by an empty MDNode.
47 ///   - An MDNode with a single null operand is replaced by an empty MDNode.
48 ///   - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
49 ///
50 /// This maintains readability of bitcode from when metadata was a type of
51 /// value, and these bridges were unnecessary.
52 static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
53                                               Metadata *MD) {
54   if (!MD)
55     // !{}
56     return MDNode::get(Context, None);
57
58   // Return early if this isn't a single-operand MDNode.
59   auto *N = dyn_cast<MDNode>(MD);
60   if (!N || N->getNumOperands() != 1)
61     return MD;
62
63   if (!N->getOperand(0))
64     // !{}
65     return MDNode::get(Context, None);
66
67   if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
68     // Look through the MDNode.
69     return C;
70
71   return MD;
72 }
73
74 MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
75   MD = canonicalizeMetadataForValue(Context, MD);
76   auto *&Entry = Context.pImpl->MetadataAsValues[MD];
77   if (!Entry)
78     Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
79   return Entry;
80 }
81
82 MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
83                                               Metadata *MD) {
84   MD = canonicalizeMetadataForValue(Context, MD);
85   auto &Store = Context.pImpl->MetadataAsValues;
86   auto I = Store.find(MD);
87   return I == Store.end() ? nullptr : I->second;
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 void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
124   bool WasInserted =
125       UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
126           .second;
127   (void)WasInserted;
128   assert(WasInserted && "Expected to add a reference");
129
130   ++NextIndex;
131   assert(NextIndex != 0 && "Unexpected overflow");
132 }
133
134 void ReplaceableMetadataImpl::dropRef(void *Ref) {
135   bool WasErased = UseMap.erase(Ref);
136   (void)WasErased;
137   assert(WasErased && "Expected to drop a reference");
138 }
139
140 void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
141                                       const Metadata &MD) {
142   auto I = UseMap.find(Ref);
143   assert(I != UseMap.end() && "Expected to move a reference");
144   auto OwnerAndIndex = I->second;
145   UseMap.erase(I);
146   bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
147   (void)WasInserted;
148   assert(WasInserted && "Expected to add a reference");
149
150   // Check that the references are direct if there's no owner.
151   (void)MD;
152   assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
153          "Reference without owner must be direct");
154   assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
155          "Reference without owner must be direct");
156 }
157
158 void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
159   assert(!(MD && isa<MDNodeFwdDecl>(MD)) && "Expected non-temp node");
160
161   if (UseMap.empty())
162     return;
163
164   // Copy out uses since UseMap will get touched below.
165   typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
166   SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
167   std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
168     return L.second.second < R.second.second;
169   });
170   for (const auto &Pair : Uses) {
171     OwnerTy Owner = Pair.second.first;
172     if (!Owner) {
173       // Update unowned tracking references directly.
174       Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
175       Ref = MD;
176       MetadataTracking::track(Ref);
177       UseMap.erase(Pair.first);
178       continue;
179     }
180
181     // Check for MetadataAsValue.
182     if (Owner.is<MetadataAsValue *>()) {
183       Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
184       continue;
185     }
186
187     // There's a Metadata owner -- dispatch.
188     Metadata *OwnerMD = Owner.get<Metadata *>();
189     switch (OwnerMD->getMetadataID()) {
190 #define HANDLE_METADATA_LEAF(CLASS)                                            \
191   case Metadata::CLASS##Kind:                                                  \
192     cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD);                \
193     continue;
194 #include "llvm/IR/Metadata.def"
195     default:
196       llvm_unreachable("Invalid metadata subclass");
197     }
198   }
199   assert(UseMap.empty() && "Expected all uses to be replaced");
200 }
201
202 void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
203   if (UseMap.empty())
204     return;
205
206   if (!ResolveUsers) {
207     UseMap.clear();
208     return;
209   }
210
211   // Copy out uses since UseMap could get touched below.
212   typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
213   SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
214   std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
215     return L.second.second < R.second.second;
216   });
217   UseMap.clear();
218   for (const auto &Pair : Uses) {
219     auto Owner = Pair.second.first;
220     if (!Owner)
221       continue;
222     if (Owner.is<MetadataAsValue *>())
223       continue;
224
225     // Resolve GenericMDNodes that point at this.
226     auto *OwnerMD = dyn_cast<GenericMDNode>(Owner.get<Metadata *>());
227     if (!OwnerMD)
228       continue;
229     if (OwnerMD->isResolved())
230       continue;
231     OwnerMD->decrementUnresolvedOperands();
232     if (!OwnerMD->hasUnresolvedOperands())
233       OwnerMD->resolve();
234   }
235 }
236
237 static Function *getLocalFunction(Value *V) {
238   assert(V && "Expected value");
239   if (auto *A = dyn_cast<Argument>(V))
240     return A->getParent();
241   if (BasicBlock *BB = cast<Instruction>(V)->getParent())
242     return BB->getParent();
243   return nullptr;
244 }
245
246 ValueAsMetadata *ValueAsMetadata::get(Value *V) {
247   assert(V && "Unexpected null Value");
248
249   auto &Context = V->getContext();
250   auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
251   if (!Entry) {
252     assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
253            "Expected constant or function-local value");
254     assert(!V->NameAndIsUsedByMD.getInt() &&
255            "Expected this to be the only metadata use");
256     V->NameAndIsUsedByMD.setInt(true);
257     if (auto *C = dyn_cast<Constant>(V))
258       Entry = new ConstantAsMetadata(Context, C);
259     else
260       Entry = new LocalAsMetadata(Context, V);
261   }
262
263   return Entry;
264 }
265
266 ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
267   assert(V && "Unexpected null Value");
268   return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
269 }
270
271 void ValueAsMetadata::handleDeletion(Value *V) {
272   assert(V && "Expected valid value");
273
274   auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
275   auto I = Store.find(V);
276   if (I == Store.end())
277     return;
278
279   // Remove old entry from the map.
280   ValueAsMetadata *MD = I->second;
281   assert(MD && "Expected valid metadata");
282   assert(MD->getValue() == V && "Expected valid mapping");
283   Store.erase(I);
284
285   // Delete the metadata.
286   MD->replaceAllUsesWith(nullptr);
287   delete MD;
288 }
289
290 void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
291   assert(From && "Expected valid value");
292   assert(To && "Expected valid value");
293   assert(From != To && "Expected changed value");
294   assert(From->getType() == To->getType() && "Unexpected type change");
295
296   LLVMContext &Context = From->getType()->getContext();
297   auto &Store = Context.pImpl->ValuesAsMetadata;
298   auto I = Store.find(From);
299   if (I == Store.end()) {
300     assert(!From->NameAndIsUsedByMD.getInt() &&
301            "Expected From not to be used by metadata");
302     return;
303   }
304
305   // Remove old entry from the map.
306   assert(From->NameAndIsUsedByMD.getInt() &&
307          "Expected From to be used by metadata");
308   From->NameAndIsUsedByMD.setInt(false);
309   ValueAsMetadata *MD = I->second;
310   assert(MD && "Expected valid metadata");
311   assert(MD->getValue() == From && "Expected valid mapping");
312   Store.erase(I);
313
314   if (isa<LocalAsMetadata>(MD)) {
315     if (auto *C = dyn_cast<Constant>(To)) {
316       // Local became a constant.
317       MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
318       delete MD;
319       return;
320     }
321     if (getLocalFunction(From) && getLocalFunction(To) &&
322         getLocalFunction(From) != getLocalFunction(To)) {
323       // Function changed.
324       MD->replaceAllUsesWith(nullptr);
325       delete MD;
326       return;
327     }
328   } else if (!isa<Constant>(To)) {
329     // Changed to function-local value.
330     MD->replaceAllUsesWith(nullptr);
331     delete MD;
332     return;
333   }
334
335   auto *&Entry = Store[To];
336   if (Entry) {
337     // The target already exists.
338     MD->replaceAllUsesWith(Entry);
339     delete MD;
340     return;
341   }
342
343   // Update MD in place (and update the map entry).
344   assert(!To->NameAndIsUsedByMD.getInt() &&
345          "Expected this to be the only metadata use");
346   To->NameAndIsUsedByMD.setInt(true);
347   MD->V = To;
348   Entry = MD;
349 }
350
351 //===----------------------------------------------------------------------===//
352 // MDString implementation.
353 //
354
355 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
356   auto &Store = Context.pImpl->MDStringCache;
357   auto I = Store.find(Str);
358   if (I != Store.end())
359     return &I->second;
360
361   auto *Entry =
362       StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
363   bool WasInserted = Store.insert(Entry);
364   (void)WasInserted;
365   assert(WasInserted && "Expected entry to be inserted");
366   Entry->second.Entry = Entry;
367   return &Entry->second;
368 }
369
370 StringRef MDString::getString() const {
371   assert(Entry && "Expected to find string map entry");
372   return Entry->first();
373 }
374
375 //===----------------------------------------------------------------------===//
376 // MDNode implementation.
377 //
378
379 void *MDNode::operator new(size_t Size, unsigned NumOps) {
380   void *Ptr = ::operator new(Size + NumOps * sizeof(MDOperand));
381   MDOperand *First = new (Ptr) MDOperand[NumOps];
382   return First + NumOps;
383 }
384
385 void MDNode::operator delete(void *Mem) {
386   MDNode *N = static_cast<MDNode *>(Mem);
387   MDOperand *Last = static_cast<MDOperand *>(Mem);
388   ::operator delete(Last - N->NumOperands);
389 }
390
391 MDNode::MDNode(LLVMContext &Context, unsigned ID, ArrayRef<Metadata *> MDs)
392     : Metadata(ID), Context(Context), NumOperands(MDs.size()),
393       MDNodeSubclassData(0) {
394   for (unsigned I = 0, E = MDs.size(); I != E; ++I)
395     setOperand(I, MDs[I]);
396 }
397
398 bool MDNode::isResolved() const {
399   if (isa<MDNodeFwdDecl>(this))
400     return false;
401   return cast<GenericMDNode>(this)->isResolved();
402 }
403
404 static bool isOperandUnresolved(Metadata *Op) {
405   if (auto *N = dyn_cast_or_null<MDNode>(Op))
406     return !N->isResolved();
407   return false;
408 }
409
410 GenericMDNode::GenericMDNode(LLVMContext &C, ArrayRef<Metadata *> Vals)
411     : MDNode(C, GenericMDNodeKind, Vals) {
412   // Check whether any operands are unresolved, requiring re-uniquing.
413   for (const auto &Op : operands())
414     if (isOperandUnresolved(Op))
415       incrementUnresolvedOperands();
416
417   if (hasUnresolvedOperands())
418     ReplaceableUses.reset(new ReplaceableMetadataImpl);
419 }
420
421 GenericMDNode::~GenericMDNode() {
422   LLVMContextImpl *pImpl = getContext().pImpl;
423   if (isStoredDistinctInContext())
424     pImpl->NonUniquedMDNodes.erase(this);
425   else
426     pImpl->MDNodeSet.erase(this);
427 }
428
429 void GenericMDNode::resolve() {
430   assert(!isResolved() && "Expected this to be unresolved");
431
432   // Move the map, so that this immediately looks resolved.
433   auto Uses = std::move(ReplaceableUses);
434   SubclassData32 = 0;
435   assert(isResolved() && "Expected this to be resolved");
436
437   // Drop RAUW support.
438   Uses->resolveAllUses();
439 }
440
441 void GenericMDNode::resolveCycles() {
442   if (isResolved())
443     return;
444
445   // Resolve this node immediately.
446   resolve();
447
448   // Resolve all operands.
449   for (const auto &Op : operands()) {
450     if (!Op)
451       continue;
452     assert(!isa<MDNodeFwdDecl>(Op) &&
453            "Expected all forward declarations to be resolved");
454     if (auto *N = dyn_cast<GenericMDNode>(Op))
455       if (!N->isResolved())
456         N->resolveCycles();
457   }
458 }
459
460 void MDNode::dropAllReferences() {
461   for (unsigned I = 0, E = NumOperands; I != E; ++I)
462     setOperand(I, nullptr);
463   if (auto *G = dyn_cast<GenericMDNode>(this))
464     if (!G->isResolved()) {
465       G->ReplaceableUses->resolveAllUses(/* ResolveUsers */ false);
466       G->ReplaceableUses.reset();
467     }
468 }
469
470 namespace llvm {
471 /// \brief Make MDOperand transparent for hashing.
472 ///
473 /// This overload of an implementation detail of the hashing library makes
474 /// MDOperand hash to the same value as a \a Metadata pointer.
475 ///
476 /// Note that overloading \a hash_value() as follows:
477 ///
478 /// \code
479 ///     size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
480 /// \endcode
481 ///
482 /// does not cause MDOperand to be transparent.  In particular, a bare pointer
483 /// doesn't get hashed before it's combined, whereas \a MDOperand would.
484 static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
485 }
486
487 void GenericMDNode::handleChangedOperand(void *Ref, Metadata *New) {
488   unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
489   assert(Op < getNumOperands() && "Expected valid operand");
490
491   if (isStoredDistinctInContext()) {
492     assert(isResolved() && "Expected distinct node to be resolved");
493
494     // This node is not uniqued.  Just set the operand and be done with it.
495     setOperand(Op, New);
496     return;
497   }
498   if (InRAUW) {
499     // We just hit a recursion due to RAUW.  Set the operand and move on, since
500     // we're about to be deleted.
501     //
502     // FIXME: Can this cycle really happen?
503     setOperand(Op, New);
504     return;
505   }
506
507   auto &Store = getContext().pImpl->MDNodeSet;
508   Store.erase(this);
509
510   Metadata *Old = getOperand(Op);
511   setOperand(Op, New);
512
513   // Drop uniquing for self-reference cycles or if an operand drops to null.
514   //
515   // FIXME: Stop dropping uniquing when an operand drops to null.  The original
516   // motivation was to prevent madness during teardown of LLVMContextImpl, but
517   // dropAllReferences() fixes that problem in a better way.  (It's just here
518   // now for better staging of semantic changes.)
519   if (New == this || !New) {
520     storeDistinctInContext();
521     setHash(0);
522     if (!isResolved())
523       resolve();
524     return;
525   }
526
527   // Re-calculate the hash.
528   setHash(hash_combine_range(op_begin(), op_end()));
529 #ifndef NDEBUG
530   {
531     SmallVector<Metadata *, 8> MDs(op_begin(), op_end());
532     unsigned RawHash = hash_combine_range(MDs.begin(), MDs.end());
533     assert(getHash() == RawHash &&
534            "Expected hash of MDOperand to equal hash of Metadata*");
535   }
536 #endif
537
538   // Re-unique the node.
539   GenericMDNodeInfo::KeyTy Key(this);
540   auto I = Store.find_as(Key);
541   if (I == Store.end()) {
542     Store.insert(this);
543
544     if (!isResolved()) {
545       // Check if the last unresolved operand has just been resolved; if so,
546       // resolve this as well.
547       if (isOperandUnresolved(Old))
548         decrementUnresolvedOperands();
549       if (isOperandUnresolved(New))
550         incrementUnresolvedOperands();
551       if (!hasUnresolvedOperands())
552         resolve();
553     }
554
555     return;
556   }
557
558   // Collision.
559   if (!isResolved()) {
560     // Still unresolved, so RAUW.
561     InRAUW = true;
562     ReplaceableUses->replaceAllUsesWith(*I);
563     delete this;
564     return;
565   }
566
567   // Store in non-uniqued form if this node has already been resolved.
568   setHash(0);
569   storeDistinctInContext();
570 }
571
572 MDNode *MDNode::getMDNode(LLVMContext &Context, ArrayRef<Metadata *> MDs,
573                           bool Insert) {
574   auto &Store = Context.pImpl->MDNodeSet;
575
576   GenericMDNodeInfo::KeyTy Key(MDs);
577   auto I = Store.find_as(Key);
578   if (I != Store.end())
579     return *I;
580   if (!Insert)
581     return nullptr;
582
583   // Coallocate space for the node and Operands together, then placement new.
584   GenericMDNode *N = new (MDs.size()) GenericMDNode(Context, MDs);
585   N->setHash(Key.Hash);
586   Store.insert(N);
587   return N;
588 }
589
590 MDNodeFwdDecl *MDNode::getTemporary(LLVMContext &Context,
591                                     ArrayRef<Metadata *> MDs) {
592   MDNodeFwdDecl *N = new (MDs.size()) MDNodeFwdDecl(Context, MDs);
593   LeakDetector::addGarbageObject(N);
594   return N;
595 }
596
597 void MDNode::deleteTemporary(MDNode *N) {
598   assert(isa<MDNodeFwdDecl>(N) && "Expected forward declaration");
599   LeakDetector::removeGarbageObject(N);
600   delete cast<MDNodeFwdDecl>(N);
601 }
602
603 void MDNode::storeDistinctInContext() {
604   assert(!IsDistinctInContext && "Expected newly distinct metadata");
605   IsDistinctInContext = true;
606   auto *G = cast<GenericMDNode>(this);
607   G->setHash(0);
608   getContext().pImpl->NonUniquedMDNodes.insert(G);
609 }
610
611 // Replace value from this node's operand list.
612 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
613   if (getOperand(I) == New)
614     return;
615
616   if (auto *N = dyn_cast<GenericMDNode>(this)) {
617     N->handleChangedOperand(mutable_begin() + I, New);
618     return;
619   }
620
621   assert(isa<MDNodeFwdDecl>(this) && "Expected an MDNode");
622   setOperand(I, New);
623 }
624
625 void MDNode::setOperand(unsigned I, Metadata *New) {
626   assert(I < NumOperands);
627   if (isStoredDistinctInContext() || isa<MDNodeFwdDecl>(this))
628     // No need for a callback, this isn't uniqued.
629     mutable_begin()[I].reset(New, nullptr);
630   else
631     mutable_begin()[I].reset(New, this);
632 }
633
634 /// \brief Get a node, or a self-reference that looks like it.
635 ///
636 /// Special handling for finding self-references, for use by \a
637 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
638 /// when self-referencing nodes were still uniqued.  If the first operand has
639 /// the same operands as \c Ops, return the first operand instead.
640 static MDNode *getOrSelfReference(LLVMContext &Context,
641                                   ArrayRef<Metadata *> Ops) {
642   if (!Ops.empty())
643     if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
644       if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
645         for (unsigned I = 1, E = Ops.size(); I != E; ++I)
646           if (Ops[I] != N->getOperand(I))
647             return MDNode::get(Context, Ops);
648         return N;
649       }
650
651   return MDNode::get(Context, Ops);
652 }
653
654 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
655   if (!A)
656     return B;
657   if (!B)
658     return A;
659
660   SmallVector<Metadata *, 4> MDs(A->getNumOperands() + B->getNumOperands());
661
662   unsigned j = 0;
663   for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i)
664     MDs[j++] = A->getOperand(i);
665   for (unsigned i = 0, ie = B->getNumOperands(); i != ie; ++i)
666     MDs[j++] = B->getOperand(i);
667
668   // FIXME: This preserves long-standing behaviour, but is it really the right
669   // behaviour?  Or was that an unintended side-effect of node uniquing?
670   return getOrSelfReference(A->getContext(), MDs);
671 }
672
673 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
674   if (!A || !B)
675     return nullptr;
676
677   SmallVector<Metadata *, 4> MDs;
678   for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i) {
679     Metadata *MD = A->getOperand(i);
680     for (unsigned j = 0, je = B->getNumOperands(); j != je; ++j)
681       if (MD == B->getOperand(j)) {
682         MDs.push_back(MD);
683         break;
684       }
685   }
686
687   // FIXME: This preserves long-standing behaviour, but is it really the right
688   // behaviour?  Or was that an unintended side-effect of node uniquing?
689   return getOrSelfReference(A->getContext(), MDs);
690 }
691
692 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
693   if (!A || !B)
694     return nullptr;
695
696   APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
697   APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
698   if (AVal.compare(BVal) == APFloat::cmpLessThan)
699     return A;
700   return B;
701 }
702
703 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
704   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
705 }
706
707 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
708   return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
709 }
710
711 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
712                           ConstantInt *Low, ConstantInt *High) {
713   ConstantRange NewRange(Low->getValue(), High->getValue());
714   unsigned Size = EndPoints.size();
715   APInt LB = EndPoints[Size - 2]->getValue();
716   APInt LE = EndPoints[Size - 1]->getValue();
717   ConstantRange LastRange(LB, LE);
718   if (canBeMerged(NewRange, LastRange)) {
719     ConstantRange Union = LastRange.unionWith(NewRange);
720     Type *Ty = High->getType();
721     EndPoints[Size - 2] =
722         cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
723     EndPoints[Size - 1] =
724         cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
725     return true;
726   }
727   return false;
728 }
729
730 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
731                      ConstantInt *Low, ConstantInt *High) {
732   if (!EndPoints.empty())
733     if (tryMergeRange(EndPoints, Low, High))
734       return;
735
736   EndPoints.push_back(Low);
737   EndPoints.push_back(High);
738 }
739
740 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
741   // Given two ranges, we want to compute the union of the ranges. This
742   // is slightly complitade by having to combine the intervals and merge
743   // the ones that overlap.
744
745   if (!A || !B)
746     return nullptr;
747
748   if (A == B)
749     return A;
750
751   // First, walk both lists in older of the lower boundary of each interval.
752   // At each step, try to merge the new interval to the last one we adedd.
753   SmallVector<ConstantInt *, 4> EndPoints;
754   int AI = 0;
755   int BI = 0;
756   int AN = A->getNumOperands() / 2;
757   int BN = B->getNumOperands() / 2;
758   while (AI < AN && BI < BN) {
759     ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
760     ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
761
762     if (ALow->getValue().slt(BLow->getValue())) {
763       addRange(EndPoints, ALow,
764                mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
765       ++AI;
766     } else {
767       addRange(EndPoints, BLow,
768                mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
769       ++BI;
770     }
771   }
772   while (AI < AN) {
773     addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
774              mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
775     ++AI;
776   }
777   while (BI < BN) {
778     addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
779              mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
780     ++BI;
781   }
782
783   // If we have more than 2 ranges (4 endpoints) we have to try to merge
784   // the last and first ones.
785   unsigned Size = EndPoints.size();
786   if (Size > 4) {
787     ConstantInt *FB = EndPoints[0];
788     ConstantInt *FE = EndPoints[1];
789     if (tryMergeRange(EndPoints, FB, FE)) {
790       for (unsigned i = 0; i < Size - 2; ++i) {
791         EndPoints[i] = EndPoints[i + 2];
792       }
793       EndPoints.resize(Size - 2);
794     }
795   }
796
797   // If in the end we have a single range, it is possible that it is now the
798   // full range. Just drop the metadata in that case.
799   if (EndPoints.size() == 2) {
800     ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
801     if (Range.isFullSet())
802       return nullptr;
803   }
804
805   SmallVector<Metadata *, 4> MDs;
806   MDs.reserve(EndPoints.size());
807   for (auto *I : EndPoints)
808     MDs.push_back(ConstantAsMetadata::get(I));
809   return MDNode::get(A->getContext(), MDs);
810 }
811
812 //===----------------------------------------------------------------------===//
813 // NamedMDNode implementation.
814 //
815
816 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
817   return *(SmallVector<TrackingMDRef, 4> *)Operands;
818 }
819
820 NamedMDNode::NamedMDNode(const Twine &N)
821     : Name(N.str()), Parent(nullptr),
822       Operands(new SmallVector<TrackingMDRef, 4>()) {}
823
824 NamedMDNode::~NamedMDNode() {
825   dropAllReferences();
826   delete &getNMDOps(Operands);
827 }
828
829 unsigned NamedMDNode::getNumOperands() const {
830   return (unsigned)getNMDOps(Operands).size();
831 }
832
833 MDNode *NamedMDNode::getOperand(unsigned i) const {
834   assert(i < getNumOperands() && "Invalid Operand number!");
835   auto *N = getNMDOps(Operands)[i].get();
836   if (N && i > 10000)
837     N->dump();
838   return cast_or_null<MDNode>(N);
839 }
840
841 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
842
843 void NamedMDNode::eraseFromParent() {
844   getParent()->eraseNamedMetadata(this);
845 }
846
847 void NamedMDNode::dropAllReferences() {
848   getNMDOps(Operands).clear();
849 }
850
851 StringRef NamedMDNode::getName() const {
852   return StringRef(Name);
853 }
854
855 //===----------------------------------------------------------------------===//
856 // Instruction Metadata method implementations.
857 //
858
859 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
860   if (!Node && !hasMetadata())
861     return;
862   setMetadata(getContext().getMDKindID(Kind), Node);
863 }
864
865 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
866   return getMetadataImpl(getContext().getMDKindID(Kind));
867 }
868
869 void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
870   SmallSet<unsigned, 5> KnownSet;
871   KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
872
873   // Drop debug if needed
874   if (KnownSet.erase(LLVMContext::MD_dbg))
875     DbgLoc = DebugLoc();
876
877   if (!hasMetadataHashEntry())
878     return; // Nothing to remove!
879
880   DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
881       getContext().pImpl->MetadataStore;
882
883   if (KnownSet.empty()) {
884     // Just drop our entry at the store.
885     MetadataStore.erase(this);
886     setHasMetadataHashEntry(false);
887     return;
888   }
889
890   LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
891   unsigned I;
892   unsigned E;
893   // Walk the array and drop any metadata we don't know.
894   for (I = 0, E = Info.size(); I != E;) {
895     if (KnownSet.count(Info[I].first)) {
896       ++I;
897       continue;
898     }
899
900     Info[I] = std::move(Info.back());
901     Info.pop_back();
902     --E;
903   }
904   assert(E == Info.size());
905
906   if (E == 0) {
907     // Drop our entry at the store.
908     MetadataStore.erase(this);
909     setHasMetadataHashEntry(false);
910   }
911 }
912
913 /// setMetadata - Set the metadata of of the specified kind to the specified
914 /// node.  This updates/replaces metadata if already present, or removes it if
915 /// Node is null.
916 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
917   if (!Node && !hasMetadata())
918     return;
919
920   // Handle 'dbg' as a special case since it is not stored in the hash table.
921   if (KindID == LLVMContext::MD_dbg) {
922     DbgLoc = DebugLoc::getFromDILocation(Node);
923     return;
924   }
925   
926   // Handle the case when we're adding/updating metadata on an instruction.
927   if (Node) {
928     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
929     assert(!Info.empty() == hasMetadataHashEntry() &&
930            "HasMetadata bit is wonked");
931     if (Info.empty()) {
932       setHasMetadataHashEntry(true);
933     } else {
934       // Handle replacement of an existing value.
935       for (auto &P : Info)
936         if (P.first == KindID) {
937           P.second.reset(Node);
938           return;
939         }
940     }
941
942     // No replacement, just add it to the list.
943     Info.emplace_back(std::piecewise_construct, std::make_tuple(KindID),
944                       std::make_tuple(Node));
945     return;
946   }
947
948   // Otherwise, we're removing metadata from an instruction.
949   assert((hasMetadataHashEntry() ==
950           (getContext().pImpl->MetadataStore.count(this) > 0)) &&
951          "HasMetadata bit out of date!");
952   if (!hasMetadataHashEntry())
953     return;  // Nothing to remove!
954   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
955
956   // Common case is removing the only entry.
957   if (Info.size() == 1 && Info[0].first == KindID) {
958     getContext().pImpl->MetadataStore.erase(this);
959     setHasMetadataHashEntry(false);
960     return;
961   }
962
963   // Handle removal of an existing value.
964   for (unsigned i = 0, e = Info.size(); i != e; ++i)
965     if (Info[i].first == KindID) {
966       Info[i] = std::move(Info.back());
967       Info.pop_back();
968       assert(!Info.empty() && "Removing last entry should be handled above");
969       return;
970     }
971   // Otherwise, removing an entry that doesn't exist on the instruction.
972 }
973
974 void Instruction::setAAMetadata(const AAMDNodes &N) {
975   setMetadata(LLVMContext::MD_tbaa, N.TBAA);
976   setMetadata(LLVMContext::MD_alias_scope, N.Scope);
977   setMetadata(LLVMContext::MD_noalias, N.NoAlias);
978 }
979
980 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
981   // Handle 'dbg' as a special case since it is not stored in the hash table.
982   if (KindID == LLVMContext::MD_dbg)
983     return DbgLoc.getAsMDNode();
984
985   if (!hasMetadataHashEntry()) return nullptr;
986   
987   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
988   assert(!Info.empty() && "bit out of sync with hash table");
989
990   for (const auto &I : Info)
991     if (I.first == KindID)
992       return I.second;
993   return nullptr;
994 }
995
996 void Instruction::getAllMetadataImpl(
997     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
998   Result.clear();
999   
1000   // Handle 'dbg' as a special case since it is not stored in the hash table.
1001   if (!DbgLoc.isUnknown()) {
1002     Result.push_back(
1003         std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1004     if (!hasMetadataHashEntry()) return;
1005   }
1006   
1007   assert(hasMetadataHashEntry() &&
1008          getContext().pImpl->MetadataStore.count(this) &&
1009          "Shouldn't have called this");
1010   const LLVMContextImpl::MDMapTy &Info =
1011     getContext().pImpl->MetadataStore.find(this)->second;
1012   assert(!Info.empty() && "Shouldn't have called this");
1013
1014   Result.reserve(Result.size() + Info.size());
1015   for (auto &I : Info)
1016     Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
1017
1018   // Sort the resulting array so it is stable.
1019   if (Result.size() > 1)
1020     array_pod_sort(Result.begin(), Result.end());
1021 }
1022
1023 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1024     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1025   Result.clear();
1026   assert(hasMetadataHashEntry() &&
1027          getContext().pImpl->MetadataStore.count(this) &&
1028          "Shouldn't have called this");
1029   const LLVMContextImpl::MDMapTy &Info =
1030     getContext().pImpl->MetadataStore.find(this)->second;
1031   assert(!Info.empty() && "Shouldn't have called this");
1032   Result.reserve(Result.size() + Info.size());
1033   for (auto &I : Info)
1034     Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
1035
1036   // Sort the resulting array so it is stable.
1037   if (Result.size() > 1)
1038     array_pod_sort(Result.begin(), Result.end());
1039 }
1040
1041 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
1042 /// this instruction.
1043 void Instruction::clearMetadataHashEntries() {
1044   assert(hasMetadataHashEntry() && "Caller should check");
1045   getContext().pImpl->MetadataStore.erase(this);
1046   setHasMetadataHashEntry(false);
1047 }
1048