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/DenseMapInfo.h"
22 #include "llvm/ADT/ilist_node.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/ADT/None.h"
25 #include "llvm/ADT/PointerUnion.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/IR/Constant.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/ErrorHandling.h"
40 #include <type_traits>
46 class ModuleSlotTracker;
48 enum LLVMConstants : uint32_t {
49 DEBUG_METADATA_VERSION = 3 // Current debug info version number.
52 /// \brief Root of the metadata hierarchy.
54 /// This is a root class for typeless data in the IR.
56 friend class ReplaceableMetadataImpl;
59 const unsigned char SubclassID;
62 /// \brief Active type of storage.
63 enum StorageType { Uniqued, Distinct, Temporary };
65 /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
66 unsigned char Storage;
67 // TODO: expose remaining bits to subclasses.
69 unsigned short SubclassData16;
70 unsigned SubclassData32;
74 #define HANDLE_METADATA_LEAF(CLASS) CLASS##Kind,
75 #include "llvm/IR/Metadata.def"
79 Metadata(unsigned ID, StorageType Storage)
80 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
81 static_assert(sizeof(*this) == 8, "Metdata fields poorly packed");
84 ~Metadata() = default;
86 /// \brief Default handling of a changed operand, which asserts.
88 /// If subclasses pass themselves in as owners to a tracking node reference,
89 /// they must provide an implementation of this method.
90 void handleChangedOperand(void *, Metadata *) {
91 llvm_unreachable("Unimplemented in Metadata subclass");
95 unsigned getMetadataID() const { return SubclassID; }
97 /// \brief User-friendly dump.
99 /// If \c M is provided, metadata nodes will be numbered canonically;
100 /// otherwise, pointer addresses are substituted.
102 /// Note: this uses an explicit overload instead of default arguments so that
103 /// the nullptr version is easy to call from a debugger.
107 void dump(const Module *M) const;
112 /// Prints definition of \c this.
114 /// If \c M is provided, metadata nodes will be numbered canonically;
115 /// otherwise, pointer addresses are substituted.
117 void print(raw_ostream &OS, const Module *M = nullptr,
118 bool IsForDebug = false) const;
119 void print(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr,
120 bool IsForDebug = false) const;
123 /// \brief Print as operand.
125 /// Prints reference of \c this.
127 /// If \c M is provided, metadata nodes will be numbered canonically;
128 /// otherwise, pointer addresses are substituted.
130 void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
131 void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
132 const Module *M = nullptr) const;
136 #define HANDLE_METADATA(CLASS) class CLASS;
137 #include "llvm/IR/Metadata.def"
139 // Provide specializations of isa so that we don't need definitions of
140 // subclasses to see if the metadata is a subclass.
141 #define HANDLE_METADATA_LEAF(CLASS) \
142 template <> struct isa_impl<CLASS, Metadata> { \
143 static inline bool doit(const Metadata &MD) { \
144 return MD.getMetadataID() == Metadata::CLASS##Kind; \
147 #include "llvm/IR/Metadata.def"
149 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
154 /// \brief Metadata wrapper in the Value hierarchy.
156 /// A member of the \a Value hierarchy to represent a reference to metadata.
157 /// This allows, e.g., instrinsics to have metadata as operands.
159 /// Notably, this is the only thing in either hierarchy that is allowed to
160 /// reference \a LocalAsMetadata.
161 class MetadataAsValue : public Value {
162 friend class ReplaceableMetadataImpl;
163 friend class LLVMContextImpl;
167 MetadataAsValue(Type *Ty, Metadata *MD);
168 ~MetadataAsValue() override;
170 /// \brief Drop use of metadata (during teardown).
171 void dropUse() { MD = nullptr; }
174 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
175 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
176 Metadata *getMetadata() const { return MD; }
178 static bool classof(const Value *V) {
179 return V->getValueID() == MetadataAsValueVal;
183 void handleChangedMetadata(Metadata *MD);
188 /// \brief API for tracking metadata references through RAUW and deletion.
190 /// Shared API for updating \a Metadata pointers in subclasses that support
193 /// This API is not meant to be used directly. See \a TrackingMDRef for a
194 /// user-friendly tracking reference.
195 class MetadataTracking {
197 /// \brief Track the reference to metadata.
199 /// Register \c MD with \c *MD, if the subclass supports tracking. If \c *MD
200 /// gets RAUW'ed, \c MD will be updated to the new address. If \c *MD gets
201 /// deleted, \c MD will be set to \c nullptr.
203 /// If tracking isn't supported, \c *MD will not change.
205 /// \return true iff tracking is supported by \c MD.
206 static bool track(Metadata *&MD) {
207 return track(&MD, *MD, static_cast<Metadata *>(nullptr));
210 /// \brief Track the reference to metadata for \a Metadata.
212 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
213 /// tell it that its operand changed. This could trigger \c Owner being
215 static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
216 return track(Ref, MD, &Owner);
219 /// \brief Track the reference to metadata for \a MetadataAsValue.
221 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
222 /// tell it that its operand changed. This could trigger \c Owner being
224 static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
225 return track(Ref, MD, &Owner);
228 /// \brief Stop tracking a reference to metadata.
230 /// Stops \c *MD from tracking \c MD.
231 static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
232 static void untrack(void *Ref, Metadata &MD);
234 /// \brief Move tracking from one reference to another.
236 /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
237 /// except that ownership callbacks are maintained.
239 /// Note: it is an error if \c *MD does not equal \c New.
241 /// \return true iff tracking is supported by \c MD.
242 static bool retrack(Metadata *&MD, Metadata *&New) {
243 return retrack(&MD, *MD, &New);
245 static bool retrack(void *Ref, Metadata &MD, void *New);
247 /// \brief Check whether metadata is replaceable.
248 static bool isReplaceable(const Metadata &MD);
250 typedef PointerUnion<MetadataAsValue *, Metadata *> OwnerTy;
253 /// \brief Track a reference to metadata for an owner.
255 /// Generalized version of tracking.
256 static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
259 /// \brief Shared implementation of use-lists for replaceable metadata.
261 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
262 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
263 /// and \a TempMDNode).
264 class ReplaceableMetadataImpl {
265 friend class MetadataTracking;
268 typedef MetadataTracking::OwnerTy OwnerTy;
271 LLVMContext &Context;
273 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
276 ReplaceableMetadataImpl(LLVMContext &Context)
277 : Context(Context), NextIndex(0) {}
279 ~ReplaceableMetadataImpl() {
280 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
283 LLVMContext &getContext() const { return Context; }
285 /// \brief Replace all uses of this with MD.
287 /// Replace all uses of this with \c MD, which is allowed to be null.
288 void replaceAllUsesWith(Metadata *MD);
290 /// \brief Resolve all uses of this.
292 /// Resolve all uses of this, turning off RAUW permanently. If \c
293 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
295 void resolveAllUses(bool ResolveUsers = true);
298 void addRef(void *Ref, OwnerTy Owner);
299 void dropRef(void *Ref);
300 void moveRef(void *Ref, void *New, const Metadata &MD);
302 /// Lazily construct RAUW support on MD.
304 /// If this is an unresolved MDNode, RAUW support will be created on-demand.
305 /// ValueAsMetadata always has RAUW support.
306 static ReplaceableMetadataImpl *getOrCreate(Metadata &MD);
308 /// Get RAUW support on MD, if it exists.
309 static ReplaceableMetadataImpl *getIfExists(Metadata &MD);
311 /// Check whether this node will support RAUW.
313 /// Returns \c true unless getOrCreate() would return null.
314 static bool isReplaceable(const Metadata &MD);
317 /// \brief Value wrapper in the Metadata hierarchy.
319 /// This is a custom value handle that allows other metadata to refer to
320 /// classes in the Value hierarchy.
322 /// Because of full uniquing support, each value is only wrapped by a single \a
323 /// ValueAsMetadata object, so the lookup maps are far more efficient than
324 /// those using ValueHandleBase.
325 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
326 friend class ReplaceableMetadataImpl;
327 friend class LLVMContextImpl;
331 /// \brief Drop users without RAUW (during teardown).
333 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
337 ValueAsMetadata(unsigned ID, Value *V)
338 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
339 assert(V && "Expected valid value");
342 ~ValueAsMetadata() = default;
345 static ValueAsMetadata *get(Value *V);
346 static ConstantAsMetadata *getConstant(Value *C) {
347 return cast<ConstantAsMetadata>(get(C));
349 static LocalAsMetadata *getLocal(Value *Local) {
350 return cast<LocalAsMetadata>(get(Local));
353 static ValueAsMetadata *getIfExists(Value *V);
354 static ConstantAsMetadata *getConstantIfExists(Value *C) {
355 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
357 static LocalAsMetadata *getLocalIfExists(Value *Local) {
358 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
361 Value *getValue() const { return V; }
362 Type *getType() const { return V->getType(); }
363 LLVMContext &getContext() const { return V->getContext(); }
365 static void handleDeletion(Value *V);
366 static void handleRAUW(Value *From, Value *To);
369 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
371 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
372 /// \a Value gets RAUW'ed and the target already exists, this is used to
373 /// merge the two metadata nodes.
374 void replaceAllUsesWith(Metadata *MD) {
375 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
379 static bool classof(const Metadata *MD) {
380 return MD->getMetadataID() == LocalAsMetadataKind ||
381 MD->getMetadataID() == ConstantAsMetadataKind;
385 class ConstantAsMetadata : public ValueAsMetadata {
386 friend class ValueAsMetadata;
388 ConstantAsMetadata(Constant *C)
389 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
392 static ConstantAsMetadata *get(Constant *C) {
393 return ValueAsMetadata::getConstant(C);
396 static ConstantAsMetadata *getIfExists(Constant *C) {
397 return ValueAsMetadata::getConstantIfExists(C);
400 Constant *getValue() const {
401 return cast<Constant>(ValueAsMetadata::getValue());
404 static bool classof(const Metadata *MD) {
405 return MD->getMetadataID() == ConstantAsMetadataKind;
409 class LocalAsMetadata : public ValueAsMetadata {
410 friend class ValueAsMetadata;
412 LocalAsMetadata(Value *Local)
413 : ValueAsMetadata(LocalAsMetadataKind, Local) {
414 assert(!isa<Constant>(Local) && "Expected local value");
418 static LocalAsMetadata *get(Value *Local) {
419 return ValueAsMetadata::getLocal(Local);
422 static LocalAsMetadata *getIfExists(Value *Local) {
423 return ValueAsMetadata::getLocalIfExists(Local);
426 static bool classof(const Metadata *MD) {
427 return MD->getMetadataID() == LocalAsMetadataKind;
431 /// \brief Transitional API for extracting constants from Metadata.
433 /// This namespace contains transitional functions for metadata that points to
436 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
437 /// operands could refer to any \a Value. There's was a lot of code like this:
441 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
444 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
445 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
446 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
447 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
448 /// requires subtle control flow changes.
450 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
451 /// so that metadata can refer to numbers without traversing a bridge to the \a
452 /// Value hierarchy. In this final state, the code above would look like this:
456 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
459 /// The API in this namespace supports the transition. \a MDInt doesn't exist
460 /// yet, and even once it does, changing each metadata schema to use it is its
461 /// own mini-project. In the meantime this API prevents us from introducing
462 /// complex and bug-prone control flow that will disappear in the end. In
463 /// particular, the above code looks like this:
467 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
470 /// The full set of provided functions includes:
472 /// mdconst::hasa <=> isa
473 /// mdconst::extract <=> cast
474 /// mdconst::extract_or_null <=> cast_or_null
475 /// mdconst::dyn_extract <=> dyn_cast
476 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
478 /// The target of the cast must be a subclass of \a Constant.
483 template <class T> T &make();
484 template <class T, class Result> struct HasDereference {
487 template <size_t N> struct SFINAE {};
489 template <class U, class V>
490 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
491 template <class U, class V> static No &hasDereference(...);
493 static const bool value =
494 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
496 template <class V, class M> struct IsValidPointer {
497 static const bool value = std::is_base_of<Constant, V>::value &&
498 HasDereference<M, const Metadata &>::value;
500 template <class V, class M> struct IsValidReference {
501 static const bool value = std::is_base_of<Constant, V>::value &&
502 std::is_convertible<M, const Metadata &>::value;
505 } // end namespace detail
507 /// \brief Check whether Metadata has a Value.
509 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
511 template <class X, class Y>
512 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
514 assert(MD && "Null pointer sent into hasa");
515 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
516 return isa<X>(V->getValue());
519 template <class X, class Y>
521 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
526 /// \brief Extract a Value from Metadata.
528 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
529 template <class X, class Y>
530 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
532 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
534 template <class X, class Y>
536 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
541 /// \brief Extract a Value from Metadata, allowing null.
543 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
544 /// from \c MD, allowing \c MD to be null.
545 template <class X, class Y>
546 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
547 extract_or_null(Y &&MD) {
548 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
549 return cast<X>(V->getValue());
553 /// \brief Extract a Value from Metadata, if any.
555 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
556 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
557 /// Value it does contain is of the wrong subclass.
558 template <class X, class Y>
559 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
560 dyn_extract(Y &&MD) {
561 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
562 return dyn_cast<X>(V->getValue());
566 /// \brief Extract a Value from Metadata, if any, allowing null.
568 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
569 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
570 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
571 template <class X, class Y>
572 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
573 dyn_extract_or_null(Y &&MD) {
574 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
575 return dyn_cast<X>(V->getValue());
579 } // end namespace mdconst
581 //===----------------------------------------------------------------------===//
582 /// \brief A single uniqued string.
584 /// These are used to efficiently contain a byte sequence for metadata.
585 /// MDString is always unnamed.
586 class MDString : public Metadata {
587 friend class StringMapEntry<MDString>;
589 StringMapEntry<MDString> *Entry;
590 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
593 MDString(const MDString &) = delete;
594 MDString &operator=(MDString &&) = delete;
595 MDString &operator=(const MDString &) = delete;
597 static MDString *get(LLVMContext &Context, StringRef Str);
598 static MDString *get(LLVMContext &Context, const char *Str) {
599 return get(Context, Str ? StringRef(Str) : StringRef());
602 StringRef getString() const;
604 unsigned getLength() const { return (unsigned)getString().size(); }
606 typedef StringRef::iterator iterator;
608 /// \brief Pointer to the first byte of the string.
609 iterator begin() const { return getString().begin(); }
611 /// \brief Pointer to one byte past the end of the string.
612 iterator end() const { return getString().end(); }
614 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
615 const unsigned char *bytes_end() const { return getString().bytes_end(); }
617 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
618 static bool classof(const Metadata *MD) {
619 return MD->getMetadataID() == MDStringKind;
623 /// \brief A collection of metadata nodes that might be associated with a
624 /// memory access used by the alias-analysis infrastructure.
626 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
628 : TBAA(T), Scope(S), NoAlias(N) {}
630 bool operator==(const AAMDNodes &A) const {
631 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
634 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
636 explicit operator bool() const { return TBAA || Scope || NoAlias; }
638 /// \brief The tag for type-based alias analysis.
641 /// \brief The tag for alias scope specification (used with noalias).
644 /// \brief The tag specifying the noalias scope.
648 // Specialize DenseMapInfo for AAMDNodes.
650 struct DenseMapInfo<AAMDNodes> {
651 static inline AAMDNodes getEmptyKey() {
652 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
656 static inline AAMDNodes getTombstoneKey() {
657 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
661 static unsigned getHashValue(const AAMDNodes &Val) {
662 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
663 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
664 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
667 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
672 /// \brief Tracking metadata reference owned by Metadata.
674 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
675 /// of \a Metadata, which has the option of registering itself for callbacks to
676 /// re-unique itself.
678 /// In particular, this is used by \a MDNode.
680 Metadata *MD = nullptr;
683 MDOperand() = default;
684 MDOperand(MDOperand &&) = delete;
685 MDOperand(const MDOperand &) = delete;
686 MDOperand &operator=(MDOperand &&) = delete;
687 MDOperand &operator=(const MDOperand &) = delete;
688 ~MDOperand() { untrack(); }
690 Metadata *get() const { return MD; }
691 operator Metadata *() const { return get(); }
692 Metadata *operator->() const { return get(); }
693 Metadata &operator*() const { return *get(); }
699 void reset(Metadata *MD, Metadata *Owner) {
706 void track(Metadata *Owner) {
709 MetadataTracking::track(this, *MD, *Owner);
711 MetadataTracking::track(MD);
716 assert(static_cast<void *>(this) == &MD && "Expected same address");
718 MetadataTracking::untrack(MD);
722 template <> struct simplify_type<MDOperand> {
723 typedef Metadata *SimpleType;
724 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
727 template <> struct simplify_type<const MDOperand> {
728 typedef Metadata *SimpleType;
729 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
732 /// \brief Pointer to the context, with optional RAUW support.
734 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
735 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
736 class ContextAndReplaceableUses {
737 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
740 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
741 ContextAndReplaceableUses(
742 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
743 : Ptr(ReplaceableUses.release()) {
744 assert(getReplaceableUses() && "Expected non-null replaceable uses");
746 ContextAndReplaceableUses() = delete;
747 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
748 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
749 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
750 ContextAndReplaceableUses &
751 operator=(const ContextAndReplaceableUses &) = delete;
752 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
754 operator LLVMContext &() { return getContext(); }
756 /// \brief Whether this contains RAUW support.
757 bool hasReplaceableUses() const {
758 return Ptr.is<ReplaceableMetadataImpl *>();
761 LLVMContext &getContext() const {
762 if (hasReplaceableUses())
763 return getReplaceableUses()->getContext();
764 return *Ptr.get<LLVMContext *>();
767 ReplaceableMetadataImpl *getReplaceableUses() const {
768 if (hasReplaceableUses())
769 return Ptr.get<ReplaceableMetadataImpl *>();
773 /// Ensure that this has RAUW support, and then return it.
774 ReplaceableMetadataImpl *getOrCreateReplaceableUses() {
775 if (!hasReplaceableUses())
776 makeReplaceable(llvm::make_unique<ReplaceableMetadataImpl>(getContext()));
777 return getReplaceableUses();
780 /// \brief Assign RAUW support to this.
782 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
785 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
786 assert(ReplaceableUses && "Expected non-null replaceable uses");
787 assert(&ReplaceableUses->getContext() == &getContext() &&
788 "Expected same context");
789 delete getReplaceableUses();
790 Ptr = ReplaceableUses.release();
793 /// \brief Drop RAUW support.
795 /// Cede ownership of RAUW support, returning it.
796 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
797 assert(hasReplaceableUses() && "Expected to own replaceable uses");
798 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
799 getReplaceableUses());
800 Ptr = &ReplaceableUses->getContext();
801 return ReplaceableUses;
805 struct TempMDNodeDeleter {
806 inline void operator()(MDNode *Node) const;
809 #define HANDLE_MDNODE_LEAF(CLASS) \
810 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
811 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
812 #include "llvm/IR/Metadata.def"
814 /// \brief Metadata node.
816 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
817 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
818 /// until forward references are known. The basic metadata node is an \a
821 /// There is limited support for RAUW at construction time. At construction
822 /// time, if any operand is a temporary node (or an unresolved uniqued node,
823 /// which indicates a transitive temporary operand), the node itself will be
824 /// unresolved. As soon as all operands become resolved, it will drop RAUW
825 /// support permanently.
827 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
828 /// to be called on some member of the cycle once all temporary nodes have been
830 class MDNode : public Metadata {
831 friend class ReplaceableMetadataImpl;
832 friend class LLVMContextImpl;
834 unsigned NumOperands;
835 unsigned NumUnresolved;
837 ContextAndReplaceableUses Context;
840 void *operator new(size_t Size, unsigned NumOps);
841 void operator delete(void *Mem);
843 /// \brief Required by std, but never called.
844 void operator delete(void *, unsigned) {
845 llvm_unreachable("Constructor throws?");
848 /// \brief Required by std, but never called.
849 void operator delete(void *, unsigned, bool) {
850 llvm_unreachable("Constructor throws?");
853 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
854 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
857 void dropAllReferences();
859 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
860 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
862 typedef iterator_range<MDOperand *> mutable_op_range;
863 mutable_op_range mutable_operands() {
864 return mutable_op_range(mutable_begin(), mutable_end());
868 MDNode(const MDNode &) = delete;
869 void operator=(const MDNode &) = delete;
870 void *operator new(size_t) = delete;
872 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
873 static inline MDTuple *getIfExists(LLVMContext &Context,
874 ArrayRef<Metadata *> MDs);
875 static inline MDTuple *getDistinct(LLVMContext &Context,
876 ArrayRef<Metadata *> MDs);
877 static inline TempMDTuple getTemporary(LLVMContext &Context,
878 ArrayRef<Metadata *> MDs);
880 /// \brief Create a (temporary) clone of this.
881 TempMDNode clone() const;
883 /// \brief Deallocate a node created by getTemporary.
885 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
886 /// references will be reset.
887 static void deleteTemporary(MDNode *N);
889 LLVMContext &getContext() const { return Context.getContext(); }
891 /// \brief Replace a specific operand.
892 void replaceOperandWith(unsigned I, Metadata *New);
894 /// \brief Check if node is fully resolved.
896 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
897 /// this always returns \c true.
899 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
900 /// support (because all operands are resolved).
902 /// As forward declarations are resolved, their containers should get
903 /// resolved automatically. However, if this (or one of its operands) is
904 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
905 bool isResolved() const { return !isTemporary() && !NumUnresolved; }
907 bool isUniqued() const { return Storage == Uniqued; }
908 bool isDistinct() const { return Storage == Distinct; }
909 bool isTemporary() const { return Storage == Temporary; }
911 /// \brief RAUW a temporary.
913 /// \pre \a isTemporary() must be \c true.
914 void replaceAllUsesWith(Metadata *MD) {
915 assert(isTemporary() && "Expected temporary node");
916 if (Context.hasReplaceableUses())
917 Context.getReplaceableUses()->replaceAllUsesWith(MD);
920 /// \brief Resolve cycles.
922 /// Once all forward declarations have been resolved, force cycles to be
925 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
926 void resolveCycles();
928 /// \brief Replace a temporary node with a permanent one.
930 /// Try to create a uniqued version of \c N -- in place, if possible -- and
931 /// return it. If \c N cannot be uniqued, return a distinct node instead.
933 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
934 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
935 return cast<T>(N.release()->replaceWithPermanentImpl());
938 /// \brief Replace a temporary node with a uniqued one.
940 /// Create a uniqued version of \c N -- in place, if possible -- and return
941 /// it. Takes ownership of the temporary node.
943 /// \pre N does not self-reference.
945 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
946 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
947 return cast<T>(N.release()->replaceWithUniquedImpl());
950 /// \brief Replace a temporary node with a distinct one.
952 /// Create a distinct version of \c N -- in place, if possible -- and return
953 /// it. Takes ownership of the temporary node.
955 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
956 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
957 return cast<T>(N.release()->replaceWithDistinctImpl());
961 MDNode *replaceWithPermanentImpl();
962 MDNode *replaceWithUniquedImpl();
963 MDNode *replaceWithDistinctImpl();
966 /// \brief Set an operand.
968 /// Sets the operand directly, without worrying about uniquing.
969 void setOperand(unsigned I, Metadata *New);
971 void storeDistinctInContext();
972 template <class T, class StoreT>
973 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
974 template <class T> static T *storeImpl(T *N, StorageType Storage);
977 void handleChangedOperand(void *Ref, Metadata *New);
979 /// Resolve a unique, unresolved node.
982 /// Drop RAUW support, if any.
983 void dropReplaceableUses();
985 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
986 void decrementUnresolvedOperandCount();
987 void countUnresolvedOperands();
989 /// \brief Mutate this to be "uniqued".
991 /// Mutate this so that \a isUniqued().
992 /// \pre \a isTemporary().
993 /// \pre already added to uniquing set.
996 /// \brief Mutate this to be "distinct".
998 /// Mutate this so that \a isDistinct().
999 /// \pre \a isTemporary().
1000 void makeDistinct();
1002 void deleteAsSubclass();
1004 void eraseFromStore();
1006 template <class NodeTy> struct HasCachedHash;
1007 template <class NodeTy>
1008 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
1009 N->recalculateHash();
1011 template <class NodeTy>
1012 static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
1013 template <class NodeTy>
1014 static void dispatchResetHash(NodeTy *N, std::true_type) {
1017 template <class NodeTy>
1018 static void dispatchResetHash(NodeTy *, std::false_type) {}
1021 typedef const MDOperand *op_iterator;
1022 typedef iterator_range<op_iterator> op_range;
1024 op_iterator op_begin() const {
1025 return const_cast<MDNode *>(this)->mutable_begin();
1028 op_iterator op_end() const {
1029 return const_cast<MDNode *>(this)->mutable_end();
1032 op_range operands() const { return op_range(op_begin(), op_end()); }
1034 const MDOperand &getOperand(unsigned I) const {
1035 assert(I < NumOperands && "Out of range");
1036 return op_begin()[I];
1039 /// \brief Return number of MDNode operands.
1040 unsigned getNumOperands() const { return NumOperands; }
1042 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
1043 static bool classof(const Metadata *MD) {
1044 switch (MD->getMetadataID()) {
1047 #define HANDLE_MDNODE_LEAF(CLASS) \
1050 #include "llvm/IR/Metadata.def"
1054 /// \brief Check whether MDNode is a vtable access.
1055 bool isTBAAVtableAccess() const;
1057 /// \brief Methods for metadata merging.
1058 static MDNode *concatenate(MDNode *A, MDNode *B);
1059 static MDNode *intersect(MDNode *A, MDNode *B);
1060 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
1061 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
1062 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
1063 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
1064 static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B);
1068 /// \brief Tuple of metadata.
1070 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
1071 /// default based on their operands.
1072 class MDTuple : public MDNode {
1073 friend class LLVMContextImpl;
1074 friend class MDNode;
1076 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1077 ArrayRef<Metadata *> Vals)
1078 : MDNode(C, MDTupleKind, Storage, Vals) {
1082 ~MDTuple() { dropAllReferences(); }
1084 void setHash(unsigned Hash) { SubclassData32 = Hash; }
1085 void recalculateHash();
1087 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
1088 StorageType Storage, bool ShouldCreate = true);
1090 TempMDTuple cloneImpl() const {
1091 return getTemporary(getContext(),
1092 SmallVector<Metadata *, 4>(op_begin(), op_end()));
1096 /// \brief Get the hash, if any.
1097 unsigned getHash() const { return SubclassData32; }
1099 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1100 return getImpl(Context, MDs, Uniqued);
1103 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1104 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1107 /// \brief Return a distinct node.
1109 /// Return a distinct node -- i.e., a node that is not uniqued.
1110 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1111 return getImpl(Context, MDs, Distinct);
1114 /// \brief Return a temporary node.
1116 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1117 /// not uniqued, may be RAUW'd, and must be manually deleted with
1118 /// deleteTemporary.
1119 static TempMDTuple getTemporary(LLVMContext &Context,
1120 ArrayRef<Metadata *> MDs) {
1121 return TempMDTuple(getImpl(Context, MDs, Temporary));
1124 /// \brief Return a (temporary) clone of this.
1125 TempMDTuple clone() const { return cloneImpl(); }
1127 static bool classof(const Metadata *MD) {
1128 return MD->getMetadataID() == MDTupleKind;
1132 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1133 return MDTuple::get(Context, MDs);
1136 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1137 return MDTuple::getIfExists(Context, MDs);
1140 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1141 return MDTuple::getDistinct(Context, MDs);
1144 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1145 ArrayRef<Metadata *> MDs) {
1146 return MDTuple::getTemporary(Context, MDs);
1149 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1150 MDNode::deleteTemporary(Node);
1153 /// \brief Typed iterator through MDNode operands.
1155 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1156 /// particular Metadata subclass.
1158 class TypedMDOperandIterator
1159 : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
1160 MDNode::op_iterator I = nullptr;
1163 TypedMDOperandIterator() = default;
1164 explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1166 T *operator*() const { return cast_or_null<T>(*I); }
1168 TypedMDOperandIterator &operator++() {
1173 TypedMDOperandIterator operator++(int) {
1174 TypedMDOperandIterator Temp(*this);
1179 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1180 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1183 /// \brief Typed, array-like tuple of metadata.
1185 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1186 /// particular type of metadata.
1187 template <class T> class MDTupleTypedArrayWrapper {
1188 const MDTuple *N = nullptr;
1191 MDTupleTypedArrayWrapper() = default;
1192 MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1195 MDTupleTypedArrayWrapper(
1196 const MDTupleTypedArrayWrapper<U> &Other,
1197 typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
1202 explicit MDTupleTypedArrayWrapper(
1203 const MDTupleTypedArrayWrapper<U> &Other,
1204 typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
1208 explicit operator bool() const { return get(); }
1209 explicit operator MDTuple *() const { return get(); }
1211 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1212 MDTuple *operator->() const { return get(); }
1213 MDTuple &operator*() const { return *get(); }
1215 // FIXME: Fix callers and remove condition on N.
1216 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1217 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1219 // FIXME: Fix callers and remove condition on N.
1220 typedef TypedMDOperandIterator<T> iterator;
1221 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1222 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1225 #define HANDLE_METADATA(CLASS) \
1226 typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
1227 #include "llvm/IR/Metadata.def"
1229 /// Placeholder metadata for operands of distinct MDNodes.
1231 /// This is a lightweight placeholder for an operand of a distinct node. It's
1232 /// purpose is to help track forward references when creating a distinct node.
1233 /// This allows distinct nodes involved in a cycle to be constructed before
1234 /// their operands without requiring a heavyweight temporary node with
1235 /// full-blown RAUW support.
1237 /// Each placeholder supports only a single MDNode user. Clients should pass
1238 /// an ID, retrieved via \a getID(), to indicate the "real" operand that this
1239 /// should be replaced with.
1241 /// While it would be possible to implement move operators, they would be
1242 /// fairly expensive. Leave them unimplemented to discourage their use
1243 /// (clients can use std::deque, std::list, BumpPtrAllocator, etc.).
1244 class DistinctMDOperandPlaceholder : public Metadata {
1245 friend class MetadataTracking;
1247 Metadata **Use = nullptr;
1250 explicit DistinctMDOperandPlaceholder(unsigned ID)
1251 : Metadata(DistinctMDOperandPlaceholderKind, Distinct) {
1252 SubclassData32 = ID;
1255 DistinctMDOperandPlaceholder() = delete;
1256 DistinctMDOperandPlaceholder(DistinctMDOperandPlaceholder &&) = delete;
1257 DistinctMDOperandPlaceholder(const DistinctMDOperandPlaceholder &) = delete;
1259 ~DistinctMDOperandPlaceholder() {
1264 unsigned getID() const { return SubclassData32; }
1266 /// Replace the use of this with MD.
1267 void replaceUseWith(Metadata *MD) {
1275 //===----------------------------------------------------------------------===//
1276 /// \brief A tuple of MDNodes.
1278 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1279 /// to modules, have names, and contain lists of MDNodes.
1281 /// TODO: Inherit from Metadata.
1282 class NamedMDNode : public ilist_node<NamedMDNode> {
1283 friend class LLVMContextImpl;
1284 friend class Module;
1288 void *Operands; // SmallVector<TrackingMDRef, 4>
1290 void setParent(Module *M) { Parent = M; }
1292 explicit NamedMDNode(const Twine &N);
1294 template<class T1, class T2>
1295 class op_iterator_impl :
1296 public std::iterator<std::bidirectional_iterator_tag, T2> {
1297 const NamedMDNode *Node = nullptr;
1300 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1302 friend class NamedMDNode;
1305 op_iterator_impl() = default;
1307 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1308 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1310 op_iterator_impl &operator++() {
1315 op_iterator_impl operator++(int) {
1316 op_iterator_impl tmp(*this);
1321 op_iterator_impl &operator--() {
1326 op_iterator_impl operator--(int) {
1327 op_iterator_impl tmp(*this);
1332 T1 operator*() const { return Node->getOperand(Idx); }
1336 NamedMDNode(const NamedMDNode &) = delete;
1339 /// \brief Drop all references and remove the node from parent module.
1340 void eraseFromParent();
1342 /// Remove all uses and clear node vector.
1343 void dropAllReferences() { clearOperands(); }
1344 /// Drop all references to this node's operands.
1345 void clearOperands();
1347 /// \brief Get the module that holds this named metadata collection.
1348 inline Module *getParent() { return Parent; }
1349 inline const Module *getParent() const { return Parent; }
1351 MDNode *getOperand(unsigned i) const;
1352 unsigned getNumOperands() const;
1353 void addOperand(MDNode *M);
1354 void setOperand(unsigned I, MDNode *New);
1355 StringRef getName() const;
1356 void print(raw_ostream &ROS, bool IsForDebug = false) const;
1357 void print(raw_ostream &ROS, ModuleSlotTracker &MST,
1358 bool IsForDebug = false) const;
1361 // ---------------------------------------------------------------------------
1362 // Operand Iterator interface...
1364 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1365 op_iterator op_begin() { return op_iterator(this, 0); }
1366 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1368 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1369 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1370 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1372 inline iterator_range<op_iterator> operands() {
1373 return make_range(op_begin(), op_end());
1375 inline iterator_range<const_op_iterator> operands() const {
1376 return make_range(op_begin(), op_end());
1380 } // end namespace llvm
1382 #endif // LLVM_IR_METADATA_H