1 //===- Metadata.cpp - Implement Metadata classes --------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Metadata classes.
11 //===----------------------------------------------------------------------===//
13 #include "LLVMContextImpl.h"
14 #include "MetadataImpl.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/IR/Argument.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/Constant.h"
32 #include "llvm/IR/ConstantRange.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DebugInfoMetadata.h"
35 #include "llvm/IR/DebugLoc.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalObject.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instruction.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/IR/Metadata.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/TrackingMDRef.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/IR/Value.h"
46 #include "llvm/IR/ValueHandle.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
56 #include <type_traits>
62 MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
63 : Value(Ty, MetadataAsValueVal), MD(MD) {
67 MetadataAsValue::~MetadataAsValue() {
68 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
72 /// Canonicalize metadata arguments to intrinsics.
74 /// To support bitcode upgrades (and assembly semantic sugar) for \a
75 /// MetadataAsValue, we need to canonicalize certain metadata.
77 /// - nullptr is replaced by an empty MDNode.
78 /// - An MDNode with a single null operand is replaced by an empty MDNode.
79 /// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
81 /// This maintains readability of bitcode from when metadata was a type of
82 /// value, and these bridges were unnecessary.
83 static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
87 return MDNode::get(Context, None);
89 // Return early if this isn't a single-operand MDNode.
90 auto *N = dyn_cast<MDNode>(MD);
91 if (!N || N->getNumOperands() != 1)
94 if (!N->getOperand(0))
96 return MDNode::get(Context, None);
98 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
99 // Look through the MDNode.
105 MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
106 MD = canonicalizeMetadataForValue(Context, MD);
107 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
109 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
113 MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
115 MD = canonicalizeMetadataForValue(Context, MD);
116 auto &Store = Context.pImpl->MetadataAsValues;
117 return Store.lookup(MD);
120 void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
121 LLVMContext &Context = getContext();
122 MD = canonicalizeMetadataForValue(Context, MD);
123 auto &Store = Context.pImpl->MetadataAsValues;
125 // Stop tracking the old metadata.
126 Store.erase(this->MD);
130 // Start tracking MD, or RAUW if necessary.
131 auto *&Entry = Store[MD];
133 replaceAllUsesWith(Entry);
143 void MetadataAsValue::track() {
145 MetadataTracking::track(&MD, *MD, *this);
148 void MetadataAsValue::untrack() {
150 MetadataTracking::untrack(MD);
153 bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
154 assert(Ref && "Expected live reference");
155 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
156 "Reference without owner must be direct");
157 if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
158 R->addRef(Ref, Owner);
161 if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
162 assert(!PH->Use && "Placeholders can only be used once");
163 assert(!Owner && "Unexpected callback to owner");
164 PH->Use = static_cast<Metadata **>(Ref);
170 void MetadataTracking::untrack(void *Ref, Metadata &MD) {
171 assert(Ref && "Expected live reference");
172 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
174 else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
178 bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
179 assert(Ref && "Expected live reference");
180 assert(New && "Expected live reference");
181 assert(Ref != New && "Expected change");
182 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
183 R->moveRef(Ref, New, MD);
186 assert(!isa<DistinctMDOperandPlaceholder>(MD) &&
187 "Unexpected move of an MDOperand");
188 assert(!isReplaceable(MD) &&
189 "Expected un-replaceable metadata, since we didn't move a reference");
193 bool MetadataTracking::isReplaceable(const Metadata &MD) {
194 return ReplaceableMetadataImpl::isReplaceable(MD);
197 void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
199 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
202 assert(WasInserted && "Expected to add a reference");
205 assert(NextIndex != 0 && "Unexpected overflow");
208 void ReplaceableMetadataImpl::dropRef(void *Ref) {
209 bool WasErased = UseMap.erase(Ref);
211 assert(WasErased && "Expected to drop a reference");
214 void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
215 const Metadata &MD) {
216 auto I = UseMap.find(Ref);
217 assert(I != UseMap.end() && "Expected to move a reference");
218 auto OwnerAndIndex = I->second;
220 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
222 assert(WasInserted && "Expected to add a reference");
224 // Check that the references are direct if there's no owner.
226 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
227 "Reference without owner must be direct");
228 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
229 "Reference without owner must be direct");
232 void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
236 // Copy out uses since UseMap will get touched below.
237 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
238 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
239 llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
240 return L.second.second < R.second.second;
242 for (const auto &Pair : Uses) {
243 // Check that this Ref hasn't disappeared after RAUW (when updating a
245 if (!UseMap.count(Pair.first))
248 OwnerTy Owner = Pair.second.first;
250 // Update unowned tracking references directly.
251 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
254 MetadataTracking::track(Ref);
255 UseMap.erase(Pair.first);
259 // Check for MetadataAsValue.
260 if (Owner.is<MetadataAsValue *>()) {
261 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
265 // There's a Metadata owner -- dispatch.
266 Metadata *OwnerMD = Owner.get<Metadata *>();
267 switch (OwnerMD->getMetadataID()) {
268 #define HANDLE_METADATA_LEAF(CLASS) \
269 case Metadata::CLASS##Kind: \
270 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
272 #include "llvm/IR/Metadata.def"
274 llvm_unreachable("Invalid metadata subclass");
277 assert(UseMap.empty() && "Expected all uses to be replaced");
280 void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
289 // Copy out uses since UseMap could get touched below.
290 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
291 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
292 llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
293 return L.second.second < R.second.second;
296 for (const auto &Pair : Uses) {
297 auto Owner = Pair.second.first;
300 if (Owner.is<MetadataAsValue *>())
303 // Resolve MDNodes that point at this.
304 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
307 if (OwnerMD->isResolved())
309 OwnerMD->decrementUnresolvedOperandCount();
313 ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
314 if (auto *N = dyn_cast<MDNode>(&MD))
315 return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
316 return dyn_cast<ValueAsMetadata>(&MD);
319 ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
320 if (auto *N = dyn_cast<MDNode>(&MD))
321 return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
322 return dyn_cast<ValueAsMetadata>(&MD);
325 bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
326 if (auto *N = dyn_cast<MDNode>(&MD))
327 return !N->isResolved();
328 return dyn_cast<ValueAsMetadata>(&MD);
331 static DISubprogram *getLocalFunctionMetadata(Value *V) {
332 assert(V && "Expected value");
333 if (auto *A = dyn_cast<Argument>(V)) {
334 if (auto *Fn = A->getParent())
335 return Fn->getSubprogram();
339 if (BasicBlock *BB = cast<Instruction>(V)->getParent()) {
340 if (auto *Fn = BB->getParent())
341 return Fn->getSubprogram();
348 ValueAsMetadata *ValueAsMetadata::get(Value *V) {
349 assert(V && "Unexpected null Value");
351 auto &Context = V->getContext();
352 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
354 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
355 "Expected constant or function-local value");
356 assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
357 V->IsUsedByMD = true;
358 if (auto *C = dyn_cast<Constant>(V))
359 Entry = new ConstantAsMetadata(C);
361 Entry = new LocalAsMetadata(V);
367 ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
368 assert(V && "Unexpected null Value");
369 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
372 void ValueAsMetadata::handleDeletion(Value *V) {
373 assert(V && "Expected valid value");
375 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
376 auto I = Store.find(V);
377 if (I == Store.end())
380 // Remove old entry from the map.
381 ValueAsMetadata *MD = I->second;
382 assert(MD && "Expected valid metadata");
383 assert(MD->getValue() == V && "Expected valid mapping");
386 // Delete the metadata.
387 MD->replaceAllUsesWith(nullptr);
391 void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
392 assert(From && "Expected valid value");
393 assert(To && "Expected valid value");
394 assert(From != To && "Expected changed value");
395 assert(From->getType() == To->getType() && "Unexpected type change");
397 LLVMContext &Context = From->getType()->getContext();
398 auto &Store = Context.pImpl->ValuesAsMetadata;
399 auto I = Store.find(From);
400 if (I == Store.end()) {
401 assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
405 // Remove old entry from the map.
406 assert(From->IsUsedByMD && "Expected From to be used by metadata");
407 From->IsUsedByMD = false;
408 ValueAsMetadata *MD = I->second;
409 assert(MD && "Expected valid metadata");
410 assert(MD->getValue() == From && "Expected valid mapping");
413 if (isa<LocalAsMetadata>(MD)) {
414 if (auto *C = dyn_cast<Constant>(To)) {
415 // Local became a constant.
416 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
420 if (getLocalFunctionMetadata(From) && getLocalFunctionMetadata(To) &&
421 getLocalFunctionMetadata(From) != getLocalFunctionMetadata(To)) {
422 // DISubprogram changed.
423 MD->replaceAllUsesWith(nullptr);
427 } else if (!isa<Constant>(To)) {
428 // Changed to function-local value.
429 MD->replaceAllUsesWith(nullptr);
434 auto *&Entry = Store[To];
436 // The target already exists.
437 MD->replaceAllUsesWith(Entry);
442 // Update MD in place (and update the map entry).
443 assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
444 To->IsUsedByMD = true;
449 //===----------------------------------------------------------------------===//
450 // MDString implementation.
453 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
454 auto &Store = Context.pImpl->MDStringCache;
455 auto I = Store.try_emplace(Str);
456 auto &MapEntry = I.first->getValue();
459 MapEntry.Entry = &*I.first;
463 StringRef MDString::getString() const {
464 assert(Entry && "Expected to find string map entry");
465 return Entry->first();
468 //===----------------------------------------------------------------------===//
469 // MDNode implementation.
472 // Assert that the MDNode types will not be unaligned by the objects
473 // prepended to them.
474 #define HANDLE_MDNODE_LEAF(CLASS) \
476 alignof(uint64_t) >= alignof(CLASS), \
477 "Alignment is insufficient after objects prepended to " #CLASS);
478 #include "llvm/IR/Metadata.def"
480 void *MDNode::operator new(size_t Size, unsigned NumOps) {
481 size_t OpSize = NumOps * sizeof(MDOperand);
482 // uint64_t is the most aligned type we need support (ensured by static_assert
484 OpSize = alignTo(OpSize, alignof(uint64_t));
485 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
486 MDOperand *O = static_cast<MDOperand *>(Ptr);
487 for (MDOperand *E = O - NumOps; O != E; --O)
488 (void)new (O - 1) MDOperand;
492 // Repress memory sanitization, due to use-after-destroy by operator
493 // delete. Bug report 24578 identifies this issue.
494 LLVM_NO_SANITIZE_MEMORY_ATTRIBUTE void MDNode::operator delete(void *Mem) {
495 MDNode *N = static_cast<MDNode *>(Mem);
496 size_t OpSize = N->NumOperands * sizeof(MDOperand);
497 OpSize = alignTo(OpSize, alignof(uint64_t));
499 MDOperand *O = static_cast<MDOperand *>(Mem);
500 for (MDOperand *E = O - N->NumOperands; O != E; --O)
501 (O - 1)->~MDOperand();
502 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
505 MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
506 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
507 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
508 NumUnresolved(0), Context(Context) {
510 for (Metadata *MD : Ops1)
511 setOperand(Op++, MD);
512 for (Metadata *MD : Ops2)
513 setOperand(Op++, MD);
518 // Count the unresolved operands. If there are any, RAUW support will be
519 // added lazily on first reference.
520 countUnresolvedOperands();
523 TempMDNode MDNode::clone() const {
524 switch (getMetadataID()) {
526 llvm_unreachable("Invalid MDNode subclass");
527 #define HANDLE_MDNODE_LEAF(CLASS) \
529 return cast<CLASS>(this)->cloneImpl();
530 #include "llvm/IR/Metadata.def"
534 static bool isOperandUnresolved(Metadata *Op) {
535 if (auto *N = dyn_cast_or_null<MDNode>(Op))
536 return !N->isResolved();
540 void MDNode::countUnresolvedOperands() {
541 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
542 assert(isUniqued() && "Expected this to be uniqued");
543 NumUnresolved = count_if(operands(), isOperandUnresolved);
546 void MDNode::makeUniqued() {
547 assert(isTemporary() && "Expected this to be temporary");
548 assert(!isResolved() && "Expected this to be unresolved");
550 // Enable uniquing callbacks.
551 for (auto &Op : mutable_operands())
552 Op.reset(Op.get(), this);
554 // Make this 'uniqued'.
556 countUnresolvedOperands();
557 if (!NumUnresolved) {
558 dropReplaceableUses();
559 assert(isResolved() && "Expected this to be resolved");
562 assert(isUniqued() && "Expected this to be uniqued");
565 void MDNode::makeDistinct() {
566 assert(isTemporary() && "Expected this to be temporary");
567 assert(!isResolved() && "Expected this to be unresolved");
569 // Drop RAUW support and store as a distinct node.
570 dropReplaceableUses();
571 storeDistinctInContext();
573 assert(isDistinct() && "Expected this to be distinct");
574 assert(isResolved() && "Expected this to be resolved");
577 void MDNode::resolve() {
578 assert(isUniqued() && "Expected this to be uniqued");
579 assert(!isResolved() && "Expected this to be unresolved");
582 dropReplaceableUses();
584 assert(isResolved() && "Expected this to be resolved");
587 void MDNode::dropReplaceableUses() {
588 assert(!NumUnresolved && "Unexpected unresolved operand");
590 // Drop any RAUW support.
591 if (Context.hasReplaceableUses())
592 Context.takeReplaceableUses()->resolveAllUses();
595 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
596 assert(isUniqued() && "Expected this to be uniqued");
597 assert(NumUnresolved != 0 && "Expected unresolved operands");
599 // Check if an operand was resolved.
600 if (!isOperandUnresolved(Old)) {
601 if (isOperandUnresolved(New))
602 // An operand was un-resolved!
604 } else if (!isOperandUnresolved(New))
605 decrementUnresolvedOperandCount();
608 void MDNode::decrementUnresolvedOperandCount() {
609 assert(!isResolved() && "Expected this to be unresolved");
613 assert(isUniqued() && "Expected this to be uniqued");
617 // Last unresolved operand has just been resolved.
618 dropReplaceableUses();
619 assert(isResolved() && "Expected this to become resolved");
622 void MDNode::resolveCycles() {
626 // Resolve this node immediately.
629 // Resolve all operands.
630 for (const auto &Op : operands()) {
631 auto *N = dyn_cast_or_null<MDNode>(Op);
635 assert(!N->isTemporary() &&
636 "Expected all forward declarations to be resolved");
637 if (!N->isResolved())
642 static bool hasSelfReference(MDNode *N) {
643 for (Metadata *MD : N->operands())
649 MDNode *MDNode::replaceWithPermanentImpl() {
650 switch (getMetadataID()) {
652 // If this type isn't uniquable, replace with a distinct node.
653 return replaceWithDistinctImpl();
655 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
658 #include "llvm/IR/Metadata.def"
661 // Even if this type is uniquable, self-references have to be distinct.
662 if (hasSelfReference(this))
663 return replaceWithDistinctImpl();
664 return replaceWithUniquedImpl();
667 MDNode *MDNode::replaceWithUniquedImpl() {
668 // Try to uniquify in place.
669 MDNode *UniquedNode = uniquify();
671 if (UniquedNode == this) {
676 // Collision, so RAUW instead.
677 replaceAllUsesWith(UniquedNode);
682 MDNode *MDNode::replaceWithDistinctImpl() {
687 void MDTuple::recalculateHash() {
688 setHash(MDTupleInfo::KeyTy::calculateHash(this));
691 void MDNode::dropAllReferences() {
692 for (unsigned I = 0, E = NumOperands; I != E; ++I)
693 setOperand(I, nullptr);
694 if (Context.hasReplaceableUses()) {
695 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
696 (void)Context.takeReplaceableUses();
700 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
701 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
702 assert(Op < getNumOperands() && "Expected valid operand");
705 // This node is not uniqued. Just set the operand and be done with it.
710 // This node is uniqued.
713 Metadata *Old = getOperand(Op);
716 // Drop uniquing for self-reference cycles and deleted constants.
717 if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
720 storeDistinctInContext();
724 // Re-unique the node.
725 auto *Uniqued = uniquify();
726 if (Uniqued == this) {
728 resolveAfterOperandChange(Old, New);
734 // Still unresolved, so RAUW.
736 // First, clear out all operands to prevent any recursion (similar to
737 // dropAllReferences(), but we still need the use-list).
738 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
739 setOperand(O, nullptr);
740 if (Context.hasReplaceableUses())
741 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
746 // Store in non-uniqued form if RAUW isn't possible.
747 storeDistinctInContext();
750 void MDNode::deleteAsSubclass() {
751 switch (getMetadataID()) {
753 llvm_unreachable("Invalid subclass of MDNode");
754 #define HANDLE_MDNODE_LEAF(CLASS) \
756 delete cast<CLASS>(this); \
758 #include "llvm/IR/Metadata.def"
762 template <class T, class InfoT>
763 static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
764 if (T *U = getUniqued(Store, N))
771 template <class NodeTy> struct MDNode::HasCachedHash {
774 template <class U, U Val> struct SFINAE {};
777 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
778 template <class U> static No &check(...);
780 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
783 MDNode *MDNode::uniquify() {
784 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
786 // Try to insert into uniquing store.
787 switch (getMetadataID()) {
789 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
790 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
791 case CLASS##Kind: { \
792 CLASS *SubclassThis = cast<CLASS>(this); \
793 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
794 ShouldRecalculateHash; \
795 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
796 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
798 #include "llvm/IR/Metadata.def"
802 void MDNode::eraseFromStore() {
803 switch (getMetadataID()) {
805 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
806 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
808 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
810 #include "llvm/IR/Metadata.def"
814 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
815 StorageType Storage, bool ShouldCreate) {
817 if (Storage == Uniqued) {
818 MDTupleInfo::KeyTy Key(MDs);
819 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
823 Hash = Key.getHash();
825 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
828 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
829 Storage, Context.pImpl->MDTuples);
832 void MDNode::deleteTemporary(MDNode *N) {
833 assert(N->isTemporary() && "Expected temporary node");
834 N->replaceAllUsesWith(nullptr);
835 N->deleteAsSubclass();
838 void MDNode::storeDistinctInContext() {
839 assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
840 assert(!NumUnresolved && "Unexpected unresolved nodes");
842 assert(isResolved() && "Expected this to be resolved");
845 switch (getMetadataID()) {
847 llvm_unreachable("Invalid subclass of MDNode");
848 #define HANDLE_MDNODE_LEAF(CLASS) \
849 case CLASS##Kind: { \
850 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
851 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
854 #include "llvm/IR/Metadata.def"
857 getContext().pImpl->DistinctMDNodes.push_back(this);
860 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
861 if (getOperand(I) == New)
869 handleChangedOperand(mutable_begin() + I, New);
872 void MDNode::setOperand(unsigned I, Metadata *New) {
873 assert(I < NumOperands);
874 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
877 /// Get a node or a self-reference that looks like it.
879 /// Special handling for finding self-references, for use by \a
880 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
881 /// when self-referencing nodes were still uniqued. If the first operand has
882 /// the same operands as \c Ops, return the first operand instead.
883 static MDNode *getOrSelfReference(LLVMContext &Context,
884 ArrayRef<Metadata *> Ops) {
886 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
887 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
888 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
889 if (Ops[I] != N->getOperand(I))
890 return MDNode::get(Context, Ops);
894 return MDNode::get(Context, Ops);
897 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
903 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
904 MDs.insert(B->op_begin(), B->op_end());
906 // FIXME: This preserves long-standing behaviour, but is it really the right
907 // behaviour? Or was that an unintended side-effect of node uniquing?
908 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
911 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
915 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
916 SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
917 MDs.remove_if([&](Metadata *MD) { return !is_contained(BSet, MD); });
919 // FIXME: This preserves long-standing behaviour, but is it really the right
920 // behaviour? Or was that an unintended side-effect of node uniquing?
921 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
924 MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
928 return concatenate(A, B);
931 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
935 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
936 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
937 if (AVal.compare(BVal) == APFloat::cmpLessThan)
942 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
943 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
946 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
947 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
950 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
951 ConstantInt *Low, ConstantInt *High) {
952 ConstantRange NewRange(Low->getValue(), High->getValue());
953 unsigned Size = EndPoints.size();
954 APInt LB = EndPoints[Size - 2]->getValue();
955 APInt LE = EndPoints[Size - 1]->getValue();
956 ConstantRange LastRange(LB, LE);
957 if (canBeMerged(NewRange, LastRange)) {
958 ConstantRange Union = LastRange.unionWith(NewRange);
959 Type *Ty = High->getType();
960 EndPoints[Size - 2] =
961 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
962 EndPoints[Size - 1] =
963 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
969 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
970 ConstantInt *Low, ConstantInt *High) {
971 if (!EndPoints.empty())
972 if (tryMergeRange(EndPoints, Low, High))
975 EndPoints.push_back(Low);
976 EndPoints.push_back(High);
979 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
980 // Given two ranges, we want to compute the union of the ranges. This
981 // is slightly complicated by having to combine the intervals and merge
982 // the ones that overlap.
990 // First, walk both lists in order of the lower boundary of each interval.
991 // At each step, try to merge the new interval to the last one we adedd.
992 SmallVector<ConstantInt *, 4> EndPoints;
995 int AN = A->getNumOperands() / 2;
996 int BN = B->getNumOperands() / 2;
997 while (AI < AN && BI < BN) {
998 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
999 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
1001 if (ALow->getValue().slt(BLow->getValue())) {
1002 addRange(EndPoints, ALow,
1003 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1006 addRange(EndPoints, BLow,
1007 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1012 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
1013 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1017 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
1018 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1022 // If we have more than 2 ranges (4 endpoints) we have to try to merge
1023 // the last and first ones.
1024 unsigned Size = EndPoints.size();
1026 ConstantInt *FB = EndPoints[0];
1027 ConstantInt *FE = EndPoints[1];
1028 if (tryMergeRange(EndPoints, FB, FE)) {
1029 for (unsigned i = 0; i < Size - 2; ++i) {
1030 EndPoints[i] = EndPoints[i + 2];
1032 EndPoints.resize(Size - 2);
1036 // If in the end we have a single range, it is possible that it is now the
1037 // full range. Just drop the metadata in that case.
1038 if (EndPoints.size() == 2) {
1039 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
1040 if (Range.isFullSet())
1044 SmallVector<Metadata *, 4> MDs;
1045 MDs.reserve(EndPoints.size());
1046 for (auto *I : EndPoints)
1047 MDs.push_back(ConstantAsMetadata::get(I));
1048 return MDNode::get(A->getContext(), MDs);
1051 MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
1055 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1056 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1057 if (AVal->getZExtValue() < BVal->getZExtValue())
1062 //===----------------------------------------------------------------------===//
1063 // NamedMDNode implementation.
1066 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1067 return *(SmallVector<TrackingMDRef, 4> *)Operands;
1070 NamedMDNode::NamedMDNode(const Twine &N)
1071 : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
1073 NamedMDNode::~NamedMDNode() {
1074 dropAllReferences();
1075 delete &getNMDOps(Operands);
1078 unsigned NamedMDNode::getNumOperands() const {
1079 return (unsigned)getNMDOps(Operands).size();
1082 MDNode *NamedMDNode::getOperand(unsigned i) const {
1083 assert(i < getNumOperands() && "Invalid Operand number!");
1084 auto *N = getNMDOps(Operands)[i].get();
1085 return cast_or_null<MDNode>(N);
1088 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
1090 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1091 assert(I < getNumOperands() && "Invalid operand number");
1092 getNMDOps(Operands)[I].reset(New);
1095 void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
1097 void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
1099 StringRef NamedMDNode::getName() const { return StringRef(Name); }
1101 //===----------------------------------------------------------------------===//
1102 // Instruction Metadata method implementations.
1104 void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1105 for (auto &I : Attachments)
1106 if (I.first == ID) {
1107 I.second.reset(&MD);
1110 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1111 std::make_tuple(&MD));
1114 bool MDAttachmentMap::erase(unsigned ID) {
1118 // Common case is one/last value.
1119 if (Attachments.back().first == ID) {
1120 Attachments.pop_back();
1124 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1126 if (I->first == ID) {
1127 *I = std::move(Attachments.back());
1128 Attachments.pop_back();
1135 MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1136 for (const auto &I : Attachments)
1142 void MDAttachmentMap::getAll(
1143 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1144 Result.append(Attachments.begin(), Attachments.end());
1146 // Sort the resulting array so it is stable.
1147 if (Result.size() > 1)
1148 array_pod_sort(Result.begin(), Result.end());
1151 void MDGlobalAttachmentMap::insert(unsigned ID, MDNode &MD) {
1152 Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
1155 MDNode *MDGlobalAttachmentMap::lookup(unsigned ID) const {
1156 for (const auto &A : Attachments)
1162 void MDGlobalAttachmentMap::get(unsigned ID,
1163 SmallVectorImpl<MDNode *> &Result) const {
1164 for (const auto &A : Attachments)
1166 Result.push_back(A.Node);
1169 bool MDGlobalAttachmentMap::erase(unsigned ID) {
1170 auto I = std::remove_if(Attachments.begin(), Attachments.end(),
1171 [ID](const Attachment &A) { return A.MDKind == ID; });
1172 bool Changed = I != Attachments.end();
1173 Attachments.erase(I, Attachments.end());
1177 void MDGlobalAttachmentMap::getAll(
1178 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1179 for (const auto &A : Attachments)
1180 Result.emplace_back(A.MDKind, A.Node);
1182 // Sort the resulting array so it is stable with respect to metadata IDs. We
1183 // need to preserve the original insertion order though.
1184 llvm::stable_sort(Result, less_first());
1187 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1188 if (!Node && !hasMetadata())
1190 setMetadata(getContext().getMDKindID(Kind), Node);
1193 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
1194 return getMetadataImpl(getContext().getMDKindID(Kind));
1197 void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
1198 if (!hasMetadataHashEntry())
1199 return; // Nothing to remove!
1201 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
1203 SmallSet<unsigned, 4> KnownSet;
1204 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1205 if (KnownSet.empty()) {
1206 // Just drop our entry at the store.
1207 InstructionMetadata.erase(this);
1208 setHasMetadataHashEntry(false);
1212 auto &Info = InstructionMetadata[this];
1213 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1214 return !KnownSet.count(I.first);
1218 // Drop our entry at the store.
1219 InstructionMetadata.erase(this);
1220 setHasMetadataHashEntry(false);
1224 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1225 if (!Node && !hasMetadata())
1228 // Handle 'dbg' as a special case since it is not stored in the hash table.
1229 if (KindID == LLVMContext::MD_dbg) {
1230 DbgLoc = DebugLoc(Node);
1234 // Handle the case when we're adding/updating metadata on an instruction.
1236 auto &Info = getContext().pImpl->InstructionMetadata[this];
1237 assert(!Info.empty() == hasMetadataHashEntry() &&
1238 "HasMetadata bit is wonked");
1240 setHasMetadataHashEntry(true);
1241 Info.set(KindID, *Node);
1245 // Otherwise, we're removing metadata from an instruction.
1246 assert((hasMetadataHashEntry() ==
1247 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
1248 "HasMetadata bit out of date!");
1249 if (!hasMetadataHashEntry())
1250 return; // Nothing to remove!
1251 auto &Info = getContext().pImpl->InstructionMetadata[this];
1253 // Handle removal of an existing value.
1259 getContext().pImpl->InstructionMetadata.erase(this);
1260 setHasMetadataHashEntry(false);
1263 void Instruction::setAAMetadata(const AAMDNodes &N) {
1264 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1265 setMetadata(LLVMContext::MD_tbaa_struct, N.TBAAStruct);
1266 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1267 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1270 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
1271 // Handle 'dbg' as a special case since it is not stored in the hash table.
1272 if (KindID == LLVMContext::MD_dbg)
1273 return DbgLoc.getAsMDNode();
1275 if (!hasMetadataHashEntry())
1277 auto &Info = getContext().pImpl->InstructionMetadata[this];
1278 assert(!Info.empty() && "bit out of sync with hash table");
1280 return Info.lookup(KindID);
1283 void Instruction::getAllMetadataImpl(
1284 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1287 // Handle 'dbg' as a special case since it is not stored in the hash table.
1290 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1291 if (!hasMetadataHashEntry())
1295 assert(hasMetadataHashEntry() &&
1296 getContext().pImpl->InstructionMetadata.count(this) &&
1297 "Shouldn't have called this");
1298 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1299 assert(!Info.empty() && "Shouldn't have called this");
1300 Info.getAll(Result);
1303 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1304 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1306 assert(hasMetadataHashEntry() &&
1307 getContext().pImpl->InstructionMetadata.count(this) &&
1308 "Shouldn't have called this");
1309 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1310 assert(!Info.empty() && "Shouldn't have called this");
1311 Info.getAll(Result);
1314 bool Instruction::extractProfMetadata(uint64_t &TrueVal,
1315 uint64_t &FalseVal) const {
1317 (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select) &&
1318 "Looking for branch weights on something besides branch or select");
1320 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1321 if (!ProfileData || ProfileData->getNumOperands() != 3)
1324 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1325 if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
1328 auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
1329 auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
1330 if (!CITrue || !CIFalse)
1333 TrueVal = CITrue->getValue().getZExtValue();
1334 FalseVal = CIFalse->getValue().getZExtValue();
1339 bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
1340 assert((getOpcode() == Instruction::Br ||
1341 getOpcode() == Instruction::Select ||
1342 getOpcode() == Instruction::Call ||
1343 getOpcode() == Instruction::Invoke ||
1344 getOpcode() == Instruction::Switch) &&
1345 "Looking for branch weights on something besides branch");
1348 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1352 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1356 if (ProfDataName->getString().equals("branch_weights")) {
1358 for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
1359 auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
1362 TotalVal += V->getValue().getZExtValue();
1365 } else if (ProfDataName->getString().equals("VP") &&
1366 ProfileData->getNumOperands() > 3) {
1367 TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
1375 void Instruction::clearMetadataHashEntries() {
1376 assert(hasMetadataHashEntry() && "Caller should check");
1377 getContext().pImpl->InstructionMetadata.erase(this);
1378 setHasMetadataHashEntry(false);
1381 void GlobalObject::getMetadata(unsigned KindID,
1382 SmallVectorImpl<MDNode *> &MDs) const {
1384 getContext().pImpl->GlobalObjectMetadata[this].get(KindID, MDs);
1387 void GlobalObject::getMetadata(StringRef Kind,
1388 SmallVectorImpl<MDNode *> &MDs) const {
1390 getMetadata(getContext().getMDKindID(Kind), MDs);
1393 void GlobalObject::addMetadata(unsigned KindID, MDNode &MD) {
1395 setHasMetadataHashEntry(true);
1397 getContext().pImpl->GlobalObjectMetadata[this].insert(KindID, MD);
1400 void GlobalObject::addMetadata(StringRef Kind, MDNode &MD) {
1401 addMetadata(getContext().getMDKindID(Kind), MD);
1404 bool GlobalObject::eraseMetadata(unsigned KindID) {
1405 // Nothing to unset.
1409 auto &Store = getContext().pImpl->GlobalObjectMetadata[this];
1410 bool Changed = Store.erase(KindID);
1416 void GlobalObject::getAllMetadata(
1417 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1423 getContext().pImpl->GlobalObjectMetadata[this].getAll(MDs);
1426 void GlobalObject::clearMetadata() {
1429 getContext().pImpl->GlobalObjectMetadata.erase(this);
1430 setHasMetadataHashEntry(false);
1433 void GlobalObject::setMetadata(unsigned KindID, MDNode *N) {
1434 eraseMetadata(KindID);
1436 addMetadata(KindID, *N);
1439 void GlobalObject::setMetadata(StringRef Kind, MDNode *N) {
1440 setMetadata(getContext().getMDKindID(Kind), N);
1443 MDNode *GlobalObject::getMetadata(unsigned KindID) const {
1445 return getContext().pImpl->GlobalObjectMetadata[this].lookup(KindID);
1449 MDNode *GlobalObject::getMetadata(StringRef Kind) const {
1450 return getMetadata(getContext().getMDKindID(Kind));
1453 void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
1454 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1455 Other->getAllMetadata(MDs);
1456 for (auto &MD : MDs) {
1457 // We need to adjust the type metadata offset.
1458 if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1459 auto *OffsetConst = cast<ConstantInt>(
1460 cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1461 Metadata *TypeId = MD.second->getOperand(1);
1462 auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1463 OffsetConst->getType(), OffsetConst->getValue() + Offset));
1464 addMetadata(LLVMContext::MD_type,
1465 *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1468 // If an offset adjustment was specified we need to modify the DIExpression
1469 // to prepend the adjustment:
1470 // !DIExpression(DW_OP_plus, Offset, [original expr])
1471 auto *Attachment = MD.second;
1472 if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
1473 DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
1474 DIExpression *E = nullptr;
1476 auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
1477 GV = GVE->getVariable();
1478 E = GVE->getExpression();
1480 ArrayRef<uint64_t> OrigElements;
1482 OrigElements = E->getElements();
1483 std::vector<uint64_t> Elements(OrigElements.size() + 2);
1484 Elements[0] = dwarf::DW_OP_plus_uconst;
1485 Elements[1] = Offset;
1486 llvm::copy(OrigElements, Elements.begin() + 2);
1487 E = DIExpression::get(getContext(), Elements);
1488 Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
1490 addMetadata(MD.first, *Attachment);
1494 void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {
1496 LLVMContext::MD_type,
1497 *MDTuple::get(getContext(),
1498 {ConstantAsMetadata::get(ConstantInt::get(
1499 Type::getInt64Ty(getContext()), Offset)),
1503 void GlobalObject::addVCallVisibilityMetadata(VCallVisibility Visibility) {
1504 addMetadata(LLVMContext::MD_vcall_visibility,
1505 *MDNode::get(getContext(),
1506 {ConstantAsMetadata::get(ConstantInt::get(
1507 Type::getInt64Ty(getContext()), Visibility))}));
1510 GlobalObject::VCallVisibility GlobalObject::getVCallVisibility() const {
1511 if (MDNode *MD = getMetadata(LLVMContext::MD_vcall_visibility)) {
1512 uint64_t Val = cast<ConstantInt>(
1513 cast<ConstantAsMetadata>(MD->getOperand(0))->getValue())
1515 assert(Val <= 2 && "unknown vcall visibility!");
1516 return (VCallVisibility)Val;
1518 return VCallVisibility::VCallVisibilityPublic;
1521 void Function::setSubprogram(DISubprogram *SP) {
1522 setMetadata(LLVMContext::MD_dbg, SP);
1525 DISubprogram *Function::getSubprogram() const {
1526 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1529 bool Function::isDebugInfoForProfiling() const {
1530 if (DISubprogram *SP = getSubprogram()) {
1531 if (DICompileUnit *CU = SP->getUnit()) {
1532 return CU->getDebugInfoForProfiling();
1538 void GlobalVariable::addDebugInfo(DIGlobalVariableExpression *GV) {
1539 addMetadata(LLVMContext::MD_dbg, *GV);
1542 void GlobalVariable::getDebugInfo(
1543 SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const {
1544 SmallVector<MDNode *, 1> MDs;
1545 getMetadata(LLVMContext::MD_dbg, MDs);
1546 for (MDNode *MD : MDs)
1547 GVs.push_back(cast<DIGlobalVariableExpression>(MD));