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>
33 class ModuleSlotTracker;
35 template<typename ValueSubClass, typename ItemParentClass>
36 class SymbolTableListTraits;
38 enum LLVMConstants : uint32_t {
39 DEBUG_METADATA_VERSION = 3 // Current debug info version number.
42 /// \brief Root of the metadata hierarchy.
44 /// This is a root class for typeless data in the IR.
46 friend class ReplaceableMetadataImpl;
49 const unsigned char SubclassID;
52 /// \brief Active type of storage.
53 enum StorageType { Uniqued, Distinct, Temporary };
55 /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
57 // TODO: expose remaining bits to subclasses.
59 unsigned short SubclassData16;
60 unsigned SubclassData32;
77 DILexicalBlockFileKind,
79 DITemplateTypeParameterKind,
80 DITemplateValueParameterKind,
86 ConstantAsMetadataKind,
92 Metadata(unsigned ID, StorageType Storage)
93 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
95 ~Metadata() = default;
97 /// \brief Default handling of a changed operand, which asserts.
99 /// If subclasses pass themselves in as owners to a tracking node reference,
100 /// they must provide an implementation of this method.
101 void handleChangedOperand(void *, Metadata *) {
102 llvm_unreachable("Unimplemented in Metadata subclass");
106 unsigned getMetadataID() const { return SubclassID; }
108 /// \brief User-friendly dump.
110 /// If \c M is provided, metadata nodes will be numbered canonically;
111 /// otherwise, pointer addresses are substituted.
113 /// Note: this uses an explicit overload instead of default arguments so that
114 /// the nullptr version is easy to call from a debugger.
118 void dump(const Module *M) const;
123 /// Prints definition of \c this.
125 /// If \c M is provided, metadata nodes will be numbered canonically;
126 /// otherwise, pointer addresses are substituted.
128 void print(raw_ostream &OS, const Module *M = nullptr) const;
129 void print(raw_ostream &OS, ModuleSlotTracker &MST,
130 const Module *M = nullptr) const;
133 /// \brief Print as operand.
135 /// Prints reference of \c this.
137 /// If \c M is provided, metadata nodes will be numbered canonically;
138 /// otherwise, pointer addresses are substituted.
140 void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
141 void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
142 const Module *M = nullptr) const;
146 #define HANDLE_METADATA(CLASS) class CLASS;
147 #include "llvm/IR/Metadata.def"
149 // Provide specializations of isa so that we don't need definitions of
150 // subclasses to see if the metadata is a subclass.
151 #define HANDLE_METADATA_LEAF(CLASS) \
152 template <> struct isa_impl<CLASS, Metadata> { \
153 static inline bool doit(const Metadata &MD) { \
154 return MD.getMetadataID() == Metadata::CLASS##Kind; \
157 #include "llvm/IR/Metadata.def"
159 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
164 /// \brief Metadata wrapper in the Value hierarchy.
166 /// A member of the \a Value hierarchy to represent a reference to metadata.
167 /// This allows, e.g., instrinsics to have metadata as operands.
169 /// Notably, this is the only thing in either hierarchy that is allowed to
170 /// reference \a LocalAsMetadata.
171 class MetadataAsValue : public Value {
172 friend class ReplaceableMetadataImpl;
173 friend class LLVMContextImpl;
177 MetadataAsValue(Type *Ty, Metadata *MD);
178 ~MetadataAsValue() override;
180 /// \brief Drop use of metadata (during teardown).
181 void dropUse() { MD = nullptr; }
184 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
185 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
186 Metadata *getMetadata() const { return MD; }
188 static bool classof(const Value *V) {
189 return V->getValueID() == MetadataAsValueVal;
193 void handleChangedMetadata(Metadata *MD);
198 /// \brief Shared implementation of use-lists for replaceable metadata.
200 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
201 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
202 /// and \a TempMDNode).
203 class ReplaceableMetadataImpl {
204 friend class MetadataTracking;
207 typedef MetadataTracking::OwnerTy OwnerTy;
210 LLVMContext &Context;
212 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
215 ReplaceableMetadataImpl(LLVMContext &Context)
216 : Context(Context), NextIndex(0) {}
217 ~ReplaceableMetadataImpl() {
218 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
221 LLVMContext &getContext() const { return Context; }
223 /// \brief Replace all uses of this with MD.
225 /// Replace all uses of this with \c MD, which is allowed to be null.
226 void replaceAllUsesWith(Metadata *MD);
228 /// \brief Resolve all uses of this.
230 /// Resolve all uses of this, turning off RAUW permanently. If \c
231 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
233 void resolveAllUses(bool ResolveUsers = true);
236 void addRef(void *Ref, OwnerTy Owner);
237 void dropRef(void *Ref);
238 void moveRef(void *Ref, void *New, const Metadata &MD);
240 static ReplaceableMetadataImpl *get(Metadata &MD);
243 /// \brief Value wrapper in the Metadata hierarchy.
245 /// This is a custom value handle that allows other metadata to refer to
246 /// classes in the Value hierarchy.
248 /// Because of full uniquing support, each value is only wrapped by a single \a
249 /// ValueAsMetadata object, so the lookup maps are far more efficient than
250 /// those using ValueHandleBase.
251 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
252 friend class ReplaceableMetadataImpl;
253 friend class LLVMContextImpl;
257 /// \brief Drop users without RAUW (during teardown).
259 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
263 ValueAsMetadata(unsigned ID, Value *V)
264 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
265 assert(V && "Expected valid value");
267 ~ValueAsMetadata() = default;
270 static ValueAsMetadata *get(Value *V);
271 static ConstantAsMetadata *getConstant(Value *C) {
272 return cast<ConstantAsMetadata>(get(C));
274 static LocalAsMetadata *getLocal(Value *Local) {
275 return cast<LocalAsMetadata>(get(Local));
278 static ValueAsMetadata *getIfExists(Value *V);
279 static ConstantAsMetadata *getConstantIfExists(Value *C) {
280 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
282 static LocalAsMetadata *getLocalIfExists(Value *Local) {
283 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
286 Value *getValue() const { return V; }
287 Type *getType() const { return V->getType(); }
288 LLVMContext &getContext() const { return V->getContext(); }
290 static void handleDeletion(Value *V);
291 static void handleRAUW(Value *From, Value *To);
294 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
296 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
297 /// \a Value gets RAUW'ed and the target already exists, this is used to
298 /// merge the two metadata nodes.
299 void replaceAllUsesWith(Metadata *MD) {
300 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
304 static bool classof(const Metadata *MD) {
305 return MD->getMetadataID() == LocalAsMetadataKind ||
306 MD->getMetadataID() == ConstantAsMetadataKind;
310 class ConstantAsMetadata : public ValueAsMetadata {
311 friend class ValueAsMetadata;
313 ConstantAsMetadata(Constant *C)
314 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
317 static ConstantAsMetadata *get(Constant *C) {
318 return ValueAsMetadata::getConstant(C);
320 static ConstantAsMetadata *getIfExists(Constant *C) {
321 return ValueAsMetadata::getConstantIfExists(C);
324 Constant *getValue() const {
325 return cast<Constant>(ValueAsMetadata::getValue());
328 static bool classof(const Metadata *MD) {
329 return MD->getMetadataID() == ConstantAsMetadataKind;
333 class LocalAsMetadata : public ValueAsMetadata {
334 friend class ValueAsMetadata;
336 LocalAsMetadata(Value *Local)
337 : ValueAsMetadata(LocalAsMetadataKind, Local) {
338 assert(!isa<Constant>(Local) && "Expected local value");
342 static LocalAsMetadata *get(Value *Local) {
343 return ValueAsMetadata::getLocal(Local);
345 static LocalAsMetadata *getIfExists(Value *Local) {
346 return ValueAsMetadata::getLocalIfExists(Local);
349 static bool classof(const Metadata *MD) {
350 return MD->getMetadataID() == LocalAsMetadataKind;
354 /// \brief Transitional API for extracting constants from Metadata.
356 /// This namespace contains transitional functions for metadata that points to
359 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
360 /// operands could refer to any \a Value. There's was a lot of code like this:
364 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
367 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
368 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
369 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
370 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
371 /// requires subtle control flow changes.
373 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
374 /// so that metadata can refer to numbers without traversing a bridge to the \a
375 /// Value hierarchy. In this final state, the code above would look like this:
379 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
382 /// The API in this namespace supports the transition. \a MDInt doesn't exist
383 /// yet, and even once it does, changing each metadata schema to use it is its
384 /// own mini-project. In the meantime this API prevents us from introducing
385 /// complex and bug-prone control flow that will disappear in the end. In
386 /// particular, the above code looks like this:
390 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
393 /// The full set of provided functions includes:
395 /// mdconst::hasa <=> isa
396 /// mdconst::extract <=> cast
397 /// mdconst::extract_or_null <=> cast_or_null
398 /// mdconst::dyn_extract <=> dyn_cast
399 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
401 /// The target of the cast must be a subclass of \a Constant.
405 template <class T> T &make();
406 template <class T, class Result> struct HasDereference {
409 template <size_t N> struct SFINAE {};
411 template <class U, class V>
412 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
413 template <class U, class V> static No &hasDereference(...);
415 static const bool value =
416 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
418 template <class V, class M> struct IsValidPointer {
419 static const bool value = std::is_base_of<Constant, V>::value &&
420 HasDereference<M, const Metadata &>::value;
422 template <class V, class M> struct IsValidReference {
423 static const bool value = std::is_base_of<Constant, V>::value &&
424 std::is_convertible<M, const Metadata &>::value;
426 } // end namespace detail
428 /// \brief Check whether Metadata has a Value.
430 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
432 template <class X, class Y>
433 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
435 assert(MD && "Null pointer sent into hasa");
436 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
437 return isa<X>(V->getValue());
440 template <class X, class Y>
442 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
447 /// \brief Extract a Value from Metadata.
449 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
450 template <class X, class Y>
451 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
453 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
455 template <class X, class Y>
457 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
462 /// \brief Extract a Value from Metadata, allowing null.
464 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
465 /// from \c MD, allowing \c MD to be null.
466 template <class X, class Y>
467 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
468 extract_or_null(Y &&MD) {
469 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
470 return cast<X>(V->getValue());
474 /// \brief Extract a Value from Metadata, if any.
476 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
477 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
478 /// Value it does contain is of the wrong subclass.
479 template <class X, class Y>
480 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
481 dyn_extract(Y &&MD) {
482 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
483 return dyn_cast<X>(V->getValue());
487 /// \brief Extract a Value from Metadata, if any, allowing null.
489 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
490 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
491 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
492 template <class X, class Y>
493 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
494 dyn_extract_or_null(Y &&MD) {
495 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
496 return dyn_cast<X>(V->getValue());
500 } // end namespace mdconst
502 //===----------------------------------------------------------------------===//
503 /// \brief A single uniqued string.
505 /// These are used to efficiently contain a byte sequence for metadata.
506 /// MDString is always unnamed.
507 class MDString : public Metadata {
508 friend class StringMapEntry<MDString>;
510 MDString(const MDString &) = delete;
511 MDString &operator=(MDString &&) = delete;
512 MDString &operator=(const MDString &) = delete;
514 StringMapEntry<MDString> *Entry;
515 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
516 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
519 static MDString *get(LLVMContext &Context, StringRef Str);
520 static MDString *get(LLVMContext &Context, const char *Str) {
521 return get(Context, Str ? StringRef(Str) : StringRef());
524 StringRef getString() const;
526 unsigned getLength() const { return (unsigned)getString().size(); }
528 typedef StringRef::iterator iterator;
530 /// \brief Pointer to the first byte of the string.
531 iterator begin() const { return getString().begin(); }
533 /// \brief Pointer to one byte past the end of the string.
534 iterator end() const { return getString().end(); }
536 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
537 const unsigned char *bytes_end() const { return getString().bytes_end(); }
539 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
540 static bool classof(const Metadata *MD) {
541 return MD->getMetadataID() == MDStringKind;
545 /// \brief A collection of metadata nodes that might be associated with a
546 /// memory access used by the alias-analysis infrastructure.
548 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
550 : TBAA(T), Scope(S), NoAlias(N) {}
552 bool operator==(const AAMDNodes &A) const {
553 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
556 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
558 explicit operator bool() const { return TBAA || Scope || NoAlias; }
560 /// \brief The tag for type-based alias analysis.
563 /// \brief The tag for alias scope specification (used with noalias).
566 /// \brief The tag specifying the noalias scope.
570 // Specialize DenseMapInfo for AAMDNodes.
572 struct DenseMapInfo<AAMDNodes> {
573 static inline AAMDNodes getEmptyKey() {
574 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
576 static inline AAMDNodes getTombstoneKey() {
577 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
579 static unsigned getHashValue(const AAMDNodes &Val) {
580 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
581 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
582 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
584 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
589 /// \brief Tracking metadata reference owned by Metadata.
591 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
592 /// of \a Metadata, which has the option of registering itself for callbacks to
593 /// re-unique itself.
595 /// In particular, this is used by \a MDNode.
597 MDOperand(MDOperand &&) = delete;
598 MDOperand(const MDOperand &) = delete;
599 MDOperand &operator=(MDOperand &&) = delete;
600 MDOperand &operator=(const MDOperand &) = delete;
605 MDOperand() : MD(nullptr) {}
606 ~MDOperand() { untrack(); }
608 Metadata *get() const { return MD; }
609 operator Metadata *() const { return get(); }
610 Metadata *operator->() const { return get(); }
611 Metadata &operator*() const { return *get(); }
617 void reset(Metadata *MD, Metadata *Owner) {
624 void track(Metadata *Owner) {
627 MetadataTracking::track(this, *MD, *Owner);
629 MetadataTracking::track(MD);
633 assert(static_cast<void *>(this) == &MD && "Expected same address");
635 MetadataTracking::untrack(MD);
639 template <> struct simplify_type<MDOperand> {
640 typedef Metadata *SimpleType;
641 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
644 template <> struct simplify_type<const MDOperand> {
645 typedef Metadata *SimpleType;
646 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
649 /// \brief Pointer to the context, with optional RAUW support.
651 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
652 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
653 class ContextAndReplaceableUses {
654 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
656 ContextAndReplaceableUses() = delete;
657 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
658 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
659 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
660 ContextAndReplaceableUses &
661 operator=(const ContextAndReplaceableUses &) = delete;
664 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
665 ContextAndReplaceableUses(
666 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
667 : Ptr(ReplaceableUses.release()) {
668 assert(getReplaceableUses() && "Expected non-null replaceable uses");
670 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
672 operator LLVMContext &() { return getContext(); }
674 /// \brief Whether this contains RAUW support.
675 bool hasReplaceableUses() const {
676 return Ptr.is<ReplaceableMetadataImpl *>();
678 LLVMContext &getContext() const {
679 if (hasReplaceableUses())
680 return getReplaceableUses()->getContext();
681 return *Ptr.get<LLVMContext *>();
683 ReplaceableMetadataImpl *getReplaceableUses() const {
684 if (hasReplaceableUses())
685 return Ptr.get<ReplaceableMetadataImpl *>();
689 /// \brief Assign RAUW support to this.
691 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
694 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
695 assert(ReplaceableUses && "Expected non-null replaceable uses");
696 assert(&ReplaceableUses->getContext() == &getContext() &&
697 "Expected same context");
698 delete getReplaceableUses();
699 Ptr = ReplaceableUses.release();
702 /// \brief Drop RAUW support.
704 /// Cede ownership of RAUW support, returning it.
705 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
706 assert(hasReplaceableUses() && "Expected to own replaceable uses");
707 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
708 getReplaceableUses());
709 Ptr = &ReplaceableUses->getContext();
710 return ReplaceableUses;
714 struct TempMDNodeDeleter {
715 inline void operator()(MDNode *Node) const;
718 #define HANDLE_MDNODE_LEAF(CLASS) \
719 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
720 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
721 #include "llvm/IR/Metadata.def"
723 /// \brief Metadata node.
725 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
726 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
727 /// until forward references are known. The basic metadata node is an \a
730 /// There is limited support for RAUW at construction time. At construction
731 /// time, if any operand is a temporary node (or an unresolved uniqued node,
732 /// which indicates a transitive temporary operand), the node itself will be
733 /// unresolved. As soon as all operands become resolved, it will drop RAUW
734 /// support permanently.
736 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
737 /// to be called on some member of the cycle once all temporary nodes have been
739 class MDNode : public Metadata {
740 friend class ReplaceableMetadataImpl;
741 friend class LLVMContextImpl;
743 MDNode(const MDNode &) = delete;
744 void operator=(const MDNode &) = delete;
745 void *operator new(size_t) = delete;
747 unsigned NumOperands;
748 unsigned NumUnresolved;
751 ContextAndReplaceableUses Context;
753 void *operator new(size_t Size, unsigned NumOps);
754 void operator delete(void *Mem);
756 /// \brief Required by std, but never called.
757 void operator delete(void *, unsigned) {
758 llvm_unreachable("Constructor throws?");
761 /// \brief Required by std, but never called.
762 void operator delete(void *, unsigned, bool) {
763 llvm_unreachable("Constructor throws?");
766 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
767 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
770 void dropAllReferences();
772 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
773 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
775 typedef iterator_range<MDOperand *> mutable_op_range;
776 mutable_op_range mutable_operands() {
777 return mutable_op_range(mutable_begin(), mutable_end());
781 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
782 static inline MDTuple *getIfExists(LLVMContext &Context,
783 ArrayRef<Metadata *> MDs);
784 static inline MDTuple *getDistinct(LLVMContext &Context,
785 ArrayRef<Metadata *> MDs);
786 static inline TempMDTuple getTemporary(LLVMContext &Context,
787 ArrayRef<Metadata *> MDs);
789 /// \brief Create a (temporary) clone of this.
790 TempMDNode clone() const;
792 /// \brief Deallocate a node created by getTemporary.
794 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
795 /// references will be reset.
796 static void deleteTemporary(MDNode *N);
798 LLVMContext &getContext() const { return Context.getContext(); }
800 /// \brief Replace a specific operand.
801 void replaceOperandWith(unsigned I, Metadata *New);
803 /// \brief Check if node is fully resolved.
805 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
806 /// this always returns \c true.
808 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
809 /// support (because all operands are resolved).
811 /// As forward declarations are resolved, their containers should get
812 /// resolved automatically. However, if this (or one of its operands) is
813 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
814 bool isResolved() const { return !Context.hasReplaceableUses(); }
816 bool isUniqued() const { return Storage == Uniqued; }
817 bool isDistinct() const { return Storage == Distinct; }
818 bool isTemporary() const { return Storage == Temporary; }
820 /// \brief RAUW a temporary.
822 /// \pre \a isTemporary() must be \c true.
823 void replaceAllUsesWith(Metadata *MD) {
824 assert(isTemporary() && "Expected temporary node");
825 assert(!isResolved() && "Expected RAUW support");
826 Context.getReplaceableUses()->replaceAllUsesWith(MD);
829 /// \brief Resolve cycles.
831 /// Once all forward declarations have been resolved, force cycles to be
834 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
835 void resolveCycles();
837 /// \brief Replace a temporary node with a permanent one.
839 /// Try to create a uniqued version of \c N -- in place, if possible -- and
840 /// return it. If \c N cannot be uniqued, return a distinct node instead.
842 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
843 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
844 return cast<T>(N.release()->replaceWithPermanentImpl());
847 /// \brief Replace a temporary node with a uniqued one.
849 /// Create a uniqued version of \c N -- in place, if possible -- and return
850 /// it. Takes ownership of the temporary node.
852 /// \pre N does not self-reference.
854 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
855 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
856 return cast<T>(N.release()->replaceWithUniquedImpl());
859 /// \brief Replace a temporary node with a distinct one.
861 /// Create a distinct version of \c N -- in place, if possible -- and return
862 /// it. Takes ownership of the temporary node.
864 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
865 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
866 return cast<T>(N.release()->replaceWithDistinctImpl());
870 MDNode *replaceWithPermanentImpl();
871 MDNode *replaceWithUniquedImpl();
872 MDNode *replaceWithDistinctImpl();
875 /// \brief Set an operand.
877 /// Sets the operand directly, without worrying about uniquing.
878 void setOperand(unsigned I, Metadata *New);
880 void storeDistinctInContext();
881 template <class T, class StoreT>
882 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
885 void handleChangedOperand(void *Ref, Metadata *New);
888 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
889 void decrementUnresolvedOperandCount();
890 unsigned countUnresolvedOperands();
892 /// \brief Mutate this to be "uniqued".
894 /// Mutate this so that \a isUniqued().
895 /// \pre \a isTemporary().
896 /// \pre already added to uniquing set.
899 /// \brief Mutate this to be "distinct".
901 /// Mutate this so that \a isDistinct().
902 /// \pre \a isTemporary().
905 void deleteAsSubclass();
907 void eraseFromStore();
909 template <class NodeTy> struct HasCachedHash;
910 template <class NodeTy>
911 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
912 N->recalculateHash();
914 template <class NodeTy>
915 static void dispatchRecalculateHash(NodeTy *N, std::false_type) {}
916 template <class NodeTy>
917 static void dispatchResetHash(NodeTy *N, std::true_type) {
920 template <class NodeTy>
921 static void dispatchResetHash(NodeTy *N, std::false_type) {}
924 typedef const MDOperand *op_iterator;
925 typedef iterator_range<op_iterator> op_range;
927 op_iterator op_begin() const {
928 return const_cast<MDNode *>(this)->mutable_begin();
930 op_iterator op_end() const {
931 return const_cast<MDNode *>(this)->mutable_end();
933 op_range operands() const { return op_range(op_begin(), op_end()); }
935 const MDOperand &getOperand(unsigned I) const {
936 assert(I < NumOperands && "Out of range");
937 return op_begin()[I];
940 /// \brief Return number of MDNode operands.
941 unsigned getNumOperands() const { return NumOperands; }
943 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
944 static bool classof(const Metadata *MD) {
945 switch (MD->getMetadataID()) {
948 #define HANDLE_MDNODE_LEAF(CLASS) \
951 #include "llvm/IR/Metadata.def"
955 /// \brief Check whether MDNode is a vtable access.
956 bool isTBAAVtableAccess() const;
958 /// \brief Methods for metadata merging.
959 static MDNode *concatenate(MDNode *A, MDNode *B);
960 static MDNode *intersect(MDNode *A, MDNode *B);
961 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
962 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
963 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
964 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
967 /// \brief Tuple of metadata.
969 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
970 /// default based on their operands.
971 class MDTuple : public MDNode {
972 friend class LLVMContextImpl;
975 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
976 ArrayRef<Metadata *> Vals)
977 : MDNode(C, MDTupleKind, Storage, Vals) {
980 ~MDTuple() { dropAllReferences(); }
982 void setHash(unsigned Hash) { SubclassData32 = Hash; }
983 void recalculateHash();
985 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
986 StorageType Storage, bool ShouldCreate = true);
988 TempMDTuple cloneImpl() const {
989 return getTemporary(getContext(),
990 SmallVector<Metadata *, 4>(op_begin(), op_end()));
994 /// \brief Get the hash, if any.
995 unsigned getHash() const { return SubclassData32; }
997 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
998 return getImpl(Context, MDs, Uniqued);
1000 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1001 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1004 /// \brief Return a distinct node.
1006 /// Return a distinct node -- i.e., a node that is not uniqued.
1007 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1008 return getImpl(Context, MDs, Distinct);
1011 /// \brief Return a temporary node.
1013 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1014 /// not uniqued, may be RAUW'd, and must be manually deleted with
1015 /// deleteTemporary.
1016 static TempMDTuple getTemporary(LLVMContext &Context,
1017 ArrayRef<Metadata *> MDs) {
1018 return TempMDTuple(getImpl(Context, MDs, Temporary));
1021 /// \brief Return a (temporary) clone of this.
1022 TempMDTuple clone() const { return cloneImpl(); }
1024 static bool classof(const Metadata *MD) {
1025 return MD->getMetadataID() == MDTupleKind;
1029 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1030 return MDTuple::get(Context, MDs);
1032 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1033 return MDTuple::getIfExists(Context, MDs);
1035 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1036 return MDTuple::getDistinct(Context, MDs);
1038 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1039 ArrayRef<Metadata *> MDs) {
1040 return MDTuple::getTemporary(Context, MDs);
1043 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1044 MDNode::deleteTemporary(Node);
1047 /// \brief Typed iterator through MDNode operands.
1049 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1050 /// particular Metadata subclass.
1052 class TypedMDOperandIterator
1053 : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
1054 MDNode::op_iterator I = nullptr;
1057 TypedMDOperandIterator() = default;
1058 explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1059 T *operator*() const { return cast_or_null<T>(*I); }
1060 TypedMDOperandIterator &operator++() {
1064 TypedMDOperandIterator operator++(int) {
1065 TypedMDOperandIterator Temp(*this);
1069 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1070 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1073 /// \brief Typed, array-like tuple of metadata.
1075 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1076 /// particular type of metadata.
1077 template <class T> class MDTupleTypedArrayWrapper {
1078 const MDTuple *N = nullptr;
1081 MDTupleTypedArrayWrapper() = default;
1082 MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1085 MDTupleTypedArrayWrapper(
1086 const MDTupleTypedArrayWrapper<U> &Other,
1087 typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
1092 explicit MDTupleTypedArrayWrapper(
1093 const MDTupleTypedArrayWrapper<U> &Other,
1094 typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
1098 explicit operator bool() const { return get(); }
1099 explicit operator MDTuple *() const { return get(); }
1101 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1102 MDTuple *operator->() const { return get(); }
1103 MDTuple &operator*() const { return *get(); }
1105 // FIXME: Fix callers and remove condition on N.
1106 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1107 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1109 // FIXME: Fix callers and remove condition on N.
1110 typedef TypedMDOperandIterator<T> iterator;
1111 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1112 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1115 #define HANDLE_METADATA(CLASS) \
1116 typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
1117 #include "llvm/IR/Metadata.def"
1119 //===----------------------------------------------------------------------===//
1120 /// \brief A tuple of MDNodes.
1122 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1123 /// to modules, have names, and contain lists of MDNodes.
1125 /// TODO: Inherit from Metadata.
1126 class NamedMDNode : public ilist_node<NamedMDNode> {
1127 friend class SymbolTableListTraits<NamedMDNode, Module>;
1128 friend struct ilist_traits<NamedMDNode>;
1129 friend class LLVMContextImpl;
1130 friend class Module;
1131 NamedMDNode(const NamedMDNode &) = delete;
1135 void *Operands; // SmallVector<TrackingMDRef, 4>
1137 void setParent(Module *M) { Parent = M; }
1139 explicit NamedMDNode(const Twine &N);
1141 template<class T1, class T2>
1142 class op_iterator_impl :
1143 public std::iterator<std::bidirectional_iterator_tag, T2> {
1144 const NamedMDNode *Node;
1146 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1148 friend class NamedMDNode;
1151 op_iterator_impl() : Node(nullptr), Idx(0) { }
1153 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1154 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1155 op_iterator_impl &operator++() {
1159 op_iterator_impl operator++(int) {
1160 op_iterator_impl tmp(*this);
1164 op_iterator_impl &operator--() {
1168 op_iterator_impl operator--(int) {
1169 op_iterator_impl tmp(*this);
1174 T1 operator*() const { return Node->getOperand(Idx); }
1178 /// \brief Drop all references and remove the node from parent module.
1179 void eraseFromParent();
1181 /// \brief Remove all uses and clear node vector.
1182 void dropAllReferences();
1186 /// \brief Get the module that holds this named metadata collection.
1187 inline Module *getParent() { return Parent; }
1188 inline const Module *getParent() const { return Parent; }
1190 MDNode *getOperand(unsigned i) const;
1191 unsigned getNumOperands() const;
1192 void addOperand(MDNode *M);
1193 void setOperand(unsigned I, MDNode *New);
1194 StringRef getName() const;
1195 void print(raw_ostream &ROS) const;
1198 // ---------------------------------------------------------------------------
1199 // Operand Iterator interface...
1201 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1202 op_iterator op_begin() { return op_iterator(this, 0); }
1203 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1205 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1206 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1207 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1209 inline iterator_range<op_iterator> operands() {
1210 return iterator_range<op_iterator>(op_begin(), op_end());
1212 inline iterator_range<const_op_iterator> operands() const {
1213 return iterator_range<const_op_iterator>(op_begin(), op_end());
1217 } // end llvm namespace