X-Git-Url: http://demsky.eecs.uci.edu/git/?a=blobdiff_plain;f=include%2Fllvm%2FIR%2FMetadata.h;h=8805cec1471b8832d9cfafebcb2b5c83f031c0c1;hb=2b762697564ca1e12e0e974e93ceeb4c3420505c;hp=81107e6980670991d0d995fe32f5273c7cdbf690;hpb=86704cc3557b8933c2dd49fb130b9c5ace27e3f7;p=oota-llvm.git diff --git a/include/llvm/IR/Metadata.h b/include/llvm/IR/Metadata.h index 81107e69806..8805cec1471 100644 --- a/include/llvm/IR/Metadata.h +++ b/include/llvm/IR/Metadata.h @@ -1,4 +1,4 @@ -//===-- llvm/Metadata.h - Metadata definitions ------------------*- C++ -*-===// +//===- llvm/IR/Metadata.h - Metadata definitions ----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -27,14 +27,13 @@ #include namespace llvm { + class LLVMContext; class Module; -template - class SymbolTableListTraits; - +class ModuleSlotTracker; enum LLVMConstants : uint32_t { - DEBUG_METADATA_VERSION = 2 // Current debug info version number. + DEBUG_METADATA_VERSION = 3 // Current debug info version number. }; /// \brief Root of the metadata hierarchy. @@ -47,8 +46,11 @@ class Metadata { const unsigned char SubclassID; protected: + /// \brief Active type of storage. + enum StorageType { Uniqued, Distinct, Temporary }; + /// \brief Storage flag for non-uniqued, otherwise unowned, metadata. - bool IsDistinctInContext : 1; + unsigned Storage : 2; // TODO: expose remaining bits to subclasses. unsigned short SubclassData16; @@ -56,21 +58,39 @@ protected: public: enum MetadataKind { - GenericMDNodeKind, - MDNodeFwdDeclKind, + MDTupleKind, + DILocationKind, + GenericDINodeKind, + DISubrangeKind, + DIEnumeratorKind, + DIBasicTypeKind, + DIDerivedTypeKind, + DICompositeTypeKind, + DISubroutineTypeKind, + DIFileKind, + DICompileUnitKind, + DISubprogramKind, + DILexicalBlockKind, + DILexicalBlockFileKind, + DINamespaceKind, + DIModuleKind, + DITemplateTypeParameterKind, + DITemplateValueParameterKind, + DIGlobalVariableKind, + DILocalVariableKind, + DIExpressionKind, + DIObjCPropertyKind, + DIImportedEntityKind, ConstantAsMetadataKind, LocalAsMetadataKind, MDStringKind }; protected: - Metadata(unsigned ID) - : SubclassID(ID), IsDistinctInContext(false), SubclassData16(0), - SubclassData32(0) {} - ~Metadata() {} - - /// \brief Store this in a big non-uniqued untyped bucket. - bool isStoredDistinctInContext() const { return IsDistinctInContext; } + Metadata(unsigned ID, StorageType Storage) + : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) { + } + ~Metadata() = default; /// \brief Default handling of a changed operand, which asserts. /// @@ -84,15 +104,57 @@ public: unsigned getMetadataID() const { return SubclassID; } /// \brief User-friendly dump. + /// + /// If \c M is provided, metadata nodes will be numbered canonically; + /// otherwise, pointer addresses are substituted. + /// + /// Note: this uses an explicit overload instead of default arguments so that + /// the nullptr version is easy to call from a debugger. + /// + /// @{ void dump() const; - void print(raw_ostream &OS) const; - void printAsOperand(raw_ostream &OS, bool PrintType = true, + void dump(const Module *M) const; + /// @} + + /// \brief Print. + /// + /// Prints definition of \c this. + /// + /// If \c M is provided, metadata nodes will be numbered canonically; + /// otherwise, pointer addresses are substituted. + /// @{ + void print(raw_ostream &OS, const Module *M = nullptr, + bool IsForDebug = false) const; + void print(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr, + bool IsForDebug = false) const; + /// @} + + /// \brief Print as operand. + /// + /// Prints reference of \c this. + /// + /// If \c M is provided, metadata nodes will be numbered canonically; + /// otherwise, pointer addresses are substituted. + /// @{ + void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const; + void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr) const; + /// @} }; #define HANDLE_METADATA(CLASS) class CLASS; #include "llvm/IR/Metadata.def" +// Provide specializations of isa so that we don't need definitions of +// subclasses to see if the metadata is a subclass. +#define HANDLE_METADATA_LEAF(CLASS) \ + template <> struct isa_impl { \ + static inline bool doit(const Metadata &MD) { \ + return MD.getMetadataID() == Metadata::CLASS##Kind; \ + } \ + }; +#include "llvm/IR/Metadata.def" + inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) { MD.print(OS); return OS; @@ -112,7 +174,10 @@ class MetadataAsValue : public Value { Metadata *MD; MetadataAsValue(Type *Ty, Metadata *MD); - ~MetadataAsValue(); + ~MetadataAsValue() override; + + /// \brief Drop use of metadata (during teardown). + void dropUse() { MD = nullptr; } public: static MetadataAsValue *get(LLVMContext &Context, Metadata *MD); @@ -141,13 +206,19 @@ public: typedef MetadataTracking::OwnerTy OwnerTy; private: - SmallDenseMap UseMap; + LLVMContext &Context; + uint64_t NextIndex; + SmallDenseMap, 4> UseMap; public: + ReplaceableMetadataImpl(LLVMContext &Context) + : Context(Context), NextIndex(0) {} ~ReplaceableMetadataImpl() { assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata"); } + LLVMContext &getContext() const { return Context; } + /// \brief Replace all uses of this with MD. /// /// Replace all uses of this with \c MD, which is allowed to be null. @@ -156,8 +227,8 @@ public: /// \brief Resolve all uses of this. /// /// Resolve all uses of this, turning off RAUW permanently. If \c - /// ResolveUsers, call \a GenericMDNode::resolve() on any users whose last - /// operand is resolved. + /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand + /// is resolved. void resolveAllUses(bool ResolveUsers = true); private: @@ -182,12 +253,17 @@ class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl { Value *V; + /// \brief Drop users without RAUW (during teardown). + void dropUsers() { + ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false); + } + protected: - ValueAsMetadata(LLVMContext &Context, unsigned ID, Value *V) - : Metadata(ID), V(V) { + ValueAsMetadata(unsigned ID, Value *V) + : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) { assert(V && "Expected valid value"); } - ~ValueAsMetadata() {} + ~ValueAsMetadata() = default; public: static ValueAsMetadata *get(Value *V); @@ -233,8 +309,8 @@ public: class ConstantAsMetadata : public ValueAsMetadata { friend class ValueAsMetadata; - ConstantAsMetadata(LLVMContext &Context, Constant *C) - : ValueAsMetadata(Context, ConstantAsMetadataKind, C) {} + ConstantAsMetadata(Constant *C) + : ValueAsMetadata(ConstantAsMetadataKind, C) {} public: static ConstantAsMetadata *get(Constant *C) { @@ -256,8 +332,8 @@ public: class LocalAsMetadata : public ValueAsMetadata { friend class ValueAsMetadata; - LocalAsMetadata(LLVMContext &Context, Value *Local) - : ValueAsMetadata(Context, LocalAsMetadataKind, Local) { + LocalAsMetadata(Value *Local) + : ValueAsMetadata(LocalAsMetadataKind, Local) { assert(!isa(Local) && "Expected local value"); } @@ -430,13 +506,13 @@ dyn_extract_or_null(Y &&MD) { class MDString : public Metadata { friend class StringMapEntry; - MDString(const MDString &) LLVM_DELETED_FUNCTION; - MDString &operator=(MDString &&) LLVM_DELETED_FUNCTION; - MDString &operator=(const MDString &) LLVM_DELETED_FUNCTION; + MDString(const MDString &) = delete; + MDString &operator=(MDString &&) = delete; + MDString &operator=(const MDString &) = delete; StringMapEntry *Entry; - MDString() : Metadata(MDStringKind), Entry(nullptr) {} - MDString(MDString &&) : Metadata(MDStringKind) {} + MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {} + MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {} public: static MDString *get(LLVMContext &Context, StringRef Str); @@ -456,6 +532,9 @@ public: /// \brief Pointer to one byte past the end of the string. iterator end() const { return getString().end(); } + const unsigned char *bytes_begin() const { return getString().bytes_begin(); } + const unsigned char *bytes_end() const { return getString().bytes_end(); } + /// \brief Methods for support type inquiry through isa, cast, and dyn_cast. static bool classof(const Metadata *MD) { return MD->getMetadataID() == MDStringKind; @@ -475,7 +554,7 @@ struct AAMDNodes { bool operator!=(const AAMDNodes &A) const { return !(*this == A); } - LLVM_EXPLICIT operator bool() const { return TBAA || Scope || NoAlias; } + explicit operator bool() const { return TBAA || Scope || NoAlias; } /// \brief The tag for type-based alias analysis. MDNode *TBAA; @@ -491,10 +570,12 @@ struct AAMDNodes { template<> struct DenseMapInfo { static inline AAMDNodes getEmptyKey() { - return AAMDNodes(DenseMapInfo::getEmptyKey(), 0, 0); + return AAMDNodes(DenseMapInfo::getEmptyKey(), + nullptr, nullptr); } static inline AAMDNodes getTombstoneKey() { - return AAMDNodes(DenseMapInfo::getTombstoneKey(), 0, 0); + return AAMDNodes(DenseMapInfo::getTombstoneKey(), + nullptr, nullptr); } static unsigned getHashValue(const AAMDNodes &Val) { return DenseMapInfo::getHashValue(Val.TBAA) ^ @@ -514,10 +595,10 @@ struct DenseMapInfo { /// /// In particular, this is used by \a MDNode. class MDOperand { - MDOperand(MDOperand &&) LLVM_DELETED_FUNCTION; - MDOperand(const MDOperand &) LLVM_DELETED_FUNCTION; - MDOperand &operator=(MDOperand &&) LLVM_DELETED_FUNCTION; - MDOperand &operator=(const MDOperand &) LLVM_DELETED_FUNCTION; + MDOperand(MDOperand &&) = delete; + MDOperand(const MDOperand &) = delete; + MDOperand &operator=(MDOperand &&) = delete; + MDOperand &operator=(const MDOperand &) = delete; Metadata *MD; @@ -566,22 +647,111 @@ template <> struct simplify_type { static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); } }; -//===----------------------------------------------------------------------===// -/// \brief Tuple of metadata. +/// \brief Pointer to the context, with optional RAUW support. +/// +/// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer +/// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext). +class ContextAndReplaceableUses { + PointerUnion Ptr; + + ContextAndReplaceableUses() = delete; + ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete; + ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete; + ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete; + ContextAndReplaceableUses & + operator=(const ContextAndReplaceableUses &) = delete; + +public: + ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {} + ContextAndReplaceableUses( + std::unique_ptr ReplaceableUses) + : Ptr(ReplaceableUses.release()) { + assert(getReplaceableUses() && "Expected non-null replaceable uses"); + } + ~ContextAndReplaceableUses() { delete getReplaceableUses(); } + + operator LLVMContext &() { return getContext(); } + + /// \brief Whether this contains RAUW support. + bool hasReplaceableUses() const { + return Ptr.is(); + } + LLVMContext &getContext() const { + if (hasReplaceableUses()) + return getReplaceableUses()->getContext(); + return *Ptr.get(); + } + ReplaceableMetadataImpl *getReplaceableUses() const { + if (hasReplaceableUses()) + return Ptr.get(); + return nullptr; + } + + /// \brief Assign RAUW support to this. + /// + /// Make this replaceable, taking ownership of \c ReplaceableUses (which must + /// not be null). + void + makeReplaceable(std::unique_ptr ReplaceableUses) { + assert(ReplaceableUses && "Expected non-null replaceable uses"); + assert(&ReplaceableUses->getContext() == &getContext() && + "Expected same context"); + delete getReplaceableUses(); + Ptr = ReplaceableUses.release(); + } + + /// \brief Drop RAUW support. + /// + /// Cede ownership of RAUW support, returning it. + std::unique_ptr takeReplaceableUses() { + assert(hasReplaceableUses() && "Expected to own replaceable uses"); + std::unique_ptr ReplaceableUses( + getReplaceableUses()); + Ptr = &ReplaceableUses->getContext(); + return ReplaceableUses; + } +}; + +struct TempMDNodeDeleter { + inline void operator()(MDNode *Node) const; +}; + +#define HANDLE_MDNODE_LEAF(CLASS) \ + typedef std::unique_ptr Temp##CLASS; +#define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS) +#include "llvm/IR/Metadata.def" + +/// \brief Metadata node. +/// +/// Metadata nodes can be uniqued, like constants, or distinct. Temporary +/// metadata nodes (with full support for RAUW) can be used to delay uniquing +/// until forward references are known. The basic metadata node is an \a +/// MDTuple. +/// +/// There is limited support for RAUW at construction time. At construction +/// time, if any operand is a temporary node (or an unresolved uniqued node, +/// which indicates a transitive temporary operand), the node itself will be +/// unresolved. As soon as all operands become resolved, it will drop RAUW +/// support permanently. +/// +/// If an unresolved node is part of a cycle, \a resolveCycles() needs +/// to be called on some member of the cycle once all temporary nodes have been +/// replaced. class MDNode : public Metadata { - MDNode(const MDNode &) LLVM_DELETED_FUNCTION; - void operator=(const MDNode &) LLVM_DELETED_FUNCTION; - void *operator new(size_t) LLVM_DELETED_FUNCTION; + friend class ReplaceableMetadataImpl; + friend class LLVMContextImpl; + + MDNode(const MDNode &) = delete; + void operator=(const MDNode &) = delete; + void *operator new(size_t) = delete; - LLVMContext &Context; unsigned NumOperands; + unsigned NumUnresolved; protected: - unsigned MDNodeSubclassData; + ContextAndReplaceableUses Context; void *operator new(size_t Size, unsigned NumOps); - - /// \brief Required by std, but never called. void operator delete(void *Mem); /// \brief Required by std, but never called. @@ -594,52 +764,113 @@ protected: llvm_unreachable("Constructor throws?"); } - MDNode(LLVMContext &Context, unsigned ID, ArrayRef MDs); - ~MDNode() { dropAllReferences(); } + MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, + ArrayRef Ops1, ArrayRef Ops2 = None); + ~MDNode() = default; void dropAllReferences(); - void storeDistinctInContext(); - - static MDNode *getMDNode(LLVMContext &C, ArrayRef MDs, - bool Insert = true); MDOperand *mutable_begin() { return mutable_end() - NumOperands; } MDOperand *mutable_end() { return reinterpret_cast(this); } -public: - static MDNode *get(LLVMContext &Context, ArrayRef MDs) { - return getMDNode(Context, MDs, true); - } - static MDNode *getWhenValsUnresolved(LLVMContext &Context, - ArrayRef MDs) { - // TODO: Remove this. - return get(Context, MDs); - } - - static MDNode *getIfExists(LLVMContext &Context, ArrayRef MDs) { - return getMDNode(Context, MDs, false); + typedef iterator_range mutable_op_range; + mutable_op_range mutable_operands() { + return mutable_op_range(mutable_begin(), mutable_end()); } - /// \brief Return a temporary MDNode - /// - /// For use in constructing cyclic MDNode structures. A temporary MDNode is - /// not uniqued, may be RAUW'd, and must be manually deleted with - /// deleteTemporary. - static MDNodeFwdDecl *getTemporary(LLVMContext &Context, +public: + static inline MDTuple *get(LLVMContext &Context, ArrayRef MDs); + static inline MDTuple *getIfExists(LLVMContext &Context, ArrayRef MDs); + static inline MDTuple *getDistinct(LLVMContext &Context, + ArrayRef MDs); + static inline TempMDTuple getTemporary(LLVMContext &Context, + ArrayRef MDs); + + /// \brief Create a (temporary) clone of this. + TempMDNode clone() const; /// \brief Deallocate a node created by getTemporary. /// - /// The node must not have any users. + /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining + /// references will be reset. static void deleteTemporary(MDNode *N); - LLVMContext &getContext() const { return Context; } + LLVMContext &getContext() const { return Context.getContext(); } /// \brief Replace a specific operand. void replaceOperandWith(unsigned I, Metadata *New); /// \brief Check if node is fully resolved. - bool isResolved() const; + /// + /// If \a isTemporary(), this always returns \c false; if \a isDistinct(), + /// this always returns \c true. + /// + /// If \a isUniqued(), returns \c true if this has already dropped RAUW + /// support (because all operands are resolved). + /// + /// As forward declarations are resolved, their containers should get + /// resolved automatically. However, if this (or one of its operands) is + /// involved in a cycle, \a resolveCycles() needs to be called explicitly. + bool isResolved() const { return !Context.hasReplaceableUses(); } + + bool isUniqued() const { return Storage == Uniqued; } + bool isDistinct() const { return Storage == Distinct; } + bool isTemporary() const { return Storage == Temporary; } + + /// \brief RAUW a temporary. + /// + /// \pre \a isTemporary() must be \c true. + void replaceAllUsesWith(Metadata *MD) { + assert(isTemporary() && "Expected temporary node"); + assert(!isResolved() && "Expected RAUW support"); + Context.getReplaceableUses()->replaceAllUsesWith(MD); + } + + /// \brief Resolve cycles. + /// + /// Once all forward declarations have been resolved, force cycles to be + /// resolved. + /// + /// \pre No operands (or operands' operands, etc.) have \a isTemporary(). + void resolveCycles(); + + /// \brief Replace a temporary node with a permanent one. + /// + /// Try to create a uniqued version of \c N -- in place, if possible -- and + /// return it. If \c N cannot be uniqued, return a distinct node instead. + template + static typename std::enable_if::value, T *>::type + replaceWithPermanent(std::unique_ptr N) { + return cast(N.release()->replaceWithPermanentImpl()); + } + + /// \brief Replace a temporary node with a uniqued one. + /// + /// Create a uniqued version of \c N -- in place, if possible -- and return + /// it. Takes ownership of the temporary node. + /// + /// \pre N does not self-reference. + template + static typename std::enable_if::value, T *>::type + replaceWithUniqued(std::unique_ptr N) { + return cast(N.release()->replaceWithUniquedImpl()); + } + + /// \brief Replace a temporary node with a distinct one. + /// + /// Create a distinct version of \c N -- in place, if possible -- and return + /// it. Takes ownership of the temporary node. + template + static typename std::enable_if::value, T *>::type + replaceWithDistinct(std::unique_ptr N) { + return cast(N.release()->replaceWithDistinctImpl()); + } + +private: + MDNode *replaceWithPermanentImpl(); + MDNode *replaceWithUniquedImpl(); + MDNode *replaceWithDistinctImpl(); protected: /// \brief Set an operand. @@ -647,6 +878,50 @@ protected: /// Sets the operand directly, without worrying about uniquing. void setOperand(unsigned I, Metadata *New); + void storeDistinctInContext(); + template + static T *storeImpl(T *N, StorageType Storage, StoreT &Store); + template static T *storeImpl(T *N, StorageType Storage); + +private: + void handleChangedOperand(void *Ref, Metadata *New); + + void resolve(); + void resolveAfterOperandChange(Metadata *Old, Metadata *New); + void decrementUnresolvedOperandCount(); + unsigned countUnresolvedOperands(); + + /// \brief Mutate this to be "uniqued". + /// + /// Mutate this so that \a isUniqued(). + /// \pre \a isTemporary(). + /// \pre already added to uniquing set. + void makeUniqued(); + + /// \brief Mutate this to be "distinct". + /// + /// Mutate this so that \a isDistinct(). + /// \pre \a isTemporary(). + void makeDistinct(); + + void deleteAsSubclass(); + MDNode *uniquify(); + void eraseFromStore(); + + template struct HasCachedHash; + template + static void dispatchRecalculateHash(NodeTy *N, std::true_type) { + N->recalculateHash(); + } + template + static void dispatchRecalculateHash(NodeTy *, std::false_type) {} + template + static void dispatchResetHash(NodeTy *N, std::true_type) { + N->setHash(0); + } + template + static void dispatchResetHash(NodeTy *, std::false_type) {} + public: typedef const MDOperand *op_iterator; typedef iterator_range op_range; @@ -669,8 +944,14 @@ public: /// \brief Methods for support type inquiry through isa, cast, and dyn_cast: static bool classof(const Metadata *MD) { - return MD->getMetadataID() == GenericMDNodeKind || - MD->getMetadataID() == MDNodeFwdDeclKind; + switch (MD->getMetadataID()) { + default: + return false; +#define HANDLE_MDNODE_LEAF(CLASS) \ + case CLASS##Kind: \ + return true; +#include "llvm/IR/Metadata.def" + } } /// \brief Check whether MDNode is a vtable access. @@ -680,99 +961,165 @@ public: static MDNode *concatenate(MDNode *A, MDNode *B); static MDNode *intersect(MDNode *A, MDNode *B); static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B); - static AAMDNodes getMostGenericAA(const AAMDNodes &A, const AAMDNodes &B); static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B); static MDNode *getMostGenericRange(MDNode *A, MDNode *B); + static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B); + static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B); + }; -/// \brief Generic metadata node. -/// -/// Generic metadata nodes, with opt-out support for uniquing. -/// -/// Although nodes are uniqued by default, \a GenericMDNode has no support for -/// RAUW. If an operand change (due to RAUW or otherwise) causes a uniquing -/// collision, the uniquing bit is dropped. +/// \brief Tuple of metadata. /// -/// TODO: Make uniquing opt-out (status: mandatory, sometimes dropped). -/// TODO: Drop support for RAUW. -class GenericMDNode : public MDNode { - friend class Metadata; - friend class MDNode; +/// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by +/// default based on their operands. +class MDTuple : public MDNode { friend class LLVMContextImpl; - friend class ReplaceableMetadataImpl; + friend class MDNode; - /// \brief Support RAUW as long as one of its arguments is replaceable. - /// - /// If an operand is an \a MDNodeFwdDecl (or a replaceable \a GenericMDNode), - /// support RAUW to support uniquing as forward declarations are resolved. - /// As soon as operands have been resolved, drop support. - /// - /// FIXME: Save memory by storing this in a pointer union with the - /// LLVMContext, and adding an LLVMContext reference to RMI. - std::unique_ptr ReplaceableUses; + MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash, + ArrayRef Vals) + : MDNode(C, MDTupleKind, Storage, Vals) { + setHash(Hash); + } + ~MDTuple() { dropAllReferences(); } - GenericMDNode(LLVMContext &C, ArrayRef Vals); - ~GenericMDNode(); + void setHash(unsigned Hash) { SubclassData32 = Hash; } + void recalculateHash(); - void setHash(unsigned Hash) { MDNodeSubclassData = Hash; } + static MDTuple *getImpl(LLVMContext &Context, ArrayRef MDs, + StorageType Storage, bool ShouldCreate = true); + + TempMDTuple cloneImpl() const { + return getTemporary(getContext(), + SmallVector(op_begin(), op_end())); + } public: /// \brief Get the hash, if any. - unsigned getHash() const { return MDNodeSubclassData; } + unsigned getHash() const { return SubclassData32; } - static bool classof(const Metadata *MD) { - return MD->getMetadataID() == GenericMDNodeKind; + static MDTuple *get(LLVMContext &Context, ArrayRef MDs) { + return getImpl(Context, MDs, Uniqued); + } + static MDTuple *getIfExists(LLVMContext &Context, ArrayRef MDs) { + return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false); } - /// \brief Check whether any operands are forward declarations. - /// - /// Returns \c true as long as any operands (or their operands, etc.) are \a - /// MDNodeFwdDecl. + /// \brief Return a distinct node. /// - /// As forward declarations are resolved, their containers should get - /// resolved automatically. However, if this (or one of its operands) is - /// involved in a cycle, \a resolveCycles() needs to be called explicitly. - bool isResolved() const { return !ReplaceableUses; } + /// Return a distinct node -- i.e., a node that is not uniqued. + static MDTuple *getDistinct(LLVMContext &Context, ArrayRef MDs) { + return getImpl(Context, MDs, Distinct); + } - /// \brief Resolve cycles. + /// \brief Return a temporary node. /// - /// Once all forward declarations have been resolved, force cycles to be - /// resolved. - /// - /// \pre No operands (or operands' operands, etc.) are \a MDNodeFwdDecl. - void resolveCycles(); + /// For use in constructing cyclic MDNode structures. A temporary MDNode is + /// not uniqued, may be RAUW'd, and must be manually deleted with + /// deleteTemporary. + static TempMDTuple getTemporary(LLVMContext &Context, + ArrayRef MDs) { + return TempMDTuple(getImpl(Context, MDs, Temporary)); + } -private: - void handleChangedOperand(void *Ref, Metadata *New); + /// \brief Return a (temporary) clone of this. + TempMDTuple clone() const { return cloneImpl(); } - bool hasUnresolvedOperands() const { return SubclassData32; } - void incrementUnresolvedOperands() { ++SubclassData32; } - void decrementUnresolvedOperands() { --SubclassData32; } - void resolve(); + static bool classof(const Metadata *MD) { + return MD->getMetadataID() == MDTupleKind; + } }; -/// \brief Forward declaration of metadata. -/// -/// Forward declaration of metadata, in the form of a metadata node. Unlike \a -/// GenericMDNode, this class has support for RAUW and is suitable for forward -/// references. -class MDNodeFwdDecl : public MDNode, ReplaceableMetadataImpl { - friend class Metadata; - friend class MDNode; - friend class ReplaceableMetadataImpl; +MDTuple *MDNode::get(LLVMContext &Context, ArrayRef MDs) { + return MDTuple::get(Context, MDs); +} +MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef MDs) { + return MDTuple::getIfExists(Context, MDs); +} +MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef MDs) { + return MDTuple::getDistinct(Context, MDs); +} +TempMDTuple MDNode::getTemporary(LLVMContext &Context, + ArrayRef MDs) { + return MDTuple::getTemporary(Context, MDs); +} + +void TempMDNodeDeleter::operator()(MDNode *Node) const { + MDNode::deleteTemporary(Node); +} - MDNodeFwdDecl(LLVMContext &C, ArrayRef Vals) - : MDNode(C, MDNodeFwdDeclKind, Vals) {} - ~MDNodeFwdDecl() {} +/// \brief Typed iterator through MDNode operands. +/// +/// An iterator that transforms an \a MDNode::iterator into an iterator over a +/// particular Metadata subclass. +template +class TypedMDOperandIterator + : std::iterator { + MDNode::op_iterator I = nullptr; public: - static bool classof(const Metadata *MD) { - return MD->getMetadataID() == MDNodeFwdDeclKind; + TypedMDOperandIterator() = default; + explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {} + T *operator*() const { return cast_or_null(*I); } + TypedMDOperandIterator &operator++() { + ++I; + return *this; } + TypedMDOperandIterator operator++(int) { + TypedMDOperandIterator Temp(*this); + ++I; + return Temp; + } + bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; } + bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; } +}; - using ReplaceableMetadataImpl::replaceAllUsesWith; +/// \brief Typed, array-like tuple of metadata. +/// +/// This is a wrapper for \a MDTuple that makes it act like an array holding a +/// particular type of metadata. +template class MDTupleTypedArrayWrapper { + const MDTuple *N = nullptr; + +public: + MDTupleTypedArrayWrapper() = default; + MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {} + + template + MDTupleTypedArrayWrapper( + const MDTupleTypedArrayWrapper &Other, + typename std::enable_if::value>::type * = + nullptr) + : N(Other.get()) {} + + template + explicit MDTupleTypedArrayWrapper( + const MDTupleTypedArrayWrapper &Other, + typename std::enable_if::value>::type * = + nullptr) + : N(Other.get()) {} + + explicit operator bool() const { return get(); } + explicit operator MDTuple *() const { return get(); } + + MDTuple *get() const { return const_cast(N); } + MDTuple *operator->() const { return get(); } + MDTuple &operator*() const { return *get(); } + + // FIXME: Fix callers and remove condition on N. + unsigned size() const { return N ? N->getNumOperands() : 0u; } + T *operator[](unsigned I) const { return cast_or_null(N->getOperand(I)); } + + // FIXME: Fix callers and remove condition on N. + typedef TypedMDOperandIterator iterator; + iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); } + iterator end() const { return N ? iterator(N->op_end()) : iterator(); } }; +#define HANDLE_METADATA(CLASS) \ + typedef MDTupleTypedArrayWrapper CLASS##Array; +#include "llvm/IR/Metadata.def" + //===----------------------------------------------------------------------===// /// \brief A tuple of MDNodes. /// @@ -781,11 +1128,10 @@ public: /// /// TODO: Inherit from Metadata. class NamedMDNode : public ilist_node { - friend class SymbolTableListTraits; friend struct ilist_traits; friend class LLVMContextImpl; friend class Module; - NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION; + NamedMDNode(const NamedMDNode &) = delete; std::string Name; Module *Parent; @@ -847,8 +1193,9 @@ public: MDNode *getOperand(unsigned i) const; unsigned getNumOperands() const; void addOperand(MDNode *M); + void setOperand(unsigned I, MDNode *New); StringRef getName() const; - void print(raw_ostream &ROS) const; + void print(raw_ostream &ROS, bool IsForDebug = false) const; void dump() const; // --------------------------------------------------------------------------- @@ -872,4 +1219,4 @@ public: } // end llvm namespace -#endif +#endif // LLVM_IR_METADATA_H