1 //===- llvm/IR/Metadata.h - Metadata definitions ----------------*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
11 /// This file contains the declarations for metadata subclasses.
12 /// They represent the different flavors of metadata that live in LLVM.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_IR_METADATA_H
17 #define LLVM_IR_METADATA_H
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/ilist_node.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/MetadataTracking.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include <type_traits>
32 template<typename ValueSubClass, typename ItemParentClass>
33 class SymbolTableListTraits;
35 enum LLVMConstants : uint32_t {
36 DEBUG_METADATA_VERSION = 3 // Current debug info version number.
39 /// \brief Root of the metadata hierarchy.
41 /// This is a root class for typeless data in the IR.
43 friend class ReplaceableMetadataImpl;
46 const unsigned char SubclassID;
49 /// \brief Active type of storage.
50 enum StorageType { Uniqued, Distinct, Temporary };
52 /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
54 // TODO: expose remaining bits to subclasses.
56 unsigned short SubclassData16;
57 unsigned SubclassData32;
74 MDLexicalBlockFileKind,
76 MDTemplateTypeParameterKind,
77 MDTemplateValueParameterKind,
83 ConstantAsMetadataKind,
89 Metadata(unsigned ID, StorageType Storage)
90 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
94 /// \brief Default handling of a changed operand, which asserts.
96 /// If subclasses pass themselves in as owners to a tracking node reference,
97 /// they must provide an implementation of this method.
98 void handleChangedOperand(void *, Metadata *) {
99 llvm_unreachable("Unimplemented in Metadata subclass");
103 unsigned getMetadataID() const { return SubclassID; }
105 /// \brief User-friendly dump.
107 /// If \c M is provided, metadata nodes will be numbered canonically;
108 /// otherwise, pointer addresses are substituted.
109 void dump(const Module *M = nullptr) const;
113 /// Prints definition of \c this.
115 /// If \c M is provided, metadata nodes will be numbered canonically;
116 /// otherwise, pointer addresses are substituted.
117 void print(raw_ostream &OS, const Module *M = nullptr) const;
119 /// \brief Print as operand.
121 /// Prints reference of \c this.
123 /// If \c M is provided, metadata nodes will be numbered canonically;
124 /// otherwise, pointer addresses are substituted.
125 void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
128 #define HANDLE_METADATA(CLASS) class CLASS;
129 #include "llvm/IR/Metadata.def"
131 // Provide specializations of isa so that we don't need definitions of
132 // subclasses to see if the metadata is a subclass.
133 #define HANDLE_METADATA_LEAF(CLASS) \
134 template <> struct isa_impl<CLASS, Metadata> { \
135 static inline bool doit(const Metadata &MD) { \
136 return MD.getMetadataID() == Metadata::CLASS##Kind; \
139 #include "llvm/IR/Metadata.def"
141 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
146 /// \brief Metadata wrapper in the Value hierarchy.
148 /// A member of the \a Value hierarchy to represent a reference to metadata.
149 /// This allows, e.g., instrinsics to have metadata as operands.
151 /// Notably, this is the only thing in either hierarchy that is allowed to
152 /// reference \a LocalAsMetadata.
153 class MetadataAsValue : public Value {
154 friend class ReplaceableMetadataImpl;
155 friend class LLVMContextImpl;
159 MetadataAsValue(Type *Ty, Metadata *MD);
162 /// \brief Drop use of metadata (during teardown).
163 void dropUse() { MD = nullptr; }
166 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
167 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
168 Metadata *getMetadata() const { return MD; }
170 static bool classof(const Value *V) {
171 return V->getValueID() == MetadataAsValueVal;
175 void handleChangedMetadata(Metadata *MD);
180 /// \brief Shared implementation of use-lists for replaceable metadata.
182 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
183 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
184 /// and \a TempMDNode).
185 class ReplaceableMetadataImpl {
186 friend class MetadataTracking;
189 typedef MetadataTracking::OwnerTy OwnerTy;
192 LLVMContext &Context;
194 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
197 ReplaceableMetadataImpl(LLVMContext &Context)
198 : Context(Context), NextIndex(0) {}
199 ~ReplaceableMetadataImpl() {
200 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
203 LLVMContext &getContext() const { return Context; }
205 /// \brief Replace all uses of this with MD.
207 /// Replace all uses of this with \c MD, which is allowed to be null.
208 void replaceAllUsesWith(Metadata *MD);
210 /// \brief Resolve all uses of this.
212 /// Resolve all uses of this, turning off RAUW permanently. If \c
213 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
215 void resolveAllUses(bool ResolveUsers = true);
218 void addRef(void *Ref, OwnerTy Owner);
219 void dropRef(void *Ref);
220 void moveRef(void *Ref, void *New, const Metadata &MD);
222 static ReplaceableMetadataImpl *get(Metadata &MD);
225 /// \brief Value wrapper in the Metadata hierarchy.
227 /// This is a custom value handle that allows other metadata to refer to
228 /// classes in the Value hierarchy.
230 /// Because of full uniquing support, each value is only wrapped by a single \a
231 /// ValueAsMetadata object, so the lookup maps are far more efficient than
232 /// those using ValueHandleBase.
233 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
234 friend class ReplaceableMetadataImpl;
235 friend class LLVMContextImpl;
239 /// \brief Drop users without RAUW (during teardown).
241 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
245 ValueAsMetadata(unsigned ID, Value *V)
246 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
247 assert(V && "Expected valid value");
249 ~ValueAsMetadata() {}
252 static ValueAsMetadata *get(Value *V);
253 static ConstantAsMetadata *getConstant(Value *C) {
254 return cast<ConstantAsMetadata>(get(C));
256 static LocalAsMetadata *getLocal(Value *Local) {
257 return cast<LocalAsMetadata>(get(Local));
260 static ValueAsMetadata *getIfExists(Value *V);
261 static ConstantAsMetadata *getConstantIfExists(Value *C) {
262 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
264 static LocalAsMetadata *getLocalIfExists(Value *Local) {
265 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
268 Value *getValue() const { return V; }
269 Type *getType() const { return V->getType(); }
270 LLVMContext &getContext() const { return V->getContext(); }
272 static void handleDeletion(Value *V);
273 static void handleRAUW(Value *From, Value *To);
276 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
278 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
279 /// \a Value gets RAUW'ed and the target already exists, this is used to
280 /// merge the two metadata nodes.
281 void replaceAllUsesWith(Metadata *MD) {
282 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
286 static bool classof(const Metadata *MD) {
287 return MD->getMetadataID() == LocalAsMetadataKind ||
288 MD->getMetadataID() == ConstantAsMetadataKind;
292 class ConstantAsMetadata : public ValueAsMetadata {
293 friend class ValueAsMetadata;
295 ConstantAsMetadata(Constant *C)
296 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
299 static ConstantAsMetadata *get(Constant *C) {
300 return ValueAsMetadata::getConstant(C);
302 static ConstantAsMetadata *getIfExists(Constant *C) {
303 return ValueAsMetadata::getConstantIfExists(C);
306 Constant *getValue() const {
307 return cast<Constant>(ValueAsMetadata::getValue());
310 static bool classof(const Metadata *MD) {
311 return MD->getMetadataID() == ConstantAsMetadataKind;
315 class LocalAsMetadata : public ValueAsMetadata {
316 friend class ValueAsMetadata;
318 LocalAsMetadata(Value *Local)
319 : ValueAsMetadata(LocalAsMetadataKind, Local) {
320 assert(!isa<Constant>(Local) && "Expected local value");
324 static LocalAsMetadata *get(Value *Local) {
325 return ValueAsMetadata::getLocal(Local);
327 static LocalAsMetadata *getIfExists(Value *Local) {
328 return ValueAsMetadata::getLocalIfExists(Local);
331 static bool classof(const Metadata *MD) {
332 return MD->getMetadataID() == LocalAsMetadataKind;
336 /// \brief Transitional API for extracting constants from Metadata.
338 /// This namespace contains transitional functions for metadata that points to
341 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
342 /// operands could refer to any \a Value. There's was a lot of code like this:
346 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
349 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
350 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
351 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
352 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
353 /// requires subtle control flow changes.
355 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
356 /// so that metadata can refer to numbers without traversing a bridge to the \a
357 /// Value hierarchy. In this final state, the code above would look like this:
361 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
364 /// The API in this namespace supports the transition. \a MDInt doesn't exist
365 /// yet, and even once it does, changing each metadata schema to use it is its
366 /// own mini-project. In the meantime this API prevents us from introducing
367 /// complex and bug-prone control flow that will disappear in the end. In
368 /// particular, the above code looks like this:
372 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
375 /// The full set of provided functions includes:
377 /// mdconst::hasa <=> isa
378 /// mdconst::extract <=> cast
379 /// mdconst::extract_or_null <=> cast_or_null
380 /// mdconst::dyn_extract <=> dyn_cast
381 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
383 /// The target of the cast must be a subclass of \a Constant.
387 template <class T> T &make();
388 template <class T, class Result> struct HasDereference {
391 template <size_t N> struct SFINAE {};
393 template <class U, class V>
394 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
395 template <class U, class V> static No &hasDereference(...);
397 static const bool value =
398 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
400 template <class V, class M> struct IsValidPointer {
401 static const bool value = std::is_base_of<Constant, V>::value &&
402 HasDereference<M, const Metadata &>::value;
404 template <class V, class M> struct IsValidReference {
405 static const bool value = std::is_base_of<Constant, V>::value &&
406 std::is_convertible<M, const Metadata &>::value;
408 } // end namespace detail
410 /// \brief Check whether Metadata has a Value.
412 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
414 template <class X, class Y>
415 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
417 assert(MD && "Null pointer sent into hasa");
418 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
419 return isa<X>(V->getValue());
422 template <class X, class Y>
424 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
429 /// \brief Extract a Value from Metadata.
431 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
432 template <class X, class Y>
433 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
435 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
437 template <class X, class Y>
439 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
444 /// \brief Extract a Value from Metadata, allowing null.
446 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
447 /// from \c MD, allowing \c MD to be null.
448 template <class X, class Y>
449 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
450 extract_or_null(Y &&MD) {
451 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
452 return cast<X>(V->getValue());
456 /// \brief Extract a Value from Metadata, if any.
458 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
459 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
460 /// Value it does contain is of the wrong subclass.
461 template <class X, class Y>
462 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
463 dyn_extract(Y &&MD) {
464 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
465 return dyn_cast<X>(V->getValue());
469 /// \brief Extract a Value from Metadata, if any, allowing null.
471 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
472 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
473 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
474 template <class X, class Y>
475 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
476 dyn_extract_or_null(Y &&MD) {
477 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
478 return dyn_cast<X>(V->getValue());
482 } // end namespace mdconst
484 //===----------------------------------------------------------------------===//
485 /// \brief A single uniqued string.
487 /// These are used to efficiently contain a byte sequence for metadata.
488 /// MDString is always unnamed.
489 class MDString : public Metadata {
490 friend class StringMapEntry<MDString>;
492 MDString(const MDString &) = delete;
493 MDString &operator=(MDString &&) = delete;
494 MDString &operator=(const MDString &) = delete;
496 StringMapEntry<MDString> *Entry;
497 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
498 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
501 static MDString *get(LLVMContext &Context, StringRef Str);
502 static MDString *get(LLVMContext &Context, const char *Str) {
503 return get(Context, Str ? StringRef(Str) : StringRef());
506 StringRef getString() const;
508 unsigned getLength() const { return (unsigned)getString().size(); }
510 typedef StringRef::iterator iterator;
512 /// \brief Pointer to the first byte of the string.
513 iterator begin() const { return getString().begin(); }
515 /// \brief Pointer to one byte past the end of the string.
516 iterator end() const { return getString().end(); }
518 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
519 const unsigned char *bytes_end() const { return getString().bytes_end(); }
521 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
522 static bool classof(const Metadata *MD) {
523 return MD->getMetadataID() == MDStringKind;
527 /// \brief A collection of metadata nodes that might be associated with a
528 /// memory access used by the alias-analysis infrastructure.
530 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
532 : TBAA(T), Scope(S), NoAlias(N) {}
534 bool operator==(const AAMDNodes &A) const {
535 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
538 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
540 explicit operator bool() const { return TBAA || Scope || NoAlias; }
542 /// \brief The tag for type-based alias analysis.
545 /// \brief The tag for alias scope specification (used with noalias).
548 /// \brief The tag specifying the noalias scope.
552 // Specialize DenseMapInfo for AAMDNodes.
554 struct DenseMapInfo<AAMDNodes> {
555 static inline AAMDNodes getEmptyKey() {
556 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
558 static inline AAMDNodes getTombstoneKey() {
559 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
561 static unsigned getHashValue(const AAMDNodes &Val) {
562 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
563 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
564 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
566 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
571 /// \brief Tracking metadata reference owned by Metadata.
573 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
574 /// of \a Metadata, which has the option of registering itself for callbacks to
575 /// re-unique itself.
577 /// In particular, this is used by \a MDNode.
579 MDOperand(MDOperand &&) = delete;
580 MDOperand(const MDOperand &) = delete;
581 MDOperand &operator=(MDOperand &&) = delete;
582 MDOperand &operator=(const MDOperand &) = delete;
587 MDOperand() : MD(nullptr) {}
588 ~MDOperand() { untrack(); }
590 Metadata *get() const { return MD; }
591 operator Metadata *() const { return get(); }
592 Metadata *operator->() const { return get(); }
593 Metadata &operator*() const { return *get(); }
599 void reset(Metadata *MD, Metadata *Owner) {
606 void track(Metadata *Owner) {
609 MetadataTracking::track(this, *MD, *Owner);
611 MetadataTracking::track(MD);
615 assert(static_cast<void *>(this) == &MD && "Expected same address");
617 MetadataTracking::untrack(MD);
621 template <> struct simplify_type<MDOperand> {
622 typedef Metadata *SimpleType;
623 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
626 template <> struct simplify_type<const MDOperand> {
627 typedef Metadata *SimpleType;
628 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
631 /// \brief Pointer to the context, with optional RAUW support.
633 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
634 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
635 class ContextAndReplaceableUses {
636 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
638 ContextAndReplaceableUses() = delete;
639 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
640 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
641 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
642 ContextAndReplaceableUses &
643 operator=(const ContextAndReplaceableUses &) = delete;
646 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
647 ContextAndReplaceableUses(
648 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
649 : Ptr(ReplaceableUses.release()) {
650 assert(getReplaceableUses() && "Expected non-null replaceable uses");
652 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
654 operator LLVMContext &() { return getContext(); }
656 /// \brief Whether this contains RAUW support.
657 bool hasReplaceableUses() const {
658 return Ptr.is<ReplaceableMetadataImpl *>();
660 LLVMContext &getContext() const {
661 if (hasReplaceableUses())
662 return getReplaceableUses()->getContext();
663 return *Ptr.get<LLVMContext *>();
665 ReplaceableMetadataImpl *getReplaceableUses() const {
666 if (hasReplaceableUses())
667 return Ptr.get<ReplaceableMetadataImpl *>();
671 /// \brief Assign RAUW support to this.
673 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
676 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
677 assert(ReplaceableUses && "Expected non-null replaceable uses");
678 assert(&ReplaceableUses->getContext() == &getContext() &&
679 "Expected same context");
680 delete getReplaceableUses();
681 Ptr = ReplaceableUses.release();
684 /// \brief Drop RAUW support.
686 /// Cede ownership of RAUW support, returning it.
687 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
688 assert(hasReplaceableUses() && "Expected to own replaceable uses");
689 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
690 getReplaceableUses());
691 Ptr = &ReplaceableUses->getContext();
692 return ReplaceableUses;
696 struct TempMDNodeDeleter {
697 inline void operator()(MDNode *Node) const;
700 #define HANDLE_MDNODE_LEAF(CLASS) \
701 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
702 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
703 #include "llvm/IR/Metadata.def"
705 /// \brief Metadata node.
707 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
708 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
709 /// until forward references are known. The basic metadata node is an \a
712 /// There is limited support for RAUW at construction time. At construction
713 /// time, if any operand is a temporary node (or an unresolved uniqued node,
714 /// which indicates a transitive temporary operand), the node itself will be
715 /// unresolved. As soon as all operands become resolved, it will drop RAUW
716 /// support permanently.
718 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
719 /// to be called on some member of the cycle once all temporary nodes have been
721 class MDNode : public Metadata {
722 friend class ReplaceableMetadataImpl;
723 friend class LLVMContextImpl;
725 MDNode(const MDNode &) = delete;
726 void operator=(const MDNode &) = delete;
727 void *operator new(size_t) = delete;
729 unsigned NumOperands;
730 unsigned NumUnresolved;
733 ContextAndReplaceableUses Context;
735 void *operator new(size_t Size, unsigned NumOps);
736 void operator delete(void *Mem);
738 /// \brief Required by std, but never called.
739 void operator delete(void *, unsigned) {
740 llvm_unreachable("Constructor throws?");
743 /// \brief Required by std, but never called.
744 void operator delete(void *, unsigned, bool) {
745 llvm_unreachable("Constructor throws?");
748 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
749 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
752 void dropAllReferences();
754 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
755 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
758 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
759 static inline MDTuple *getIfExists(LLVMContext &Context,
760 ArrayRef<Metadata *> MDs);
761 static inline MDTuple *getDistinct(LLVMContext &Context,
762 ArrayRef<Metadata *> MDs);
763 static inline TempMDTuple getTemporary(LLVMContext &Context,
764 ArrayRef<Metadata *> MDs);
766 /// \brief Create a (temporary) clone of this.
767 TempMDNode clone() const;
769 /// \brief Deallocate a node created by getTemporary.
771 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
772 /// references will be reset.
773 static void deleteTemporary(MDNode *N);
775 LLVMContext &getContext() const { return Context.getContext(); }
777 /// \brief Replace a specific operand.
778 void replaceOperandWith(unsigned I, Metadata *New);
780 /// \brief Check if node is fully resolved.
782 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
783 /// this always returns \c true.
785 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
786 /// support (because all operands are resolved).
788 /// As forward declarations are resolved, their containers should get
789 /// resolved automatically. However, if this (or one of its operands) is
790 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
791 bool isResolved() const { return !Context.hasReplaceableUses(); }
793 bool isUniqued() const { return Storage == Uniqued; }
794 bool isDistinct() const { return Storage == Distinct; }
795 bool isTemporary() const { return Storage == Temporary; }
797 /// \brief RAUW a temporary.
799 /// \pre \a isTemporary() must be \c true.
800 void replaceAllUsesWith(Metadata *MD) {
801 assert(isTemporary() && "Expected temporary node");
802 assert(!isResolved() && "Expected RAUW support");
803 Context.getReplaceableUses()->replaceAllUsesWith(MD);
806 /// \brief Resolve cycles.
808 /// Once all forward declarations have been resolved, force cycles to be
811 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
812 void resolveCycles();
814 /// \brief Replace a temporary node with a permanent one.
816 /// Try to create a uniqued version of \c N -- in place, if possible -- and
817 /// return it. If \c N cannot be uniqued, return a distinct node instead.
819 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
820 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
821 return cast<T>(N.release()->replaceWithPermanentImpl());
824 /// \brief Replace a temporary node with a uniqued one.
826 /// Create a uniqued version of \c N -- in place, if possible -- and return
827 /// it. Takes ownership of the temporary node.
829 /// \pre N does not self-reference.
831 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
832 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
833 return cast<T>(N.release()->replaceWithUniquedImpl());
836 /// \brief Replace a temporary node with a distinct one.
838 /// Create a distinct version of \c N -- in place, if possible -- and return
839 /// it. Takes ownership of the temporary node.
841 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
842 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
843 return cast<T>(N.release()->replaceWithDistinctImpl());
847 MDNode *replaceWithPermanentImpl();
848 MDNode *replaceWithUniquedImpl();
849 MDNode *replaceWithDistinctImpl();
852 /// \brief Set an operand.
854 /// Sets the operand directly, without worrying about uniquing.
855 void setOperand(unsigned I, Metadata *New);
857 void storeDistinctInContext();
858 template <class T, class StoreT>
859 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
862 void handleChangedOperand(void *Ref, Metadata *New);
865 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
866 void decrementUnresolvedOperandCount();
867 unsigned countUnresolvedOperands();
869 /// \brief Mutate this to be "uniqued".
871 /// Mutate this so that \a isUniqued().
872 /// \pre \a isTemporary().
873 /// \pre already added to uniquing set.
876 /// \brief Mutate this to be "distinct".
878 /// Mutate this so that \a isDistinct().
879 /// \pre \a isTemporary().
882 void deleteAsSubclass();
884 void eraseFromStore();
886 template <class NodeTy> struct HasCachedHash;
887 template <class NodeTy>
888 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
889 N->recalculateHash();
891 template <class NodeTy>
892 static void dispatchRecalculateHash(NodeTy *N, std::false_type) {}
893 template <class NodeTy>
894 static void dispatchResetHash(NodeTy *N, std::true_type) {
897 template <class NodeTy>
898 static void dispatchResetHash(NodeTy *N, std::false_type) {}
901 typedef const MDOperand *op_iterator;
902 typedef iterator_range<op_iterator> op_range;
904 op_iterator op_begin() const {
905 return const_cast<MDNode *>(this)->mutable_begin();
907 op_iterator op_end() const {
908 return const_cast<MDNode *>(this)->mutable_end();
910 op_range operands() const { return op_range(op_begin(), op_end()); }
912 const MDOperand &getOperand(unsigned I) const {
913 assert(I < NumOperands && "Out of range");
914 return op_begin()[I];
917 /// \brief Return number of MDNode operands.
918 unsigned getNumOperands() const { return NumOperands; }
920 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
921 static bool classof(const Metadata *MD) {
922 switch (MD->getMetadataID()) {
925 #define HANDLE_MDNODE_LEAF(CLASS) \
928 #include "llvm/IR/Metadata.def"
932 /// \brief Check whether MDNode is a vtable access.
933 bool isTBAAVtableAccess() const;
935 /// \brief Methods for metadata merging.
936 static MDNode *concatenate(MDNode *A, MDNode *B);
937 static MDNode *intersect(MDNode *A, MDNode *B);
938 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
939 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
940 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
941 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
944 /// \brief Tuple of metadata.
946 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
947 /// default based on their operands.
948 class MDTuple : public MDNode {
949 friend class LLVMContextImpl;
952 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
953 ArrayRef<Metadata *> Vals)
954 : MDNode(C, MDTupleKind, Storage, Vals) {
957 ~MDTuple() { dropAllReferences(); }
959 void setHash(unsigned Hash) { SubclassData32 = Hash; }
960 void recalculateHash();
962 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
963 StorageType Storage, bool ShouldCreate = true);
965 TempMDTuple cloneImpl() const {
966 return getTemporary(getContext(),
967 SmallVector<Metadata *, 4>(op_begin(), op_end()));
971 /// \brief Get the hash, if any.
972 unsigned getHash() const { return SubclassData32; }
974 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
975 return getImpl(Context, MDs, Uniqued);
977 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
978 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
981 /// \brief Return a distinct node.
983 /// Return a distinct node -- i.e., a node that is not uniqued.
984 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
985 return getImpl(Context, MDs, Distinct);
988 /// \brief Return a temporary node.
990 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
991 /// not uniqued, may be RAUW'd, and must be manually deleted with
993 static TempMDTuple getTemporary(LLVMContext &Context,
994 ArrayRef<Metadata *> MDs) {
995 return TempMDTuple(getImpl(Context, MDs, Temporary));
998 /// \brief Return a (temporary) clone of this.
999 TempMDTuple clone() const { return cloneImpl(); }
1001 static bool classof(const Metadata *MD) {
1002 return MD->getMetadataID() == MDTupleKind;
1006 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1007 return MDTuple::get(Context, MDs);
1009 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1010 return MDTuple::getIfExists(Context, MDs);
1012 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1013 return MDTuple::getDistinct(Context, MDs);
1015 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1016 ArrayRef<Metadata *> MDs) {
1017 return MDTuple::getTemporary(Context, MDs);
1020 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1021 MDNode::deleteTemporary(Node);
1024 //===----------------------------------------------------------------------===//
1025 /// \brief A tuple of MDNodes.
1027 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1028 /// to modules, have names, and contain lists of MDNodes.
1030 /// TODO: Inherit from Metadata.
1031 class NamedMDNode : public ilist_node<NamedMDNode> {
1032 friend class SymbolTableListTraits<NamedMDNode, Module>;
1033 friend struct ilist_traits<NamedMDNode>;
1034 friend class LLVMContextImpl;
1035 friend class Module;
1036 NamedMDNode(const NamedMDNode &) = delete;
1040 void *Operands; // SmallVector<TrackingMDRef, 4>
1042 void setParent(Module *M) { Parent = M; }
1044 explicit NamedMDNode(const Twine &N);
1046 template<class T1, class T2>
1047 class op_iterator_impl :
1048 public std::iterator<std::bidirectional_iterator_tag, T2> {
1049 const NamedMDNode *Node;
1051 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1053 friend class NamedMDNode;
1056 op_iterator_impl() : Node(nullptr), Idx(0) { }
1058 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1059 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1060 op_iterator_impl &operator++() {
1064 op_iterator_impl operator++(int) {
1065 op_iterator_impl tmp(*this);
1069 op_iterator_impl &operator--() {
1073 op_iterator_impl operator--(int) {
1074 op_iterator_impl tmp(*this);
1079 T1 operator*() const { return Node->getOperand(Idx); }
1083 /// \brief Drop all references and remove the node from parent module.
1084 void eraseFromParent();
1086 /// \brief Remove all uses and clear node vector.
1087 void dropAllReferences();
1091 /// \brief Get the module that holds this named metadata collection.
1092 inline Module *getParent() { return Parent; }
1093 inline const Module *getParent() const { return Parent; }
1095 MDNode *getOperand(unsigned i) const;
1096 unsigned getNumOperands() const;
1097 void addOperand(MDNode *M);
1098 void setOperand(unsigned I, MDNode *New);
1099 StringRef getName() const;
1100 void print(raw_ostream &ROS) const;
1103 // ---------------------------------------------------------------------------
1104 // Operand Iterator interface...
1106 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1107 op_iterator op_begin() { return op_iterator(this, 0); }
1108 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1110 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1111 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1112 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1114 inline iterator_range<op_iterator> operands() {
1115 return iterator_range<op_iterator>(op_begin(), op_end());
1117 inline iterator_range<const_op_iterator> operands() const {
1118 return iterator_range<const_op_iterator>(op_begin(), op_end());
1122 } // end llvm namespace