LLVM  mainline
Metadata.h
Go to the documentation of this file.
00001 //===- llvm/IR/Metadata.h - Metadata definitions ----------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 /// @file
00011 /// This file contains the declarations for metadata subclasses.
00012 /// They represent the different flavors of metadata that live in LLVM.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #ifndef LLVM_IR_METADATA_H
00017 #define LLVM_IR_METADATA_H
00018 
00019 #include "llvm/ADT/ArrayRef.h"
00020 #include "llvm/ADT/DenseMap.h"
00021 #include "llvm/ADT/PointerUnion.h"
00022 #include "llvm/ADT/ilist_node.h"
00023 #include "llvm/ADT/iterator_range.h"
00024 #include "llvm/IR/Constant.h"
00025 #include "llvm/IR/LLVMContext.h"
00026 #include "llvm/IR/Value.h"
00027 #include "llvm/Support/ErrorHandling.h"
00028 #include <type_traits>
00029 
00030 namespace llvm {
00031 
00032 class LLVMContext;
00033 class Module;
00034 class ModuleSlotTracker;
00035 
00036 enum LLVMConstants : uint32_t {
00037   DEBUG_METADATA_VERSION = 3 // Current debug info version number.
00038 };
00039 
00040 /// \brief Root of the metadata hierarchy.
00041 ///
00042 /// This is a root class for typeless data in the IR.
00043 class Metadata {
00044   friend class ReplaceableMetadataImpl;
00045 
00046   /// \brief RTTI.
00047   const unsigned char SubclassID;
00048 
00049 protected:
00050   /// \brief Active type of storage.
00051   enum StorageType { Uniqued, Distinct, Temporary };
00052 
00053   /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
00054   unsigned Storage : 2;
00055   // TODO: expose remaining bits to subclasses.
00056 
00057   unsigned short SubclassData16;
00058   unsigned SubclassData32;
00059 
00060 public:
00061   enum MetadataKind {
00062     MDTupleKind,
00063     DILocationKind,
00064     GenericDINodeKind,
00065     DISubrangeKind,
00066     DIEnumeratorKind,
00067     DIBasicTypeKind,
00068     DIDerivedTypeKind,
00069     DICompositeTypeKind,
00070     DISubroutineTypeKind,
00071     DIFileKind,
00072     DICompileUnitKind,
00073     DISubprogramKind,
00074     DILexicalBlockKind,
00075     DILexicalBlockFileKind,
00076     DINamespaceKind,
00077     DIModuleKind,
00078     DITemplateTypeParameterKind,
00079     DITemplateValueParameterKind,
00080     DIGlobalVariableKind,
00081     DILocalVariableKind,
00082     DIExpressionKind,
00083     DIObjCPropertyKind,
00084     DIImportedEntityKind,
00085     ConstantAsMetadataKind,
00086     LocalAsMetadataKind,
00087     MDStringKind,
00088     DIMacroKind,
00089     DIMacroFileKind
00090   };
00091 
00092 protected:
00093   Metadata(unsigned ID, StorageType Storage)
00094       : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
00095   }
00096   ~Metadata() = default;
00097 
00098   /// \brief Default handling of a changed operand, which asserts.
00099   ///
00100   /// If subclasses pass themselves in as owners to a tracking node reference,
00101   /// they must provide an implementation of this method.
00102   void handleChangedOperand(void *, Metadata *) {
00103     llvm_unreachable("Unimplemented in Metadata subclass");
00104   }
00105 
00106 public:
00107   unsigned getMetadataID() const { return SubclassID; }
00108 
00109   /// \brief User-friendly dump.
00110   ///
00111   /// If \c M is provided, metadata nodes will be numbered canonically;
00112   /// otherwise, pointer addresses are substituted.
00113   ///
00114   /// Note: this uses an explicit overload instead of default arguments so that
00115   /// the nullptr version is easy to call from a debugger.
00116   ///
00117   /// @{
00118   void dump() const;
00119   void dump(const Module *M) const;
00120   /// @}
00121 
00122   /// \brief Print.
00123   ///
00124   /// Prints definition of \c this.
00125   ///
00126   /// If \c M is provided, metadata nodes will be numbered canonically;
00127   /// otherwise, pointer addresses are substituted.
00128   /// @{
00129   void print(raw_ostream &OS, const Module *M = nullptr,
00130              bool IsForDebug = false) const;
00131   void print(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr,
00132              bool IsForDebug = false) const;
00133   /// @}
00134 
00135   /// \brief Print as operand.
00136   ///
00137   /// Prints reference of \c this.
00138   ///
00139   /// If \c M is provided, metadata nodes will be numbered canonically;
00140   /// otherwise, pointer addresses are substituted.
00141   /// @{
00142   void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
00143   void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
00144                       const Module *M = nullptr) const;
00145   /// @}
00146 };
00147 
00148 #define HANDLE_METADATA(CLASS) class CLASS;
00149 #include "llvm/IR/Metadata.def"
00150 
00151 // Provide specializations of isa so that we don't need definitions of
00152 // subclasses to see if the metadata is a subclass.
00153 #define HANDLE_METADATA_LEAF(CLASS)                                            \
00154   template <> struct isa_impl<CLASS, Metadata> {                               \
00155     static inline bool doit(const Metadata &MD) {                              \
00156       return MD.getMetadataID() == Metadata::CLASS##Kind;                      \
00157     }                                                                          \
00158   };
00159 #include "llvm/IR/Metadata.def"
00160 
00161 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
00162   MD.print(OS);
00163   return OS;
00164 }
00165 
00166 /// \brief Metadata wrapper in the Value hierarchy.
00167 ///
00168 /// A member of the \a Value hierarchy to represent a reference to metadata.
00169 /// This allows, e.g., instrinsics to have metadata as operands.
00170 ///
00171 /// Notably, this is the only thing in either hierarchy that is allowed to
00172 /// reference \a LocalAsMetadata.
00173 class MetadataAsValue : public Value {
00174   friend class ReplaceableMetadataImpl;
00175   friend class LLVMContextImpl;
00176 
00177   Metadata *MD;
00178 
00179   MetadataAsValue(Type *Ty, Metadata *MD);
00180   ~MetadataAsValue() override;
00181 
00182   /// \brief Drop use of metadata (during teardown).
00183   void dropUse() { MD = nullptr; }
00184 
00185 public:
00186   static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
00187   static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
00188   Metadata *getMetadata() const { return MD; }
00189 
00190   static bool classof(const Value *V) {
00191     return V->getValueID() == MetadataAsValueVal;
00192   }
00193 
00194 private:
00195   void handleChangedMetadata(Metadata *MD);
00196   void track();
00197   void untrack();
00198 };
00199 
00200 /// \brief API for tracking metadata references through RAUW and deletion.
00201 ///
00202 /// Shared API for updating \a Metadata pointers in subclasses that support
00203 /// RAUW.
00204 ///
00205 /// This API is not meant to be used directly.  See \a TrackingMDRef for a
00206 /// user-friendly tracking reference.
00207 class MetadataTracking {
00208 public:
00209   /// \brief Track the reference to metadata.
00210   ///
00211   /// Register \c MD with \c *MD, if the subclass supports tracking.  If \c *MD
00212   /// gets RAUW'ed, \c MD will be updated to the new address.  If \c *MD gets
00213   /// deleted, \c MD will be set to \c nullptr.
00214   ///
00215   /// If tracking isn't supported, \c *MD will not change.
00216   ///
00217   /// \return true iff tracking is supported by \c MD.
00218   static bool track(Metadata *&MD) {
00219     return track(&MD, *MD, static_cast<Metadata *>(nullptr));
00220   }
00221 
00222   /// \brief Track the reference to metadata for \a Metadata.
00223   ///
00224   /// As \a track(Metadata*&), but with support for calling back to \c Owner to
00225   /// tell it that its operand changed.  This could trigger \c Owner being
00226   /// re-uniqued.
00227   static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
00228     return track(Ref, MD, &Owner);
00229   }
00230 
00231   /// \brief Track the reference to metadata for \a MetadataAsValue.
00232   ///
00233   /// As \a track(Metadata*&), but with support for calling back to \c Owner to
00234   /// tell it that its operand changed.  This could trigger \c Owner being
00235   /// re-uniqued.
00236   static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
00237     return track(Ref, MD, &Owner);
00238   }
00239 
00240   /// \brief Stop tracking a reference to metadata.
00241   ///
00242   /// Stops \c *MD from tracking \c MD.
00243   static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
00244   static void untrack(void *Ref, Metadata &MD);
00245 
00246   /// \brief Move tracking from one reference to another.
00247   ///
00248   /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
00249   /// except that ownership callbacks are maintained.
00250   ///
00251   /// Note: it is an error if \c *MD does not equal \c New.
00252   ///
00253   /// \return true iff tracking is supported by \c MD.
00254   static bool retrack(Metadata *&MD, Metadata *&New) {
00255     return retrack(&MD, *MD, &New);
00256   }
00257   static bool retrack(void *Ref, Metadata &MD, void *New);
00258 
00259   /// \brief Check whether metadata is replaceable.
00260   static bool isReplaceable(const Metadata &MD);
00261 
00262   typedef PointerUnion<MetadataAsValue *, Metadata *> OwnerTy;
00263 
00264 private:
00265   /// \brief Track a reference to metadata for an owner.
00266   ///
00267   /// Generalized version of tracking.
00268   static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
00269 };
00270 
00271 /// \brief Shared implementation of use-lists for replaceable metadata.
00272 ///
00273 /// Most metadata cannot be RAUW'ed.  This is a shared implementation of
00274 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
00275 /// and \a TempMDNode).
00276 class ReplaceableMetadataImpl {
00277   friend class MetadataTracking;
00278 
00279 public:
00280   typedef MetadataTracking::OwnerTy OwnerTy;
00281 
00282 private:
00283   LLVMContext &Context;
00284   uint64_t NextIndex;
00285   SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
00286   /// Flag that can be set to false if this metadata should not be
00287   /// RAUW'ed, e.g. if it is used as the key of a map.
00288   bool CanReplace;
00289 
00290 public:
00291   ReplaceableMetadataImpl(LLVMContext &Context)
00292       : Context(Context), NextIndex(0), CanReplace(true) {}
00293   ~ReplaceableMetadataImpl() {
00294     assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
00295   }
00296 
00297   /// Set the CanReplace flag to the given value.
00298   void setCanReplace(bool Replaceable) { CanReplace = Replaceable; }
00299 
00300   LLVMContext &getContext() const { return Context; }
00301 
00302   /// \brief Replace all uses of this with MD.
00303   ///
00304   /// Replace all uses of this with \c MD, which is allowed to be null.
00305   void replaceAllUsesWith(Metadata *MD);
00306 
00307   /// \brief Resolve all uses of this.
00308   ///
00309   /// Resolve all uses of this, turning off RAUW permanently.  If \c
00310   /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
00311   /// is resolved.
00312   void resolveAllUses(bool ResolveUsers = true);
00313 
00314 private:
00315   void addRef(void *Ref, OwnerTy Owner);
00316   void dropRef(void *Ref);
00317   void moveRef(void *Ref, void *New, const Metadata &MD);
00318 
00319   static ReplaceableMetadataImpl *get(Metadata &MD);
00320 };
00321 
00322 /// \brief Value wrapper in the Metadata hierarchy.
00323 ///
00324 /// This is a custom value handle that allows other metadata to refer to
00325 /// classes in the Value hierarchy.
00326 ///
00327 /// Because of full uniquing support, each value is only wrapped by a single \a
00328 /// ValueAsMetadata object, so the lookup maps are far more efficient than
00329 /// those using ValueHandleBase.
00330 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
00331   friend class ReplaceableMetadataImpl;
00332   friend class LLVMContextImpl;
00333 
00334   Value *V;
00335 
00336   /// \brief Drop users without RAUW (during teardown).
00337   void dropUsers() {
00338     ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
00339   }
00340 
00341 protected:
00342   ValueAsMetadata(unsigned ID, Value *V)
00343       : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
00344     assert(V && "Expected valid value");
00345   }
00346   ~ValueAsMetadata() = default;
00347 
00348 public:
00349   static ValueAsMetadata *get(Value *V);
00350   static ConstantAsMetadata *getConstant(Value *C) {
00351     return cast<ConstantAsMetadata>(get(C));
00352   }
00353   static LocalAsMetadata *getLocal(Value *Local) {
00354     return cast<LocalAsMetadata>(get(Local));
00355   }
00356 
00357   static ValueAsMetadata *getIfExists(Value *V);
00358   static ConstantAsMetadata *getConstantIfExists(Value *C) {
00359     return cast_or_null<ConstantAsMetadata>(getIfExists(C));
00360   }
00361   static LocalAsMetadata *getLocalIfExists(Value *Local) {
00362     return cast_or_null<LocalAsMetadata>(getIfExists(Local));
00363   }
00364 
00365   Value *getValue() const { return V; }
00366   Type *getType() const { return V->getType(); }
00367   LLVMContext &getContext() const { return V->getContext(); }
00368 
00369   static void handleDeletion(Value *V);
00370   static void handleRAUW(Value *From, Value *To);
00371 
00372 protected:
00373   /// \brief Handle collisions after \a Value::replaceAllUsesWith().
00374   ///
00375   /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
00376   /// \a Value gets RAUW'ed and the target already exists, this is used to
00377   /// merge the two metadata nodes.
00378   void replaceAllUsesWith(Metadata *MD) {
00379     ReplaceableMetadataImpl::replaceAllUsesWith(MD);
00380   }
00381 
00382 public:
00383   static bool classof(const Metadata *MD) {
00384     return MD->getMetadataID() == LocalAsMetadataKind ||
00385            MD->getMetadataID() == ConstantAsMetadataKind;
00386   }
00387 };
00388 
00389 class ConstantAsMetadata : public ValueAsMetadata {
00390   friend class ValueAsMetadata;
00391 
00392   ConstantAsMetadata(Constant *C)
00393       : ValueAsMetadata(ConstantAsMetadataKind, C) {}
00394 
00395 public:
00396   static ConstantAsMetadata *get(Constant *C) {
00397     return ValueAsMetadata::getConstant(C);
00398   }
00399   static ConstantAsMetadata *getIfExists(Constant *C) {
00400     return ValueAsMetadata::getConstantIfExists(C);
00401   }
00402 
00403   Constant *getValue() const {
00404     return cast<Constant>(ValueAsMetadata::getValue());
00405   }
00406 
00407   static bool classof(const Metadata *MD) {
00408     return MD->getMetadataID() == ConstantAsMetadataKind;
00409   }
00410 };
00411 
00412 class LocalAsMetadata : public ValueAsMetadata {
00413   friend class ValueAsMetadata;
00414 
00415   LocalAsMetadata(Value *Local)
00416       : ValueAsMetadata(LocalAsMetadataKind, Local) {
00417     assert(!isa<Constant>(Local) && "Expected local value");
00418   }
00419 
00420 public:
00421   static LocalAsMetadata *get(Value *Local) {
00422     return ValueAsMetadata::getLocal(Local);
00423   }
00424   static LocalAsMetadata *getIfExists(Value *Local) {
00425     return ValueAsMetadata::getLocalIfExists(Local);
00426   }
00427 
00428   static bool classof(const Metadata *MD) {
00429     return MD->getMetadataID() == LocalAsMetadataKind;
00430   }
00431 };
00432 
00433 /// \brief Transitional API for extracting constants from Metadata.
00434 ///
00435 /// This namespace contains transitional functions for metadata that points to
00436 /// \a Constants.
00437 ///
00438 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
00439 /// operands could refer to any \a Value.  There's was a lot of code like this:
00440 ///
00441 /// \code
00442 ///     MDNode *N = ...;
00443 ///     auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
00444 /// \endcode
00445 ///
00446 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
00447 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
00448 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
00449 /// cast in the \a Value hierarchy.  Besides creating boiler-plate, this
00450 /// requires subtle control flow changes.
00451 ///
00452 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
00453 /// so that metadata can refer to numbers without traversing a bridge to the \a
00454 /// Value hierarchy.  In this final state, the code above would look like this:
00455 ///
00456 /// \code
00457 ///     MDNode *N = ...;
00458 ///     auto *MI = dyn_cast<MDInt>(N->getOperand(2));
00459 /// \endcode
00460 ///
00461 /// The API in this namespace supports the transition.  \a MDInt doesn't exist
00462 /// yet, and even once it does, changing each metadata schema to use it is its
00463 /// own mini-project.  In the meantime this API prevents us from introducing
00464 /// complex and bug-prone control flow that will disappear in the end.  In
00465 /// particular, the above code looks like this:
00466 ///
00467 /// \code
00468 ///     MDNode *N = ...;
00469 ///     auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
00470 /// \endcode
00471 ///
00472 /// The full set of provided functions includes:
00473 ///
00474 ///   mdconst::hasa                <=> isa
00475 ///   mdconst::extract             <=> cast
00476 ///   mdconst::extract_or_null     <=> cast_or_null
00477 ///   mdconst::dyn_extract         <=> dyn_cast
00478 ///   mdconst::dyn_extract_or_null <=> dyn_cast_or_null
00479 ///
00480 /// The target of the cast must be a subclass of \a Constant.
00481 namespace mdconst {
00482 
00483 namespace detail {
00484 template <class T> T &make();
00485 template <class T, class Result> struct HasDereference {
00486   typedef char Yes[1];
00487   typedef char No[2];
00488   template <size_t N> struct SFINAE {};
00489 
00490   template <class U, class V>
00491   static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
00492   template <class U, class V> static No &hasDereference(...);
00493 
00494   static const bool value =
00495       sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
00496 };
00497 template <class V, class M> struct IsValidPointer {
00498   static const bool value = std::is_base_of<Constant, V>::value &&
00499                             HasDereference<M, const Metadata &>::value;
00500 };
00501 template <class V, class M> struct IsValidReference {
00502   static const bool value = std::is_base_of<Constant, V>::value &&
00503                             std::is_convertible<M, const Metadata &>::value;
00504 };
00505 } // end namespace detail
00506 
00507 /// \brief Check whether Metadata has a Value.
00508 ///
00509 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
00510 /// type \c X.
00511 template <class X, class Y>
00512 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
00513 hasa(Y &&MD) {
00514   assert(MD && "Null pointer sent into hasa");
00515   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
00516     return isa<X>(V->getValue());
00517   return false;
00518 }
00519 template <class X, class Y>
00520 inline
00521     typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
00522     hasa(Y &MD) {
00523   return hasa(&MD);
00524 }
00525 
00526 /// \brief Extract a Value from Metadata.
00527 ///
00528 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
00529 template <class X, class Y>
00530 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
00531 extract(Y &&MD) {
00532   return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
00533 }
00534 template <class X, class Y>
00535 inline
00536     typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
00537     extract(Y &MD) {
00538   return extract(&MD);
00539 }
00540 
00541 /// \brief Extract a Value from Metadata, allowing null.
00542 ///
00543 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
00544 /// from \c MD, allowing \c MD to be null.
00545 template <class X, class Y>
00546 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
00547 extract_or_null(Y &&MD) {
00548   if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
00549     return cast<X>(V->getValue());
00550   return nullptr;
00551 }
00552 
00553 /// \brief Extract a Value from Metadata, if any.
00554 ///
00555 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
00556 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
00557 /// Value it does contain is of the wrong subclass.
00558 template <class X, class Y>
00559 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
00560 dyn_extract(Y &&MD) {
00561   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
00562     return dyn_cast<X>(V->getValue());
00563   return nullptr;
00564 }
00565 
00566 /// \brief Extract a Value from Metadata, if any, allowing null.
00567 ///
00568 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
00569 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
00570 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
00571 template <class X, class Y>
00572 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
00573 dyn_extract_or_null(Y &&MD) {
00574   if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
00575     return dyn_cast<X>(V->getValue());
00576   return nullptr;
00577 }
00578 
00579 } // end namespace mdconst
00580 
00581 //===----------------------------------------------------------------------===//
00582 /// \brief A single uniqued string.
00583 ///
00584 /// These are used to efficiently contain a byte sequence for metadata.
00585 /// MDString is always unnamed.
00586 class MDString : public Metadata {
00587   friend class StringMapEntry<MDString>;
00588 
00589   MDString(const MDString &) = delete;
00590   MDString &operator=(MDString &&) = delete;
00591   MDString &operator=(const MDString &) = delete;
00592 
00593   StringMapEntry<MDString> *Entry;
00594   MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
00595   MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
00596 
00597 public:
00598   static MDString *get(LLVMContext &Context, StringRef Str);
00599   static MDString *get(LLVMContext &Context, const char *Str) {
00600     return get(Context, Str ? StringRef(Str) : StringRef());
00601   }
00602 
00603   StringRef getString() const;
00604 
00605   unsigned getLength() const { return (unsigned)getString().size(); }
00606 
00607   typedef StringRef::iterator iterator;
00608 
00609   /// \brief Pointer to the first byte of the string.
00610   iterator begin() const { return getString().begin(); }
00611 
00612   /// \brief Pointer to one byte past the end of the string.
00613   iterator end() const { return getString().end(); }
00614 
00615   const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
00616   const unsigned char *bytes_end() const { return getString().bytes_end(); }
00617 
00618   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
00619   static bool classof(const Metadata *MD) {
00620     return MD->getMetadataID() == MDStringKind;
00621   }
00622 };
00623 
00624 /// \brief A collection of metadata nodes that might be associated with a
00625 /// memory access used by the alias-analysis infrastructure.
00626 struct AAMDNodes {
00627   explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
00628                      MDNode *N = nullptr)
00629       : TBAA(T), Scope(S), NoAlias(N) {}
00630 
00631   bool operator==(const AAMDNodes &A) const {
00632     return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
00633   }
00634 
00635   bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
00636 
00637   explicit operator bool() const { return TBAA || Scope || NoAlias; }
00638 
00639   /// \brief The tag for type-based alias analysis.
00640   MDNode *TBAA;
00641 
00642   /// \brief The tag for alias scope specification (used with noalias).
00643   MDNode *Scope;
00644 
00645   /// \brief The tag specifying the noalias scope.
00646   MDNode *NoAlias;
00647 };
00648 
00649 // Specialize DenseMapInfo for AAMDNodes.
00650 template<>
00651 struct DenseMapInfo<AAMDNodes> {
00652   static inline AAMDNodes getEmptyKey() {
00653     return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
00654                      nullptr, nullptr);
00655   }
00656   static inline AAMDNodes getTombstoneKey() {
00657     return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
00658                      nullptr, nullptr);
00659   }
00660   static unsigned getHashValue(const AAMDNodes &Val) {
00661     return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
00662            DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
00663            DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
00664   }
00665   static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
00666     return LHS == RHS;
00667   }
00668 };
00669 
00670 /// \brief Tracking metadata reference owned by Metadata.
00671 ///
00672 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
00673 /// of \a Metadata, which has the option of registering itself for callbacks to
00674 /// re-unique itself.
00675 ///
00676 /// In particular, this is used by \a MDNode.
00677 class MDOperand {
00678   MDOperand(MDOperand &&) = delete;
00679   MDOperand(const MDOperand &) = delete;
00680   MDOperand &operator=(MDOperand &&) = delete;
00681   MDOperand &operator=(const MDOperand &) = delete;
00682 
00683   Metadata *MD;
00684 
00685 public:
00686   MDOperand() : MD(nullptr) {}
00687   ~MDOperand() { untrack(); }
00688 
00689   Metadata *get() const { return MD; }
00690   operator Metadata *() const { return get(); }
00691   Metadata *operator->() const { return get(); }
00692   Metadata &operator*() const { return *get(); }
00693 
00694   void reset() {
00695     untrack();
00696     MD = nullptr;
00697   }
00698   void reset(Metadata *MD, Metadata *Owner) {
00699     untrack();
00700     this->MD = MD;
00701     track(Owner);
00702   }
00703 
00704 private:
00705   void track(Metadata *Owner) {
00706     if (MD) {
00707       if (Owner)
00708         MetadataTracking::track(this, *MD, *Owner);
00709       else
00710         MetadataTracking::track(MD);
00711     }
00712   }
00713   void untrack() {
00714     assert(static_cast<void *>(this) == &MD && "Expected same address");
00715     if (MD)
00716       MetadataTracking::untrack(MD);
00717   }
00718 };
00719 
00720 template <> struct simplify_type<MDOperand> {
00721   typedef Metadata *SimpleType;
00722   static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
00723 };
00724 
00725 template <> struct simplify_type<const MDOperand> {
00726   typedef Metadata *SimpleType;
00727   static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
00728 };
00729 
00730 /// \brief Pointer to the context, with optional RAUW support.
00731 ///
00732 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
00733 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
00734 class ContextAndReplaceableUses {
00735   PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
00736 
00737   ContextAndReplaceableUses() = delete;
00738   ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
00739   ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
00740   ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
00741   ContextAndReplaceableUses &
00742   operator=(const ContextAndReplaceableUses &) = delete;
00743 
00744 public:
00745   ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
00746   ContextAndReplaceableUses(
00747       std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
00748       : Ptr(ReplaceableUses.release()) {
00749     assert(getReplaceableUses() && "Expected non-null replaceable uses");
00750   }
00751   ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
00752 
00753   operator LLVMContext &() { return getContext(); }
00754 
00755   /// \brief Whether this contains RAUW support.
00756   bool hasReplaceableUses() const {
00757     return Ptr.is<ReplaceableMetadataImpl *>();
00758   }
00759   LLVMContext &getContext() const {
00760     if (hasReplaceableUses())
00761       return getReplaceableUses()->getContext();
00762     return *Ptr.get<LLVMContext *>();
00763   }
00764   ReplaceableMetadataImpl *getReplaceableUses() const {
00765     if (hasReplaceableUses())
00766       return Ptr.get<ReplaceableMetadataImpl *>();
00767     return nullptr;
00768   }
00769 
00770   /// \brief Assign RAUW support to this.
00771   ///
00772   /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
00773   /// not be null).
00774   void
00775   makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
00776     assert(ReplaceableUses && "Expected non-null replaceable uses");
00777     assert(&ReplaceableUses->getContext() == &getContext() &&
00778            "Expected same context");
00779     delete getReplaceableUses();
00780     Ptr = ReplaceableUses.release();
00781   }
00782 
00783   /// \brief Drop RAUW support.
00784   ///
00785   /// Cede ownership of RAUW support, returning it.
00786   std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
00787     assert(hasReplaceableUses() && "Expected to own replaceable uses");
00788     std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
00789         getReplaceableUses());
00790     Ptr = &ReplaceableUses->getContext();
00791     return ReplaceableUses;
00792   }
00793 };
00794 
00795 struct TempMDNodeDeleter {
00796   inline void operator()(MDNode *Node) const;
00797 };
00798 
00799 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00800   typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
00801 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
00802 #include "llvm/IR/Metadata.def"
00803 
00804 /// \brief Metadata node.
00805 ///
00806 /// Metadata nodes can be uniqued, like constants, or distinct.  Temporary
00807 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
00808 /// until forward references are known.  The basic metadata node is an \a
00809 /// MDTuple.
00810 ///
00811 /// There is limited support for RAUW at construction time.  At construction
00812 /// time, if any operand is a temporary node (or an unresolved uniqued node,
00813 /// which indicates a transitive temporary operand), the node itself will be
00814 /// unresolved.  As soon as all operands become resolved, it will drop RAUW
00815 /// support permanently.
00816 ///
00817 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
00818 /// to be called on some member of the cycle once all temporary nodes have been
00819 /// replaced.
00820 class MDNode : public Metadata {
00821   friend class ReplaceableMetadataImpl;
00822   friend class LLVMContextImpl;
00823 
00824   MDNode(const MDNode &) = delete;
00825   void operator=(const MDNode &) = delete;
00826   void *operator new(size_t) = delete;
00827 
00828   unsigned NumOperands;
00829   unsigned NumUnresolved;
00830 
00831 protected:
00832   ContextAndReplaceableUses Context;
00833 
00834   void *operator new(size_t Size, unsigned NumOps);
00835   void operator delete(void *Mem);
00836 
00837   /// \brief Required by std, but never called.
00838   void operator delete(void *, unsigned) {
00839     llvm_unreachable("Constructor throws?");
00840   }
00841 
00842   /// \brief Required by std, but never called.
00843   void operator delete(void *, unsigned, bool) {
00844     llvm_unreachable("Constructor throws?");
00845   }
00846 
00847   MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
00848          ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
00849   ~MDNode() = default;
00850 
00851   void dropAllReferences();
00852 
00853   MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
00854   MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
00855 
00856   typedef iterator_range<MDOperand *> mutable_op_range;
00857   mutable_op_range mutable_operands() {
00858     return mutable_op_range(mutable_begin(), mutable_end());
00859   }
00860 
00861 public:
00862   static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
00863   static inline MDTuple *getIfExists(LLVMContext &Context,
00864                                      ArrayRef<Metadata *> MDs);
00865   static inline MDTuple *getDistinct(LLVMContext &Context,
00866                                      ArrayRef<Metadata *> MDs);
00867   static inline TempMDTuple getTemporary(LLVMContext &Context,
00868                                          ArrayRef<Metadata *> MDs);
00869 
00870   /// \brief Create a (temporary) clone of this.
00871   TempMDNode clone() const;
00872 
00873   /// \brief Deallocate a node created by getTemporary.
00874   ///
00875   /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
00876   /// references will be reset.
00877   static void deleteTemporary(MDNode *N);
00878 
00879   LLVMContext &getContext() const { return Context.getContext(); }
00880 
00881   /// \brief Replace a specific operand.
00882   void replaceOperandWith(unsigned I, Metadata *New);
00883 
00884   /// \brief Check if node is fully resolved.
00885   ///
00886   /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
00887   /// this always returns \c true.
00888   ///
00889   /// If \a isUniqued(), returns \c true if this has already dropped RAUW
00890   /// support (because all operands are resolved).
00891   ///
00892   /// As forward declarations are resolved, their containers should get
00893   /// resolved automatically.  However, if this (or one of its operands) is
00894   /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
00895   bool isResolved() const { return !Context.hasReplaceableUses(); }
00896 
00897   bool isUniqued() const { return Storage == Uniqued; }
00898   bool isDistinct() const { return Storage == Distinct; }
00899   bool isTemporary() const { return Storage == Temporary; }
00900 
00901   /// \brief RAUW a temporary.
00902   ///
00903   /// \pre \a isTemporary() must be \c true.
00904   void replaceAllUsesWith(Metadata *MD) {
00905     assert(isTemporary() && "Expected temporary node");
00906     assert(!isResolved() && "Expected RAUW support");
00907     Context.getReplaceableUses()->replaceAllUsesWith(MD);
00908   }
00909 
00910   /// Set the CanReplace flag to the given value.
00911   void setCanReplace(bool Replaceable) {
00912     Context.getReplaceableUses()->setCanReplace(Replaceable);
00913   }
00914 
00915   /// \brief Resolve cycles.
00916   ///
00917   /// Once all forward declarations have been resolved, force cycles to be
00918   /// resolved. This interface is used when there are no more temporaries,
00919   /// and thus unresolved nodes are part of cycles and no longer need RAUW
00920   /// support.
00921   ///
00922   /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
00923   void resolveCycles() { resolveRecursivelyImpl(/* AllowTemps */ false); }
00924 
00925   /// \brief Resolve cycles while ignoring temporaries.
00926   ///
00927   /// This drops RAUW support for any temporaries, which can no longer
00928   /// be uniqued.
00929   ///
00930   void resolveNonTemporaries() {
00931     resolveRecursivelyImpl(/* AllowTemps */ true);
00932   }
00933 
00934   /// \brief Replace a temporary node with a permanent one.
00935   ///
00936   /// Try to create a uniqued version of \c N -- in place, if possible -- and
00937   /// return it.  If \c N cannot be uniqued, return a distinct node instead.
00938   template <class T>
00939   static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
00940   replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
00941     return cast<T>(N.release()->replaceWithPermanentImpl());
00942   }
00943 
00944   /// \brief Replace a temporary node with a uniqued one.
00945   ///
00946   /// Create a uniqued version of \c N -- in place, if possible -- and return
00947   /// it.  Takes ownership of the temporary node.
00948   ///
00949   /// \pre N does not self-reference.
00950   template <class T>
00951   static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
00952   replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
00953     return cast<T>(N.release()->replaceWithUniquedImpl());
00954   }
00955 
00956   /// \brief Replace a temporary node with a distinct one.
00957   ///
00958   /// Create a distinct version of \c N -- in place, if possible -- and return
00959   /// it.  Takes ownership of the temporary node.
00960   template <class T>
00961   static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
00962   replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
00963     return cast<T>(N.release()->replaceWithDistinctImpl());
00964   }
00965 
00966 private:
00967   MDNode *replaceWithPermanentImpl();
00968   MDNode *replaceWithUniquedImpl();
00969   MDNode *replaceWithDistinctImpl();
00970 
00971 protected:
00972   /// \brief Set an operand.
00973   ///
00974   /// Sets the operand directly, without worrying about uniquing.
00975   void setOperand(unsigned I, Metadata *New);
00976 
00977   void storeDistinctInContext();
00978   template <class T, class StoreT>
00979   static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
00980   template <class T> static T *storeImpl(T *N, StorageType Storage);
00981 
00982 private:
00983   void handleChangedOperand(void *Ref, Metadata *New);
00984 
00985   void resolve();
00986   void resolveAfterOperandChange(Metadata *Old, Metadata *New);
00987   void decrementUnresolvedOperandCount();
00988   unsigned countUnresolvedOperands();
00989 
00990   /// Resolve cycles recursively. If \p AllowTemps is true, then any temporary
00991   /// metadata is ignored, otherwise it asserts when encountering temporary
00992   /// metadata.
00993   void resolveRecursivelyImpl(bool AllowTemps);
00994 
00995   /// \brief Mutate this to be "uniqued".
00996   ///
00997   /// Mutate this so that \a isUniqued().
00998   /// \pre \a isTemporary().
00999   /// \pre already added to uniquing set.
01000   void makeUniqued();
01001 
01002   /// \brief Mutate this to be "distinct".
01003   ///
01004   /// Mutate this so that \a isDistinct().
01005   /// \pre \a isTemporary().
01006   void makeDistinct();
01007 
01008   void deleteAsSubclass();
01009   MDNode *uniquify();
01010   void eraseFromStore();
01011 
01012   template <class NodeTy> struct HasCachedHash;
01013   template <class NodeTy>
01014   static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
01015     N->recalculateHash();
01016   }
01017   template <class NodeTy>
01018   static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
01019   template <class NodeTy>
01020   static void dispatchResetHash(NodeTy *N, std::true_type) {
01021     N->setHash(0);
01022   }
01023   template <class NodeTy>
01024   static void dispatchResetHash(NodeTy *, std::false_type) {}
01025 
01026 public:
01027   typedef const MDOperand *op_iterator;
01028   typedef iterator_range<op_iterator> op_range;
01029 
01030   op_iterator op_begin() const {
01031     return const_cast<MDNode *>(this)->mutable_begin();
01032   }
01033   op_iterator op_end() const {
01034     return const_cast<MDNode *>(this)->mutable_end();
01035   }
01036   op_range operands() const { return op_range(op_begin(), op_end()); }
01037 
01038   const MDOperand &getOperand(unsigned I) const {
01039     assert(I < NumOperands && "Out of range");
01040     return op_begin()[I];
01041   }
01042 
01043   /// \brief Return number of MDNode operands.
01044   unsigned getNumOperands() const { return NumOperands; }
01045 
01046   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
01047   static bool classof(const Metadata *MD) {
01048     switch (MD->getMetadataID()) {
01049     default:
01050       return false;
01051 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
01052   case CLASS##Kind:                                                            \
01053     return true;
01054 #include "llvm/IR/Metadata.def"
01055     }
01056   }
01057 
01058   /// \brief Check whether MDNode is a vtable access.
01059   bool isTBAAVtableAccess() const;
01060 
01061   /// \brief Methods for metadata merging.
01062   static MDNode *concatenate(MDNode *A, MDNode *B);
01063   static MDNode *intersect(MDNode *A, MDNode *B);
01064   static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
01065   static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
01066   static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
01067   static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
01068   static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B);
01069 
01070 };
01071 
01072 /// \brief Tuple of metadata.
01073 ///
01074 /// This is the simple \a MDNode arbitrary tuple.  Nodes are uniqued by
01075 /// default based on their operands.
01076 class MDTuple : public MDNode {
01077   friend class LLVMContextImpl;
01078   friend class MDNode;
01079 
01080   MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
01081           ArrayRef<Metadata *> Vals)
01082       : MDNode(C, MDTupleKind, Storage, Vals) {
01083     setHash(Hash);
01084   }
01085   ~MDTuple() { dropAllReferences(); }
01086 
01087   void setHash(unsigned Hash) { SubclassData32 = Hash; }
01088   void recalculateHash();
01089 
01090   static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
01091                           StorageType Storage, bool ShouldCreate = true);
01092 
01093   TempMDTuple cloneImpl() const {
01094     return getTemporary(getContext(),
01095                         SmallVector<Metadata *, 4>(op_begin(), op_end()));
01096   }
01097 
01098 public:
01099   /// \brief Get the hash, if any.
01100   unsigned getHash() const { return SubclassData32; }
01101 
01102   static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
01103     return getImpl(Context, MDs, Uniqued);
01104   }
01105   static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
01106     return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
01107   }
01108 
01109   /// \brief Return a distinct node.
01110   ///
01111   /// Return a distinct node -- i.e., a node that is not uniqued.
01112   static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
01113     return getImpl(Context, MDs, Distinct);
01114   }
01115 
01116   /// \brief Return a temporary node.
01117   ///
01118   /// For use in constructing cyclic MDNode structures. A temporary MDNode is
01119   /// not uniqued, may be RAUW'd, and must be manually deleted with
01120   /// deleteTemporary.
01121   static TempMDTuple getTemporary(LLVMContext &Context,
01122                                   ArrayRef<Metadata *> MDs) {
01123     return TempMDTuple(getImpl(Context, MDs, Temporary));
01124   }
01125 
01126   /// \brief Return a (temporary) clone of this.
01127   TempMDTuple clone() const { return cloneImpl(); }
01128 
01129   static bool classof(const Metadata *MD) {
01130     return MD->getMetadataID() == MDTupleKind;
01131   }
01132 };
01133 
01134 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
01135   return MDTuple::get(Context, MDs);
01136 }
01137 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
01138   return MDTuple::getIfExists(Context, MDs);
01139 }
01140 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
01141   return MDTuple::getDistinct(Context, MDs);
01142 }
01143 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
01144                                  ArrayRef<Metadata *> MDs) {
01145   return MDTuple::getTemporary(Context, MDs);
01146 }
01147 
01148 void TempMDNodeDeleter::operator()(MDNode *Node) const {
01149   MDNode::deleteTemporary(Node);
01150 }
01151 
01152 /// \brief Typed iterator through MDNode operands.
01153 ///
01154 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
01155 /// particular Metadata subclass.
01156 template <class T>
01157 class TypedMDOperandIterator
01158     : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
01159   MDNode::op_iterator I = nullptr;
01160 
01161 public:
01162   TypedMDOperandIterator() = default;
01163   explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
01164   T *operator*() const { return cast_or_null<T>(*I); }
01165   TypedMDOperandIterator &operator++() {
01166     ++I;
01167     return *this;
01168   }
01169   TypedMDOperandIterator operator++(int) {
01170     TypedMDOperandIterator Temp(*this);
01171     ++I;
01172     return Temp;
01173   }
01174   bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
01175   bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
01176 };
01177 
01178 /// \brief Typed, array-like tuple of metadata.
01179 ///
01180 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
01181 /// particular type of metadata.
01182 template <class T> class MDTupleTypedArrayWrapper {
01183   const MDTuple *N = nullptr;
01184 
01185 public:
01186   MDTupleTypedArrayWrapper() = default;
01187   MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
01188 
01189   template <class U>
01190   MDTupleTypedArrayWrapper(
01191       const MDTupleTypedArrayWrapper<U> &Other,
01192       typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
01193           nullptr)
01194       : N(Other.get()) {}
01195 
01196   template <class U>
01197   explicit MDTupleTypedArrayWrapper(
01198       const MDTupleTypedArrayWrapper<U> &Other,
01199       typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
01200           nullptr)
01201       : N(Other.get()) {}
01202 
01203   explicit operator bool() const { return get(); }
01204   explicit operator MDTuple *() const { return get(); }
01205 
01206   MDTuple *get() const { return const_cast<MDTuple *>(N); }
01207   MDTuple *operator->() const { return get(); }
01208   MDTuple &operator*() const { return *get(); }
01209 
01210   // FIXME: Fix callers and remove condition on N.
01211   unsigned size() const { return N ? N->getNumOperands() : 0u; }
01212   T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
01213 
01214   // FIXME: Fix callers and remove condition on N.
01215   typedef TypedMDOperandIterator<T> iterator;
01216   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
01217   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
01218 };
01219 
01220 #define HANDLE_METADATA(CLASS)                                                 \
01221   typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
01222 #include "llvm/IR/Metadata.def"
01223 
01224 //===----------------------------------------------------------------------===//
01225 /// \brief A tuple of MDNodes.
01226 ///
01227 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
01228 /// to modules, have names, and contain lists of MDNodes.
01229 ///
01230 /// TODO: Inherit from Metadata.
01231 class NamedMDNode : public ilist_node<NamedMDNode> {
01232   friend struct ilist_traits<NamedMDNode>;
01233   friend class LLVMContextImpl;
01234   friend class Module;
01235   NamedMDNode(const NamedMDNode &) = delete;
01236 
01237   std::string Name;
01238   Module *Parent;
01239   void *Operands; // SmallVector<TrackingMDRef, 4>
01240 
01241   void setParent(Module *M) { Parent = M; }
01242 
01243   explicit NamedMDNode(const Twine &N);
01244 
01245   template<class T1, class T2>
01246   class op_iterator_impl :
01247       public std::iterator<std::bidirectional_iterator_tag, T2> {
01248     const NamedMDNode *Node;
01249     unsigned Idx;
01250     op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
01251 
01252     friend class NamedMDNode;
01253 
01254   public:
01255     op_iterator_impl() : Node(nullptr), Idx(0) { }
01256 
01257     bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
01258     bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
01259     op_iterator_impl &operator++() {
01260       ++Idx;
01261       return *this;
01262     }
01263     op_iterator_impl operator++(int) {
01264       op_iterator_impl tmp(*this);
01265       operator++();
01266       return tmp;
01267     }
01268     op_iterator_impl &operator--() {
01269       --Idx;
01270       return *this;
01271     }
01272     op_iterator_impl operator--(int) {
01273       op_iterator_impl tmp(*this);
01274       operator--();
01275       return tmp;
01276     }
01277 
01278     T1 operator*() const { return Node->getOperand(Idx); }
01279   };
01280 
01281 public:
01282   /// \brief Drop all references and remove the node from parent module.
01283   void eraseFromParent();
01284 
01285   /// \brief Remove all uses and clear node vector.
01286   void dropAllReferences();
01287 
01288   ~NamedMDNode();
01289 
01290   /// \brief Get the module that holds this named metadata collection.
01291   inline Module *getParent() { return Parent; }
01292   inline const Module *getParent() const { return Parent; }
01293 
01294   MDNode *getOperand(unsigned i) const;
01295   unsigned getNumOperands() const;
01296   void addOperand(MDNode *M);
01297   void setOperand(unsigned I, MDNode *New);
01298   StringRef getName() const;
01299   void print(raw_ostream &ROS, bool IsForDebug = false) const;
01300   void dump() const;
01301 
01302   // ---------------------------------------------------------------------------
01303   // Operand Iterator interface...
01304   //
01305   typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
01306   op_iterator op_begin() { return op_iterator(this, 0); }
01307   op_iterator op_end()   { return op_iterator(this, getNumOperands()); }
01308 
01309   typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
01310   const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
01311   const_op_iterator op_end()   const { return const_op_iterator(this, getNumOperands()); }
01312 
01313   inline iterator_range<op_iterator>  operands() {
01314     return make_range(op_begin(), op_end());
01315   }
01316   inline iterator_range<const_op_iterator> operands() const {
01317     return make_range(op_begin(), op_end());
01318   }
01319 };
01320 
01321 } // end llvm namespace
01322 
01323 #endif // LLVM_IR_METADATA_H