1 //===- Metadata.cpp - Implement Metadata classes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Metadata classes.
12 //===----------------------------------------------------------------------===//
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"
32 MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
33 : Value(Ty, MetadataAsValueVal), MD(MD) {
37 MetadataAsValue::~MetadataAsValue() {
38 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
42 /// \brief Canonicalize metadata arguments to intrinsics.
44 /// To support bitcode upgrades (and assembly semantic sugar) for \a
45 /// MetadataAsValue, we need to canonicalize certain metadata.
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.
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,
57 return MDNode::get(Context, None);
59 // Return early if this isn't a single-operand MDNode.
60 auto *N = dyn_cast<MDNode>(MD);
61 if (!N || N->getNumOperands() != 1)
64 if (!N->getOperand(0))
66 return MDNode::get(Context, None);
68 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
69 // Look through the MDNode.
75 MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
76 MD = canonicalizeMetadataForValue(Context, MD);
77 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
79 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
83 MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
85 MD = canonicalizeMetadataForValue(Context, MD);
86 auto &Store = Context.pImpl->MetadataAsValues;
87 return Store.lookup(MD);
90 void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
91 LLVMContext &Context = getContext();
92 MD = canonicalizeMetadataForValue(Context, MD);
93 auto &Store = Context.pImpl->MetadataAsValues;
95 // Stop tracking the old metadata.
96 Store.erase(this->MD);
100 // Start tracking MD, or RAUW if necessary.
101 auto *&Entry = Store[MD];
103 replaceAllUsesWith(Entry);
113 void MetadataAsValue::track() {
115 MetadataTracking::track(&MD, *MD, *this);
118 void MetadataAsValue::untrack() {
120 MetadataTracking::untrack(MD);
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);
134 void MetadataTracking::untrack(void *Ref, Metadata &MD) {
135 assert(Ref && "Expected live reference");
136 if (auto *R = ReplaceableMetadataImpl::get(MD))
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);
151 bool MetadataTracking::isReplaceable(const Metadata &MD) {
152 return ReplaceableMetadataImpl::get(const_cast<Metadata &>(MD));
155 void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
157 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
160 assert(WasInserted && "Expected to add a reference");
163 assert(NextIndex != 0 && "Unexpected overflow");
166 void ReplaceableMetadataImpl::dropRef(void *Ref) {
167 bool WasErased = UseMap.erase(Ref);
169 assert(WasErased && "Expected to drop a reference");
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;
178 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
180 assert(WasInserted && "Expected to add a reference");
182 // Check that the references are direct if there's no owner.
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");
190 void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
191 assert(!(MD && isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary()) &&
192 "Expected non-temp node");
194 "Attempted to replace Metadata marked for no replacement");
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;
205 for (const auto &Pair : Uses) {
206 // Check that this Ref hasn't disappeared after RAUW (when updating a
208 if (!UseMap.count(Pair.first))
211 OwnerTy Owner = Pair.second.first;
213 // Update unowned tracking references directly.
214 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
217 MetadataTracking::track(Ref);
218 UseMap.erase(Pair.first);
222 // Check for MetadataAsValue.
223 if (Owner.is<MetadataAsValue *>()) {
224 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
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); \
235 #include "llvm/IR/Metadata.def"
237 llvm_unreachable("Invalid metadata subclass");
240 assert(UseMap.empty() && "Expected all uses to be replaced");
243 void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
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;
259 for (const auto &Pair : Uses) {
260 auto Owner = Pair.second.first;
263 if (Owner.is<MetadataAsValue *>())
266 // Resolve MDNodes that point at this.
267 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
270 if (OwnerMD->isResolved())
272 OwnerMD->decrementUnresolvedOperandCount();
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);
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();
291 ValueAsMetadata *ValueAsMetadata::get(Value *V) {
292 assert(V && "Unexpected null Value");
294 auto &Context = V->getContext();
295 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
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);
305 Entry = new LocalAsMetadata(V);
311 ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
312 assert(V && "Unexpected null Value");
313 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
316 void ValueAsMetadata::handleDeletion(Value *V) {
317 assert(V && "Expected valid value");
319 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
320 auto I = Store.find(V);
321 if (I == Store.end())
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");
330 // Delete the metadata.
331 MD->replaceAllUsesWith(nullptr);
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");
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");
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");
359 if (isa<LocalAsMetadata>(MD)) {
360 if (auto *C = dyn_cast<Constant>(To)) {
361 // Local became a constant.
362 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
366 if (getLocalFunction(From) && getLocalFunction(To) &&
367 getLocalFunction(From) != getLocalFunction(To)) {
369 MD->replaceAllUsesWith(nullptr);
373 } else if (!isa<Constant>(To)) {
374 // Changed to function-local value.
375 MD->replaceAllUsesWith(nullptr);
380 auto *&Entry = Store[To];
382 // The target already exists.
383 MD->replaceAllUsesWith(Entry);
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;
396 //===----------------------------------------------------------------------===//
397 // MDString implementation.
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())
407 StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
408 bool WasInserted = Store.insert(Entry);
410 assert(WasInserted && "Expected entry to be inserted");
411 Entry->second.Entry = Entry;
412 return &Entry->second;
415 StringRef MDString::getString() const {
416 assert(Entry && "Expected to find string map entry");
417 return Entry->first();
420 //===----------------------------------------------------------------------===//
421 // MDNode implementation.
424 // Assert that the MDNode types will not be unaligned by the objects
425 // prepended to them.
426 #define HANDLE_MDNODE_LEAF(CLASS) \
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"
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
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;
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>());
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);
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) {
460 for (Metadata *MD : Ops1)
461 setOperand(Op++, MD);
462 for (Metadata *MD : Ops2)
463 setOperand(Op++, MD);
469 // Check whether any operands are unresolved, requiring re-uniquing. If
470 // not, don't support RAUW.
471 if (!countUnresolvedOperands())
474 this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
477 TempMDNode MDNode::clone() const {
478 switch (getMetadataID()) {
480 llvm_unreachable("Invalid MDNode subclass");
481 #define HANDLE_MDNODE_LEAF(CLASS) \
483 return cast<CLASS>(this)->cloneImpl();
484 #include "llvm/IR/Metadata.def"
488 static bool isOperandUnresolved(Metadata *Op) {
489 if (auto *N = dyn_cast_or_null<MDNode>(Op))
490 return !N->isResolved();
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;
500 void MDNode::makeUniqued() {
501 assert(isTemporary() && "Expected this to be temporary");
502 assert(!isResolved() && "Expected this to be unresolved");
504 // Enable uniquing callbacks.
505 for (auto &Op : mutable_operands())
506 Op.reset(Op.get(), this);
508 // Make this 'uniqued'.
510 if (!countUnresolvedOperands())
513 assert(isUniqued() && "Expected this to be uniqued");
516 void MDNode::makeDistinct() {
517 assert(isTemporary() && "Expected this to be temporary");
518 assert(!isResolved() && "Expected this to be unresolved");
520 // Pretend to be uniqued, resolve the node, and then store in distinct table.
523 storeDistinctInContext();
525 assert(isDistinct() && "Expected this to be distinct");
526 assert(isResolved() && "Expected this to be resolved");
529 void MDNode::resolve() {
530 assert(isUniqued() && "Expected this to be uniqued");
531 assert(!isResolved() && "Expected this to be unresolved");
533 // Move the map, so that this immediately looks resolved.
534 auto Uses = Context.takeReplaceableUses();
536 assert(isResolved() && "Expected this to be resolved");
538 // Drop RAUW support.
539 Uses->resolveAllUses();
542 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
543 assert(NumUnresolved != 0 && "Expected unresolved operands");
545 // Check if an operand was resolved.
546 if (!isOperandUnresolved(Old)) {
547 if (isOperandUnresolved(New))
548 // An operand was un-resolved!
550 } else if (!isOperandUnresolved(New))
551 decrementUnresolvedOperandCount();
554 void MDNode::decrementUnresolvedOperandCount() {
555 if (!--NumUnresolved)
556 // Last unresolved operand has just been resolved.
560 void MDNode::resolveCycles(bool AllowTemps) {
564 // Resolve this node immediately.
567 // Resolve all operands.
568 for (const auto &Op : operands()) {
569 auto *N = dyn_cast_or_null<MDNode>(Op);
573 if (N->isTemporary() && AllowTemps)
575 assert(!N->isTemporary() &&
576 "Expected all forward declarations to be resolved");
577 if (!N->isResolved())
582 static bool hasSelfReference(MDNode *N) {
583 for (Metadata *MD : N->operands())
589 MDNode *MDNode::replaceWithPermanentImpl() {
590 switch (getMetadataID()) {
592 // If this type isn't uniquable, replace with a distinct node.
593 return replaceWithDistinctImpl();
595 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
598 #include "llvm/IR/Metadata.def"
601 // Even if this type is uniquable, self-references have to be distinct.
602 if (hasSelfReference(this))
603 return replaceWithDistinctImpl();
604 return replaceWithUniquedImpl();
607 MDNode *MDNode::replaceWithUniquedImpl() {
608 // Try to uniquify in place.
609 MDNode *UniquedNode = uniquify();
611 if (UniquedNode == this) {
616 // Collision, so RAUW instead.
617 replaceAllUsesWith(UniquedNode);
622 MDNode *MDNode::replaceWithDistinctImpl() {
627 void MDTuple::recalculateHash() {
628 setHash(MDTupleInfo::KeyTy::calculateHash(this));
631 void MDNode::dropAllReferences() {
632 for (unsigned I = 0, E = NumOperands; I != E; ++I)
633 setOperand(I, nullptr);
635 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
636 (void)Context.takeReplaceableUses();
640 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
641 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
642 assert(Op < getNumOperands() && "Expected valid operand");
645 // This node is not uniqued. Just set the operand and be done with it.
650 // This node is uniqued.
653 Metadata *Old = getOperand(Op);
656 // Drop uniquing for self-reference cycles.
660 storeDistinctInContext();
664 // Re-unique the node.
665 auto *Uniqued = uniquify();
666 if (Uniqued == this) {
668 resolveAfterOperandChange(Old, New);
674 // Still unresolved, so RAUW.
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);
685 // Store in non-uniqued form if RAUW isn't possible.
686 storeDistinctInContext();
689 void MDNode::deleteAsSubclass() {
690 switch (getMetadataID()) {
692 llvm_unreachable("Invalid subclass of MDNode");
693 #define HANDLE_MDNODE_LEAF(CLASS) \
695 delete cast<CLASS>(this); \
697 #include "llvm/IR/Metadata.def"
701 template <class T, class InfoT>
702 static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
703 if (T *U = getUniqued(Store, N))
710 template <class NodeTy> struct MDNode::HasCachedHash {
713 template <class U, U Val> struct SFINAE {};
716 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
717 template <class U> static No &check(...);
719 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
722 MDNode *MDNode::uniquify() {
723 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
725 // Try to insert into uniquing store.
726 switch (getMetadataID()) {
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); \
737 #include "llvm/IR/Metadata.def"
741 void MDNode::eraseFromStore() {
742 switch (getMetadataID()) {
744 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
745 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
747 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
749 #include "llvm/IR/Metadata.def"
753 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
754 StorageType Storage, bool ShouldCreate) {
756 if (Storage == Uniqued) {
757 MDTupleInfo::KeyTy Key(MDs);
758 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
762 Hash = Key.getHash();
764 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
767 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
768 Storage, Context.pImpl->MDTuples);
771 void MDNode::deleteTemporary(MDNode *N) {
772 assert(N->isTemporary() && "Expected temporary node");
773 N->replaceAllUsesWith(nullptr);
774 N->deleteAsSubclass();
777 void MDNode::storeDistinctInContext() {
778 assert(isResolved() && "Expected resolved nodes");
782 switch (getMetadataID()) {
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); \
791 #include "llvm/IR/Metadata.def"
794 getContext().pImpl->DistinctMDNodes.insert(this);
797 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
798 if (getOperand(I) == New)
806 handleChangedOperand(mutable_begin() + I, New);
809 void MDNode::setOperand(unsigned I, Metadata *New) {
810 assert(I < NumOperands);
811 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
814 /// \brief Get a node, or a self-reference that looks like it.
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) {
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);
831 return MDNode::get(Context, Ops);
834 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
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());
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);
850 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
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())
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);
864 MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
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())
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);
878 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
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)
889 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
890 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
893 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
894 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
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()));
916 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
917 ConstantInt *Low, ConstantInt *High) {
918 if (!EndPoints.empty())
919 if (tryMergeRange(EndPoints, Low, High))
922 EndPoints.push_back(Low);
923 EndPoints.push_back(High);
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.
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;
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));
948 if (ALow->getValue().slt(BLow->getValue())) {
949 addRange(EndPoints, ALow,
950 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
953 addRange(EndPoints, BLow,
954 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
959 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
960 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
964 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
965 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
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();
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];
979 EndPoints.resize(Size - 2);
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())
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);
998 MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
1002 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1003 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1004 if (AVal->getZExtValue() < BVal->getZExtValue())
1009 //===----------------------------------------------------------------------===//
1010 // NamedMDNode implementation.
1013 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1014 return *(SmallVector<TrackingMDRef, 4> *)Operands;
1017 NamedMDNode::NamedMDNode(const Twine &N)
1018 : Name(N.str()), Parent(nullptr),
1019 Operands(new SmallVector<TrackingMDRef, 4>()) {}
1021 NamedMDNode::~NamedMDNode() {
1022 dropAllReferences();
1023 delete &getNMDOps(Operands);
1026 unsigned NamedMDNode::getNumOperands() const {
1027 return (unsigned)getNMDOps(Operands).size();
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);
1036 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
1038 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1039 assert(I < getNumOperands() && "Invalid operand number");
1040 getNMDOps(Operands)[I].reset(New);
1043 void NamedMDNode::eraseFromParent() {
1044 getParent()->eraseNamedMetadata(this);
1047 void NamedMDNode::dropAllReferences() {
1048 getNMDOps(Operands).clear();
1051 StringRef NamedMDNode::getName() const {
1052 return StringRef(Name);
1055 //===----------------------------------------------------------------------===//
1056 // Instruction Metadata method implementations.
1058 void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1059 for (auto &I : Attachments)
1060 if (I.first == ID) {
1061 I.second.reset(&MD);
1064 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1065 std::make_tuple(&MD));
1068 void MDAttachmentMap::erase(unsigned ID) {
1072 // Common case is one/last value.
1073 if (Attachments.back().first == ID) {
1074 Attachments.pop_back();
1078 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1080 if (I->first == ID) {
1081 *I = std::move(Attachments.back());
1082 Attachments.pop_back();
1087 MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1088 for (const auto &I : Attachments)
1094 void MDAttachmentMap::getAll(
1095 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1096 Result.append(Attachments.begin(), Attachments.end());
1098 // Sort the resulting array so it is stable.
1099 if (Result.size() > 1)
1100 array_pod_sort(Result.begin(), Result.end());
1103 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1104 if (!Node && !hasMetadata())
1106 setMetadata(getContext().getMDKindID(Kind), Node);
1109 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
1110 return getMetadataImpl(getContext().getMDKindID(Kind));
1113 void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
1114 SmallSet<unsigned, 5> KnownSet;
1115 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1117 if (!hasMetadataHashEntry())
1118 return; // Nothing to remove!
1120 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
1122 if (KnownSet.empty()) {
1123 // Just drop our entry at the store.
1124 InstructionMetadata.erase(this);
1125 setHasMetadataHashEntry(false);
1129 auto &Info = InstructionMetadata[this];
1130 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1131 return !KnownSet.count(I.first);
1135 // Drop our entry at the store.
1136 InstructionMetadata.erase(this);
1137 setHasMetadataHashEntry(false);
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
1144 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1145 if (!Node && !hasMetadata())
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);
1154 // Handle the case when we're adding/updating metadata on an instruction.
1156 auto &Info = getContext().pImpl->InstructionMetadata[this];
1157 assert(!Info.empty() == hasMetadataHashEntry() &&
1158 "HasMetadata bit is wonked");
1160 setHasMetadataHashEntry(true);
1161 Info.set(KindID, *Node);
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];
1173 // Handle removal of an existing value.
1179 getContext().pImpl->InstructionMetadata.erase(this);
1180 setHasMetadataHashEntry(false);
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);
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();
1194 if (!hasMetadataHashEntry())
1196 auto &Info = getContext().pImpl->InstructionMetadata[this];
1197 assert(!Info.empty() && "bit out of sync with hash table");
1199 return Info.lookup(KindID);
1202 void Instruction::getAllMetadataImpl(
1203 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1206 // Handle 'dbg' as a special case since it is not stored in the hash table.
1209 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1210 if (!hasMetadataHashEntry()) return;
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);
1221 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1222 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
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);
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);
1240 MDNode *Function::getMetadata(unsigned KindID) const {
1243 return getContext().pImpl->FunctionMetadata[this].lookup(KindID);
1246 MDNode *Function::getMetadata(StringRef Kind) const {
1249 return getMetadata(getContext().getMDKindID(Kind));
1252 void Function::setMetadata(unsigned KindID, MDNode *MD) {
1255 setHasMetadataHashEntry(true);
1257 getContext().pImpl->FunctionMetadata[this].set(KindID, *MD);
1261 // Nothing to unset.
1265 auto &Store = getContext().pImpl->FunctionMetadata[this];
1266 Store.erase(KindID);
1271 void Function::setMetadata(StringRef Kind, MDNode *MD) {
1272 if (!MD && !hasMetadata())
1274 setMetadata(getContext().getMDKindID(Kind), MD);
1277 void Function::getAllMetadata(
1278 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1284 getContext().pImpl->FunctionMetadata[this].getAll(MDs);
1287 void Function::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
1290 if (KnownIDs.empty()) {
1295 SmallSet<unsigned, 5> KnownSet;
1296 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1298 auto &Store = getContext().pImpl->FunctionMetadata[this];
1299 assert(!Store.empty());
1301 Store.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1302 return !KnownSet.count(I.first);
1309 void Function::clearMetadata() {
1312 getContext().pImpl->FunctionMetadata.erase(this);
1313 setHasMetadataHashEntry(false);
1316 void Function::setSubprogram(DISubprogram *SP) {
1317 setMetadata(LLVMContext::MD_dbg, SP);
1320 DISubprogram *Function::getSubprogram() const {
1321 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));