2ea591383f82543d22fe42233e8593f044857770
[oota-llvm.git] / include / llvm / IR / Metadata.h
1 //===- llvm/IR/Metadata.h - Metadata definitions ----------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// @file
11 /// This file contains the declarations for metadata subclasses.
12 /// They represent the different flavors of metadata that live in LLVM.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_IR_METADATA_H
17 #define LLVM_IR_METADATA_H
18
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/PointerUnion.h"
22 #include "llvm/ADT/ilist_node.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/IR/Constant.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Value.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include <type_traits>
29
30 namespace llvm {
31
32 class LLVMContext;
33 class Module;
34 class ModuleSlotTracker;
35
36 enum LLVMConstants : uint32_t {
37   DEBUG_METADATA_VERSION = 3 // Current debug info version number.
38 };
39
40 /// \brief Root of the metadata hierarchy.
41 ///
42 /// This is a root class for typeless data in the IR.
43 class Metadata {
44   friend class ReplaceableMetadataImpl;
45
46   /// \brief RTTI.
47   const unsigned char SubclassID;
48
49 protected:
50   /// \brief Active type of storage.
51   enum StorageType { Uniqued, Distinct, Temporary };
52
53   /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
54   unsigned Storage : 2;
55   // TODO: expose remaining bits to subclasses.
56
57   unsigned short SubclassData16;
58   unsigned SubclassData32;
59
60 public:
61   enum MetadataKind {
62     MDTupleKind,
63     DILocationKind,
64     GenericDINodeKind,
65     DISubrangeKind,
66     DIEnumeratorKind,
67     DIBasicTypeKind,
68     DIDerivedTypeKind,
69     DICompositeTypeKind,
70     DISubroutineTypeKind,
71     DIFileKind,
72     DICompileUnitKind,
73     DISubprogramKind,
74     DILexicalBlockKind,
75     DILexicalBlockFileKind,
76     DINamespaceKind,
77     DIModuleKind,
78     DITemplateTypeParameterKind,
79     DITemplateValueParameterKind,
80     DIGlobalVariableKind,
81     DILocalVariableKind,
82     DIExpressionKind,
83     DIObjCPropertyKind,
84     DIImportedEntityKind,
85     ConstantAsMetadataKind,
86     LocalAsMetadataKind,
87     MDStringKind,
88     DIMacroKind,
89     DIMacroFileKind
90   };
91
92 protected:
93   Metadata(unsigned ID, StorageType Storage)
94       : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
95   }
96   ~Metadata() = default;
97
98   /// \brief Default handling of a changed operand, which asserts.
99   ///
100   /// If subclasses pass themselves in as owners to a tracking node reference,
101   /// they must provide an implementation of this method.
102   void handleChangedOperand(void *, Metadata *) {
103     llvm_unreachable("Unimplemented in Metadata subclass");
104   }
105
106 public:
107   unsigned getMetadataID() const { return SubclassID; }
108
109   /// \brief User-friendly dump.
110   ///
111   /// If \c M is provided, metadata nodes will be numbered canonically;
112   /// otherwise, pointer addresses are substituted.
113   ///
114   /// Note: this uses an explicit overload instead of default arguments so that
115   /// the nullptr version is easy to call from a debugger.
116   ///
117   /// @{
118   void dump() const;
119   void dump(const Module *M) const;
120   /// @}
121
122   /// \brief Print.
123   ///
124   /// Prints definition of \c this.
125   ///
126   /// If \c M is provided, metadata nodes will be numbered canonically;
127   /// otherwise, pointer addresses are substituted.
128   /// @{
129   void print(raw_ostream &OS, const Module *M = nullptr,
130              bool IsForDebug = false) const;
131   void print(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr,
132              bool IsForDebug = false) const;
133   /// @}
134
135   /// \brief Print as operand.
136   ///
137   /// Prints reference of \c this.
138   ///
139   /// If \c M is provided, metadata nodes will be numbered canonically;
140   /// otherwise, pointer addresses are substituted.
141   /// @{
142   void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
143   void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
144                       const Module *M = nullptr) const;
145   /// @}
146 };
147
148 #define HANDLE_METADATA(CLASS) class CLASS;
149 #include "llvm/IR/Metadata.def"
150
151 // Provide specializations of isa so that we don't need definitions of
152 // subclasses to see if the metadata is a subclass.
153 #define HANDLE_METADATA_LEAF(CLASS)                                            \
154   template <> struct isa_impl<CLASS, Metadata> {                               \
155     static inline bool doit(const Metadata &MD) {                              \
156       return MD.getMetadataID() == Metadata::CLASS##Kind;                      \
157     }                                                                          \
158   };
159 #include "llvm/IR/Metadata.def"
160
161 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
162   MD.print(OS);
163   return OS;
164 }
165
166 /// \brief Metadata wrapper in the Value hierarchy.
167 ///
168 /// A member of the \a Value hierarchy to represent a reference to metadata.
169 /// This allows, e.g., instrinsics to have metadata as operands.
170 ///
171 /// Notably, this is the only thing in either hierarchy that is allowed to
172 /// reference \a LocalAsMetadata.
173 class MetadataAsValue : public Value {
174   friend class ReplaceableMetadataImpl;
175   friend class LLVMContextImpl;
176
177   Metadata *MD;
178
179   MetadataAsValue(Type *Ty, Metadata *MD);
180   ~MetadataAsValue() override;
181
182   /// \brief Drop use of metadata (during teardown).
183   void dropUse() { MD = nullptr; }
184
185 public:
186   static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
187   static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
188   Metadata *getMetadata() const { return MD; }
189
190   static bool classof(const Value *V) {
191     return V->getValueID() == MetadataAsValueVal;
192   }
193
194 private:
195   void handleChangedMetadata(Metadata *MD);
196   void track();
197   void untrack();
198 };
199
200 /// \brief API for tracking metadata references through RAUW and deletion.
201 ///
202 /// Shared API for updating \a Metadata pointers in subclasses that support
203 /// RAUW.
204 ///
205 /// This API is not meant to be used directly.  See \a TrackingMDRef for a
206 /// user-friendly tracking reference.
207 class MetadataTracking {
208 public:
209   /// \brief Track the reference to metadata.
210   ///
211   /// Register \c MD with \c *MD, if the subclass supports tracking.  If \c *MD
212   /// gets RAUW'ed, \c MD will be updated to the new address.  If \c *MD gets
213   /// deleted, \c MD will be set to \c nullptr.
214   ///
215   /// If tracking isn't supported, \c *MD will not change.
216   ///
217   /// \return true iff tracking is supported by \c MD.
218   static bool track(Metadata *&MD) {
219     return track(&MD, *MD, static_cast<Metadata *>(nullptr));
220   }
221
222   /// \brief Track the reference to metadata for \a Metadata.
223   ///
224   /// As \a track(Metadata*&), but with support for calling back to \c Owner to
225   /// tell it that its operand changed.  This could trigger \c Owner being
226   /// re-uniqued.
227   static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
228     return track(Ref, MD, &Owner);
229   }
230
231   /// \brief Track the reference to metadata for \a MetadataAsValue.
232   ///
233   /// As \a track(Metadata*&), but with support for calling back to \c Owner to
234   /// tell it that its operand changed.  This could trigger \c Owner being
235   /// re-uniqued.
236   static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
237     return track(Ref, MD, &Owner);
238   }
239
240   /// \brief Stop tracking a reference to metadata.
241   ///
242   /// Stops \c *MD from tracking \c MD.
243   static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
244   static void untrack(void *Ref, Metadata &MD);
245
246   /// \brief Move tracking from one reference to another.
247   ///
248   /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
249   /// except that ownership callbacks are maintained.
250   ///
251   /// Note: it is an error if \c *MD does not equal \c New.
252   ///
253   /// \return true iff tracking is supported by \c MD.
254   static bool retrack(Metadata *&MD, Metadata *&New) {
255     return retrack(&MD, *MD, &New);
256   }
257   static bool retrack(void *Ref, Metadata &MD, void *New);
258
259   /// \brief Check whether metadata is replaceable.
260   static bool isReplaceable(const Metadata &MD);
261
262   typedef PointerUnion<MetadataAsValue *, Metadata *> OwnerTy;
263
264 private:
265   /// \brief Track a reference to metadata for an owner.
266   ///
267   /// Generalized version of tracking.
268   static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
269 };
270
271 /// \brief Shared implementation of use-lists for replaceable metadata.
272 ///
273 /// Most metadata cannot be RAUW'ed.  This is a shared implementation of
274 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
275 /// and \a TempMDNode).
276 class ReplaceableMetadataImpl {
277   friend class MetadataTracking;
278
279 public:
280   typedef MetadataTracking::OwnerTy OwnerTy;
281
282 private:
283   LLVMContext &Context;
284   uint64_t NextIndex;
285   SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
286
287 public:
288   ReplaceableMetadataImpl(LLVMContext &Context)
289       : Context(Context), NextIndex(0) {}
290   ~ReplaceableMetadataImpl() {
291     assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
292   }
293
294   LLVMContext &getContext() const { return Context; }
295
296   /// \brief Replace all uses of this with MD.
297   ///
298   /// Replace all uses of this with \c MD, which is allowed to be null.
299   void replaceAllUsesWith(Metadata *MD);
300
301   /// \brief Resolve all uses of this.
302   ///
303   /// Resolve all uses of this, turning off RAUW permanently.  If \c
304   /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
305   /// is resolved.
306   void resolveAllUses(bool ResolveUsers = true);
307
308 private:
309   void addRef(void *Ref, OwnerTy Owner);
310   void dropRef(void *Ref);
311   void moveRef(void *Ref, void *New, const Metadata &MD);
312
313   static ReplaceableMetadataImpl *get(Metadata &MD);
314 };
315
316 /// \brief Value wrapper in the Metadata hierarchy.
317 ///
318 /// This is a custom value handle that allows other metadata to refer to
319 /// classes in the Value hierarchy.
320 ///
321 /// Because of full uniquing support, each value is only wrapped by a single \a
322 /// ValueAsMetadata object, so the lookup maps are far more efficient than
323 /// those using ValueHandleBase.
324 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
325   friend class ReplaceableMetadataImpl;
326   friend class LLVMContextImpl;
327
328   Value *V;
329
330   /// \brief Drop users without RAUW (during teardown).
331   void dropUsers() {
332     ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
333   }
334
335 protected:
336   ValueAsMetadata(unsigned ID, Value *V)
337       : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
338     assert(V && "Expected valid value");
339   }
340   ~ValueAsMetadata() = default;
341
342 public:
343   static ValueAsMetadata *get(Value *V);
344   static ConstantAsMetadata *getConstant(Value *C) {
345     return cast<ConstantAsMetadata>(get(C));
346   }
347   static LocalAsMetadata *getLocal(Value *Local) {
348     return cast<LocalAsMetadata>(get(Local));
349   }
350
351   static ValueAsMetadata *getIfExists(Value *V);
352   static ConstantAsMetadata *getConstantIfExists(Value *C) {
353     return cast_or_null<ConstantAsMetadata>(getIfExists(C));
354   }
355   static LocalAsMetadata *getLocalIfExists(Value *Local) {
356     return cast_or_null<LocalAsMetadata>(getIfExists(Local));
357   }
358
359   Value *getValue() const { return V; }
360   Type *getType() const { return V->getType(); }
361   LLVMContext &getContext() const { return V->getContext(); }
362
363   static void handleDeletion(Value *V);
364   static void handleRAUW(Value *From, Value *To);
365
366 protected:
367   /// \brief Handle collisions after \a Value::replaceAllUsesWith().
368   ///
369   /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
370   /// \a Value gets RAUW'ed and the target already exists, this is used to
371   /// merge the two metadata nodes.
372   void replaceAllUsesWith(Metadata *MD) {
373     ReplaceableMetadataImpl::replaceAllUsesWith(MD);
374   }
375
376 public:
377   static bool classof(const Metadata *MD) {
378     return MD->getMetadataID() == LocalAsMetadataKind ||
379            MD->getMetadataID() == ConstantAsMetadataKind;
380   }
381 };
382
383 class ConstantAsMetadata : public ValueAsMetadata {
384   friend class ValueAsMetadata;
385
386   ConstantAsMetadata(Constant *C)
387       : ValueAsMetadata(ConstantAsMetadataKind, C) {}
388
389 public:
390   static ConstantAsMetadata *get(Constant *C) {
391     return ValueAsMetadata::getConstant(C);
392   }
393   static ConstantAsMetadata *getIfExists(Constant *C) {
394     return ValueAsMetadata::getConstantIfExists(C);
395   }
396
397   Constant *getValue() const {
398     return cast<Constant>(ValueAsMetadata::getValue());
399   }
400
401   static bool classof(const Metadata *MD) {
402     return MD->getMetadataID() == ConstantAsMetadataKind;
403   }
404 };
405
406 class LocalAsMetadata : public ValueAsMetadata {
407   friend class ValueAsMetadata;
408
409   LocalAsMetadata(Value *Local)
410       : ValueAsMetadata(LocalAsMetadataKind, Local) {
411     assert(!isa<Constant>(Local) && "Expected local value");
412   }
413
414 public:
415   static LocalAsMetadata *get(Value *Local) {
416     return ValueAsMetadata::getLocal(Local);
417   }
418   static LocalAsMetadata *getIfExists(Value *Local) {
419     return ValueAsMetadata::getLocalIfExists(Local);
420   }
421
422   static bool classof(const Metadata *MD) {
423     return MD->getMetadataID() == LocalAsMetadataKind;
424   }
425 };
426
427 /// \brief Transitional API for extracting constants from Metadata.
428 ///
429 /// This namespace contains transitional functions for metadata that points to
430 /// \a Constants.
431 ///
432 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
433 /// operands could refer to any \a Value.  There's was a lot of code like this:
434 ///
435 /// \code
436 ///     MDNode *N = ...;
437 ///     auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
438 /// \endcode
439 ///
440 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
441 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
442 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
443 /// cast in the \a Value hierarchy.  Besides creating boiler-plate, this
444 /// requires subtle control flow changes.
445 ///
446 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
447 /// so that metadata can refer to numbers without traversing a bridge to the \a
448 /// Value hierarchy.  In this final state, the code above would look like this:
449 ///
450 /// \code
451 ///     MDNode *N = ...;
452 ///     auto *MI = dyn_cast<MDInt>(N->getOperand(2));
453 /// \endcode
454 ///
455 /// The API in this namespace supports the transition.  \a MDInt doesn't exist
456 /// yet, and even once it does, changing each metadata schema to use it is its
457 /// own mini-project.  In the meantime this API prevents us from introducing
458 /// complex and bug-prone control flow that will disappear in the end.  In
459 /// particular, the above code looks like this:
460 ///
461 /// \code
462 ///     MDNode *N = ...;
463 ///     auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
464 /// \endcode
465 ///
466 /// The full set of provided functions includes:
467 ///
468 ///   mdconst::hasa                <=> isa
469 ///   mdconst::extract             <=> cast
470 ///   mdconst::extract_or_null     <=> cast_or_null
471 ///   mdconst::dyn_extract         <=> dyn_cast
472 ///   mdconst::dyn_extract_or_null <=> dyn_cast_or_null
473 ///
474 /// The target of the cast must be a subclass of \a Constant.
475 namespace mdconst {
476
477 namespace detail {
478 template <class T> T &make();
479 template <class T, class Result> struct HasDereference {
480   typedef char Yes[1];
481   typedef char No[2];
482   template <size_t N> struct SFINAE {};
483
484   template <class U, class V>
485   static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
486   template <class U, class V> static No &hasDereference(...);
487
488   static const bool value =
489       sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
490 };
491 template <class V, class M> struct IsValidPointer {
492   static const bool value = std::is_base_of<Constant, V>::value &&
493                             HasDereference<M, const Metadata &>::value;
494 };
495 template <class V, class M> struct IsValidReference {
496   static const bool value = std::is_base_of<Constant, V>::value &&
497                             std::is_convertible<M, const Metadata &>::value;
498 };
499 } // end namespace detail
500
501 /// \brief Check whether Metadata has a Value.
502 ///
503 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
504 /// type \c X.
505 template <class X, class Y>
506 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
507 hasa(Y &&MD) {
508   assert(MD && "Null pointer sent into hasa");
509   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
510     return isa<X>(V->getValue());
511   return false;
512 }
513 template <class X, class Y>
514 inline
515     typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
516     hasa(Y &MD) {
517   return hasa(&MD);
518 }
519
520 /// \brief Extract a Value from Metadata.
521 ///
522 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
523 template <class X, class Y>
524 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
525 extract(Y &&MD) {
526   return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
527 }
528 template <class X, class Y>
529 inline
530     typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
531     extract(Y &MD) {
532   return extract(&MD);
533 }
534
535 /// \brief Extract a Value from Metadata, allowing null.
536 ///
537 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
538 /// from \c MD, allowing \c MD to be null.
539 template <class X, class Y>
540 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
541 extract_or_null(Y &&MD) {
542   if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
543     return cast<X>(V->getValue());
544   return nullptr;
545 }
546
547 /// \brief Extract a Value from Metadata, if any.
548 ///
549 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
550 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
551 /// Value it does contain is of the wrong subclass.
552 template <class X, class Y>
553 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
554 dyn_extract(Y &&MD) {
555   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
556     return dyn_cast<X>(V->getValue());
557   return nullptr;
558 }
559
560 /// \brief Extract a Value from Metadata, if any, allowing null.
561 ///
562 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
563 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
564 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
565 template <class X, class Y>
566 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
567 dyn_extract_or_null(Y &&MD) {
568   if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
569     return dyn_cast<X>(V->getValue());
570   return nullptr;
571 }
572
573 } // end namespace mdconst
574
575 //===----------------------------------------------------------------------===//
576 /// \brief A single uniqued string.
577 ///
578 /// These are used to efficiently contain a byte sequence for metadata.
579 /// MDString is always unnamed.
580 class MDString : public Metadata {
581   friend class StringMapEntry<MDString>;
582
583   MDString(const MDString &) = delete;
584   MDString &operator=(MDString &&) = delete;
585   MDString &operator=(const MDString &) = delete;
586
587   StringMapEntry<MDString> *Entry;
588   MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
589   MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
590
591 public:
592   static MDString *get(LLVMContext &Context, StringRef Str);
593   static MDString *get(LLVMContext &Context, const char *Str) {
594     return get(Context, Str ? StringRef(Str) : StringRef());
595   }
596
597   StringRef getString() const;
598
599   unsigned getLength() const { return (unsigned)getString().size(); }
600
601   typedef StringRef::iterator iterator;
602
603   /// \brief Pointer to the first byte of the string.
604   iterator begin() const { return getString().begin(); }
605
606   /// \brief Pointer to one byte past the end of the string.
607   iterator end() const { return getString().end(); }
608
609   const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
610   const unsigned char *bytes_end() const { return getString().bytes_end(); }
611
612   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
613   static bool classof(const Metadata *MD) {
614     return MD->getMetadataID() == MDStringKind;
615   }
616 };
617
618 /// \brief A collection of metadata nodes that might be associated with a
619 /// memory access used by the alias-analysis infrastructure.
620 struct AAMDNodes {
621   explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
622                      MDNode *N = nullptr)
623       : TBAA(T), Scope(S), NoAlias(N) {}
624
625   bool operator==(const AAMDNodes &A) const {
626     return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
627   }
628
629   bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
630
631   explicit operator bool() const { return TBAA || Scope || NoAlias; }
632
633   /// \brief The tag for type-based alias analysis.
634   MDNode *TBAA;
635
636   /// \brief The tag for alias scope specification (used with noalias).
637   MDNode *Scope;
638
639   /// \brief The tag specifying the noalias scope.
640   MDNode *NoAlias;
641 };
642
643 // Specialize DenseMapInfo for AAMDNodes.
644 template<>
645 struct DenseMapInfo<AAMDNodes> {
646   static inline AAMDNodes getEmptyKey() {
647     return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
648                      nullptr, nullptr);
649   }
650   static inline AAMDNodes getTombstoneKey() {
651     return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
652                      nullptr, nullptr);
653   }
654   static unsigned getHashValue(const AAMDNodes &Val) {
655     return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
656            DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
657            DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
658   }
659   static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
660     return LHS == RHS;
661   }
662 };
663
664 /// \brief Tracking metadata reference owned by Metadata.
665 ///
666 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
667 /// of \a Metadata, which has the option of registering itself for callbacks to
668 /// re-unique itself.
669 ///
670 /// In particular, this is used by \a MDNode.
671 class MDOperand {
672   MDOperand(MDOperand &&) = delete;
673   MDOperand(const MDOperand &) = delete;
674   MDOperand &operator=(MDOperand &&) = delete;
675   MDOperand &operator=(const MDOperand &) = delete;
676
677   Metadata *MD;
678
679 public:
680   MDOperand() : MD(nullptr) {}
681   ~MDOperand() { untrack(); }
682
683   Metadata *get() const { return MD; }
684   operator Metadata *() const { return get(); }
685   Metadata *operator->() const { return get(); }
686   Metadata &operator*() const { return *get(); }
687
688   void reset() {
689     untrack();
690     MD = nullptr;
691   }
692   void reset(Metadata *MD, Metadata *Owner) {
693     untrack();
694     this->MD = MD;
695     track(Owner);
696   }
697
698 private:
699   void track(Metadata *Owner) {
700     if (MD) {
701       if (Owner)
702         MetadataTracking::track(this, *MD, *Owner);
703       else
704         MetadataTracking::track(MD);
705     }
706   }
707   void untrack() {
708     assert(static_cast<void *>(this) == &MD && "Expected same address");
709     if (MD)
710       MetadataTracking::untrack(MD);
711   }
712 };
713
714 template <> struct simplify_type<MDOperand> {
715   typedef Metadata *SimpleType;
716   static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
717 };
718
719 template <> struct simplify_type<const MDOperand> {
720   typedef Metadata *SimpleType;
721   static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
722 };
723
724 /// \brief Pointer to the context, with optional RAUW support.
725 ///
726 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
727 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
728 class ContextAndReplaceableUses {
729   PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
730
731   ContextAndReplaceableUses() = delete;
732   ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
733   ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
734   ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
735   ContextAndReplaceableUses &
736   operator=(const ContextAndReplaceableUses &) = delete;
737
738 public:
739   ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
740   ContextAndReplaceableUses(
741       std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
742       : Ptr(ReplaceableUses.release()) {
743     assert(getReplaceableUses() && "Expected non-null replaceable uses");
744   }
745   ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
746
747   operator LLVMContext &() { return getContext(); }
748
749   /// \brief Whether this contains RAUW support.
750   bool hasReplaceableUses() const {
751     return Ptr.is<ReplaceableMetadataImpl *>();
752   }
753   LLVMContext &getContext() const {
754     if (hasReplaceableUses())
755       return getReplaceableUses()->getContext();
756     return *Ptr.get<LLVMContext *>();
757   }
758   ReplaceableMetadataImpl *getReplaceableUses() const {
759     if (hasReplaceableUses())
760       return Ptr.get<ReplaceableMetadataImpl *>();
761     return nullptr;
762   }
763
764   /// \brief Assign RAUW support to this.
765   ///
766   /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
767   /// not be null).
768   void
769   makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
770     assert(ReplaceableUses && "Expected non-null replaceable uses");
771     assert(&ReplaceableUses->getContext() == &getContext() &&
772            "Expected same context");
773     delete getReplaceableUses();
774     Ptr = ReplaceableUses.release();
775   }
776
777   /// \brief Drop RAUW support.
778   ///
779   /// Cede ownership of RAUW support, returning it.
780   std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
781     assert(hasReplaceableUses() && "Expected to own replaceable uses");
782     std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
783         getReplaceableUses());
784     Ptr = &ReplaceableUses->getContext();
785     return ReplaceableUses;
786   }
787 };
788
789 struct TempMDNodeDeleter {
790   inline void operator()(MDNode *Node) const;
791 };
792
793 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
794   typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
795 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
796 #include "llvm/IR/Metadata.def"
797
798 /// \brief Metadata node.
799 ///
800 /// Metadata nodes can be uniqued, like constants, or distinct.  Temporary
801 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
802 /// until forward references are known.  The basic metadata node is an \a
803 /// MDTuple.
804 ///
805 /// There is limited support for RAUW at construction time.  At construction
806 /// time, if any operand is a temporary node (or an unresolved uniqued node,
807 /// which indicates a transitive temporary operand), the node itself will be
808 /// unresolved.  As soon as all operands become resolved, it will drop RAUW
809 /// support permanently.
810 ///
811 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
812 /// to be called on some member of the cycle once all temporary nodes have been
813 /// replaced.
814 class MDNode : public Metadata {
815   friend class ReplaceableMetadataImpl;
816   friend class LLVMContextImpl;
817
818   MDNode(const MDNode &) = delete;
819   void operator=(const MDNode &) = delete;
820   void *operator new(size_t) = delete;
821
822   unsigned NumOperands;
823   unsigned NumUnresolved;
824
825 protected:
826   ContextAndReplaceableUses Context;
827
828   void *operator new(size_t Size, unsigned NumOps);
829   void operator delete(void *Mem);
830
831   /// \brief Required by std, but never called.
832   void operator delete(void *, unsigned) {
833     llvm_unreachable("Constructor throws?");
834   }
835
836   /// \brief Required by std, but never called.
837   void operator delete(void *, unsigned, bool) {
838     llvm_unreachable("Constructor throws?");
839   }
840
841   MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
842          ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
843   ~MDNode() = default;
844
845   void dropAllReferences();
846
847   MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
848   MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
849
850   typedef iterator_range<MDOperand *> mutable_op_range;
851   mutable_op_range mutable_operands() {
852     return mutable_op_range(mutable_begin(), mutable_end());
853   }
854
855 public:
856   static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
857   static inline MDTuple *getIfExists(LLVMContext &Context,
858                                      ArrayRef<Metadata *> MDs);
859   static inline MDTuple *getDistinct(LLVMContext &Context,
860                                      ArrayRef<Metadata *> MDs);
861   static inline TempMDTuple getTemporary(LLVMContext &Context,
862                                          ArrayRef<Metadata *> MDs);
863
864   /// \brief Create a (temporary) clone of this.
865   TempMDNode clone() const;
866
867   /// \brief Deallocate a node created by getTemporary.
868   ///
869   /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
870   /// references will be reset.
871   static void deleteTemporary(MDNode *N);
872
873   LLVMContext &getContext() const { return Context.getContext(); }
874
875   /// \brief Replace a specific operand.
876   void replaceOperandWith(unsigned I, Metadata *New);
877
878   /// \brief Check if node is fully resolved.
879   ///
880   /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
881   /// this always returns \c true.
882   ///
883   /// If \a isUniqued(), returns \c true if this has already dropped RAUW
884   /// support (because all operands are resolved).
885   ///
886   /// As forward declarations are resolved, their containers should get
887   /// resolved automatically.  However, if this (or one of its operands) is
888   /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
889   bool isResolved() const { return !Context.hasReplaceableUses(); }
890
891   bool isUniqued() const { return Storage == Uniqued; }
892   bool isDistinct() const { return Storage == Distinct; }
893   bool isTemporary() const { return Storage == Temporary; }
894
895   /// \brief RAUW a temporary.
896   ///
897   /// \pre \a isTemporary() must be \c true.
898   void replaceAllUsesWith(Metadata *MD) {
899     assert(isTemporary() && "Expected temporary node");
900     assert(!isResolved() && "Expected RAUW support");
901     Context.getReplaceableUses()->replaceAllUsesWith(MD);
902   }
903
904   /// \brief Resolve cycles.
905   ///
906   /// Once all forward declarations have been resolved, force cycles to be
907   /// resolved. If \p MDMaterialized is true, then any temporary metadata
908   /// is ignored, otherwise it asserts when encountering temporary metadata.
909   ///
910   /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
911   void resolveCycles(bool MDMaterialized = true);
912
913   /// \brief Replace a temporary node with a permanent one.
914   ///
915   /// Try to create a uniqued version of \c N -- in place, if possible -- and
916   /// return it.  If \c N cannot be uniqued, return a distinct node instead.
917   template <class T>
918   static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
919   replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
920     return cast<T>(N.release()->replaceWithPermanentImpl());
921   }
922
923   /// \brief Replace a temporary node with a uniqued one.
924   ///
925   /// Create a uniqued version of \c N -- in place, if possible -- and return
926   /// it.  Takes ownership of the temporary node.
927   ///
928   /// \pre N does not self-reference.
929   template <class T>
930   static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
931   replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
932     return cast<T>(N.release()->replaceWithUniquedImpl());
933   }
934
935   /// \brief Replace a temporary node with a distinct one.
936   ///
937   /// Create a distinct version of \c N -- in place, if possible -- and return
938   /// it.  Takes ownership of the temporary node.
939   template <class T>
940   static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
941   replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
942     return cast<T>(N.release()->replaceWithDistinctImpl());
943   }
944
945 private:
946   MDNode *replaceWithPermanentImpl();
947   MDNode *replaceWithUniquedImpl();
948   MDNode *replaceWithDistinctImpl();
949
950 protected:
951   /// \brief Set an operand.
952   ///
953   /// Sets the operand directly, without worrying about uniquing.
954   void setOperand(unsigned I, Metadata *New);
955
956   void storeDistinctInContext();
957   template <class T, class StoreT>
958   static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
959   template <class T> static T *storeImpl(T *N, StorageType Storage);
960
961 private:
962   void handleChangedOperand(void *Ref, Metadata *New);
963
964   void resolve();
965   void resolveAfterOperandChange(Metadata *Old, Metadata *New);
966   void decrementUnresolvedOperandCount();
967   unsigned countUnresolvedOperands();
968
969   /// \brief Mutate this to be "uniqued".
970   ///
971   /// Mutate this so that \a isUniqued().
972   /// \pre \a isTemporary().
973   /// \pre already added to uniquing set.
974   void makeUniqued();
975
976   /// \brief Mutate this to be "distinct".
977   ///
978   /// Mutate this so that \a isDistinct().
979   /// \pre \a isTemporary().
980   void makeDistinct();
981
982   void deleteAsSubclass();
983   MDNode *uniquify();
984   void eraseFromStore();
985
986   template <class NodeTy> struct HasCachedHash;
987   template <class NodeTy>
988   static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
989     N->recalculateHash();
990   }
991   template <class NodeTy>
992   static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
993   template <class NodeTy>
994   static void dispatchResetHash(NodeTy *N, std::true_type) {
995     N->setHash(0);
996   }
997   template <class NodeTy>
998   static void dispatchResetHash(NodeTy *, std::false_type) {}
999
1000 public:
1001   typedef const MDOperand *op_iterator;
1002   typedef iterator_range<op_iterator> op_range;
1003
1004   op_iterator op_begin() const {
1005     return const_cast<MDNode *>(this)->mutable_begin();
1006   }
1007   op_iterator op_end() const {
1008     return const_cast<MDNode *>(this)->mutable_end();
1009   }
1010   op_range operands() const { return op_range(op_begin(), op_end()); }
1011
1012   const MDOperand &getOperand(unsigned I) const {
1013     assert(I < NumOperands && "Out of range");
1014     return op_begin()[I];
1015   }
1016
1017   /// \brief Return number of MDNode operands.
1018   unsigned getNumOperands() const { return NumOperands; }
1019
1020   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
1021   static bool classof(const Metadata *MD) {
1022     switch (MD->getMetadataID()) {
1023     default:
1024       return false;
1025 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1026   case CLASS##Kind:                                                            \
1027     return true;
1028 #include "llvm/IR/Metadata.def"
1029     }
1030   }
1031
1032   /// \brief Check whether MDNode is a vtable access.
1033   bool isTBAAVtableAccess() const;
1034
1035   /// \brief Methods for metadata merging.
1036   static MDNode *concatenate(MDNode *A, MDNode *B);
1037   static MDNode *intersect(MDNode *A, MDNode *B);
1038   static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
1039   static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
1040   static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
1041   static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
1042   static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B);
1043
1044 };
1045
1046 /// \brief Tuple of metadata.
1047 ///
1048 /// This is the simple \a MDNode arbitrary tuple.  Nodes are uniqued by
1049 /// default based on their operands.
1050 class MDTuple : public MDNode {
1051   friend class LLVMContextImpl;
1052   friend class MDNode;
1053
1054   MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1055           ArrayRef<Metadata *> Vals)
1056       : MDNode(C, MDTupleKind, Storage, Vals) {
1057     setHash(Hash);
1058   }
1059   ~MDTuple() { dropAllReferences(); }
1060
1061   void setHash(unsigned Hash) { SubclassData32 = Hash; }
1062   void recalculateHash();
1063
1064   static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
1065                           StorageType Storage, bool ShouldCreate = true);
1066
1067   TempMDTuple cloneImpl() const {
1068     return getTemporary(getContext(),
1069                         SmallVector<Metadata *, 4>(op_begin(), op_end()));
1070   }
1071
1072 public:
1073   /// \brief Get the hash, if any.
1074   unsigned getHash() const { return SubclassData32; }
1075
1076   static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1077     return getImpl(Context, MDs, Uniqued);
1078   }
1079   static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1080     return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1081   }
1082
1083   /// \brief Return a distinct node.
1084   ///
1085   /// Return a distinct node -- i.e., a node that is not uniqued.
1086   static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1087     return getImpl(Context, MDs, Distinct);
1088   }
1089
1090   /// \brief Return a temporary node.
1091   ///
1092   /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1093   /// not uniqued, may be RAUW'd, and must be manually deleted with
1094   /// deleteTemporary.
1095   static TempMDTuple getTemporary(LLVMContext &Context,
1096                                   ArrayRef<Metadata *> MDs) {
1097     return TempMDTuple(getImpl(Context, MDs, Temporary));
1098   }
1099
1100   /// \brief Return a (temporary) clone of this.
1101   TempMDTuple clone() const { return cloneImpl(); }
1102
1103   static bool classof(const Metadata *MD) {
1104     return MD->getMetadataID() == MDTupleKind;
1105   }
1106 };
1107
1108 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1109   return MDTuple::get(Context, MDs);
1110 }
1111 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1112   return MDTuple::getIfExists(Context, MDs);
1113 }
1114 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1115   return MDTuple::getDistinct(Context, MDs);
1116 }
1117 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1118                                  ArrayRef<Metadata *> MDs) {
1119   return MDTuple::getTemporary(Context, MDs);
1120 }
1121
1122 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1123   MDNode::deleteTemporary(Node);
1124 }
1125
1126 /// \brief Typed iterator through MDNode operands.
1127 ///
1128 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1129 /// particular Metadata subclass.
1130 template <class T>
1131 class TypedMDOperandIterator
1132     : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
1133   MDNode::op_iterator I = nullptr;
1134
1135 public:
1136   TypedMDOperandIterator() = default;
1137   explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1138   T *operator*() const { return cast_or_null<T>(*I); }
1139   TypedMDOperandIterator &operator++() {
1140     ++I;
1141     return *this;
1142   }
1143   TypedMDOperandIterator operator++(int) {
1144     TypedMDOperandIterator Temp(*this);
1145     ++I;
1146     return Temp;
1147   }
1148   bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1149   bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1150 };
1151
1152 /// \brief Typed, array-like tuple of metadata.
1153 ///
1154 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1155 /// particular type of metadata.
1156 template <class T> class MDTupleTypedArrayWrapper {
1157   const MDTuple *N = nullptr;
1158
1159 public:
1160   MDTupleTypedArrayWrapper() = default;
1161   MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1162
1163   template <class U>
1164   MDTupleTypedArrayWrapper(
1165       const MDTupleTypedArrayWrapper<U> &Other,
1166       typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
1167           nullptr)
1168       : N(Other.get()) {}
1169
1170   template <class U>
1171   explicit MDTupleTypedArrayWrapper(
1172       const MDTupleTypedArrayWrapper<U> &Other,
1173       typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
1174           nullptr)
1175       : N(Other.get()) {}
1176
1177   explicit operator bool() const { return get(); }
1178   explicit operator MDTuple *() const { return get(); }
1179
1180   MDTuple *get() const { return const_cast<MDTuple *>(N); }
1181   MDTuple *operator->() const { return get(); }
1182   MDTuple &operator*() const { return *get(); }
1183
1184   // FIXME: Fix callers and remove condition on N.
1185   unsigned size() const { return N ? N->getNumOperands() : 0u; }
1186   T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1187
1188   // FIXME: Fix callers and remove condition on N.
1189   typedef TypedMDOperandIterator<T> iterator;
1190   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1191   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1192 };
1193
1194 #define HANDLE_METADATA(CLASS)                                                 \
1195   typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
1196 #include "llvm/IR/Metadata.def"
1197
1198 //===----------------------------------------------------------------------===//
1199 /// \brief A tuple of MDNodes.
1200 ///
1201 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1202 /// to modules, have names, and contain lists of MDNodes.
1203 ///
1204 /// TODO: Inherit from Metadata.
1205 class NamedMDNode : public ilist_node<NamedMDNode> {
1206   friend struct ilist_traits<NamedMDNode>;
1207   friend class LLVMContextImpl;
1208   friend class Module;
1209   NamedMDNode(const NamedMDNode &) = delete;
1210
1211   std::string Name;
1212   Module *Parent;
1213   void *Operands; // SmallVector<TrackingMDRef, 4>
1214
1215   void setParent(Module *M) { Parent = M; }
1216
1217   explicit NamedMDNode(const Twine &N);
1218
1219   template<class T1, class T2>
1220   class op_iterator_impl :
1221       public std::iterator<std::bidirectional_iterator_tag, T2> {
1222     const NamedMDNode *Node;
1223     unsigned Idx;
1224     op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1225
1226     friend class NamedMDNode;
1227
1228   public:
1229     op_iterator_impl() : Node(nullptr), Idx(0) { }
1230
1231     bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1232     bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1233     op_iterator_impl &operator++() {
1234       ++Idx;
1235       return *this;
1236     }
1237     op_iterator_impl operator++(int) {
1238       op_iterator_impl tmp(*this);
1239       operator++();
1240       return tmp;
1241     }
1242     op_iterator_impl &operator--() {
1243       --Idx;
1244       return *this;
1245     }
1246     op_iterator_impl operator--(int) {
1247       op_iterator_impl tmp(*this);
1248       operator--();
1249       return tmp;
1250     }
1251
1252     T1 operator*() const { return Node->getOperand(Idx); }
1253   };
1254
1255 public:
1256   /// \brief Drop all references and remove the node from parent module.
1257   void eraseFromParent();
1258
1259   /// \brief Remove all uses and clear node vector.
1260   void dropAllReferences();
1261
1262   ~NamedMDNode();
1263
1264   /// \brief Get the module that holds this named metadata collection.
1265   inline Module *getParent() { return Parent; }
1266   inline const Module *getParent() const { return Parent; }
1267
1268   MDNode *getOperand(unsigned i) const;
1269   unsigned getNumOperands() const;
1270   void addOperand(MDNode *M);
1271   void setOperand(unsigned I, MDNode *New);
1272   StringRef getName() const;
1273   void print(raw_ostream &ROS, bool IsForDebug = false) const;
1274   void dump() const;
1275
1276   // ---------------------------------------------------------------------------
1277   // Operand Iterator interface...
1278   //
1279   typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1280   op_iterator op_begin() { return op_iterator(this, 0); }
1281   op_iterator op_end()   { return op_iterator(this, getNumOperands()); }
1282
1283   typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1284   const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1285   const_op_iterator op_end()   const { return const_op_iterator(this, getNumOperands()); }
1286
1287   inline iterator_range<op_iterator>  operands() {
1288     return make_range(op_begin(), op_end());
1289   }
1290   inline iterator_range<const_op_iterator> operands() const {
1291     return make_range(op_begin(), op_end());
1292   }
1293 };
1294
1295 } // end llvm namespace
1296
1297 #endif // LLVM_IR_METADATA_H