1 //===- llvm/IR/Metadata.h - Metadata definitions ----------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file contains the declarations for metadata subclasses.
12 /// They represent the different flavors of metadata that live in LLVM.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_IR_METADATA_H
17 #define LLVM_IR_METADATA_H
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/ilist_node.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/MetadataTracking.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include <type_traits>
32 template<typename ValueSubClass, typename ItemParentClass>
33 class SymbolTableListTraits;
36 enum LLVMConstants : uint32_t {
37 DEBUG_METADATA_VERSION = 2 // Current debug info version number.
40 /// \brief Root of the metadata hierarchy.
42 /// This is a root class for typeless data in the IR.
44 friend class ReplaceableMetadataImpl;
47 const unsigned char SubclassID;
50 /// \brief Active type of storage.
51 enum StorageType { Uniqued, Distinct, Temporary };
53 /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
55 // TODO: expose remaining bits to subclasses.
57 unsigned short SubclassData16;
58 unsigned SubclassData32;
75 MDLexicalBlockFileKind,
77 MDTemplateTypeParameterKind,
78 MDTemplateValueParameterKind,
84 ConstantAsMetadataKind,
90 Metadata(unsigned ID, StorageType Storage)
91 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
95 /// \brief Default handling of a changed operand, which asserts.
97 /// If subclasses pass themselves in as owners to a tracking node reference,
98 /// they must provide an implementation of this method.
99 void handleChangedOperand(void *, Metadata *) {
100 llvm_unreachable("Unimplemented in Metadata subclass");
104 unsigned getMetadataID() const { return SubclassID; }
106 /// \brief User-friendly dump.
108 void print(raw_ostream &OS) const;
109 void printAsOperand(raw_ostream &OS, bool PrintType = true,
110 const Module *M = nullptr) const;
113 #define HANDLE_METADATA(CLASS) class CLASS;
114 #include "llvm/IR/Metadata.def"
116 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
121 /// \brief Metadata wrapper in the Value hierarchy.
123 /// A member of the \a Value hierarchy to represent a reference to metadata.
124 /// This allows, e.g., instrinsics to have metadata as operands.
126 /// Notably, this is the only thing in either hierarchy that is allowed to
127 /// reference \a LocalAsMetadata.
128 class MetadataAsValue : public Value {
129 friend class ReplaceableMetadataImpl;
130 friend class LLVMContextImpl;
134 MetadataAsValue(Type *Ty, Metadata *MD);
137 /// \brief Drop use of metadata (during teardown).
138 void dropUse() { MD = nullptr; }
141 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
142 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
143 Metadata *getMetadata() const { return MD; }
145 static bool classof(const Value *V) {
146 return V->getValueID() == MetadataAsValueVal;
150 void handleChangedMetadata(Metadata *MD);
155 /// \brief Shared implementation of use-lists for replaceable metadata.
157 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
158 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
159 /// and \a TempMDNode).
160 class ReplaceableMetadataImpl {
161 friend class MetadataTracking;
164 typedef MetadataTracking::OwnerTy OwnerTy;
167 LLVMContext &Context;
169 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
172 ReplaceableMetadataImpl(LLVMContext &Context)
173 : Context(Context), NextIndex(0) {}
174 ~ReplaceableMetadataImpl() {
175 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
178 LLVMContext &getContext() const { return Context; }
180 /// \brief Replace all uses of this with MD.
182 /// Replace all uses of this with \c MD, which is allowed to be null.
183 void replaceAllUsesWith(Metadata *MD);
185 /// \brief Resolve all uses of this.
187 /// Resolve all uses of this, turning off RAUW permanently. If \c
188 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
190 void resolveAllUses(bool ResolveUsers = true);
193 void addRef(void *Ref, OwnerTy Owner);
194 void dropRef(void *Ref);
195 void moveRef(void *Ref, void *New, const Metadata &MD);
197 static ReplaceableMetadataImpl *get(Metadata &MD);
200 /// \brief Value wrapper in the Metadata hierarchy.
202 /// This is a custom value handle that allows other metadata to refer to
203 /// classes in the Value hierarchy.
205 /// Because of full uniquing support, each value is only wrapped by a single \a
206 /// ValueAsMetadata object, so the lookup maps are far more efficient than
207 /// those using ValueHandleBase.
208 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
209 friend class ReplaceableMetadataImpl;
210 friend class LLVMContextImpl;
214 /// \brief Drop users without RAUW (during teardown).
216 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
220 ValueAsMetadata(unsigned ID, Value *V)
221 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
222 assert(V && "Expected valid value");
224 ~ValueAsMetadata() {}
227 static ValueAsMetadata *get(Value *V);
228 static ConstantAsMetadata *getConstant(Value *C) {
229 return cast<ConstantAsMetadata>(get(C));
231 static LocalAsMetadata *getLocal(Value *Local) {
232 return cast<LocalAsMetadata>(get(Local));
235 static ValueAsMetadata *getIfExists(Value *V);
236 static ConstantAsMetadata *getConstantIfExists(Value *C) {
237 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
239 static LocalAsMetadata *getLocalIfExists(Value *Local) {
240 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
243 Value *getValue() const { return V; }
244 Type *getType() const { return V->getType(); }
245 LLVMContext &getContext() const { return V->getContext(); }
247 static void handleDeletion(Value *V);
248 static void handleRAUW(Value *From, Value *To);
251 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
253 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
254 /// \a Value gets RAUW'ed and the target already exists, this is used to
255 /// merge the two metadata nodes.
256 void replaceAllUsesWith(Metadata *MD) {
257 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
261 static bool classof(const Metadata *MD) {
262 return MD->getMetadataID() == LocalAsMetadataKind ||
263 MD->getMetadataID() == ConstantAsMetadataKind;
267 class ConstantAsMetadata : public ValueAsMetadata {
268 friend class ValueAsMetadata;
270 ConstantAsMetadata(Constant *C)
271 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
274 static ConstantAsMetadata *get(Constant *C) {
275 return ValueAsMetadata::getConstant(C);
277 static ConstantAsMetadata *getIfExists(Constant *C) {
278 return ValueAsMetadata::getConstantIfExists(C);
281 Constant *getValue() const {
282 return cast<Constant>(ValueAsMetadata::getValue());
285 static bool classof(const Metadata *MD) {
286 return MD->getMetadataID() == ConstantAsMetadataKind;
290 class LocalAsMetadata : public ValueAsMetadata {
291 friend class ValueAsMetadata;
293 LocalAsMetadata(Value *Local)
294 : ValueAsMetadata(LocalAsMetadataKind, Local) {
295 assert(!isa<Constant>(Local) && "Expected local value");
299 static LocalAsMetadata *get(Value *Local) {
300 return ValueAsMetadata::getLocal(Local);
302 static LocalAsMetadata *getIfExists(Value *Local) {
303 return ValueAsMetadata::getLocalIfExists(Local);
306 static bool classof(const Metadata *MD) {
307 return MD->getMetadataID() == LocalAsMetadataKind;
311 /// \brief Transitional API for extracting constants from Metadata.
313 /// This namespace contains transitional functions for metadata that points to
316 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
317 /// operands could refer to any \a Value. There's was a lot of code like this:
321 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
324 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
325 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
326 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
327 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
328 /// requires subtle control flow changes.
330 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
331 /// so that metadata can refer to numbers without traversing a bridge to the \a
332 /// Value hierarchy. In this final state, the code above would look like this:
336 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
339 /// The API in this namespace supports the transition. \a MDInt doesn't exist
340 /// yet, and even once it does, changing each metadata schema to use it is its
341 /// own mini-project. In the meantime this API prevents us from introducing
342 /// complex and bug-prone control flow that will disappear in the end. In
343 /// particular, the above code looks like this:
347 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
350 /// The full set of provided functions includes:
352 /// mdconst::hasa <=> isa
353 /// mdconst::extract <=> cast
354 /// mdconst::extract_or_null <=> cast_or_null
355 /// mdconst::dyn_extract <=> dyn_cast
356 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
358 /// The target of the cast must be a subclass of \a Constant.
362 template <class T> T &make();
363 template <class T, class Result> struct HasDereference {
366 template <size_t N> struct SFINAE {};
368 template <class U, class V>
369 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
370 template <class U, class V> static No &hasDereference(...);
372 static const bool value =
373 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
375 template <class V, class M> struct IsValidPointer {
376 static const bool value = std::is_base_of<Constant, V>::value &&
377 HasDereference<M, const Metadata &>::value;
379 template <class V, class M> struct IsValidReference {
380 static const bool value = std::is_base_of<Constant, V>::value &&
381 std::is_convertible<M, const Metadata &>::value;
383 } // end namespace detail
385 /// \brief Check whether Metadata has a Value.
387 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
389 template <class X, class Y>
390 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
392 assert(MD && "Null pointer sent into hasa");
393 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
394 return isa<X>(V->getValue());
397 template <class X, class Y>
399 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
404 /// \brief Extract a Value from Metadata.
406 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
407 template <class X, class Y>
408 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
410 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
412 template <class X, class Y>
414 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
419 /// \brief Extract a Value from Metadata, allowing null.
421 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
422 /// from \c MD, allowing \c MD to be null.
423 template <class X, class Y>
424 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
425 extract_or_null(Y &&MD) {
426 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
427 return cast<X>(V->getValue());
431 /// \brief Extract a Value from Metadata, if any.
433 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
434 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
435 /// Value it does contain is of the wrong subclass.
436 template <class X, class Y>
437 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
438 dyn_extract(Y &&MD) {
439 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
440 return dyn_cast<X>(V->getValue());
444 /// \brief Extract a Value from Metadata, if any, allowing null.
446 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
447 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
448 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
449 template <class X, class Y>
450 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
451 dyn_extract_or_null(Y &&MD) {
452 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
453 return dyn_cast<X>(V->getValue());
457 } // end namespace mdconst
459 //===----------------------------------------------------------------------===//
460 /// \brief A single uniqued string.
462 /// These are used to efficiently contain a byte sequence for metadata.
463 /// MDString is always unnamed.
464 class MDString : public Metadata {
465 friend class StringMapEntry<MDString>;
467 MDString(const MDString &) = delete;
468 MDString &operator=(MDString &&) = delete;
469 MDString &operator=(const MDString &) = delete;
471 StringMapEntry<MDString> *Entry;
472 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
473 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
476 static MDString *get(LLVMContext &Context, StringRef Str);
477 static MDString *get(LLVMContext &Context, const char *Str) {
478 return get(Context, Str ? StringRef(Str) : StringRef());
481 StringRef getString() const;
483 unsigned getLength() const { return (unsigned)getString().size(); }
485 typedef StringRef::iterator iterator;
487 /// \brief Pointer to the first byte of the string.
488 iterator begin() const { return getString().begin(); }
490 /// \brief Pointer to one byte past the end of the string.
491 iterator end() const { return getString().end(); }
493 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
494 const unsigned char *bytes_end() const { return getString().bytes_end(); }
496 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
497 static bool classof(const Metadata *MD) {
498 return MD->getMetadataID() == MDStringKind;
502 /// \brief A collection of metadata nodes that might be associated with a
503 /// memory access used by the alias-analysis infrastructure.
505 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
507 : TBAA(T), Scope(S), NoAlias(N) {}
509 bool operator==(const AAMDNodes &A) const {
510 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
513 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
515 explicit operator bool() const { return TBAA || Scope || NoAlias; }
517 /// \brief The tag for type-based alias analysis.
520 /// \brief The tag for alias scope specification (used with noalias).
523 /// \brief The tag specifying the noalias scope.
527 // Specialize DenseMapInfo for AAMDNodes.
529 struct DenseMapInfo<AAMDNodes> {
530 static inline AAMDNodes getEmptyKey() {
531 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
533 static inline AAMDNodes getTombstoneKey() {
534 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
536 static unsigned getHashValue(const AAMDNodes &Val) {
537 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
538 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
539 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
541 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
546 /// \brief Tracking metadata reference owned by Metadata.
548 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
549 /// of \a Metadata, which has the option of registering itself for callbacks to
550 /// re-unique itself.
552 /// In particular, this is used by \a MDNode.
554 MDOperand(MDOperand &&) = delete;
555 MDOperand(const MDOperand &) = delete;
556 MDOperand &operator=(MDOperand &&) = delete;
557 MDOperand &operator=(const MDOperand &) = delete;
562 MDOperand() : MD(nullptr) {}
563 ~MDOperand() { untrack(); }
565 Metadata *get() const { return MD; }
566 operator Metadata *() const { return get(); }
567 Metadata *operator->() const { return get(); }
568 Metadata &operator*() const { return *get(); }
574 void reset(Metadata *MD, Metadata *Owner) {
581 void track(Metadata *Owner) {
584 MetadataTracking::track(this, *MD, *Owner);
586 MetadataTracking::track(MD);
590 assert(static_cast<void *>(this) == &MD && "Expected same address");
592 MetadataTracking::untrack(MD);
596 template <> struct simplify_type<MDOperand> {
597 typedef Metadata *SimpleType;
598 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
601 template <> struct simplify_type<const MDOperand> {
602 typedef Metadata *SimpleType;
603 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
606 /// \brief Pointer to the context, with optional RAUW support.
608 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
609 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
610 class ContextAndReplaceableUses {
611 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
613 ContextAndReplaceableUses() = delete;
614 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
615 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
616 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
617 ContextAndReplaceableUses &
618 operator=(const ContextAndReplaceableUses &) = delete;
621 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
622 ContextAndReplaceableUses(
623 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
624 : Ptr(ReplaceableUses.release()) {
625 assert(getReplaceableUses() && "Expected non-null replaceable uses");
627 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
629 operator LLVMContext &() { return getContext(); }
631 /// \brief Whether this contains RAUW support.
632 bool hasReplaceableUses() const {
633 return Ptr.is<ReplaceableMetadataImpl *>();
635 LLVMContext &getContext() const {
636 if (hasReplaceableUses())
637 return getReplaceableUses()->getContext();
638 return *Ptr.get<LLVMContext *>();
640 ReplaceableMetadataImpl *getReplaceableUses() const {
641 if (hasReplaceableUses())
642 return Ptr.get<ReplaceableMetadataImpl *>();
646 /// \brief Assign RAUW support to this.
648 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
651 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
652 assert(ReplaceableUses && "Expected non-null replaceable uses");
653 assert(&ReplaceableUses->getContext() == &getContext() &&
654 "Expected same context");
655 delete getReplaceableUses();
656 Ptr = ReplaceableUses.release();
659 /// \brief Drop RAUW support.
661 /// Cede ownership of RAUW support, returning it.
662 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
663 assert(hasReplaceableUses() && "Expected to own replaceable uses");
664 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
665 getReplaceableUses());
666 Ptr = &ReplaceableUses->getContext();
667 return ReplaceableUses;
671 struct TempMDNodeDeleter {
672 inline void operator()(MDNode *Node) const;
675 #define HANDLE_MDNODE_LEAF(CLASS) \
676 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
677 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
678 #include "llvm/IR/Metadata.def"
680 /// \brief Metadata node.
682 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
683 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
684 /// until forward references are known. The basic metadata node is an \a
687 /// There is limited support for RAUW at construction time. At construction
688 /// time, if any operand is a temporary node (or an unresolved uniqued node,
689 /// which indicates a transitive temporary operand), the node itself will be
690 /// unresolved. As soon as all operands become resolved, it will drop RAUW
691 /// support permanently.
693 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
694 /// to be called on some member of the cycle once all temporary nodes have been
696 class MDNode : public Metadata {
697 friend class ReplaceableMetadataImpl;
698 friend class LLVMContextImpl;
700 MDNode(const MDNode &) = delete;
701 void operator=(const MDNode &) = delete;
702 void *operator new(size_t) = delete;
704 unsigned NumOperands;
705 unsigned NumUnresolved;
708 ContextAndReplaceableUses Context;
710 void *operator new(size_t Size, unsigned NumOps);
711 void operator delete(void *Mem);
713 /// \brief Required by std, but never called.
714 void operator delete(void *, unsigned) {
715 llvm_unreachable("Constructor throws?");
718 /// \brief Required by std, but never called.
719 void operator delete(void *, unsigned, bool) {
720 llvm_unreachable("Constructor throws?");
723 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
724 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
727 void dropAllReferences();
729 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
730 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
733 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
734 static inline MDTuple *getIfExists(LLVMContext &Context,
735 ArrayRef<Metadata *> MDs);
736 static inline MDTuple *getDistinct(LLVMContext &Context,
737 ArrayRef<Metadata *> MDs);
738 static inline TempMDTuple getTemporary(LLVMContext &Context,
739 ArrayRef<Metadata *> MDs);
741 /// \brief Create a (temporary) clone of this.
742 TempMDNode clone() const;
744 /// \brief Deallocate a node created by getTemporary.
746 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
747 /// references will be reset.
748 static void deleteTemporary(MDNode *N);
750 LLVMContext &getContext() const { return Context.getContext(); }
752 /// \brief Replace a specific operand.
753 void replaceOperandWith(unsigned I, Metadata *New);
755 /// \brief Check if node is fully resolved.
757 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
758 /// this always returns \c true.
760 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
761 /// support (because all operands are resolved).
763 /// As forward declarations are resolved, their containers should get
764 /// resolved automatically. However, if this (or one of its operands) is
765 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
766 bool isResolved() const { return !Context.hasReplaceableUses(); }
768 bool isUniqued() const { return Storage == Uniqued; }
769 bool isDistinct() const { return Storage == Distinct; }
770 bool isTemporary() const { return Storage == Temporary; }
772 /// \brief RAUW a temporary.
774 /// \pre \a isTemporary() must be \c true.
775 void replaceAllUsesWith(Metadata *MD) {
776 assert(isTemporary() && "Expected temporary node");
777 assert(!isResolved() && "Expected RAUW support");
778 Context.getReplaceableUses()->replaceAllUsesWith(MD);
781 /// \brief Resolve cycles.
783 /// Once all forward declarations have been resolved, force cycles to be
786 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
787 void resolveCycles();
789 /// \brief Replace a temporary node with a permanent one.
791 /// Try to create a uniqued version of \c N -- in place, if possible -- and
792 /// return it. If \c N cannot be uniqued, return a distinct node instead.
794 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
795 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
796 return cast<T>(N.release()->replaceWithPermanentImpl());
799 /// \brief Replace a temporary node with a uniqued one.
801 /// Create a uniqued version of \c N -- in place, if possible -- and return
802 /// it. Takes ownership of the temporary node.
804 /// \pre N does not self-reference.
806 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
807 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
808 return cast<T>(N.release()->replaceWithUniquedImpl());
811 /// \brief Replace a temporary node with a distinct one.
813 /// Create a distinct version of \c N -- in place, if possible -- and return
814 /// it. Takes ownership of the temporary node.
816 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
817 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
818 return cast<T>(N.release()->replaceWithDistinctImpl());
822 MDNode *replaceWithPermanentImpl();
823 MDNode *replaceWithUniquedImpl();
824 MDNode *replaceWithDistinctImpl();
827 /// \brief Set an operand.
829 /// Sets the operand directly, without worrying about uniquing.
830 void setOperand(unsigned I, Metadata *New);
832 void storeDistinctInContext();
833 template <class T, class StoreT>
834 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
837 void handleChangedOperand(void *Ref, Metadata *New);
840 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
841 void decrementUnresolvedOperandCount();
842 unsigned countUnresolvedOperands();
844 /// \brief Mutate this to be "uniqued".
846 /// Mutate this so that \a isUniqued().
847 /// \pre \a isTemporary().
848 /// \pre already added to uniquing set.
851 /// \brief Mutate this to be "distinct".
853 /// Mutate this so that \a isDistinct().
854 /// \pre \a isTemporary().
857 void deleteAsSubclass();
859 void eraseFromStore();
861 template <class NodeTy> struct HasCachedHash;
862 template <class NodeTy>
863 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
864 N->recalculateHash();
866 template <class NodeTy>
867 static void dispatchRecalculateHash(NodeTy *N, std::false_type) {}
868 template <class NodeTy>
869 static void dispatchResetHash(NodeTy *N, std::true_type) {
872 template <class NodeTy>
873 static void dispatchResetHash(NodeTy *N, std::false_type) {}
876 typedef const MDOperand *op_iterator;
877 typedef iterator_range<op_iterator> op_range;
879 op_iterator op_begin() const {
880 return const_cast<MDNode *>(this)->mutable_begin();
882 op_iterator op_end() const {
883 return const_cast<MDNode *>(this)->mutable_end();
885 op_range operands() const { return op_range(op_begin(), op_end()); }
887 const MDOperand &getOperand(unsigned I) const {
888 assert(I < NumOperands && "Out of range");
889 return op_begin()[I];
892 /// \brief Return number of MDNode operands.
893 unsigned getNumOperands() const { return NumOperands; }
895 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
896 static bool classof(const Metadata *MD) {
897 switch (MD->getMetadataID()) {
900 #define HANDLE_MDNODE_LEAF(CLASS) \
903 #include "llvm/IR/Metadata.def"
907 /// \brief Check whether MDNode is a vtable access.
908 bool isTBAAVtableAccess() const;
910 /// \brief Methods for metadata merging.
911 static MDNode *concatenate(MDNode *A, MDNode *B);
912 static MDNode *intersect(MDNode *A, MDNode *B);
913 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
914 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
915 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
916 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
919 /// \brief Tuple of metadata.
921 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
922 /// default based on their operands.
923 class MDTuple : public MDNode {
924 friend class LLVMContextImpl;
927 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
928 ArrayRef<Metadata *> Vals)
929 : MDNode(C, MDTupleKind, Storage, Vals) {
932 ~MDTuple() { dropAllReferences(); }
934 void setHash(unsigned Hash) { SubclassData32 = Hash; }
935 void recalculateHash();
937 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
938 StorageType Storage, bool ShouldCreate = true);
940 TempMDTuple cloneImpl() const {
941 return getTemporary(getContext(),
942 SmallVector<Metadata *, 4>(op_begin(), op_end()));
946 /// \brief Get the hash, if any.
947 unsigned getHash() const { return SubclassData32; }
949 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
950 return getImpl(Context, MDs, Uniqued);
952 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
953 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
956 /// \brief Return a distinct node.
958 /// Return a distinct node -- i.e., a node that is not uniqued.
959 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
960 return getImpl(Context, MDs, Distinct);
963 /// \brief Return a temporary node.
965 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
966 /// not uniqued, may be RAUW'd, and must be manually deleted with
968 static TempMDTuple getTemporary(LLVMContext &Context,
969 ArrayRef<Metadata *> MDs) {
970 return TempMDTuple(getImpl(Context, MDs, Temporary));
973 /// \brief Return a (temporary) clone of this.
974 TempMDTuple clone() const { return cloneImpl(); }
976 static bool classof(const Metadata *MD) {
977 return MD->getMetadataID() == MDTupleKind;
981 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
982 return MDTuple::get(Context, MDs);
984 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
985 return MDTuple::getIfExists(Context, MDs);
987 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
988 return MDTuple::getDistinct(Context, MDs);
990 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
991 ArrayRef<Metadata *> MDs) {
992 return MDTuple::getTemporary(Context, MDs);
995 void TempMDNodeDeleter::operator()(MDNode *Node) const {
996 MDNode::deleteTemporary(Node);
999 //===----------------------------------------------------------------------===//
1000 /// \brief A tuple of MDNodes.
1002 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1003 /// to modules, have names, and contain lists of MDNodes.
1005 /// TODO: Inherit from Metadata.
1006 class NamedMDNode : public ilist_node<NamedMDNode> {
1007 friend class SymbolTableListTraits<NamedMDNode, Module>;
1008 friend struct ilist_traits<NamedMDNode>;
1009 friend class LLVMContextImpl;
1010 friend class Module;
1011 NamedMDNode(const NamedMDNode &) = delete;
1015 void *Operands; // SmallVector<TrackingMDRef, 4>
1017 void setParent(Module *M) { Parent = M; }
1019 explicit NamedMDNode(const Twine &N);
1021 template<class T1, class T2>
1022 class op_iterator_impl :
1023 public std::iterator<std::bidirectional_iterator_tag, T2> {
1024 const NamedMDNode *Node;
1026 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1028 friend class NamedMDNode;
1031 op_iterator_impl() : Node(nullptr), Idx(0) { }
1033 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1034 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1035 op_iterator_impl &operator++() {
1039 op_iterator_impl operator++(int) {
1040 op_iterator_impl tmp(*this);
1044 op_iterator_impl &operator--() {
1048 op_iterator_impl operator--(int) {
1049 op_iterator_impl tmp(*this);
1054 T1 operator*() const { return Node->getOperand(Idx); }
1058 /// \brief Drop all references and remove the node from parent module.
1059 void eraseFromParent();
1061 /// \brief Remove all uses and clear node vector.
1062 void dropAllReferences();
1066 /// \brief Get the module that holds this named metadata collection.
1067 inline Module *getParent() { return Parent; }
1068 inline const Module *getParent() const { return Parent; }
1070 MDNode *getOperand(unsigned i) const;
1071 unsigned getNumOperands() const;
1072 void addOperand(MDNode *M);
1073 void setOperand(unsigned I, MDNode *New);
1074 StringRef getName() const;
1075 void print(raw_ostream &ROS) const;
1078 // ---------------------------------------------------------------------------
1079 // Operand Iterator interface...
1081 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1082 op_iterator op_begin() { return op_iterator(this, 0); }
1083 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1085 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1086 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1087 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1089 inline iterator_range<op_iterator> operands() {
1090 return iterator_range<op_iterator>(op_begin(), op_end());
1092 inline iterator_range<const_op_iterator> operands() const {
1093 return iterator_range<const_op_iterator>(op_begin(), op_end());
1097 } // end llvm namespace