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