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 enum LLVMConstants : uint32_t {
36 DEBUG_METADATA_VERSION = 3 // Current debug info version number.
39 /// \brief Root of the metadata hierarchy.
41 /// This is a root class for typeless data in the IR.
43 friend class ReplaceableMetadataImpl;
46 const unsigned char SubclassID;
49 /// \brief Active type of storage.
50 enum StorageType { Uniqued, Distinct, Temporary };
52 /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
54 // TODO: expose remaining bits to subclasses.
56 unsigned short SubclassData16;
57 unsigned SubclassData32;
74 DILexicalBlockFileKind,
77 DITemplateTypeParameterKind,
78 DITemplateValueParameterKind,
84 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,
129 bool IsForDebug = false) const;
130 void print(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr,
131 bool IsForDebug = false) const;
134 /// \brief Print as operand.
136 /// Prints reference of \c this.
138 /// If \c M is provided, metadata nodes will be numbered canonically;
139 /// otherwise, pointer addresses are substituted.
141 void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
142 void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
143 const Module *M = nullptr) const;
147 #define HANDLE_METADATA(CLASS) class CLASS;
148 #include "llvm/IR/Metadata.def"
150 // Provide specializations of isa so that we don't need definitions of
151 // subclasses to see if the metadata is a subclass.
152 #define HANDLE_METADATA_LEAF(CLASS) \
153 template <> struct isa_impl<CLASS, Metadata> { \
154 static inline bool doit(const Metadata &MD) { \
155 return MD.getMetadataID() == Metadata::CLASS##Kind; \
158 #include "llvm/IR/Metadata.def"
160 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
165 /// \brief Metadata wrapper in the Value hierarchy.
167 /// A member of the \a Value hierarchy to represent a reference to metadata.
168 /// This allows, e.g., instrinsics to have metadata as operands.
170 /// Notably, this is the only thing in either hierarchy that is allowed to
171 /// reference \a LocalAsMetadata.
172 class MetadataAsValue : public Value {
173 friend class ReplaceableMetadataImpl;
174 friend class LLVMContextImpl;
178 MetadataAsValue(Type *Ty, Metadata *MD);
179 ~MetadataAsValue() override;
181 /// \brief Drop use of metadata (during teardown).
182 void dropUse() { MD = nullptr; }
185 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
186 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
187 Metadata *getMetadata() const { return MD; }
189 static bool classof(const Value *V) {
190 return V->getValueID() == MetadataAsValueVal;
194 void handleChangedMetadata(Metadata *MD);
199 /// \brief Shared implementation of use-lists for replaceable metadata.
201 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
202 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
203 /// and \a TempMDNode).
204 class ReplaceableMetadataImpl {
205 friend class MetadataTracking;
208 typedef MetadataTracking::OwnerTy OwnerTy;
211 LLVMContext &Context;
213 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
216 ReplaceableMetadataImpl(LLVMContext &Context)
217 : Context(Context), NextIndex(0) {}
218 ~ReplaceableMetadataImpl() {
219 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
222 LLVMContext &getContext() const { return Context; }
224 /// \brief Replace all uses of this with MD.
226 /// Replace all uses of this with \c MD, which is allowed to be null.
227 void replaceAllUsesWith(Metadata *MD);
229 /// \brief Resolve all uses of this.
231 /// Resolve all uses of this, turning off RAUW permanently. If \c
232 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
234 void resolveAllUses(bool ResolveUsers = true);
237 void addRef(void *Ref, OwnerTy Owner);
238 void dropRef(void *Ref);
239 void moveRef(void *Ref, void *New, const Metadata &MD);
241 static ReplaceableMetadataImpl *get(Metadata &MD);
244 /// \brief Value wrapper in the Metadata hierarchy.
246 /// This is a custom value handle that allows other metadata to refer to
247 /// classes in the Value hierarchy.
249 /// Because of full uniquing support, each value is only wrapped by a single \a
250 /// ValueAsMetadata object, so the lookup maps are far more efficient than
251 /// those using ValueHandleBase.
252 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
253 friend class ReplaceableMetadataImpl;
254 friend class LLVMContextImpl;
258 /// \brief Drop users without RAUW (during teardown).
260 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
264 ValueAsMetadata(unsigned ID, Value *V)
265 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
266 assert(V && "Expected valid value");
268 ~ValueAsMetadata() = default;
271 static ValueAsMetadata *get(Value *V);
272 static ConstantAsMetadata *getConstant(Value *C) {
273 return cast<ConstantAsMetadata>(get(C));
275 static LocalAsMetadata *getLocal(Value *Local) {
276 return cast<LocalAsMetadata>(get(Local));
279 static ValueAsMetadata *getIfExists(Value *V);
280 static ConstantAsMetadata *getConstantIfExists(Value *C) {
281 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
283 static LocalAsMetadata *getLocalIfExists(Value *Local) {
284 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
287 Value *getValue() const { return V; }
288 Type *getType() const { return V->getType(); }
289 LLVMContext &getContext() const { return V->getContext(); }
291 static void handleDeletion(Value *V);
292 static void handleRAUW(Value *From, Value *To);
295 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
297 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
298 /// \a Value gets RAUW'ed and the target already exists, this is used to
299 /// merge the two metadata nodes.
300 void replaceAllUsesWith(Metadata *MD) {
301 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
305 static bool classof(const Metadata *MD) {
306 return MD->getMetadataID() == LocalAsMetadataKind ||
307 MD->getMetadataID() == ConstantAsMetadataKind;
311 class ConstantAsMetadata : public ValueAsMetadata {
312 friend class ValueAsMetadata;
314 ConstantAsMetadata(Constant *C)
315 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
318 static ConstantAsMetadata *get(Constant *C) {
319 return ValueAsMetadata::getConstant(C);
321 static ConstantAsMetadata *getIfExists(Constant *C) {
322 return ValueAsMetadata::getConstantIfExists(C);
325 Constant *getValue() const {
326 return cast<Constant>(ValueAsMetadata::getValue());
329 static bool classof(const Metadata *MD) {
330 return MD->getMetadataID() == ConstantAsMetadataKind;
334 class LocalAsMetadata : public ValueAsMetadata {
335 friend class ValueAsMetadata;
337 LocalAsMetadata(Value *Local)
338 : ValueAsMetadata(LocalAsMetadataKind, Local) {
339 assert(!isa<Constant>(Local) && "Expected local value");
343 static LocalAsMetadata *get(Value *Local) {
344 return ValueAsMetadata::getLocal(Local);
346 static LocalAsMetadata *getIfExists(Value *Local) {
347 return ValueAsMetadata::getLocalIfExists(Local);
350 static bool classof(const Metadata *MD) {
351 return MD->getMetadataID() == LocalAsMetadataKind;
355 /// \brief Transitional API for extracting constants from Metadata.
357 /// This namespace contains transitional functions for metadata that points to
360 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
361 /// operands could refer to any \a Value. There's was a lot of code like this:
365 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
368 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
369 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
370 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
371 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
372 /// requires subtle control flow changes.
374 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
375 /// so that metadata can refer to numbers without traversing a bridge to the \a
376 /// Value hierarchy. In this final state, the code above would look like this:
380 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
383 /// The API in this namespace supports the transition. \a MDInt doesn't exist
384 /// yet, and even once it does, changing each metadata schema to use it is its
385 /// own mini-project. In the meantime this API prevents us from introducing
386 /// complex and bug-prone control flow that will disappear in the end. In
387 /// particular, the above code looks like this:
391 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
394 /// The full set of provided functions includes:
396 /// mdconst::hasa <=> isa
397 /// mdconst::extract <=> cast
398 /// mdconst::extract_or_null <=> cast_or_null
399 /// mdconst::dyn_extract <=> dyn_cast
400 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
402 /// The target of the cast must be a subclass of \a Constant.
406 template <class T> T &make();
407 template <class T, class Result> struct HasDereference {
410 template <size_t N> struct SFINAE {};
412 template <class U, class V>
413 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
414 template <class U, class V> static No &hasDereference(...);
416 static const bool value =
417 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
419 template <class V, class M> struct IsValidPointer {
420 static const bool value = std::is_base_of<Constant, V>::value &&
421 HasDereference<M, const Metadata &>::value;
423 template <class V, class M> struct IsValidReference {
424 static const bool value = std::is_base_of<Constant, V>::value &&
425 std::is_convertible<M, const Metadata &>::value;
427 } // end namespace detail
429 /// \brief Check whether Metadata has a Value.
431 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
433 template <class X, class Y>
434 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
436 assert(MD && "Null pointer sent into hasa");
437 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
438 return isa<X>(V->getValue());
441 template <class X, class Y>
443 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
448 /// \brief Extract a Value from Metadata.
450 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
451 template <class X, class Y>
452 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
454 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
456 template <class X, class Y>
458 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
463 /// \brief Extract a Value from Metadata, allowing null.
465 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
466 /// from \c MD, allowing \c MD to be null.
467 template <class X, class Y>
468 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
469 extract_or_null(Y &&MD) {
470 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
471 return cast<X>(V->getValue());
475 /// \brief Extract a Value from Metadata, if any.
477 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
478 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
479 /// Value it does contain is of the wrong subclass.
480 template <class X, class Y>
481 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
482 dyn_extract(Y &&MD) {
483 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
484 return dyn_cast<X>(V->getValue());
488 /// \brief Extract a Value from Metadata, if any, allowing null.
490 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
491 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
492 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
493 template <class X, class Y>
494 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
495 dyn_extract_or_null(Y &&MD) {
496 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
497 return dyn_cast<X>(V->getValue());
501 } // end namespace mdconst
503 //===----------------------------------------------------------------------===//
504 /// \brief A single uniqued string.
506 /// These are used to efficiently contain a byte sequence for metadata.
507 /// MDString is always unnamed.
508 class MDString : public Metadata {
509 friend class StringMapEntry<MDString>;
511 MDString(const MDString &) = delete;
512 MDString &operator=(MDString &&) = delete;
513 MDString &operator=(const MDString &) = delete;
515 StringMapEntry<MDString> *Entry;
516 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
517 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
520 static MDString *get(LLVMContext &Context, StringRef Str);
521 static MDString *get(LLVMContext &Context, const char *Str) {
522 return get(Context, Str ? StringRef(Str) : StringRef());
525 StringRef getString() const;
527 unsigned getLength() const { return (unsigned)getString().size(); }
529 typedef StringRef::iterator iterator;
531 /// \brief Pointer to the first byte of the string.
532 iterator begin() const { return getString().begin(); }
534 /// \brief Pointer to one byte past the end of the string.
535 iterator end() const { return getString().end(); }
537 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
538 const unsigned char *bytes_end() const { return getString().bytes_end(); }
540 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
541 static bool classof(const Metadata *MD) {
542 return MD->getMetadataID() == MDStringKind;
546 /// \brief A collection of metadata nodes that might be associated with a
547 /// memory access used by the alias-analysis infrastructure.
549 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
551 : TBAA(T), Scope(S), NoAlias(N) {}
553 bool operator==(const AAMDNodes &A) const {
554 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
557 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
559 explicit operator bool() const { return TBAA || Scope || NoAlias; }
561 /// \brief The tag for type-based alias analysis.
564 /// \brief The tag for alias scope specification (used with noalias).
567 /// \brief The tag specifying the noalias scope.
571 // Specialize DenseMapInfo for AAMDNodes.
573 struct DenseMapInfo<AAMDNodes> {
574 static inline AAMDNodes getEmptyKey() {
575 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
578 static inline AAMDNodes getTombstoneKey() {
579 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
582 static unsigned getHashValue(const AAMDNodes &Val) {
583 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
584 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
585 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
587 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
592 /// \brief Tracking metadata reference owned by Metadata.
594 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
595 /// of \a Metadata, which has the option of registering itself for callbacks to
596 /// re-unique itself.
598 /// In particular, this is used by \a MDNode.
600 MDOperand(MDOperand &&) = delete;
601 MDOperand(const MDOperand &) = delete;
602 MDOperand &operator=(MDOperand &&) = delete;
603 MDOperand &operator=(const MDOperand &) = delete;
608 MDOperand() : MD(nullptr) {}
609 ~MDOperand() { untrack(); }
611 Metadata *get() const { return MD; }
612 operator Metadata *() const { return get(); }
613 Metadata *operator->() const { return get(); }
614 Metadata &operator*() const { return *get(); }
620 void reset(Metadata *MD, Metadata *Owner) {
627 void track(Metadata *Owner) {
630 MetadataTracking::track(this, *MD, *Owner);
632 MetadataTracking::track(MD);
636 assert(static_cast<void *>(this) == &MD && "Expected same address");
638 MetadataTracking::untrack(MD);
642 template <> struct simplify_type<MDOperand> {
643 typedef Metadata *SimpleType;
644 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
647 template <> struct simplify_type<const MDOperand> {
648 typedef Metadata *SimpleType;
649 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
652 /// \brief Pointer to the context, with optional RAUW support.
654 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
655 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
656 class ContextAndReplaceableUses {
657 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
659 ContextAndReplaceableUses() = delete;
660 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
661 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
662 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
663 ContextAndReplaceableUses &
664 operator=(const ContextAndReplaceableUses &) = delete;
667 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
668 ContextAndReplaceableUses(
669 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
670 : Ptr(ReplaceableUses.release()) {
671 assert(getReplaceableUses() && "Expected non-null replaceable uses");
673 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
675 operator LLVMContext &() { return getContext(); }
677 /// \brief Whether this contains RAUW support.
678 bool hasReplaceableUses() const {
679 return Ptr.is<ReplaceableMetadataImpl *>();
681 LLVMContext &getContext() const {
682 if (hasReplaceableUses())
683 return getReplaceableUses()->getContext();
684 return *Ptr.get<LLVMContext *>();
686 ReplaceableMetadataImpl *getReplaceableUses() const {
687 if (hasReplaceableUses())
688 return Ptr.get<ReplaceableMetadataImpl *>();
692 /// \brief Assign RAUW support to this.
694 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
697 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
698 assert(ReplaceableUses && "Expected non-null replaceable uses");
699 assert(&ReplaceableUses->getContext() == &getContext() &&
700 "Expected same context");
701 delete getReplaceableUses();
702 Ptr = ReplaceableUses.release();
705 /// \brief Drop RAUW support.
707 /// Cede ownership of RAUW support, returning it.
708 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
709 assert(hasReplaceableUses() && "Expected to own replaceable uses");
710 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
711 getReplaceableUses());
712 Ptr = &ReplaceableUses->getContext();
713 return ReplaceableUses;
717 struct TempMDNodeDeleter {
718 inline void operator()(MDNode *Node) const;
721 #define HANDLE_MDNODE_LEAF(CLASS) \
722 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
723 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
724 #include "llvm/IR/Metadata.def"
726 /// \brief Metadata node.
728 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
729 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
730 /// until forward references are known. The basic metadata node is an \a
733 /// There is limited support for RAUW at construction time. At construction
734 /// time, if any operand is a temporary node (or an unresolved uniqued node,
735 /// which indicates a transitive temporary operand), the node itself will be
736 /// unresolved. As soon as all operands become resolved, it will drop RAUW
737 /// support permanently.
739 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
740 /// to be called on some member of the cycle once all temporary nodes have been
742 class MDNode : public Metadata {
743 friend class ReplaceableMetadataImpl;
744 friend class LLVMContextImpl;
746 MDNode(const MDNode &) = delete;
747 void operator=(const MDNode &) = delete;
748 void *operator new(size_t) = delete;
750 unsigned NumOperands;
751 unsigned NumUnresolved;
754 ContextAndReplaceableUses Context;
756 void *operator new(size_t Size, unsigned NumOps);
757 void operator delete(void *Mem);
759 /// \brief Required by std, but never called.
760 void operator delete(void *, unsigned) {
761 llvm_unreachable("Constructor throws?");
764 /// \brief Required by std, but never called.
765 void operator delete(void *, unsigned, bool) {
766 llvm_unreachable("Constructor throws?");
769 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
770 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
773 void dropAllReferences();
775 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
776 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
778 typedef iterator_range<MDOperand *> mutable_op_range;
779 mutable_op_range mutable_operands() {
780 return mutable_op_range(mutable_begin(), mutable_end());
784 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
785 static inline MDTuple *getIfExists(LLVMContext &Context,
786 ArrayRef<Metadata *> MDs);
787 static inline MDTuple *getDistinct(LLVMContext &Context,
788 ArrayRef<Metadata *> MDs);
789 static inline TempMDTuple getTemporary(LLVMContext &Context,
790 ArrayRef<Metadata *> MDs);
792 /// \brief Create a (temporary) clone of this.
793 TempMDNode clone() const;
795 /// \brief Deallocate a node created by getTemporary.
797 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
798 /// references will be reset.
799 static void deleteTemporary(MDNode *N);
801 LLVMContext &getContext() const { return Context.getContext(); }
803 /// \brief Replace a specific operand.
804 void replaceOperandWith(unsigned I, Metadata *New);
806 /// \brief Check if node is fully resolved.
808 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
809 /// this always returns \c true.
811 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
812 /// support (because all operands are resolved).
814 /// As forward declarations are resolved, their containers should get
815 /// resolved automatically. However, if this (or one of its operands) is
816 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
817 bool isResolved() const { return !Context.hasReplaceableUses(); }
819 bool isUniqued() const { return Storage == Uniqued; }
820 bool isDistinct() const { return Storage == Distinct; }
821 bool isTemporary() const { return Storage == Temporary; }
823 /// \brief RAUW a temporary.
825 /// \pre \a isTemporary() must be \c true.
826 void replaceAllUsesWith(Metadata *MD) {
827 assert(isTemporary() && "Expected temporary node");
828 assert(!isResolved() && "Expected RAUW support");
829 Context.getReplaceableUses()->replaceAllUsesWith(MD);
832 /// \brief Resolve cycles.
834 /// Once all forward declarations have been resolved, force cycles to be
835 /// resolved. If \p MDMaterialized is true, then any temporary metadata
836 /// is ignored, otherwise it asserts when encountering temporary metadata.
838 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
839 void resolveCycles(bool MDMaterialized = true);
841 /// \brief Replace a temporary node with a permanent one.
843 /// Try to create a uniqued version of \c N -- in place, if possible -- and
844 /// return it. If \c N cannot be uniqued, return a distinct node instead.
846 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
847 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
848 return cast<T>(N.release()->replaceWithPermanentImpl());
851 /// \brief Replace a temporary node with a uniqued one.
853 /// Create a uniqued version of \c N -- in place, if possible -- and return
854 /// it. Takes ownership of the temporary node.
856 /// \pre N does not self-reference.
858 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
859 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
860 return cast<T>(N.release()->replaceWithUniquedImpl());
863 /// \brief Replace a temporary node with a distinct one.
865 /// Create a distinct version of \c N -- in place, if possible -- and return
866 /// it. Takes ownership of the temporary node.
868 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
869 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
870 return cast<T>(N.release()->replaceWithDistinctImpl());
874 MDNode *replaceWithPermanentImpl();
875 MDNode *replaceWithUniquedImpl();
876 MDNode *replaceWithDistinctImpl();
879 /// \brief Set an operand.
881 /// Sets the operand directly, without worrying about uniquing.
882 void setOperand(unsigned I, Metadata *New);
884 void storeDistinctInContext();
885 template <class T, class StoreT>
886 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
887 template <class T> static T *storeImpl(T *N, StorageType Storage);
890 void handleChangedOperand(void *Ref, Metadata *New);
893 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
894 void decrementUnresolvedOperandCount();
895 unsigned countUnresolvedOperands();
897 /// \brief Mutate this to be "uniqued".
899 /// Mutate this so that \a isUniqued().
900 /// \pre \a isTemporary().
901 /// \pre already added to uniquing set.
904 /// \brief Mutate this to be "distinct".
906 /// Mutate this so that \a isDistinct().
907 /// \pre \a isTemporary().
910 void deleteAsSubclass();
912 void eraseFromStore();
914 template <class NodeTy> struct HasCachedHash;
915 template <class NodeTy>
916 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
917 N->recalculateHash();
919 template <class NodeTy>
920 static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
921 template <class NodeTy>
922 static void dispatchResetHash(NodeTy *N, std::true_type) {
925 template <class NodeTy>
926 static void dispatchResetHash(NodeTy *, std::false_type) {}
929 typedef const MDOperand *op_iterator;
930 typedef iterator_range<op_iterator> op_range;
932 op_iterator op_begin() const {
933 return const_cast<MDNode *>(this)->mutable_begin();
935 op_iterator op_end() const {
936 return const_cast<MDNode *>(this)->mutable_end();
938 op_range operands() const { return op_range(op_begin(), op_end()); }
940 const MDOperand &getOperand(unsigned I) const {
941 assert(I < NumOperands && "Out of range");
942 return op_begin()[I];
945 /// \brief Return number of MDNode operands.
946 unsigned getNumOperands() const { return NumOperands; }
948 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
949 static bool classof(const Metadata *MD) {
950 switch (MD->getMetadataID()) {
953 #define HANDLE_MDNODE_LEAF(CLASS) \
956 #include "llvm/IR/Metadata.def"
960 /// \brief Check whether MDNode is a vtable access.
961 bool isTBAAVtableAccess() const;
963 /// \brief Methods for metadata merging.
964 static MDNode *concatenate(MDNode *A, MDNode *B);
965 static MDNode *intersect(MDNode *A, MDNode *B);
966 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
967 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
968 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
969 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
970 static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B);
974 /// \brief Tuple of metadata.
976 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
977 /// default based on their operands.
978 class MDTuple : public MDNode {
979 friend class LLVMContextImpl;
982 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
983 ArrayRef<Metadata *> Vals)
984 : MDNode(C, MDTupleKind, Storage, Vals) {
987 ~MDTuple() { dropAllReferences(); }
989 void setHash(unsigned Hash) { SubclassData32 = Hash; }
990 void recalculateHash();
992 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
993 StorageType Storage, bool ShouldCreate = true);
995 TempMDTuple cloneImpl() const {
996 return getTemporary(getContext(),
997 SmallVector<Metadata *, 4>(op_begin(), op_end()));
1001 /// \brief Get the hash, if any.
1002 unsigned getHash() const { return SubclassData32; }
1004 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1005 return getImpl(Context, MDs, Uniqued);
1007 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1008 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1011 /// \brief Return a distinct node.
1013 /// Return a distinct node -- i.e., a node that is not uniqued.
1014 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1015 return getImpl(Context, MDs, Distinct);
1018 /// \brief Return a temporary node.
1020 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1021 /// not uniqued, may be RAUW'd, and must be manually deleted with
1022 /// deleteTemporary.
1023 static TempMDTuple getTemporary(LLVMContext &Context,
1024 ArrayRef<Metadata *> MDs) {
1025 return TempMDTuple(getImpl(Context, MDs, Temporary));
1028 /// \brief Return a (temporary) clone of this.
1029 TempMDTuple clone() const { return cloneImpl(); }
1031 static bool classof(const Metadata *MD) {
1032 return MD->getMetadataID() == MDTupleKind;
1036 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1037 return MDTuple::get(Context, MDs);
1039 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1040 return MDTuple::getIfExists(Context, MDs);
1042 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1043 return MDTuple::getDistinct(Context, MDs);
1045 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1046 ArrayRef<Metadata *> MDs) {
1047 return MDTuple::getTemporary(Context, MDs);
1050 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1051 MDNode::deleteTemporary(Node);
1054 /// \brief Typed iterator through MDNode operands.
1056 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1057 /// particular Metadata subclass.
1059 class TypedMDOperandIterator
1060 : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
1061 MDNode::op_iterator I = nullptr;
1064 TypedMDOperandIterator() = default;
1065 explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1066 T *operator*() const { return cast_or_null<T>(*I); }
1067 TypedMDOperandIterator &operator++() {
1071 TypedMDOperandIterator operator++(int) {
1072 TypedMDOperandIterator Temp(*this);
1076 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1077 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1080 /// \brief Typed, array-like tuple of metadata.
1082 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1083 /// particular type of metadata.
1084 template <class T> class MDTupleTypedArrayWrapper {
1085 const MDTuple *N = nullptr;
1088 MDTupleTypedArrayWrapper() = default;
1089 MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1092 MDTupleTypedArrayWrapper(
1093 const MDTupleTypedArrayWrapper<U> &Other,
1094 typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
1099 explicit MDTupleTypedArrayWrapper(
1100 const MDTupleTypedArrayWrapper<U> &Other,
1101 typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
1105 explicit operator bool() const { return get(); }
1106 explicit operator MDTuple *() const { return get(); }
1108 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1109 MDTuple *operator->() const { return get(); }
1110 MDTuple &operator*() const { return *get(); }
1112 // FIXME: Fix callers and remove condition on N.
1113 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1114 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1116 // FIXME: Fix callers and remove condition on N.
1117 typedef TypedMDOperandIterator<T> iterator;
1118 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1119 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1122 #define HANDLE_METADATA(CLASS) \
1123 typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
1124 #include "llvm/IR/Metadata.def"
1126 //===----------------------------------------------------------------------===//
1127 /// \brief A tuple of MDNodes.
1129 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1130 /// to modules, have names, and contain lists of MDNodes.
1132 /// TODO: Inherit from Metadata.
1133 class NamedMDNode : public ilist_node<NamedMDNode> {
1134 friend struct ilist_traits<NamedMDNode>;
1135 friend class LLVMContextImpl;
1136 friend class Module;
1137 NamedMDNode(const NamedMDNode &) = delete;
1141 void *Operands; // SmallVector<TrackingMDRef, 4>
1143 void setParent(Module *M) { Parent = M; }
1145 explicit NamedMDNode(const Twine &N);
1147 template<class T1, class T2>
1148 class op_iterator_impl :
1149 public std::iterator<std::bidirectional_iterator_tag, T2> {
1150 const NamedMDNode *Node;
1152 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1154 friend class NamedMDNode;
1157 op_iterator_impl() : Node(nullptr), Idx(0) { }
1159 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1160 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1161 op_iterator_impl &operator++() {
1165 op_iterator_impl operator++(int) {
1166 op_iterator_impl tmp(*this);
1170 op_iterator_impl &operator--() {
1174 op_iterator_impl operator--(int) {
1175 op_iterator_impl tmp(*this);
1180 T1 operator*() const { return Node->getOperand(Idx); }
1184 /// \brief Drop all references and remove the node from parent module.
1185 void eraseFromParent();
1187 /// \brief Remove all uses and clear node vector.
1188 void dropAllReferences();
1192 /// \brief Get the module that holds this named metadata collection.
1193 inline Module *getParent() { return Parent; }
1194 inline const Module *getParent() const { return Parent; }
1196 MDNode *getOperand(unsigned i) const;
1197 unsigned getNumOperands() const;
1198 void addOperand(MDNode *M);
1199 void setOperand(unsigned I, MDNode *New);
1200 StringRef getName() const;
1201 void print(raw_ostream &ROS, bool IsForDebug = false) const;
1204 // ---------------------------------------------------------------------------
1205 // Operand Iterator interface...
1207 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1208 op_iterator op_begin() { return op_iterator(this, 0); }
1209 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1211 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1212 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1213 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1215 inline iterator_range<op_iterator> operands() {
1216 return make_range(op_begin(), op_end());
1218 inline iterator_range<const_op_iterator> operands() const {
1219 return make_range(op_begin(), op_end());
1223 } // end llvm namespace
1225 #endif // LLVM_IR_METADATA_H