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