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 DILexicalBlockFileKind,
76 DITemplateTypeParameterKind,
77 DITemplateValueParameterKind,
83 ConstantAsMetadataKind,
89 Metadata(unsigned ID, StorageType Storage)
90 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
92 ~Metadata() = default;
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.
110 /// Note: this uses an explicit overload instead of default arguments so that
111 /// the nullptr version is easy to call from a debugger.
115 void dump(const Module *M) const;
120 /// Prints definition of \c this.
122 /// If \c M is provided, metadata nodes will be numbered canonically;
123 /// otherwise, pointer addresses are substituted.
124 void print(raw_ostream &OS, const Module *M = nullptr) const;
126 /// \brief Print as operand.
128 /// Prints reference of \c this.
130 /// If \c M is provided, metadata nodes will be numbered canonically;
131 /// otherwise, pointer addresses are substituted.
132 void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
135 #define HANDLE_METADATA(CLASS) class CLASS;
136 #include "llvm/IR/Metadata.def"
138 // Provide specializations of isa so that we don't need definitions of
139 // subclasses to see if the metadata is a subclass.
140 #define HANDLE_METADATA_LEAF(CLASS) \
141 template <> struct isa_impl<CLASS, Metadata> { \
142 static inline bool doit(const Metadata &MD) { \
143 return MD.getMetadataID() == Metadata::CLASS##Kind; \
146 #include "llvm/IR/Metadata.def"
148 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
153 /// \brief Metadata wrapper in the Value hierarchy.
155 /// A member of the \a Value hierarchy to represent a reference to metadata.
156 /// This allows, e.g., instrinsics to have metadata as operands.
158 /// Notably, this is the only thing in either hierarchy that is allowed to
159 /// reference \a LocalAsMetadata.
160 class MetadataAsValue : public Value {
161 friend class ReplaceableMetadataImpl;
162 friend class LLVMContextImpl;
166 MetadataAsValue(Type *Ty, Metadata *MD);
167 ~MetadataAsValue() override;
169 /// \brief Drop use of metadata (during teardown).
170 void dropUse() { MD = nullptr; }
173 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
174 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
175 Metadata *getMetadata() const { return MD; }
177 static bool classof(const Value *V) {
178 return V->getValueID() == MetadataAsValueVal;
182 void handleChangedMetadata(Metadata *MD);
187 /// \brief Shared implementation of use-lists for replaceable metadata.
189 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
190 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
191 /// and \a TempMDNode).
192 class ReplaceableMetadataImpl {
193 friend class MetadataTracking;
196 typedef MetadataTracking::OwnerTy OwnerTy;
199 LLVMContext &Context;
201 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
204 ReplaceableMetadataImpl(LLVMContext &Context)
205 : Context(Context), NextIndex(0) {}
206 ~ReplaceableMetadataImpl() {
207 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
210 LLVMContext &getContext() const { return Context; }
212 /// \brief Replace all uses of this with MD.
214 /// Replace all uses of this with \c MD, which is allowed to be null.
215 void replaceAllUsesWith(Metadata *MD);
217 /// \brief Resolve all uses of this.
219 /// Resolve all uses of this, turning off RAUW permanently. If \c
220 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
222 void resolveAllUses(bool ResolveUsers = true);
225 void addRef(void *Ref, OwnerTy Owner);
226 void dropRef(void *Ref);
227 void moveRef(void *Ref, void *New, const Metadata &MD);
229 static ReplaceableMetadataImpl *get(Metadata &MD);
232 /// \brief Value wrapper in the Metadata hierarchy.
234 /// This is a custom value handle that allows other metadata to refer to
235 /// classes in the Value hierarchy.
237 /// Because of full uniquing support, each value is only wrapped by a single \a
238 /// ValueAsMetadata object, so the lookup maps are far more efficient than
239 /// those using ValueHandleBase.
240 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
241 friend class ReplaceableMetadataImpl;
242 friend class LLVMContextImpl;
246 /// \brief Drop users without RAUW (during teardown).
248 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
252 ValueAsMetadata(unsigned ID, Value *V)
253 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
254 assert(V && "Expected valid value");
256 ~ValueAsMetadata() = default;
259 static ValueAsMetadata *get(Value *V);
260 static ConstantAsMetadata *getConstant(Value *C) {
261 return cast<ConstantAsMetadata>(get(C));
263 static LocalAsMetadata *getLocal(Value *Local) {
264 return cast<LocalAsMetadata>(get(Local));
267 static ValueAsMetadata *getIfExists(Value *V);
268 static ConstantAsMetadata *getConstantIfExists(Value *C) {
269 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
271 static LocalAsMetadata *getLocalIfExists(Value *Local) {
272 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
275 Value *getValue() const { return V; }
276 Type *getType() const { return V->getType(); }
277 LLVMContext &getContext() const { return V->getContext(); }
279 static void handleDeletion(Value *V);
280 static void handleRAUW(Value *From, Value *To);
283 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
285 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
286 /// \a Value gets RAUW'ed and the target already exists, this is used to
287 /// merge the two metadata nodes.
288 void replaceAllUsesWith(Metadata *MD) {
289 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
293 static bool classof(const Metadata *MD) {
294 return MD->getMetadataID() == LocalAsMetadataKind ||
295 MD->getMetadataID() == ConstantAsMetadataKind;
299 class ConstantAsMetadata : public ValueAsMetadata {
300 friend class ValueAsMetadata;
302 ConstantAsMetadata(Constant *C)
303 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
306 static ConstantAsMetadata *get(Constant *C) {
307 return ValueAsMetadata::getConstant(C);
309 static ConstantAsMetadata *getIfExists(Constant *C) {
310 return ValueAsMetadata::getConstantIfExists(C);
313 Constant *getValue() const {
314 return cast<Constant>(ValueAsMetadata::getValue());
317 static bool classof(const Metadata *MD) {
318 return MD->getMetadataID() == ConstantAsMetadataKind;
322 class LocalAsMetadata : public ValueAsMetadata {
323 friend class ValueAsMetadata;
325 LocalAsMetadata(Value *Local)
326 : ValueAsMetadata(LocalAsMetadataKind, Local) {
327 assert(!isa<Constant>(Local) && "Expected local value");
331 static LocalAsMetadata *get(Value *Local) {
332 return ValueAsMetadata::getLocal(Local);
334 static LocalAsMetadata *getIfExists(Value *Local) {
335 return ValueAsMetadata::getLocalIfExists(Local);
338 static bool classof(const Metadata *MD) {
339 return MD->getMetadataID() == LocalAsMetadataKind;
343 /// \brief Transitional API for extracting constants from Metadata.
345 /// This namespace contains transitional functions for metadata that points to
348 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
349 /// operands could refer to any \a Value. There's was a lot of code like this:
353 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
356 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
357 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
358 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
359 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
360 /// requires subtle control flow changes.
362 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
363 /// so that metadata can refer to numbers without traversing a bridge to the \a
364 /// Value hierarchy. In this final state, the code above would look like this:
368 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
371 /// The API in this namespace supports the transition. \a MDInt doesn't exist
372 /// yet, and even once it does, changing each metadata schema to use it is its
373 /// own mini-project. In the meantime this API prevents us from introducing
374 /// complex and bug-prone control flow that will disappear in the end. In
375 /// particular, the above code looks like this:
379 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
382 /// The full set of provided functions includes:
384 /// mdconst::hasa <=> isa
385 /// mdconst::extract <=> cast
386 /// mdconst::extract_or_null <=> cast_or_null
387 /// mdconst::dyn_extract <=> dyn_cast
388 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
390 /// The target of the cast must be a subclass of \a Constant.
394 template <class T> T &make();
395 template <class T, class Result> struct HasDereference {
398 template <size_t N> struct SFINAE {};
400 template <class U, class V>
401 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
402 template <class U, class V> static No &hasDereference(...);
404 static const bool value =
405 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
407 template <class V, class M> struct IsValidPointer {
408 static const bool value = std::is_base_of<Constant, V>::value &&
409 HasDereference<M, const Metadata &>::value;
411 template <class V, class M> struct IsValidReference {
412 static const bool value = std::is_base_of<Constant, V>::value &&
413 std::is_convertible<M, const Metadata &>::value;
415 } // end namespace detail
417 /// \brief Check whether Metadata has a Value.
419 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
421 template <class X, class Y>
422 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
424 assert(MD && "Null pointer sent into hasa");
425 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
426 return isa<X>(V->getValue());
429 template <class X, class Y>
431 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
436 /// \brief Extract a Value from Metadata.
438 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
439 template <class X, class Y>
440 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
442 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
444 template <class X, class Y>
446 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
451 /// \brief Extract a Value from Metadata, allowing null.
453 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
454 /// from \c MD, allowing \c MD to be null.
455 template <class X, class Y>
456 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
457 extract_or_null(Y &&MD) {
458 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
459 return cast<X>(V->getValue());
463 /// \brief Extract a Value from Metadata, if any.
465 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
466 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
467 /// Value it does contain is of the wrong subclass.
468 template <class X, class Y>
469 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
470 dyn_extract(Y &&MD) {
471 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
472 return dyn_cast<X>(V->getValue());
476 /// \brief Extract a Value from Metadata, if any, allowing null.
478 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
479 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
480 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
481 template <class X, class Y>
482 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
483 dyn_extract_or_null(Y &&MD) {
484 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
485 return dyn_cast<X>(V->getValue());
489 } // end namespace mdconst
491 //===----------------------------------------------------------------------===//
492 /// \brief A single uniqued string.
494 /// These are used to efficiently contain a byte sequence for metadata.
495 /// MDString is always unnamed.
496 class MDString : public Metadata {
497 friend class StringMapEntry<MDString>;
499 MDString(const MDString &) = delete;
500 MDString &operator=(MDString &&) = delete;
501 MDString &operator=(const MDString &) = delete;
503 StringMapEntry<MDString> *Entry;
504 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
505 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
508 static MDString *get(LLVMContext &Context, StringRef Str);
509 static MDString *get(LLVMContext &Context, const char *Str) {
510 return get(Context, Str ? StringRef(Str) : StringRef());
513 StringRef getString() const;
515 unsigned getLength() const { return (unsigned)getString().size(); }
517 typedef StringRef::iterator iterator;
519 /// \brief Pointer to the first byte of the string.
520 iterator begin() const { return getString().begin(); }
522 /// \brief Pointer to one byte past the end of the string.
523 iterator end() const { return getString().end(); }
525 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
526 const unsigned char *bytes_end() const { return getString().bytes_end(); }
528 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
529 static bool classof(const Metadata *MD) {
530 return MD->getMetadataID() == MDStringKind;
534 /// \brief A collection of metadata nodes that might be associated with a
535 /// memory access used by the alias-analysis infrastructure.
537 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
539 : TBAA(T), Scope(S), NoAlias(N) {}
541 bool operator==(const AAMDNodes &A) const {
542 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
545 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
547 explicit operator bool() const { return TBAA || Scope || NoAlias; }
549 /// \brief The tag for type-based alias analysis.
552 /// \brief The tag for alias scope specification (used with noalias).
555 /// \brief The tag specifying the noalias scope.
559 // Specialize DenseMapInfo for AAMDNodes.
561 struct DenseMapInfo<AAMDNodes> {
562 static inline AAMDNodes getEmptyKey() {
563 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
565 static inline AAMDNodes getTombstoneKey() {
566 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
568 static unsigned getHashValue(const AAMDNodes &Val) {
569 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
570 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
571 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
573 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
578 /// \brief Tracking metadata reference owned by Metadata.
580 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
581 /// of \a Metadata, which has the option of registering itself for callbacks to
582 /// re-unique itself.
584 /// In particular, this is used by \a MDNode.
586 MDOperand(MDOperand &&) = delete;
587 MDOperand(const MDOperand &) = delete;
588 MDOperand &operator=(MDOperand &&) = delete;
589 MDOperand &operator=(const MDOperand &) = delete;
594 MDOperand() : MD(nullptr) {}
595 ~MDOperand() { untrack(); }
597 Metadata *get() const { return MD; }
598 operator Metadata *() const { return get(); }
599 Metadata *operator->() const { return get(); }
600 Metadata &operator*() const { return *get(); }
606 void reset(Metadata *MD, Metadata *Owner) {
613 void track(Metadata *Owner) {
616 MetadataTracking::track(this, *MD, *Owner);
618 MetadataTracking::track(MD);
622 assert(static_cast<void *>(this) == &MD && "Expected same address");
624 MetadataTracking::untrack(MD);
628 template <> struct simplify_type<MDOperand> {
629 typedef Metadata *SimpleType;
630 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
633 template <> struct simplify_type<const MDOperand> {
634 typedef Metadata *SimpleType;
635 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
638 /// \brief Pointer to the context, with optional RAUW support.
640 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
641 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
642 class ContextAndReplaceableUses {
643 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
645 ContextAndReplaceableUses() = delete;
646 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
647 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
648 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
649 ContextAndReplaceableUses &
650 operator=(const ContextAndReplaceableUses &) = delete;
653 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
654 ContextAndReplaceableUses(
655 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
656 : Ptr(ReplaceableUses.release()) {
657 assert(getReplaceableUses() && "Expected non-null replaceable uses");
659 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
661 operator LLVMContext &() { return getContext(); }
663 /// \brief Whether this contains RAUW support.
664 bool hasReplaceableUses() const {
665 return Ptr.is<ReplaceableMetadataImpl *>();
667 LLVMContext &getContext() const {
668 if (hasReplaceableUses())
669 return getReplaceableUses()->getContext();
670 return *Ptr.get<LLVMContext *>();
672 ReplaceableMetadataImpl *getReplaceableUses() const {
673 if (hasReplaceableUses())
674 return Ptr.get<ReplaceableMetadataImpl *>();
678 /// \brief Assign RAUW support to this.
680 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
683 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
684 assert(ReplaceableUses && "Expected non-null replaceable uses");
685 assert(&ReplaceableUses->getContext() == &getContext() &&
686 "Expected same context");
687 delete getReplaceableUses();
688 Ptr = ReplaceableUses.release();
691 /// \brief Drop RAUW support.
693 /// Cede ownership of RAUW support, returning it.
694 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
695 assert(hasReplaceableUses() && "Expected to own replaceable uses");
696 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
697 getReplaceableUses());
698 Ptr = &ReplaceableUses->getContext();
699 return ReplaceableUses;
703 struct TempMDNodeDeleter {
704 inline void operator()(MDNode *Node) const;
707 #define HANDLE_MDNODE_LEAF(CLASS) \
708 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
709 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
710 #include "llvm/IR/Metadata.def"
712 /// \brief Metadata node.
714 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
715 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
716 /// until forward references are known. The basic metadata node is an \a
719 /// There is limited support for RAUW at construction time. At construction
720 /// time, if any operand is a temporary node (or an unresolved uniqued node,
721 /// which indicates a transitive temporary operand), the node itself will be
722 /// unresolved. As soon as all operands become resolved, it will drop RAUW
723 /// support permanently.
725 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
726 /// to be called on some member of the cycle once all temporary nodes have been
728 class MDNode : public Metadata {
729 friend class ReplaceableMetadataImpl;
730 friend class LLVMContextImpl;
732 MDNode(const MDNode &) = delete;
733 void operator=(const MDNode &) = delete;
734 void *operator new(size_t) = delete;
736 unsigned NumOperands;
737 unsigned NumUnresolved;
740 ContextAndReplaceableUses Context;
742 void *operator new(size_t Size, unsigned NumOps);
743 void operator delete(void *Mem);
745 /// \brief Required by std, but never called.
746 void operator delete(void *, unsigned) {
747 llvm_unreachable("Constructor throws?");
750 /// \brief Required by std, but never called.
751 void operator delete(void *, unsigned, bool) {
752 llvm_unreachable("Constructor throws?");
755 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
756 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
759 void dropAllReferences();
761 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
762 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
764 typedef iterator_range<MDOperand *> mutable_op_range;
765 mutable_op_range mutable_operands() {
766 return mutable_op_range(mutable_begin(), mutable_end());
770 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
771 static inline MDTuple *getIfExists(LLVMContext &Context,
772 ArrayRef<Metadata *> MDs);
773 static inline MDTuple *getDistinct(LLVMContext &Context,
774 ArrayRef<Metadata *> MDs);
775 static inline TempMDTuple getTemporary(LLVMContext &Context,
776 ArrayRef<Metadata *> MDs);
778 /// \brief Create a (temporary) clone of this.
779 TempMDNode clone() const;
781 /// \brief Deallocate a node created by getTemporary.
783 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
784 /// references will be reset.
785 static void deleteTemporary(MDNode *N);
787 LLVMContext &getContext() const { return Context.getContext(); }
789 /// \brief Replace a specific operand.
790 void replaceOperandWith(unsigned I, Metadata *New);
792 /// \brief Check if node is fully resolved.
794 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
795 /// this always returns \c true.
797 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
798 /// support (because all operands are resolved).
800 /// As forward declarations are resolved, their containers should get
801 /// resolved automatically. However, if this (or one of its operands) is
802 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
803 bool isResolved() const { return !Context.hasReplaceableUses(); }
805 bool isUniqued() const { return Storage == Uniqued; }
806 bool isDistinct() const { return Storage == Distinct; }
807 bool isTemporary() const { return Storage == Temporary; }
809 /// \brief RAUW a temporary.
811 /// \pre \a isTemporary() must be \c true.
812 void replaceAllUsesWith(Metadata *MD) {
813 assert(isTemporary() && "Expected temporary node");
814 assert(!isResolved() && "Expected RAUW support");
815 Context.getReplaceableUses()->replaceAllUsesWith(MD);
818 /// \brief Resolve cycles.
820 /// Once all forward declarations have been resolved, force cycles to be
823 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
824 void resolveCycles();
826 /// \brief Replace a temporary node with a permanent one.
828 /// Try to create a uniqued version of \c N -- in place, if possible -- and
829 /// return it. If \c N cannot be uniqued, return a distinct node instead.
831 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
832 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
833 return cast<T>(N.release()->replaceWithPermanentImpl());
836 /// \brief Replace a temporary node with a uniqued one.
838 /// Create a uniqued version of \c N -- in place, if possible -- and return
839 /// it. Takes ownership of the temporary node.
841 /// \pre N does not self-reference.
843 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
844 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
845 return cast<T>(N.release()->replaceWithUniquedImpl());
848 /// \brief Replace a temporary node with a distinct one.
850 /// Create a distinct version of \c N -- in place, if possible -- and return
851 /// it. Takes ownership of the temporary node.
853 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
854 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
855 return cast<T>(N.release()->replaceWithDistinctImpl());
859 MDNode *replaceWithPermanentImpl();
860 MDNode *replaceWithUniquedImpl();
861 MDNode *replaceWithDistinctImpl();
864 /// \brief Set an operand.
866 /// Sets the operand directly, without worrying about uniquing.
867 void setOperand(unsigned I, Metadata *New);
869 void storeDistinctInContext();
870 template <class T, class StoreT>
871 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
874 void handleChangedOperand(void *Ref, Metadata *New);
877 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
878 void decrementUnresolvedOperandCount();
879 unsigned countUnresolvedOperands();
881 /// \brief Mutate this to be "uniqued".
883 /// Mutate this so that \a isUniqued().
884 /// \pre \a isTemporary().
885 /// \pre already added to uniquing set.
888 /// \brief Mutate this to be "distinct".
890 /// Mutate this so that \a isDistinct().
891 /// \pre \a isTemporary().
894 void deleteAsSubclass();
896 void eraseFromStore();
898 template <class NodeTy> struct HasCachedHash;
899 template <class NodeTy>
900 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
901 N->recalculateHash();
903 template <class NodeTy>
904 static void dispatchRecalculateHash(NodeTy *N, std::false_type) {}
905 template <class NodeTy>
906 static void dispatchResetHash(NodeTy *N, std::true_type) {
909 template <class NodeTy>
910 static void dispatchResetHash(NodeTy *N, std::false_type) {}
913 typedef const MDOperand *op_iterator;
914 typedef iterator_range<op_iterator> op_range;
916 op_iterator op_begin() const {
917 return const_cast<MDNode *>(this)->mutable_begin();
919 op_iterator op_end() const {
920 return const_cast<MDNode *>(this)->mutable_end();
922 op_range operands() const { return op_range(op_begin(), op_end()); }
924 const MDOperand &getOperand(unsigned I) const {
925 assert(I < NumOperands && "Out of range");
926 return op_begin()[I];
929 /// \brief Return number of MDNode operands.
930 unsigned getNumOperands() const { return NumOperands; }
932 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
933 static bool classof(const Metadata *MD) {
934 switch (MD->getMetadataID()) {
937 #define HANDLE_MDNODE_LEAF(CLASS) \
940 #include "llvm/IR/Metadata.def"
944 /// \brief Check whether MDNode is a vtable access.
945 bool isTBAAVtableAccess() const;
947 /// \brief Methods for metadata merging.
948 static MDNode *concatenate(MDNode *A, MDNode *B);
949 static MDNode *intersect(MDNode *A, MDNode *B);
950 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
951 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
952 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
953 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
956 /// \brief Tuple of metadata.
958 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
959 /// default based on their operands.
960 class MDTuple : public MDNode {
961 friend class LLVMContextImpl;
964 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
965 ArrayRef<Metadata *> Vals)
966 : MDNode(C, MDTupleKind, Storage, Vals) {
969 ~MDTuple() { dropAllReferences(); }
971 void setHash(unsigned Hash) { SubclassData32 = Hash; }
972 void recalculateHash();
974 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
975 StorageType Storage, bool ShouldCreate = true);
977 TempMDTuple cloneImpl() const {
978 return getTemporary(getContext(),
979 SmallVector<Metadata *, 4>(op_begin(), op_end()));
983 /// \brief Get the hash, if any.
984 unsigned getHash() const { return SubclassData32; }
986 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
987 return getImpl(Context, MDs, Uniqued);
989 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
990 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
993 /// \brief Return a distinct node.
995 /// Return a distinct node -- i.e., a node that is not uniqued.
996 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
997 return getImpl(Context, MDs, Distinct);
1000 /// \brief Return a temporary node.
1002 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1003 /// not uniqued, may be RAUW'd, and must be manually deleted with
1004 /// deleteTemporary.
1005 static TempMDTuple getTemporary(LLVMContext &Context,
1006 ArrayRef<Metadata *> MDs) {
1007 return TempMDTuple(getImpl(Context, MDs, Temporary));
1010 /// \brief Return a (temporary) clone of this.
1011 TempMDTuple clone() const { return cloneImpl(); }
1013 static bool classof(const Metadata *MD) {
1014 return MD->getMetadataID() == MDTupleKind;
1018 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1019 return MDTuple::get(Context, MDs);
1021 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1022 return MDTuple::getIfExists(Context, MDs);
1024 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1025 return MDTuple::getDistinct(Context, MDs);
1027 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1028 ArrayRef<Metadata *> MDs) {
1029 return MDTuple::getTemporary(Context, MDs);
1032 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1033 MDNode::deleteTemporary(Node);
1036 /// \brief Typed iterator through MDNode operands.
1038 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1039 /// particular Metadata subclass.
1041 class TypedMDOperandIterator
1042 : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
1043 MDNode::op_iterator I = nullptr;
1046 TypedMDOperandIterator() = default;
1047 explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1048 T *operator*() const { return cast_or_null<T>(*I); }
1049 TypedMDOperandIterator &operator++() {
1053 TypedMDOperandIterator operator++(int) {
1054 TypedMDOperandIterator Temp(*this);
1058 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1059 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1062 /// \brief Typed, array-like tuple of metadata.
1064 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1065 /// particular type of metadata.
1066 template <class T> class MDTupleTypedArrayWrapper {
1067 const MDTuple *N = nullptr;
1070 MDTupleTypedArrayWrapper() = default;
1071 MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1074 MDTupleTypedArrayWrapper(
1075 const MDTupleTypedArrayWrapper<U> &Other,
1076 typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
1081 explicit MDTupleTypedArrayWrapper(
1082 const MDTupleTypedArrayWrapper<U> &Other,
1083 typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
1087 explicit operator bool() const { return get(); }
1088 explicit operator MDTuple *() const { return get(); }
1090 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1091 MDTuple *operator->() const { return get(); }
1092 MDTuple &operator*() const { return *get(); }
1094 // FIXME: Fix callers and remove condition on N.
1095 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1096 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1098 // FIXME: Fix callers and remove condition on N.
1099 typedef TypedMDOperandIterator<T> iterator;
1100 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1101 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1104 #define HANDLE_METADATA(CLASS) \
1105 typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
1106 #include "llvm/IR/Metadata.def"
1108 //===----------------------------------------------------------------------===//
1109 /// \brief A tuple of MDNodes.
1111 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1112 /// to modules, have names, and contain lists of MDNodes.
1114 /// TODO: Inherit from Metadata.
1115 class NamedMDNode : public ilist_node<NamedMDNode> {
1116 friend class SymbolTableListTraits<NamedMDNode, Module>;
1117 friend struct ilist_traits<NamedMDNode>;
1118 friend class LLVMContextImpl;
1119 friend class Module;
1120 NamedMDNode(const NamedMDNode &) = delete;
1124 void *Operands; // SmallVector<TrackingMDRef, 4>
1126 void setParent(Module *M) { Parent = M; }
1128 explicit NamedMDNode(const Twine &N);
1130 template<class T1, class T2>
1131 class op_iterator_impl :
1132 public std::iterator<std::bidirectional_iterator_tag, T2> {
1133 const NamedMDNode *Node;
1135 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1137 friend class NamedMDNode;
1140 op_iterator_impl() : Node(nullptr), Idx(0) { }
1142 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1143 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1144 op_iterator_impl &operator++() {
1148 op_iterator_impl operator++(int) {
1149 op_iterator_impl tmp(*this);
1153 op_iterator_impl &operator--() {
1157 op_iterator_impl operator--(int) {
1158 op_iterator_impl tmp(*this);
1163 T1 operator*() const { return Node->getOperand(Idx); }
1167 /// \brief Drop all references and remove the node from parent module.
1168 void eraseFromParent();
1170 /// \brief Remove all uses and clear node vector.
1171 void dropAllReferences();
1175 /// \brief Get the module that holds this named metadata collection.
1176 inline Module *getParent() { return Parent; }
1177 inline const Module *getParent() const { return Parent; }
1179 MDNode *getOperand(unsigned i) const;
1180 unsigned getNumOperands() const;
1181 void addOperand(MDNode *M);
1182 void setOperand(unsigned I, MDNode *New);
1183 StringRef getName() const;
1184 void print(raw_ostream &ROS) const;
1187 // ---------------------------------------------------------------------------
1188 // Operand Iterator interface...
1190 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1191 op_iterator op_begin() { return op_iterator(this, 0); }
1192 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1194 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1195 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1196 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1198 inline iterator_range<op_iterator> operands() {
1199 return iterator_range<op_iterator>(op_begin(), op_end());
1201 inline iterator_range<const_op_iterator> operands() const {
1202 return iterator_range<const_op_iterator>(op_begin(), op_end());
1206 } // end llvm namespace