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");
197 // Copy out uses since UseMap will get touched below.
198 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
199 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
200 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
201 return L.second.second < R.second.second;
203 for (const auto &Pair : Uses) {
204 // Check that this Ref hasn't disappeared after RAUW (when updating a
206 if (!UseMap.count(Pair.first))
209 OwnerTy Owner = Pair.second.first;
211 // Update unowned tracking references directly.
212 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
215 MetadataTracking::track(Ref);
216 UseMap.erase(Pair.first);
220 // Check for MetadataAsValue.
221 if (Owner.is<MetadataAsValue *>()) {
222 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
226 // There's a Metadata owner -- dispatch.
227 Metadata *OwnerMD = Owner.get<Metadata *>();
228 switch (OwnerMD->getMetadataID()) {
229 #define HANDLE_METADATA_LEAF(CLASS) \
230 case Metadata::CLASS##Kind: \
231 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
233 #include "llvm/IR/Metadata.def"
235 llvm_unreachable("Invalid metadata subclass");
238 assert(UseMap.empty() && "Expected all uses to be replaced");
241 void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
250 // Copy out uses since UseMap could get touched below.
251 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
252 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
253 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
254 return L.second.second < R.second.second;
257 for (const auto &Pair : Uses) {
258 auto Owner = Pair.second.first;
261 if (Owner.is<MetadataAsValue *>())
264 // Resolve MDNodes that point at this.
265 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
268 if (OwnerMD->isResolved())
270 OwnerMD->decrementUnresolvedOperandCount();
274 ReplaceableMetadataImpl *ReplaceableMetadataImpl::get(Metadata &MD) {
275 if (auto *N = dyn_cast<MDNode>(&MD))
276 return N->Context.getReplaceableUses();
277 return dyn_cast<ValueAsMetadata>(&MD);
280 static Function *getLocalFunction(Value *V) {
281 assert(V && "Expected value");
282 if (auto *A = dyn_cast<Argument>(V))
283 return A->getParent();
284 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
285 return BB->getParent();
289 ValueAsMetadata *ValueAsMetadata::get(Value *V) {
290 assert(V && "Unexpected null Value");
292 auto &Context = V->getContext();
293 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
295 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
296 "Expected constant or function-local value");
297 assert(!V->IsUsedByMD &&
298 "Expected this to be the only metadata use");
299 V->IsUsedByMD = true;
300 if (auto *C = dyn_cast<Constant>(V))
301 Entry = new ConstantAsMetadata(C);
303 Entry = new LocalAsMetadata(V);
309 ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
310 assert(V && "Unexpected null Value");
311 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
314 void ValueAsMetadata::handleDeletion(Value *V) {
315 assert(V && "Expected valid value");
317 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
318 auto I = Store.find(V);
319 if (I == Store.end())
322 // Remove old entry from the map.
323 ValueAsMetadata *MD = I->second;
324 assert(MD && "Expected valid metadata");
325 assert(MD->getValue() == V && "Expected valid mapping");
328 // Delete the metadata.
329 MD->replaceAllUsesWith(nullptr);
333 void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
334 assert(From && "Expected valid value");
335 assert(To && "Expected valid value");
336 assert(From != To && "Expected changed value");
337 assert(From->getType() == To->getType() && "Unexpected type change");
339 LLVMContext &Context = From->getType()->getContext();
340 auto &Store = Context.pImpl->ValuesAsMetadata;
341 auto I = Store.find(From);
342 if (I == Store.end()) {
343 assert(!From->IsUsedByMD &&
344 "Expected From not to be used by metadata");
348 // Remove old entry from the map.
349 assert(From->IsUsedByMD &&
350 "Expected From to be used by metadata");
351 From->IsUsedByMD = false;
352 ValueAsMetadata *MD = I->second;
353 assert(MD && "Expected valid metadata");
354 assert(MD->getValue() == From && "Expected valid mapping");
357 if (isa<LocalAsMetadata>(MD)) {
358 if (auto *C = dyn_cast<Constant>(To)) {
359 // Local became a constant.
360 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
364 if (getLocalFunction(From) && getLocalFunction(To) &&
365 getLocalFunction(From) != getLocalFunction(To)) {
367 MD->replaceAllUsesWith(nullptr);
371 } else if (!isa<Constant>(To)) {
372 // Changed to function-local value.
373 MD->replaceAllUsesWith(nullptr);
378 auto *&Entry = Store[To];
380 // The target already exists.
381 MD->replaceAllUsesWith(Entry);
386 // Update MD in place (and update the map entry).
387 assert(!To->IsUsedByMD &&
388 "Expected this to be the only metadata use");
389 To->IsUsedByMD = true;
394 //===----------------------------------------------------------------------===//
395 // MDString implementation.
398 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
399 auto &Store = Context.pImpl->MDStringCache;
400 auto I = Store.find(Str);
401 if (I != Store.end())
405 StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
406 bool WasInserted = Store.insert(Entry);
408 assert(WasInserted && "Expected entry to be inserted");
409 Entry->second.Entry = Entry;
410 return &Entry->second;
413 StringRef MDString::getString() const {
414 assert(Entry && "Expected to find string map entry");
415 return Entry->first();
418 //===----------------------------------------------------------------------===//
419 // MDNode implementation.
422 // Assert that the MDNode types will not be unaligned by the objects
423 // prepended to them.
424 #define HANDLE_MDNODE_LEAF(CLASS) \
426 llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment, \
427 "Alignment is insufficient after objects prepended to " #CLASS);
428 #include "llvm/IR/Metadata.def"
430 void *MDNode::operator new(size_t Size, unsigned NumOps) {
431 size_t OpSize = NumOps * sizeof(MDOperand);
432 // uint64_t is the most aligned type we need support (ensured by static_assert
434 OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
435 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
436 MDOperand *O = static_cast<MDOperand *>(Ptr);
437 for (MDOperand *E = O - NumOps; O != E; --O)
438 (void)new (O - 1) MDOperand;
442 void MDNode::operator delete(void *Mem) {
443 MDNode *N = static_cast<MDNode *>(Mem);
444 size_t OpSize = N->NumOperands * sizeof(MDOperand);
445 OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
447 MDOperand *O = static_cast<MDOperand *>(Mem);
448 for (MDOperand *E = O - N->NumOperands; O != E; --O)
449 (O - 1)->~MDOperand();
450 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
453 MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
454 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
455 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
456 NumUnresolved(0), Context(Context) {
458 for (Metadata *MD : Ops1)
459 setOperand(Op++, MD);
460 for (Metadata *MD : Ops2)
461 setOperand(Op++, MD);
467 // Check whether any operands are unresolved, requiring re-uniquing. If
468 // not, don't support RAUW.
469 if (!countUnresolvedOperands())
472 this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
475 TempMDNode MDNode::clone() const {
476 switch (getMetadataID()) {
478 llvm_unreachable("Invalid MDNode subclass");
479 #define HANDLE_MDNODE_LEAF(CLASS) \
481 return cast<CLASS>(this)->cloneImpl();
482 #include "llvm/IR/Metadata.def"
486 static bool isOperandUnresolved(Metadata *Op) {
487 if (auto *N = dyn_cast_or_null<MDNode>(Op))
488 return !N->isResolved();
492 unsigned MDNode::countUnresolvedOperands() {
493 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
494 NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
495 return NumUnresolved;
498 void MDNode::makeUniqued() {
499 assert(isTemporary() && "Expected this to be temporary");
500 assert(!isResolved() && "Expected this to be unresolved");
502 // Enable uniquing callbacks.
503 for (auto &Op : mutable_operands())
504 Op.reset(Op.get(), this);
506 // Make this 'uniqued'.
508 if (!countUnresolvedOperands())
511 assert(isUniqued() && "Expected this to be uniqued");
514 void MDNode::makeDistinct() {
515 assert(isTemporary() && "Expected this to be temporary");
516 assert(!isResolved() && "Expected this to be unresolved");
518 // Pretend to be uniqued, resolve the node, and then store in distinct table.
521 storeDistinctInContext();
523 assert(isDistinct() && "Expected this to be distinct");
524 assert(isResolved() && "Expected this to be resolved");
527 void MDNode::resolve() {
528 assert(isUniqued() && "Expected this to be uniqued");
529 assert(!isResolved() && "Expected this to be unresolved");
531 // Move the map, so that this immediately looks resolved.
532 auto Uses = Context.takeReplaceableUses();
534 assert(isResolved() && "Expected this to be resolved");
536 // Drop RAUW support.
537 Uses->resolveAllUses();
540 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
541 assert(NumUnresolved != 0 && "Expected unresolved operands");
543 // Check if an operand was resolved.
544 if (!isOperandUnresolved(Old)) {
545 if (isOperandUnresolved(New))
546 // An operand was un-resolved!
548 } else if (!isOperandUnresolved(New))
549 decrementUnresolvedOperandCount();
552 void MDNode::decrementUnresolvedOperandCount() {
553 if (!--NumUnresolved)
554 // Last unresolved operand has just been resolved.
558 void MDNode::resolveCycles(bool MDMaterialized) {
562 // Resolve this node immediately.
565 // Resolve all operands.
566 for (const auto &Op : operands()) {
567 auto *N = dyn_cast_or_null<MDNode>(Op);
571 if (N->isTemporary() && !MDMaterialized)
573 assert(!N->isTemporary() &&
574 "Expected all forward declarations to be resolved");
575 if (!N->isResolved())
580 static bool hasSelfReference(MDNode *N) {
581 for (Metadata *MD : N->operands())
587 MDNode *MDNode::replaceWithPermanentImpl() {
588 switch (getMetadataID()) {
590 // If this type isn't uniquable, replace with a distinct node.
591 return replaceWithDistinctImpl();
593 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
596 #include "llvm/IR/Metadata.def"
599 // Even if this type is uniquable, self-references have to be distinct.
600 if (hasSelfReference(this))
601 return replaceWithDistinctImpl();
602 return replaceWithUniquedImpl();
605 MDNode *MDNode::replaceWithUniquedImpl() {
606 // Try to uniquify in place.
607 MDNode *UniquedNode = uniquify();
609 if (UniquedNode == this) {
614 // Collision, so RAUW instead.
615 replaceAllUsesWith(UniquedNode);
620 MDNode *MDNode::replaceWithDistinctImpl() {
625 void MDTuple::recalculateHash() {
626 setHash(MDTupleInfo::KeyTy::calculateHash(this));
629 void MDNode::dropAllReferences() {
630 for (unsigned I = 0, E = NumOperands; I != E; ++I)
631 setOperand(I, nullptr);
633 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
634 (void)Context.takeReplaceableUses();
638 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
639 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
640 assert(Op < getNumOperands() && "Expected valid operand");
643 // This node is not uniqued. Just set the operand and be done with it.
648 // This node is uniqued.
651 Metadata *Old = getOperand(Op);
654 // Drop uniquing for self-reference cycles.
658 storeDistinctInContext();
662 // Re-unique the node.
663 auto *Uniqued = uniquify();
664 if (Uniqued == this) {
666 resolveAfterOperandChange(Old, New);
672 // Still unresolved, so RAUW.
674 // First, clear out all operands to prevent any recursion (similar to
675 // dropAllReferences(), but we still need the use-list).
676 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
677 setOperand(O, nullptr);
678 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
683 // Store in non-uniqued form if RAUW isn't possible.
684 storeDistinctInContext();
687 void MDNode::deleteAsSubclass() {
688 switch (getMetadataID()) {
690 llvm_unreachable("Invalid subclass of MDNode");
691 #define HANDLE_MDNODE_LEAF(CLASS) \
693 delete cast<CLASS>(this); \
695 #include "llvm/IR/Metadata.def"
699 template <class T, class InfoT>
700 static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
701 if (T *U = getUniqued(Store, N))
708 template <class NodeTy> struct MDNode::HasCachedHash {
711 template <class U, U Val> struct SFINAE {};
714 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
715 template <class U> static No &check(...);
717 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
720 MDNode *MDNode::uniquify() {
721 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
723 // Try to insert into uniquing store.
724 switch (getMetadataID()) {
726 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
727 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
728 case CLASS##Kind: { \
729 CLASS *SubclassThis = cast<CLASS>(this); \
730 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
731 ShouldRecalculateHash; \
732 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
733 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
735 #include "llvm/IR/Metadata.def"
739 void MDNode::eraseFromStore() {
740 switch (getMetadataID()) {
742 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
743 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
745 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
747 #include "llvm/IR/Metadata.def"
751 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
752 StorageType Storage, bool ShouldCreate) {
754 if (Storage == Uniqued) {
755 MDTupleInfo::KeyTy Key(MDs);
756 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
760 Hash = Key.getHash();
762 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
765 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
766 Storage, Context.pImpl->MDTuples);
769 void MDNode::deleteTemporary(MDNode *N) {
770 assert(N->isTemporary() && "Expected temporary node");
771 N->replaceAllUsesWith(nullptr);
772 N->deleteAsSubclass();
775 void MDNode::storeDistinctInContext() {
776 assert(isResolved() && "Expected resolved nodes");
780 switch (getMetadataID()) {
782 llvm_unreachable("Invalid subclass of MDNode");
783 #define HANDLE_MDNODE_LEAF(CLASS) \
784 case CLASS##Kind: { \
785 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
786 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
789 #include "llvm/IR/Metadata.def"
792 getContext().pImpl->DistinctMDNodes.insert(this);
795 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
796 if (getOperand(I) == New)
804 handleChangedOperand(mutable_begin() + I, New);
807 void MDNode::setOperand(unsigned I, Metadata *New) {
808 assert(I < NumOperands);
809 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
812 /// \brief Get a node, or a self-reference that looks like it.
814 /// Special handling for finding self-references, for use by \a
815 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
816 /// when self-referencing nodes were still uniqued. If the first operand has
817 /// the same operands as \c Ops, return the first operand instead.
818 static MDNode *getOrSelfReference(LLVMContext &Context,
819 ArrayRef<Metadata *> Ops) {
821 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
822 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
823 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
824 if (Ops[I] != N->getOperand(I))
825 return MDNode::get(Context, Ops);
829 return MDNode::get(Context, Ops);
832 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
838 SmallVector<Metadata *, 4> MDs;
839 MDs.reserve(A->getNumOperands() + B->getNumOperands());
840 MDs.append(A->op_begin(), A->op_end());
841 MDs.append(B->op_begin(), B->op_end());
843 // FIXME: This preserves long-standing behaviour, but is it really the right
844 // behaviour? Or was that an unintended side-effect of node uniquing?
845 return getOrSelfReference(A->getContext(), MDs);
848 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
852 SmallVector<Metadata *, 4> MDs;
853 for (Metadata *MD : A->operands())
854 if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
857 // FIXME: This preserves long-standing behaviour, but is it really the right
858 // behaviour? Or was that an unintended side-effect of node uniquing?
859 return getOrSelfReference(A->getContext(), MDs);
862 MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
866 SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
867 for (Metadata *MD : A->operands())
868 if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
871 // FIXME: This preserves long-standing behaviour, but is it really the right
872 // behaviour? Or was that an unintended side-effect of node uniquing?
873 return getOrSelfReference(A->getContext(), MDs);
876 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
880 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
881 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
882 if (AVal.compare(BVal) == APFloat::cmpLessThan)
887 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
888 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
891 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
892 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
895 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
896 ConstantInt *Low, ConstantInt *High) {
897 ConstantRange NewRange(Low->getValue(), High->getValue());
898 unsigned Size = EndPoints.size();
899 APInt LB = EndPoints[Size - 2]->getValue();
900 APInt LE = EndPoints[Size - 1]->getValue();
901 ConstantRange LastRange(LB, LE);
902 if (canBeMerged(NewRange, LastRange)) {
903 ConstantRange Union = LastRange.unionWith(NewRange);
904 Type *Ty = High->getType();
905 EndPoints[Size - 2] =
906 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
907 EndPoints[Size - 1] =
908 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
914 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
915 ConstantInt *Low, ConstantInt *High) {
916 if (!EndPoints.empty())
917 if (tryMergeRange(EndPoints, Low, High))
920 EndPoints.push_back(Low);
921 EndPoints.push_back(High);
924 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
925 // Given two ranges, we want to compute the union of the ranges. This
926 // is slightly complitade by having to combine the intervals and merge
927 // the ones that overlap.
935 // First, walk both lists in older of the lower boundary of each interval.
936 // At each step, try to merge the new interval to the last one we adedd.
937 SmallVector<ConstantInt *, 4> EndPoints;
940 int AN = A->getNumOperands() / 2;
941 int BN = B->getNumOperands() / 2;
942 while (AI < AN && BI < BN) {
943 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
944 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
946 if (ALow->getValue().slt(BLow->getValue())) {
947 addRange(EndPoints, ALow,
948 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
951 addRange(EndPoints, BLow,
952 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
957 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
958 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
962 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
963 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
967 // If we have more than 2 ranges (4 endpoints) we have to try to merge
968 // the last and first ones.
969 unsigned Size = EndPoints.size();
971 ConstantInt *FB = EndPoints[0];
972 ConstantInt *FE = EndPoints[1];
973 if (tryMergeRange(EndPoints, FB, FE)) {
974 for (unsigned i = 0; i < Size - 2; ++i) {
975 EndPoints[i] = EndPoints[i + 2];
977 EndPoints.resize(Size - 2);
981 // If in the end we have a single range, it is possible that it is now the
982 // full range. Just drop the metadata in that case.
983 if (EndPoints.size() == 2) {
984 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
985 if (Range.isFullSet())
989 SmallVector<Metadata *, 4> MDs;
990 MDs.reserve(EndPoints.size());
991 for (auto *I : EndPoints)
992 MDs.push_back(ConstantAsMetadata::get(I));
993 return MDNode::get(A->getContext(), MDs);
996 MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
1000 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1001 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1002 if (AVal->getZExtValue() < BVal->getZExtValue())
1007 //===----------------------------------------------------------------------===//
1008 // NamedMDNode implementation.
1011 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1012 return *(SmallVector<TrackingMDRef, 4> *)Operands;
1015 NamedMDNode::NamedMDNode(const Twine &N)
1016 : Name(N.str()), Parent(nullptr),
1017 Operands(new SmallVector<TrackingMDRef, 4>()) {}
1019 NamedMDNode::~NamedMDNode() {
1020 dropAllReferences();
1021 delete &getNMDOps(Operands);
1024 unsigned NamedMDNode::getNumOperands() const {
1025 return (unsigned)getNMDOps(Operands).size();
1028 MDNode *NamedMDNode::getOperand(unsigned i) const {
1029 assert(i < getNumOperands() && "Invalid Operand number!");
1030 auto *N = getNMDOps(Operands)[i].get();
1031 return cast_or_null<MDNode>(N);
1034 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
1036 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1037 assert(I < getNumOperands() && "Invalid operand number");
1038 getNMDOps(Operands)[I].reset(New);
1041 void NamedMDNode::eraseFromParent() {
1042 getParent()->eraseNamedMetadata(this);
1045 void NamedMDNode::dropAllReferences() {
1046 getNMDOps(Operands).clear();
1049 StringRef NamedMDNode::getName() const {
1050 return StringRef(Name);
1053 //===----------------------------------------------------------------------===//
1054 // Instruction Metadata method implementations.
1056 void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1057 for (auto &I : Attachments)
1058 if (I.first == ID) {
1059 I.second.reset(&MD);
1062 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1063 std::make_tuple(&MD));
1066 void MDAttachmentMap::erase(unsigned ID) {
1070 // Common case is one/last value.
1071 if (Attachments.back().first == ID) {
1072 Attachments.pop_back();
1076 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1078 if (I->first == ID) {
1079 *I = std::move(Attachments.back());
1080 Attachments.pop_back();
1085 MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1086 for (const auto &I : Attachments)
1092 void MDAttachmentMap::getAll(
1093 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1094 Result.append(Attachments.begin(), Attachments.end());
1096 // Sort the resulting array so it is stable.
1097 if (Result.size() > 1)
1098 array_pod_sort(Result.begin(), Result.end());
1101 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1102 if (!Node && !hasMetadata())
1104 setMetadata(getContext().getMDKindID(Kind), Node);
1107 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
1108 return getMetadataImpl(getContext().getMDKindID(Kind));
1111 void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
1112 SmallSet<unsigned, 5> KnownSet;
1113 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1115 if (!hasMetadataHashEntry())
1116 return; // Nothing to remove!
1118 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
1120 if (KnownSet.empty()) {
1121 // Just drop our entry at the store.
1122 InstructionMetadata.erase(this);
1123 setHasMetadataHashEntry(false);
1127 auto &Info = InstructionMetadata[this];
1128 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1129 return !KnownSet.count(I.first);
1133 // Drop our entry at the store.
1134 InstructionMetadata.erase(this);
1135 setHasMetadataHashEntry(false);
1139 /// setMetadata - Set the metadata of the specified kind to the specified
1140 /// node. This updates/replaces metadata if already present, or removes it if
1142 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1143 if (!Node && !hasMetadata())
1146 // Handle 'dbg' as a special case since it is not stored in the hash table.
1147 if (KindID == LLVMContext::MD_dbg) {
1148 DbgLoc = DebugLoc(Node);
1152 // Handle the case when we're adding/updating metadata on an instruction.
1154 auto &Info = getContext().pImpl->InstructionMetadata[this];
1155 assert(!Info.empty() == hasMetadataHashEntry() &&
1156 "HasMetadata bit is wonked");
1158 setHasMetadataHashEntry(true);
1159 Info.set(KindID, *Node);
1163 // Otherwise, we're removing metadata from an instruction.
1164 assert((hasMetadataHashEntry() ==
1165 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
1166 "HasMetadata bit out of date!");
1167 if (!hasMetadataHashEntry())
1168 return; // Nothing to remove!
1169 auto &Info = getContext().pImpl->InstructionMetadata[this];
1171 // Handle removal of an existing value.
1177 getContext().pImpl->InstructionMetadata.erase(this);
1178 setHasMetadataHashEntry(false);
1181 void Instruction::setAAMetadata(const AAMDNodes &N) {
1182 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1183 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1184 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1187 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
1188 // Handle 'dbg' as a special case since it is not stored in the hash table.
1189 if (KindID == LLVMContext::MD_dbg)
1190 return DbgLoc.getAsMDNode();
1192 if (!hasMetadataHashEntry())
1194 auto &Info = getContext().pImpl->InstructionMetadata[this];
1195 assert(!Info.empty() && "bit out of sync with hash table");
1197 return Info.lookup(KindID);
1200 void Instruction::getAllMetadataImpl(
1201 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1204 // Handle 'dbg' as a special case since it is not stored in the hash table.
1207 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1208 if (!hasMetadataHashEntry()) return;
1211 assert(hasMetadataHashEntry() &&
1212 getContext().pImpl->InstructionMetadata.count(this) &&
1213 "Shouldn't have called this");
1214 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1215 assert(!Info.empty() && "Shouldn't have called this");
1216 Info.getAll(Result);
1219 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1220 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1222 assert(hasMetadataHashEntry() &&
1223 getContext().pImpl->InstructionMetadata.count(this) &&
1224 "Shouldn't have called this");
1225 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1226 assert(!Info.empty() && "Shouldn't have called this");
1227 Info.getAll(Result);
1230 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
1231 /// this instruction.
1232 void Instruction::clearMetadataHashEntries() {
1233 assert(hasMetadataHashEntry() && "Caller should check");
1234 getContext().pImpl->InstructionMetadata.erase(this);
1235 setHasMetadataHashEntry(false);
1238 MDNode *Function::getMetadata(unsigned KindID) const {
1241 return getContext().pImpl->FunctionMetadata[this].lookup(KindID);
1244 MDNode *Function::getMetadata(StringRef Kind) const {
1247 return getMetadata(getContext().getMDKindID(Kind));
1250 void Function::setMetadata(unsigned KindID, MDNode *MD) {
1253 setHasMetadataHashEntry(true);
1255 getContext().pImpl->FunctionMetadata[this].set(KindID, *MD);
1259 // Nothing to unset.
1263 auto &Store = getContext().pImpl->FunctionMetadata[this];
1264 Store.erase(KindID);
1269 void Function::setMetadata(StringRef Kind, MDNode *MD) {
1270 if (!MD && !hasMetadata())
1272 setMetadata(getContext().getMDKindID(Kind), MD);
1275 void Function::getAllMetadata(
1276 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1282 getContext().pImpl->FunctionMetadata[this].getAll(MDs);
1285 void Function::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
1288 if (KnownIDs.empty()) {
1293 SmallSet<unsigned, 5> KnownSet;
1294 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1296 auto &Store = getContext().pImpl->FunctionMetadata[this];
1297 assert(!Store.empty());
1299 Store.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1300 return !KnownSet.count(I.first);
1307 void Function::clearMetadata() {
1310 getContext().pImpl->FunctionMetadata.erase(this);
1311 setHasMetadataHashEntry(false);
1314 void Function::setSubprogram(DISubprogram *SP) {
1315 setMetadata(LLVMContext::MD_dbg, SP);
1318 DISubprogram *Function::getSubprogram() const {
1319 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));