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/CBindingWrapping.h"
34 #include "llvm/Support/ErrorHandling.h"
41 #include <type_traits>
47 class ModuleSlotTracker;
49 enum LLVMConstants : uint32_t {
50 DEBUG_METADATA_VERSION = 3 // Current debug info version number.
53 /// \brief Root of the metadata hierarchy.
55 /// This is a root class for typeless data in the IR.
57 friend class ReplaceableMetadataImpl;
60 const unsigned char SubclassID;
63 /// \brief Active type of storage.
64 enum StorageType { Uniqued, Distinct, Temporary };
66 /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
67 unsigned char Storage;
68 // TODO: expose remaining bits to subclasses.
70 unsigned short SubclassData16;
71 unsigned SubclassData32;
75 #define HANDLE_METADATA_LEAF(CLASS) CLASS##Kind,
76 #include "llvm/IR/Metadata.def"
80 Metadata(unsigned ID, StorageType Storage)
81 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
82 static_assert(sizeof(*this) == 8, "Metadata fields poorly packed");
85 ~Metadata() = default;
87 /// \brief Default handling of a changed operand, which asserts.
89 /// If subclasses pass themselves in as owners to a tracking node reference,
90 /// they must provide an implementation of this method.
91 void handleChangedOperand(void *, Metadata *) {
92 llvm_unreachable("Unimplemented in Metadata subclass");
96 unsigned getMetadataID() const { return SubclassID; }
98 /// \brief User-friendly dump.
100 /// If \c M is provided, metadata nodes will be numbered canonically;
101 /// otherwise, pointer addresses are substituted.
103 /// Note: this uses an explicit overload instead of default arguments so that
104 /// the nullptr version is easy to call from a debugger.
108 void dump(const Module *M) const;
113 /// Prints definition of \c this.
115 /// If \c M is provided, metadata nodes will be numbered canonically;
116 /// otherwise, pointer addresses are substituted.
118 void print(raw_ostream &OS, const Module *M = nullptr,
119 bool IsForDebug = false) const;
120 void print(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr,
121 bool IsForDebug = false) const;
124 /// \brief Print as operand.
126 /// Prints reference of \c this.
128 /// If \c M is provided, metadata nodes will be numbered canonically;
129 /// otherwise, pointer addresses are substituted.
131 void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
132 void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
133 const Module *M = nullptr) const;
137 // Create wrappers for C Binding types (see CBindingWrapping.h).
138 DEFINE_ISA_CONVERSION_FUNCTIONS(Metadata, LLVMMetadataRef)
140 // Specialized opaque metadata conversions.
141 inline Metadata **unwrap(LLVMMetadataRef *MDs) {
142 return reinterpret_cast<Metadata**>(MDs);
145 #define HANDLE_METADATA(CLASS) class CLASS;
146 #include "llvm/IR/Metadata.def"
148 // Provide specializations of isa so that we don't need definitions of
149 // subclasses to see if the metadata is a subclass.
150 #define HANDLE_METADATA_LEAF(CLASS) \
151 template <> struct isa_impl<CLASS, Metadata> { \
152 static inline bool doit(const Metadata &MD) { \
153 return MD.getMetadataID() == Metadata::CLASS##Kind; \
156 #include "llvm/IR/Metadata.def"
158 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
163 /// \brief Metadata wrapper in the Value hierarchy.
165 /// A member of the \a Value hierarchy to represent a reference to metadata.
166 /// This allows, e.g., instrinsics to have metadata as operands.
168 /// Notably, this is the only thing in either hierarchy that is allowed to
169 /// reference \a LocalAsMetadata.
170 class MetadataAsValue : public Value {
171 friend class ReplaceableMetadataImpl;
172 friend class LLVMContextImpl;
176 MetadataAsValue(Type *Ty, Metadata *MD);
178 /// \brief Drop use of metadata (during teardown).
179 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 API for tracking metadata references through RAUW and deletion.
200 /// Shared API for updating \a Metadata pointers in subclasses that support
203 /// This API is not meant to be used directly. See \a TrackingMDRef for a
204 /// user-friendly tracking reference.
205 class MetadataTracking {
207 /// \brief Track the reference to metadata.
209 /// Register \c MD with \c *MD, if the subclass supports tracking. If \c *MD
210 /// gets RAUW'ed, \c MD will be updated to the new address. If \c *MD gets
211 /// deleted, \c MD will be set to \c nullptr.
213 /// If tracking isn't supported, \c *MD will not change.
215 /// \return true iff tracking is supported by \c MD.
216 static bool track(Metadata *&MD) {
217 return track(&MD, *MD, static_cast<Metadata *>(nullptr));
220 /// \brief Track the reference to metadata for \a Metadata.
222 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
223 /// tell it that its operand changed. This could trigger \c Owner being
225 static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
226 return track(Ref, MD, &Owner);
229 /// \brief Track the reference to metadata for \a MetadataAsValue.
231 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
232 /// tell it that its operand changed. This could trigger \c Owner being
234 static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
235 return track(Ref, MD, &Owner);
238 /// \brief Stop tracking a reference to metadata.
240 /// Stops \c *MD from tracking \c MD.
241 static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
242 static void untrack(void *Ref, Metadata &MD);
244 /// \brief Move tracking from one reference to another.
246 /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
247 /// except that ownership callbacks are maintained.
249 /// Note: it is an error if \c *MD does not equal \c New.
251 /// \return true iff tracking is supported by \c MD.
252 static bool retrack(Metadata *&MD, Metadata *&New) {
253 return retrack(&MD, *MD, &New);
255 static bool retrack(void *Ref, Metadata &MD, void *New);
257 /// \brief Check whether metadata is replaceable.
258 static bool isReplaceable(const Metadata &MD);
260 typedef PointerUnion<MetadataAsValue *, Metadata *> OwnerTy;
263 /// \brief Track a reference to metadata for an owner.
265 /// Generalized version of tracking.
266 static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
269 /// \brief Shared implementation of use-lists for replaceable metadata.
271 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
272 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
273 /// and \a TempMDNode).
274 class ReplaceableMetadataImpl {
275 friend class MetadataTracking;
278 typedef MetadataTracking::OwnerTy OwnerTy;
281 LLVMContext &Context;
282 uint64_t NextIndex = 0;
283 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
286 ReplaceableMetadataImpl(LLVMContext &Context) : Context(Context) {}
288 ~ReplaceableMetadataImpl() {
289 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
292 LLVMContext &getContext() const { return Context; }
294 /// \brief Replace all uses of this with MD.
296 /// Replace all uses of this with \c MD, which is allowed to be null.
297 void replaceAllUsesWith(Metadata *MD);
299 /// \brief Resolve all uses of this.
301 /// Resolve all uses of this, turning off RAUW permanently. If \c
302 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
304 void resolveAllUses(bool ResolveUsers = true);
307 void addRef(void *Ref, OwnerTy Owner);
308 void dropRef(void *Ref);
309 void moveRef(void *Ref, void *New, const Metadata &MD);
311 /// Lazily construct RAUW support on MD.
313 /// If this is an unresolved MDNode, RAUW support will be created on-demand.
314 /// ValueAsMetadata always has RAUW support.
315 static ReplaceableMetadataImpl *getOrCreate(Metadata &MD);
317 /// Get RAUW support on MD, if it exists.
318 static ReplaceableMetadataImpl *getIfExists(Metadata &MD);
320 /// Check whether this node will support RAUW.
322 /// Returns \c true unless getOrCreate() would return null.
323 static bool isReplaceable(const Metadata &MD);
326 /// \brief Value wrapper in the Metadata hierarchy.
328 /// This is a custom value handle that allows other metadata to refer to
329 /// classes in the Value hierarchy.
331 /// Because of full uniquing support, each value is only wrapped by a single \a
332 /// ValueAsMetadata object, so the lookup maps are far more efficient than
333 /// those using ValueHandleBase.
334 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
335 friend class ReplaceableMetadataImpl;
336 friend class LLVMContextImpl;
340 /// \brief Drop users without RAUW (during teardown).
342 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
346 ValueAsMetadata(unsigned ID, Value *V)
347 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
348 assert(V && "Expected valid value");
351 ~ValueAsMetadata() = default;
354 static ValueAsMetadata *get(Value *V);
355 static ConstantAsMetadata *getConstant(Value *C) {
356 return cast<ConstantAsMetadata>(get(C));
358 static LocalAsMetadata *getLocal(Value *Local) {
359 return cast<LocalAsMetadata>(get(Local));
362 static ValueAsMetadata *getIfExists(Value *V);
363 static ConstantAsMetadata *getConstantIfExists(Value *C) {
364 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
366 static LocalAsMetadata *getLocalIfExists(Value *Local) {
367 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
370 Value *getValue() const { return V; }
371 Type *getType() const { return V->getType(); }
372 LLVMContext &getContext() const { return V->getContext(); }
374 static void handleDeletion(Value *V);
375 static void handleRAUW(Value *From, Value *To);
378 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
380 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
381 /// \a Value gets RAUW'ed and the target already exists, this is used to
382 /// merge the two metadata nodes.
383 void replaceAllUsesWith(Metadata *MD) {
384 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
388 static bool classof(const Metadata *MD) {
389 return MD->getMetadataID() == LocalAsMetadataKind ||
390 MD->getMetadataID() == ConstantAsMetadataKind;
394 class ConstantAsMetadata : public ValueAsMetadata {
395 friend class ValueAsMetadata;
397 ConstantAsMetadata(Constant *C)
398 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
401 static ConstantAsMetadata *get(Constant *C) {
402 return ValueAsMetadata::getConstant(C);
405 static ConstantAsMetadata *getIfExists(Constant *C) {
406 return ValueAsMetadata::getConstantIfExists(C);
409 Constant *getValue() const {
410 return cast<Constant>(ValueAsMetadata::getValue());
413 static bool classof(const Metadata *MD) {
414 return MD->getMetadataID() == ConstantAsMetadataKind;
418 class LocalAsMetadata : public ValueAsMetadata {
419 friend class ValueAsMetadata;
421 LocalAsMetadata(Value *Local)
422 : ValueAsMetadata(LocalAsMetadataKind, Local) {
423 assert(!isa<Constant>(Local) && "Expected local value");
427 static LocalAsMetadata *get(Value *Local) {
428 return ValueAsMetadata::getLocal(Local);
431 static LocalAsMetadata *getIfExists(Value *Local) {
432 return ValueAsMetadata::getLocalIfExists(Local);
435 static bool classof(const Metadata *MD) {
436 return MD->getMetadataID() == LocalAsMetadataKind;
440 /// \brief Transitional API for extracting constants from Metadata.
442 /// This namespace contains transitional functions for metadata that points to
445 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
446 /// operands could refer to any \a Value. There's was a lot of code like this:
450 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
453 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
454 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
455 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
456 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
457 /// requires subtle control flow changes.
459 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
460 /// so that metadata can refer to numbers without traversing a bridge to the \a
461 /// Value hierarchy. In this final state, the code above would look like this:
465 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
468 /// The API in this namespace supports the transition. \a MDInt doesn't exist
469 /// yet, and even once it does, changing each metadata schema to use it is its
470 /// own mini-project. In the meantime this API prevents us from introducing
471 /// complex and bug-prone control flow that will disappear in the end. In
472 /// particular, the above code looks like this:
476 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
479 /// The full set of provided functions includes:
481 /// mdconst::hasa <=> isa
482 /// mdconst::extract <=> cast
483 /// mdconst::extract_or_null <=> cast_or_null
484 /// mdconst::dyn_extract <=> dyn_cast
485 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
487 /// The target of the cast must be a subclass of \a Constant.
492 template <class T> T &make();
493 template <class T, class Result> struct HasDereference {
496 template <size_t N> struct SFINAE {};
498 template <class U, class V>
499 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
500 template <class U, class V> static No &hasDereference(...);
502 static const bool value =
503 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
505 template <class V, class M> struct IsValidPointer {
506 static const bool value = std::is_base_of<Constant, V>::value &&
507 HasDereference<M, const Metadata &>::value;
509 template <class V, class M> struct IsValidReference {
510 static const bool value = std::is_base_of<Constant, V>::value &&
511 std::is_convertible<M, const Metadata &>::value;
514 } // end namespace detail
516 /// \brief Check whether Metadata has a Value.
518 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
520 template <class X, class Y>
521 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
523 assert(MD && "Null pointer sent into hasa");
524 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
525 return isa<X>(V->getValue());
528 template <class X, class Y>
530 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
535 /// \brief Extract a Value from Metadata.
537 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
538 template <class X, class Y>
539 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
541 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
543 template <class X, class Y>
545 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
550 /// \brief Extract a Value from Metadata, allowing null.
552 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
553 /// from \c MD, allowing \c MD to be null.
554 template <class X, class Y>
555 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
556 extract_or_null(Y &&MD) {
557 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
558 return cast<X>(V->getValue());
562 /// \brief Extract a Value from Metadata, if any.
564 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
565 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
566 /// Value it does contain is of the wrong subclass.
567 template <class X, class Y>
568 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
569 dyn_extract(Y &&MD) {
570 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
571 return dyn_cast<X>(V->getValue());
575 /// \brief Extract a Value from Metadata, if any, allowing null.
577 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
578 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
579 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
580 template <class X, class Y>
581 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
582 dyn_extract_or_null(Y &&MD) {
583 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
584 return dyn_cast<X>(V->getValue());
588 } // end namespace mdconst
590 //===----------------------------------------------------------------------===//
591 /// \brief A single uniqued string.
593 /// These are used to efficiently contain a byte sequence for metadata.
594 /// MDString is always unnamed.
595 class MDString : public Metadata {
596 friend class StringMapEntry<MDString>;
598 StringMapEntry<MDString> *Entry = nullptr;
600 MDString() : Metadata(MDStringKind, Uniqued) {}
603 MDString(const MDString &) = delete;
604 MDString &operator=(MDString &&) = delete;
605 MDString &operator=(const MDString &) = delete;
607 static MDString *get(LLVMContext &Context, StringRef Str);
608 static MDString *get(LLVMContext &Context, const char *Str) {
609 return get(Context, Str ? StringRef(Str) : StringRef());
612 StringRef getString() const;
614 unsigned getLength() const { return (unsigned)getString().size(); }
616 typedef StringRef::iterator iterator;
618 /// \brief Pointer to the first byte of the string.
619 iterator begin() const { return getString().begin(); }
621 /// \brief Pointer to one byte past the end of the string.
622 iterator end() const { return getString().end(); }
624 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
625 const unsigned char *bytes_end() const { return getString().bytes_end(); }
627 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
628 static bool classof(const Metadata *MD) {
629 return MD->getMetadataID() == MDStringKind;
633 /// \brief A collection of metadata nodes that might be associated with a
634 /// memory access used by the alias-analysis infrastructure.
636 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
638 : TBAA(T), Scope(S), NoAlias(N) {}
640 bool operator==(const AAMDNodes &A) const {
641 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
644 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
646 explicit operator bool() const { return TBAA || Scope || NoAlias; }
648 /// \brief The tag for type-based alias analysis.
651 /// \brief The tag for alias scope specification (used with noalias).
654 /// \brief The tag specifying the noalias scope.
658 // Specialize DenseMapInfo for AAMDNodes.
660 struct DenseMapInfo<AAMDNodes> {
661 static inline AAMDNodes getEmptyKey() {
662 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
666 static inline AAMDNodes getTombstoneKey() {
667 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
671 static unsigned getHashValue(const AAMDNodes &Val) {
672 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
673 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
674 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
677 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
682 /// \brief Tracking metadata reference owned by Metadata.
684 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
685 /// of \a Metadata, which has the option of registering itself for callbacks to
686 /// re-unique itself.
688 /// In particular, this is used by \a MDNode.
690 Metadata *MD = nullptr;
693 MDOperand() = default;
694 MDOperand(MDOperand &&) = delete;
695 MDOperand(const MDOperand &) = delete;
696 MDOperand &operator=(MDOperand &&) = delete;
697 MDOperand &operator=(const MDOperand &) = delete;
698 ~MDOperand() { untrack(); }
700 Metadata *get() const { return MD; }
701 operator Metadata *() const { return get(); }
702 Metadata *operator->() const { return get(); }
703 Metadata &operator*() const { return *get(); }
709 void reset(Metadata *MD, Metadata *Owner) {
716 void track(Metadata *Owner) {
719 MetadataTracking::track(this, *MD, *Owner);
721 MetadataTracking::track(MD);
726 assert(static_cast<void *>(this) == &MD && "Expected same address");
728 MetadataTracking::untrack(MD);
732 template <> struct simplify_type<MDOperand> {
733 typedef Metadata *SimpleType;
734 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
737 template <> struct simplify_type<const MDOperand> {
738 typedef Metadata *SimpleType;
739 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
742 /// \brief Pointer to the context, with optional RAUW support.
744 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
745 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
746 class ContextAndReplaceableUses {
747 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
750 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
751 ContextAndReplaceableUses(
752 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
753 : Ptr(ReplaceableUses.release()) {
754 assert(getReplaceableUses() && "Expected non-null replaceable uses");
756 ContextAndReplaceableUses() = delete;
757 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
758 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
759 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
760 ContextAndReplaceableUses &
761 operator=(const ContextAndReplaceableUses &) = delete;
762 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
764 operator LLVMContext &() { return getContext(); }
766 /// \brief Whether this contains RAUW support.
767 bool hasReplaceableUses() const {
768 return Ptr.is<ReplaceableMetadataImpl *>();
771 LLVMContext &getContext() const {
772 if (hasReplaceableUses())
773 return getReplaceableUses()->getContext();
774 return *Ptr.get<LLVMContext *>();
777 ReplaceableMetadataImpl *getReplaceableUses() const {
778 if (hasReplaceableUses())
779 return Ptr.get<ReplaceableMetadataImpl *>();
783 /// Ensure that this has RAUW support, and then return it.
784 ReplaceableMetadataImpl *getOrCreateReplaceableUses() {
785 if (!hasReplaceableUses())
786 makeReplaceable(llvm::make_unique<ReplaceableMetadataImpl>(getContext()));
787 return getReplaceableUses();
790 /// \brief Assign RAUW support to this.
792 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
795 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
796 assert(ReplaceableUses && "Expected non-null replaceable uses");
797 assert(&ReplaceableUses->getContext() == &getContext() &&
798 "Expected same context");
799 delete getReplaceableUses();
800 Ptr = ReplaceableUses.release();
803 /// \brief Drop RAUW support.
805 /// Cede ownership of RAUW support, returning it.
806 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
807 assert(hasReplaceableUses() && "Expected to own replaceable uses");
808 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
809 getReplaceableUses());
810 Ptr = &ReplaceableUses->getContext();
811 return ReplaceableUses;
815 struct TempMDNodeDeleter {
816 inline void operator()(MDNode *Node) const;
819 #define HANDLE_MDNODE_LEAF(CLASS) \
820 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
821 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
822 #include "llvm/IR/Metadata.def"
824 /// \brief Metadata node.
826 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
827 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
828 /// until forward references are known. The basic metadata node is an \a
831 /// There is limited support for RAUW at construction time. At construction
832 /// time, if any operand is a temporary node (or an unresolved uniqued node,
833 /// which indicates a transitive temporary operand), the node itself will be
834 /// unresolved. As soon as all operands become resolved, it will drop RAUW
835 /// support permanently.
837 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
838 /// to be called on some member of the cycle once all temporary nodes have been
840 class MDNode : public Metadata {
841 friend class ReplaceableMetadataImpl;
842 friend class LLVMContextImpl;
844 unsigned NumOperands;
845 unsigned NumUnresolved;
847 ContextAndReplaceableUses Context;
850 void *operator new(size_t Size, unsigned NumOps);
851 void operator delete(void *Mem);
853 /// \brief Required by std, but never called.
854 void operator delete(void *, unsigned) {
855 llvm_unreachable("Constructor throws?");
858 /// \brief Required by std, but never called.
859 void operator delete(void *, unsigned, bool) {
860 llvm_unreachable("Constructor throws?");
863 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
864 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
867 void dropAllReferences();
869 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
870 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
872 typedef iterator_range<MDOperand *> mutable_op_range;
873 mutable_op_range mutable_operands() {
874 return mutable_op_range(mutable_begin(), mutable_end());
878 MDNode(const MDNode &) = delete;
879 void operator=(const MDNode &) = delete;
880 void *operator new(size_t) = delete;
882 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
883 static inline MDTuple *getIfExists(LLVMContext &Context,
884 ArrayRef<Metadata *> MDs);
885 static inline MDTuple *getDistinct(LLVMContext &Context,
886 ArrayRef<Metadata *> MDs);
887 static inline TempMDTuple getTemporary(LLVMContext &Context,
888 ArrayRef<Metadata *> MDs);
890 /// \brief Create a (temporary) clone of this.
891 TempMDNode clone() const;
893 /// \brief Deallocate a node created by getTemporary.
895 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
896 /// references will be reset.
897 static void deleteTemporary(MDNode *N);
899 LLVMContext &getContext() const { return Context.getContext(); }
901 /// \brief Replace a specific operand.
902 void replaceOperandWith(unsigned I, Metadata *New);
904 /// \brief Check if node is fully resolved.
906 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
907 /// this always returns \c true.
909 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
910 /// support (because all operands are resolved).
912 /// As forward declarations are resolved, their containers should get
913 /// resolved automatically. However, if this (or one of its operands) is
914 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
915 bool isResolved() const { return !isTemporary() && !NumUnresolved; }
917 bool isUniqued() const { return Storage == Uniqued; }
918 bool isDistinct() const { return Storage == Distinct; }
919 bool isTemporary() const { return Storage == Temporary; }
921 /// \brief RAUW a temporary.
923 /// \pre \a isTemporary() must be \c true.
924 void replaceAllUsesWith(Metadata *MD) {
925 assert(isTemporary() && "Expected temporary node");
926 if (Context.hasReplaceableUses())
927 Context.getReplaceableUses()->replaceAllUsesWith(MD);
930 /// \brief Resolve cycles.
932 /// Once all forward declarations have been resolved, force cycles to be
935 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
936 void resolveCycles();
938 /// \brief Replace a temporary node with a permanent one.
940 /// Try to create a uniqued version of \c N -- in place, if possible -- and
941 /// return it. If \c N cannot be uniqued, return a distinct node instead.
943 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
944 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
945 return cast<T>(N.release()->replaceWithPermanentImpl());
948 /// \brief Replace a temporary node with a uniqued one.
950 /// Create a uniqued version of \c N -- in place, if possible -- and return
951 /// it. Takes ownership of the temporary node.
953 /// \pre N does not self-reference.
955 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
956 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
957 return cast<T>(N.release()->replaceWithUniquedImpl());
960 /// \brief Replace a temporary node with a distinct one.
962 /// Create a distinct version of \c N -- in place, if possible -- and return
963 /// it. Takes ownership of the temporary node.
965 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
966 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
967 return cast<T>(N.release()->replaceWithDistinctImpl());
971 MDNode *replaceWithPermanentImpl();
972 MDNode *replaceWithUniquedImpl();
973 MDNode *replaceWithDistinctImpl();
976 /// \brief Set an operand.
978 /// Sets the operand directly, without worrying about uniquing.
979 void setOperand(unsigned I, Metadata *New);
981 void storeDistinctInContext();
982 template <class T, class StoreT>
983 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
984 template <class T> static T *storeImpl(T *N, StorageType Storage);
987 void handleChangedOperand(void *Ref, Metadata *New);
989 /// Resolve a unique, unresolved node.
992 /// Drop RAUW support, if any.
993 void dropReplaceableUses();
995 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
996 void decrementUnresolvedOperandCount();
997 void countUnresolvedOperands();
999 /// \brief Mutate this to be "uniqued".
1001 /// Mutate this so that \a isUniqued().
1002 /// \pre \a isTemporary().
1003 /// \pre already added to uniquing set.
1006 /// \brief Mutate this to be "distinct".
1008 /// Mutate this so that \a isDistinct().
1009 /// \pre \a isTemporary().
1010 void makeDistinct();
1012 void deleteAsSubclass();
1014 void eraseFromStore();
1016 template <class NodeTy> struct HasCachedHash;
1017 template <class NodeTy>
1018 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
1019 N->recalculateHash();
1021 template <class NodeTy>
1022 static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
1023 template <class NodeTy>
1024 static void dispatchResetHash(NodeTy *N, std::true_type) {
1027 template <class NodeTy>
1028 static void dispatchResetHash(NodeTy *, std::false_type) {}
1031 typedef const MDOperand *op_iterator;
1032 typedef iterator_range<op_iterator> op_range;
1034 op_iterator op_begin() const {
1035 return const_cast<MDNode *>(this)->mutable_begin();
1038 op_iterator op_end() const {
1039 return const_cast<MDNode *>(this)->mutable_end();
1042 op_range operands() const { return op_range(op_begin(), op_end()); }
1044 const MDOperand &getOperand(unsigned I) const {
1045 assert(I < NumOperands && "Out of range");
1046 return op_begin()[I];
1049 /// \brief Return number of MDNode operands.
1050 unsigned getNumOperands() const { return NumOperands; }
1052 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
1053 static bool classof(const Metadata *MD) {
1054 switch (MD->getMetadataID()) {
1057 #define HANDLE_MDNODE_LEAF(CLASS) \
1060 #include "llvm/IR/Metadata.def"
1064 /// \brief Check whether MDNode is a vtable access.
1065 bool isTBAAVtableAccess() const;
1067 /// \brief Methods for metadata merging.
1068 static MDNode *concatenate(MDNode *A, MDNode *B);
1069 static MDNode *intersect(MDNode *A, MDNode *B);
1070 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
1071 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
1072 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
1073 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
1074 static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B);
1077 /// \brief Tuple of metadata.
1079 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
1080 /// default based on their operands.
1081 class MDTuple : public MDNode {
1082 friend class LLVMContextImpl;
1083 friend class MDNode;
1085 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1086 ArrayRef<Metadata *> Vals)
1087 : MDNode(C, MDTupleKind, Storage, Vals) {
1091 ~MDTuple() { dropAllReferences(); }
1093 void setHash(unsigned Hash) { SubclassData32 = Hash; }
1094 void recalculateHash();
1096 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
1097 StorageType Storage, bool ShouldCreate = true);
1099 TempMDTuple cloneImpl() const {
1100 return getTemporary(getContext(),
1101 SmallVector<Metadata *, 4>(op_begin(), op_end()));
1105 /// \brief Get the hash, if any.
1106 unsigned getHash() const { return SubclassData32; }
1108 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1109 return getImpl(Context, MDs, Uniqued);
1112 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1113 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1116 /// \brief Return a distinct node.
1118 /// Return a distinct node -- i.e., a node that is not uniqued.
1119 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1120 return getImpl(Context, MDs, Distinct);
1123 /// \brief Return a temporary node.
1125 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1126 /// not uniqued, may be RAUW'd, and must be manually deleted with
1127 /// deleteTemporary.
1128 static TempMDTuple getTemporary(LLVMContext &Context,
1129 ArrayRef<Metadata *> MDs) {
1130 return TempMDTuple(getImpl(Context, MDs, Temporary));
1133 /// \brief Return a (temporary) clone of this.
1134 TempMDTuple clone() const { return cloneImpl(); }
1136 static bool classof(const Metadata *MD) {
1137 return MD->getMetadataID() == MDTupleKind;
1141 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1142 return MDTuple::get(Context, MDs);
1145 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1146 return MDTuple::getIfExists(Context, MDs);
1149 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1150 return MDTuple::getDistinct(Context, MDs);
1153 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1154 ArrayRef<Metadata *> MDs) {
1155 return MDTuple::getTemporary(Context, MDs);
1158 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1159 MDNode::deleteTemporary(Node);
1162 /// \brief Typed iterator through MDNode operands.
1164 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1165 /// particular Metadata subclass.
1167 class TypedMDOperandIterator
1168 : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
1169 MDNode::op_iterator I = nullptr;
1172 TypedMDOperandIterator() = default;
1173 explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1175 T *operator*() const { return cast_or_null<T>(*I); }
1177 TypedMDOperandIterator &operator++() {
1182 TypedMDOperandIterator operator++(int) {
1183 TypedMDOperandIterator Temp(*this);
1188 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1189 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1192 /// \brief Typed, array-like tuple of metadata.
1194 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1195 /// particular type of metadata.
1196 template <class T> class MDTupleTypedArrayWrapper {
1197 const MDTuple *N = nullptr;
1200 MDTupleTypedArrayWrapper() = default;
1201 MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1204 MDTupleTypedArrayWrapper(
1205 const MDTupleTypedArrayWrapper<U> &Other,
1206 typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
1211 explicit MDTupleTypedArrayWrapper(
1212 const MDTupleTypedArrayWrapper<U> &Other,
1213 typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
1217 explicit operator bool() const { return get(); }
1218 explicit operator MDTuple *() const { return get(); }
1220 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1221 MDTuple *operator->() const { return get(); }
1222 MDTuple &operator*() const { return *get(); }
1224 // FIXME: Fix callers and remove condition on N.
1225 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1226 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1228 // FIXME: Fix callers and remove condition on N.
1229 typedef TypedMDOperandIterator<T> iterator;
1230 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1231 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1234 #define HANDLE_METADATA(CLASS) \
1235 typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
1236 #include "llvm/IR/Metadata.def"
1238 /// Placeholder metadata for operands of distinct MDNodes.
1240 /// This is a lightweight placeholder for an operand of a distinct node. It's
1241 /// purpose is to help track forward references when creating a distinct node.
1242 /// This allows distinct nodes involved in a cycle to be constructed before
1243 /// their operands without requiring a heavyweight temporary node with
1244 /// full-blown RAUW support.
1246 /// Each placeholder supports only a single MDNode user. Clients should pass
1247 /// an ID, retrieved via \a getID(), to indicate the "real" operand that this
1248 /// should be replaced with.
1250 /// While it would be possible to implement move operators, they would be
1251 /// fairly expensive. Leave them unimplemented to discourage their use
1252 /// (clients can use std::deque, std::list, BumpPtrAllocator, etc.).
1253 class DistinctMDOperandPlaceholder : public Metadata {
1254 friend class MetadataTracking;
1256 Metadata **Use = nullptr;
1259 explicit DistinctMDOperandPlaceholder(unsigned ID)
1260 : Metadata(DistinctMDOperandPlaceholderKind, Distinct) {
1261 SubclassData32 = ID;
1264 DistinctMDOperandPlaceholder() = delete;
1265 DistinctMDOperandPlaceholder(DistinctMDOperandPlaceholder &&) = delete;
1266 DistinctMDOperandPlaceholder(const DistinctMDOperandPlaceholder &) = delete;
1268 ~DistinctMDOperandPlaceholder() {
1273 unsigned getID() const { return SubclassData32; }
1275 /// Replace the use of this with MD.
1276 void replaceUseWith(Metadata *MD) {
1284 //===----------------------------------------------------------------------===//
1285 /// \brief A tuple of MDNodes.
1287 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1288 /// to modules, have names, and contain lists of MDNodes.
1290 /// TODO: Inherit from Metadata.
1291 class NamedMDNode : public ilist_node<NamedMDNode> {
1292 friend class LLVMContextImpl;
1293 friend class Module;
1296 Module *Parent = nullptr;
1297 void *Operands; // SmallVector<TrackingMDRef, 4>
1299 void setParent(Module *M) { Parent = M; }
1301 explicit NamedMDNode(const Twine &N);
1303 template<class T1, class T2>
1304 class op_iterator_impl :
1305 public std::iterator<std::bidirectional_iterator_tag, T2> {
1306 const NamedMDNode *Node = nullptr;
1309 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1311 friend class NamedMDNode;
1314 op_iterator_impl() = default;
1316 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1317 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1319 op_iterator_impl &operator++() {
1324 op_iterator_impl operator++(int) {
1325 op_iterator_impl tmp(*this);
1330 op_iterator_impl &operator--() {
1335 op_iterator_impl operator--(int) {
1336 op_iterator_impl tmp(*this);
1341 T1 operator*() const { return Node->getOperand(Idx); }
1345 NamedMDNode(const NamedMDNode &) = delete;
1348 /// \brief Drop all references and remove the node from parent module.
1349 void eraseFromParent();
1351 /// Remove all uses and clear node vector.
1352 void dropAllReferences() { clearOperands(); }
1353 /// Drop all references to this node's operands.
1354 void clearOperands();
1356 /// \brief Get the module that holds this named metadata collection.
1357 inline Module *getParent() { return Parent; }
1358 inline const Module *getParent() const { return Parent; }
1360 MDNode *getOperand(unsigned i) const;
1361 unsigned getNumOperands() const;
1362 void addOperand(MDNode *M);
1363 void setOperand(unsigned I, MDNode *New);
1364 StringRef getName() const;
1365 void print(raw_ostream &ROS, bool IsForDebug = false) const;
1366 void print(raw_ostream &ROS, ModuleSlotTracker &MST,
1367 bool IsForDebug = false) const;
1370 // ---------------------------------------------------------------------------
1371 // Operand Iterator interface...
1373 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1374 op_iterator op_begin() { return op_iterator(this, 0); }
1375 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1377 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1378 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1379 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1381 inline iterator_range<op_iterator> operands() {
1382 return make_range(op_begin(), op_end());
1384 inline iterator_range<const_op_iterator> operands() const {
1385 return make_range(op_begin(), op_end());
1389 } // end namespace llvm
1391 #endif // LLVM_IR_METADATA_H