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;
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 MDLexicalBlockFileKind,
76 MDTemplateTypeParameterKind,
77 MDTemplateValueParameterKind,
83 ConstantAsMetadataKind,
89 Metadata(unsigned ID, StorageType Storage)
90 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
94 /// \brief Default handling of a changed operand, which asserts.
96 /// If subclasses pass themselves in as owners to a tracking node reference,
97 /// they must provide an implementation of this method.
98 void handleChangedOperand(void *, Metadata *) {
99 llvm_unreachable("Unimplemented in Metadata subclass");
103 unsigned getMetadataID() const { return SubclassID; }
105 /// \brief User-friendly dump.
107 void print(raw_ostream &OS) const;
108 void printAsOperand(raw_ostream &OS, bool PrintType = true,
109 const Module *M = nullptr) const;
112 #define HANDLE_METADATA(CLASS) class CLASS;
113 #include "llvm/IR/Metadata.def"
115 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
120 /// \brief Metadata wrapper in the Value hierarchy.
122 /// A member of the \a Value hierarchy to represent a reference to metadata.
123 /// This allows, e.g., instrinsics to have metadata as operands.
125 /// Notably, this is the only thing in either hierarchy that is allowed to
126 /// reference \a LocalAsMetadata.
127 class MetadataAsValue : public Value {
128 friend class ReplaceableMetadataImpl;
129 friend class LLVMContextImpl;
133 MetadataAsValue(Type *Ty, Metadata *MD);
136 /// \brief Drop use of metadata (during teardown).
137 void dropUse() { MD = nullptr; }
140 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
141 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
142 Metadata *getMetadata() const { return MD; }
144 static bool classof(const Value *V) {
145 return V->getValueID() == MetadataAsValueVal;
149 void handleChangedMetadata(Metadata *MD);
154 /// \brief Shared implementation of use-lists for replaceable metadata.
156 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
157 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
158 /// and \a TempMDNode).
159 class ReplaceableMetadataImpl {
160 friend class MetadataTracking;
163 typedef MetadataTracking::OwnerTy OwnerTy;
166 LLVMContext &Context;
168 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
171 ReplaceableMetadataImpl(LLVMContext &Context)
172 : Context(Context), NextIndex(0) {}
173 ~ReplaceableMetadataImpl() {
174 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
177 LLVMContext &getContext() const { return Context; }
179 /// \brief Replace all uses of this with MD.
181 /// Replace all uses of this with \c MD, which is allowed to be null.
182 void replaceAllUsesWith(Metadata *MD);
184 /// \brief Resolve all uses of this.
186 /// Resolve all uses of this, turning off RAUW permanently. If \c
187 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
189 void resolveAllUses(bool ResolveUsers = true);
192 void addRef(void *Ref, OwnerTy Owner);
193 void dropRef(void *Ref);
194 void moveRef(void *Ref, void *New, const Metadata &MD);
196 static ReplaceableMetadataImpl *get(Metadata &MD);
199 /// \brief Value wrapper in the Metadata hierarchy.
201 /// This is a custom value handle that allows other metadata to refer to
202 /// classes in the Value hierarchy.
204 /// Because of full uniquing support, each value is only wrapped by a single \a
205 /// ValueAsMetadata object, so the lookup maps are far more efficient than
206 /// those using ValueHandleBase.
207 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
208 friend class ReplaceableMetadataImpl;
209 friend class LLVMContextImpl;
213 /// \brief Drop users without RAUW (during teardown).
215 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
219 ValueAsMetadata(unsigned ID, Value *V)
220 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
221 assert(V && "Expected valid value");
223 ~ValueAsMetadata() {}
226 static ValueAsMetadata *get(Value *V);
227 static ConstantAsMetadata *getConstant(Value *C) {
228 return cast<ConstantAsMetadata>(get(C));
230 static LocalAsMetadata *getLocal(Value *Local) {
231 return cast<LocalAsMetadata>(get(Local));
234 static ValueAsMetadata *getIfExists(Value *V);
235 static ConstantAsMetadata *getConstantIfExists(Value *C) {
236 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
238 static LocalAsMetadata *getLocalIfExists(Value *Local) {
239 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
242 Value *getValue() const { return V; }
243 Type *getType() const { return V->getType(); }
244 LLVMContext &getContext() const { return V->getContext(); }
246 static void handleDeletion(Value *V);
247 static void handleRAUW(Value *From, Value *To);
250 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
252 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
253 /// \a Value gets RAUW'ed and the target already exists, this is used to
254 /// merge the two metadata nodes.
255 void replaceAllUsesWith(Metadata *MD) {
256 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
260 static bool classof(const Metadata *MD) {
261 return MD->getMetadataID() == LocalAsMetadataKind ||
262 MD->getMetadataID() == ConstantAsMetadataKind;
266 class ConstantAsMetadata : public ValueAsMetadata {
267 friend class ValueAsMetadata;
269 ConstantAsMetadata(Constant *C)
270 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
273 static ConstantAsMetadata *get(Constant *C) {
274 return ValueAsMetadata::getConstant(C);
276 static ConstantAsMetadata *getIfExists(Constant *C) {
277 return ValueAsMetadata::getConstantIfExists(C);
280 Constant *getValue() const {
281 return cast<Constant>(ValueAsMetadata::getValue());
284 static bool classof(const Metadata *MD) {
285 return MD->getMetadataID() == ConstantAsMetadataKind;
289 class LocalAsMetadata : public ValueAsMetadata {
290 friend class ValueAsMetadata;
292 LocalAsMetadata(Value *Local)
293 : ValueAsMetadata(LocalAsMetadataKind, Local) {
294 assert(!isa<Constant>(Local) && "Expected local value");
298 static LocalAsMetadata *get(Value *Local) {
299 return ValueAsMetadata::getLocal(Local);
301 static LocalAsMetadata *getIfExists(Value *Local) {
302 return ValueAsMetadata::getLocalIfExists(Local);
305 static bool classof(const Metadata *MD) {
306 return MD->getMetadataID() == LocalAsMetadataKind;
310 /// \brief Transitional API for extracting constants from Metadata.
312 /// This namespace contains transitional functions for metadata that points to
315 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
316 /// operands could refer to any \a Value. There's was a lot of code like this:
320 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
323 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
324 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
325 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
326 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
327 /// requires subtle control flow changes.
329 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
330 /// so that metadata can refer to numbers without traversing a bridge to the \a
331 /// Value hierarchy. In this final state, the code above would look like this:
335 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
338 /// The API in this namespace supports the transition. \a MDInt doesn't exist
339 /// yet, and even once it does, changing each metadata schema to use it is its
340 /// own mini-project. In the meantime this API prevents us from introducing
341 /// complex and bug-prone control flow that will disappear in the end. In
342 /// particular, the above code looks like this:
346 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
349 /// The full set of provided functions includes:
351 /// mdconst::hasa <=> isa
352 /// mdconst::extract <=> cast
353 /// mdconst::extract_or_null <=> cast_or_null
354 /// mdconst::dyn_extract <=> dyn_cast
355 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
357 /// The target of the cast must be a subclass of \a Constant.
361 template <class T> T &make();
362 template <class T, class Result> struct HasDereference {
365 template <size_t N> struct SFINAE {};
367 template <class U, class V>
368 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
369 template <class U, class V> static No &hasDereference(...);
371 static const bool value =
372 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
374 template <class V, class M> struct IsValidPointer {
375 static const bool value = std::is_base_of<Constant, V>::value &&
376 HasDereference<M, const Metadata &>::value;
378 template <class V, class M> struct IsValidReference {
379 static const bool value = std::is_base_of<Constant, V>::value &&
380 std::is_convertible<M, const Metadata &>::value;
382 } // end namespace detail
384 /// \brief Check whether Metadata has a Value.
386 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
388 template <class X, class Y>
389 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
391 assert(MD && "Null pointer sent into hasa");
392 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
393 return isa<X>(V->getValue());
396 template <class X, class Y>
398 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
403 /// \brief Extract a Value from Metadata.
405 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
406 template <class X, class Y>
407 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
409 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
411 template <class X, class Y>
413 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
418 /// \brief Extract a Value from Metadata, allowing null.
420 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
421 /// from \c MD, allowing \c MD to be null.
422 template <class X, class Y>
423 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
424 extract_or_null(Y &&MD) {
425 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
426 return cast<X>(V->getValue());
430 /// \brief Extract a Value from Metadata, if any.
432 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
433 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
434 /// Value it does contain is of the wrong subclass.
435 template <class X, class Y>
436 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
437 dyn_extract(Y &&MD) {
438 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
439 return dyn_cast<X>(V->getValue());
443 /// \brief Extract a Value from Metadata, if any, allowing null.
445 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
446 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
447 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
448 template <class X, class Y>
449 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
450 dyn_extract_or_null(Y &&MD) {
451 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
452 return dyn_cast<X>(V->getValue());
456 } // end namespace mdconst
458 //===----------------------------------------------------------------------===//
459 /// \brief A single uniqued string.
461 /// These are used to efficiently contain a byte sequence for metadata.
462 /// MDString is always unnamed.
463 class MDString : public Metadata {
464 friend class StringMapEntry<MDString>;
466 MDString(const MDString &) = delete;
467 MDString &operator=(MDString &&) = delete;
468 MDString &operator=(const MDString &) = delete;
470 StringMapEntry<MDString> *Entry;
471 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
472 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
475 static MDString *get(LLVMContext &Context, StringRef Str);
476 static MDString *get(LLVMContext &Context, const char *Str) {
477 return get(Context, Str ? StringRef(Str) : StringRef());
480 StringRef getString() const;
482 unsigned getLength() const { return (unsigned)getString().size(); }
484 typedef StringRef::iterator iterator;
486 /// \brief Pointer to the first byte of the string.
487 iterator begin() const { return getString().begin(); }
489 /// \brief Pointer to one byte past the end of the string.
490 iterator end() const { return getString().end(); }
492 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
493 const unsigned char *bytes_end() const { return getString().bytes_end(); }
495 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
496 static bool classof(const Metadata *MD) {
497 return MD->getMetadataID() == MDStringKind;
501 /// \brief A collection of metadata nodes that might be associated with a
502 /// memory access used by the alias-analysis infrastructure.
504 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
506 : TBAA(T), Scope(S), NoAlias(N) {}
508 bool operator==(const AAMDNodes &A) const {
509 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
512 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
514 explicit operator bool() const { return TBAA || Scope || NoAlias; }
516 /// \brief The tag for type-based alias analysis.
519 /// \brief The tag for alias scope specification (used with noalias).
522 /// \brief The tag specifying the noalias scope.
526 // Specialize DenseMapInfo for AAMDNodes.
528 struct DenseMapInfo<AAMDNodes> {
529 static inline AAMDNodes getEmptyKey() {
530 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
532 static inline AAMDNodes getTombstoneKey() {
533 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
535 static unsigned getHashValue(const AAMDNodes &Val) {
536 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
537 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
538 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
540 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
545 /// \brief Tracking metadata reference owned by Metadata.
547 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
548 /// of \a Metadata, which has the option of registering itself for callbacks to
549 /// re-unique itself.
551 /// In particular, this is used by \a MDNode.
553 MDOperand(MDOperand &&) = delete;
554 MDOperand(const MDOperand &) = delete;
555 MDOperand &operator=(MDOperand &&) = delete;
556 MDOperand &operator=(const MDOperand &) = delete;
561 MDOperand() : MD(nullptr) {}
562 ~MDOperand() { untrack(); }
564 Metadata *get() const { return MD; }
565 operator Metadata *() const { return get(); }
566 Metadata *operator->() const { return get(); }
567 Metadata &operator*() const { return *get(); }
573 void reset(Metadata *MD, Metadata *Owner) {
580 void track(Metadata *Owner) {
583 MetadataTracking::track(this, *MD, *Owner);
585 MetadataTracking::track(MD);
589 assert(static_cast<void *>(this) == &MD && "Expected same address");
591 MetadataTracking::untrack(MD);
595 template <> struct simplify_type<MDOperand> {
596 typedef Metadata *SimpleType;
597 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
600 template <> struct simplify_type<const MDOperand> {
601 typedef Metadata *SimpleType;
602 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
605 /// \brief Pointer to the context, with optional RAUW support.
607 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
608 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
609 class ContextAndReplaceableUses {
610 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
612 ContextAndReplaceableUses() = delete;
613 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
614 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
615 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
616 ContextAndReplaceableUses &
617 operator=(const ContextAndReplaceableUses &) = delete;
620 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
621 ContextAndReplaceableUses(
622 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
623 : Ptr(ReplaceableUses.release()) {
624 assert(getReplaceableUses() && "Expected non-null replaceable uses");
626 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
628 operator LLVMContext &() { return getContext(); }
630 /// \brief Whether this contains RAUW support.
631 bool hasReplaceableUses() const {
632 return Ptr.is<ReplaceableMetadataImpl *>();
634 LLVMContext &getContext() const {
635 if (hasReplaceableUses())
636 return getReplaceableUses()->getContext();
637 return *Ptr.get<LLVMContext *>();
639 ReplaceableMetadataImpl *getReplaceableUses() const {
640 if (hasReplaceableUses())
641 return Ptr.get<ReplaceableMetadataImpl *>();
645 /// \brief Assign RAUW support to this.
647 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
650 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
651 assert(ReplaceableUses && "Expected non-null replaceable uses");
652 assert(&ReplaceableUses->getContext() == &getContext() &&
653 "Expected same context");
654 delete getReplaceableUses();
655 Ptr = ReplaceableUses.release();
658 /// \brief Drop RAUW support.
660 /// Cede ownership of RAUW support, returning it.
661 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
662 assert(hasReplaceableUses() && "Expected to own replaceable uses");
663 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
664 getReplaceableUses());
665 Ptr = &ReplaceableUses->getContext();
666 return ReplaceableUses;
670 struct TempMDNodeDeleter {
671 inline void operator()(MDNode *Node) const;
674 #define HANDLE_MDNODE_LEAF(CLASS) \
675 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
676 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
677 #include "llvm/IR/Metadata.def"
679 /// \brief Metadata node.
681 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
682 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
683 /// until forward references are known. The basic metadata node is an \a
686 /// There is limited support for RAUW at construction time. At construction
687 /// time, if any operand is a temporary node (or an unresolved uniqued node,
688 /// which indicates a transitive temporary operand), the node itself will be
689 /// unresolved. As soon as all operands become resolved, it will drop RAUW
690 /// support permanently.
692 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
693 /// to be called on some member of the cycle once all temporary nodes have been
695 class MDNode : public Metadata {
696 friend class ReplaceableMetadataImpl;
697 friend class LLVMContextImpl;
699 MDNode(const MDNode &) = delete;
700 void operator=(const MDNode &) = delete;
701 void *operator new(size_t) = delete;
703 unsigned NumOperands;
704 unsigned NumUnresolved;
707 ContextAndReplaceableUses Context;
709 void *operator new(size_t Size, unsigned NumOps);
710 void operator delete(void *Mem);
712 /// \brief Required by std, but never called.
713 void operator delete(void *, unsigned) {
714 llvm_unreachable("Constructor throws?");
717 /// \brief Required by std, but never called.
718 void operator delete(void *, unsigned, bool) {
719 llvm_unreachable("Constructor throws?");
722 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
723 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
726 void dropAllReferences();
728 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
729 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
732 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
733 static inline MDTuple *getIfExists(LLVMContext &Context,
734 ArrayRef<Metadata *> MDs);
735 static inline MDTuple *getDistinct(LLVMContext &Context,
736 ArrayRef<Metadata *> MDs);
737 static inline TempMDTuple getTemporary(LLVMContext &Context,
738 ArrayRef<Metadata *> MDs);
740 /// \brief Create a (temporary) clone of this.
741 TempMDNode clone() const;
743 /// \brief Deallocate a node created by getTemporary.
745 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
746 /// references will be reset.
747 static void deleteTemporary(MDNode *N);
749 LLVMContext &getContext() const { return Context.getContext(); }
751 /// \brief Replace a specific operand.
752 void replaceOperandWith(unsigned I, Metadata *New);
754 /// \brief Check if node is fully resolved.
756 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
757 /// this always returns \c true.
759 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
760 /// support (because all operands are resolved).
762 /// As forward declarations are resolved, their containers should get
763 /// resolved automatically. However, if this (or one of its operands) is
764 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
765 bool isResolved() const { return !Context.hasReplaceableUses(); }
767 bool isUniqued() const { return Storage == Uniqued; }
768 bool isDistinct() const { return Storage == Distinct; }
769 bool isTemporary() const { return Storage == Temporary; }
771 /// \brief RAUW a temporary.
773 /// \pre \a isTemporary() must be \c true.
774 void replaceAllUsesWith(Metadata *MD) {
775 assert(isTemporary() && "Expected temporary node");
776 assert(!isResolved() && "Expected RAUW support");
777 Context.getReplaceableUses()->replaceAllUsesWith(MD);
780 /// \brief Resolve cycles.
782 /// Once all forward declarations have been resolved, force cycles to be
785 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
786 void resolveCycles();
788 /// \brief Replace a temporary node with a permanent one.
790 /// Try to create a uniqued version of \c N -- in place, if possible -- and
791 /// return it. If \c N cannot be uniqued, return a distinct node instead.
793 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
794 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
795 return cast<T>(N.release()->replaceWithPermanentImpl());
798 /// \brief Replace a temporary node with a uniqued one.
800 /// Create a uniqued version of \c N -- in place, if possible -- and return
801 /// it. Takes ownership of the temporary node.
803 /// \pre N does not self-reference.
805 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
806 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
807 return cast<T>(N.release()->replaceWithUniquedImpl());
810 /// \brief Replace a temporary node with a distinct one.
812 /// Create a distinct version of \c N -- in place, if possible -- and return
813 /// it. Takes ownership of the temporary node.
815 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
816 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
817 return cast<T>(N.release()->replaceWithDistinctImpl());
821 MDNode *replaceWithPermanentImpl();
822 MDNode *replaceWithUniquedImpl();
823 MDNode *replaceWithDistinctImpl();
826 /// \brief Set an operand.
828 /// Sets the operand directly, without worrying about uniquing.
829 void setOperand(unsigned I, Metadata *New);
831 void storeDistinctInContext();
832 template <class T, class StoreT>
833 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
836 void handleChangedOperand(void *Ref, Metadata *New);
839 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
840 void decrementUnresolvedOperandCount();
841 unsigned countUnresolvedOperands();
843 /// \brief Mutate this to be "uniqued".
845 /// Mutate this so that \a isUniqued().
846 /// \pre \a isTemporary().
847 /// \pre already added to uniquing set.
850 /// \brief Mutate this to be "distinct".
852 /// Mutate this so that \a isDistinct().
853 /// \pre \a isTemporary().
856 void deleteAsSubclass();
858 void eraseFromStore();
860 template <class NodeTy> struct HasCachedHash;
861 template <class NodeTy>
862 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
863 N->recalculateHash();
865 template <class NodeTy>
866 static void dispatchRecalculateHash(NodeTy *N, std::false_type) {}
867 template <class NodeTy>
868 static void dispatchResetHash(NodeTy *N, std::true_type) {
871 template <class NodeTy>
872 static void dispatchResetHash(NodeTy *N, std::false_type) {}
875 typedef const MDOperand *op_iterator;
876 typedef iterator_range<op_iterator> op_range;
878 op_iterator op_begin() const {
879 return const_cast<MDNode *>(this)->mutable_begin();
881 op_iterator op_end() const {
882 return const_cast<MDNode *>(this)->mutable_end();
884 op_range operands() const { return op_range(op_begin(), op_end()); }
886 const MDOperand &getOperand(unsigned I) const {
887 assert(I < NumOperands && "Out of range");
888 return op_begin()[I];
891 /// \brief Return number of MDNode operands.
892 unsigned getNumOperands() const { return NumOperands; }
894 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
895 static bool classof(const Metadata *MD) {
896 switch (MD->getMetadataID()) {
899 #define HANDLE_MDNODE_LEAF(CLASS) \
902 #include "llvm/IR/Metadata.def"
906 /// \brief Check whether MDNode is a vtable access.
907 bool isTBAAVtableAccess() const;
909 /// \brief Methods for metadata merging.
910 static MDNode *concatenate(MDNode *A, MDNode *B);
911 static MDNode *intersect(MDNode *A, MDNode *B);
912 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
913 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
914 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
915 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
918 /// \brief Tuple of metadata.
920 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
921 /// default based on their operands.
922 class MDTuple : public MDNode {
923 friend class LLVMContextImpl;
926 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
927 ArrayRef<Metadata *> Vals)
928 : MDNode(C, MDTupleKind, Storage, Vals) {
931 ~MDTuple() { dropAllReferences(); }
933 void setHash(unsigned Hash) { SubclassData32 = Hash; }
934 void recalculateHash();
936 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
937 StorageType Storage, bool ShouldCreate = true);
939 TempMDTuple cloneImpl() const {
940 return getTemporary(getContext(),
941 SmallVector<Metadata *, 4>(op_begin(), op_end()));
945 /// \brief Get the hash, if any.
946 unsigned getHash() const { return SubclassData32; }
948 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
949 return getImpl(Context, MDs, Uniqued);
951 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
952 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
955 /// \brief Return a distinct node.
957 /// Return a distinct node -- i.e., a node that is not uniqued.
958 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
959 return getImpl(Context, MDs, Distinct);
962 /// \brief Return a temporary node.
964 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
965 /// not uniqued, may be RAUW'd, and must be manually deleted with
967 static TempMDTuple getTemporary(LLVMContext &Context,
968 ArrayRef<Metadata *> MDs) {
969 return TempMDTuple(getImpl(Context, MDs, Temporary));
972 /// \brief Return a (temporary) clone of this.
973 TempMDTuple clone() const { return cloneImpl(); }
975 static bool classof(const Metadata *MD) {
976 return MD->getMetadataID() == MDTupleKind;
980 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
981 return MDTuple::get(Context, MDs);
983 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
984 return MDTuple::getIfExists(Context, MDs);
986 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
987 return MDTuple::getDistinct(Context, MDs);
989 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
990 ArrayRef<Metadata *> MDs) {
991 return MDTuple::getTemporary(Context, MDs);
994 void TempMDNodeDeleter::operator()(MDNode *Node) const {
995 MDNode::deleteTemporary(Node);
998 //===----------------------------------------------------------------------===//
999 /// \brief A tuple of MDNodes.
1001 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1002 /// to modules, have names, and contain lists of MDNodes.
1004 /// TODO: Inherit from Metadata.
1005 class NamedMDNode : public ilist_node<NamedMDNode> {
1006 friend class SymbolTableListTraits<NamedMDNode, Module>;
1007 friend struct ilist_traits<NamedMDNode>;
1008 friend class LLVMContextImpl;
1009 friend class Module;
1010 NamedMDNode(const NamedMDNode &) = delete;
1014 void *Operands; // SmallVector<TrackingMDRef, 4>
1016 void setParent(Module *M) { Parent = M; }
1018 explicit NamedMDNode(const Twine &N);
1020 template<class T1, class T2>
1021 class op_iterator_impl :
1022 public std::iterator<std::bidirectional_iterator_tag, T2> {
1023 const NamedMDNode *Node;
1025 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1027 friend class NamedMDNode;
1030 op_iterator_impl() : Node(nullptr), Idx(0) { }
1032 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1033 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1034 op_iterator_impl &operator++() {
1038 op_iterator_impl operator++(int) {
1039 op_iterator_impl tmp(*this);
1043 op_iterator_impl &operator--() {
1047 op_iterator_impl operator--(int) {
1048 op_iterator_impl tmp(*this);
1053 T1 operator*() const { return Node->getOperand(Idx); }
1057 /// \brief Drop all references and remove the node from parent module.
1058 void eraseFromParent();
1060 /// \brief Remove all uses and clear node vector.
1061 void dropAllReferences();
1065 /// \brief Get the module that holds this named metadata collection.
1066 inline Module *getParent() { return Parent; }
1067 inline const Module *getParent() const { return Parent; }
1069 MDNode *getOperand(unsigned i) const;
1070 unsigned getNumOperands() const;
1071 void addOperand(MDNode *M);
1072 void setOperand(unsigned I, MDNode *New);
1073 StringRef getName() const;
1074 void print(raw_ostream &ROS) const;
1077 // ---------------------------------------------------------------------------
1078 // Operand Iterator interface...
1080 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1081 op_iterator op_begin() { return op_iterator(this, 0); }
1082 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1084 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1085 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1086 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1088 inline iterator_range<op_iterator> operands() {
1089 return iterator_range<op_iterator>(op_begin(), op_end());
1091 inline iterator_range<const_op_iterator> operands() const {
1092 return iterator_range<const_op_iterator>(op_begin(), op_end());
1096 } // end llvm namespace