Try fixing MSVC build after r223802
[oota-llvm.git] / include / llvm / IR / Metadata.h
1 //===-- llvm/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/ilist_node.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/MetadataTracking.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include <type_traits>
28
29 namespace llvm {
30 class LLVMContext;
31 class Module;
32 template<typename ValueSubClass, typename ItemParentClass>
33   class SymbolTableListTraits;
34
35
36 enum LLVMConstants : uint32_t {
37   DEBUG_METADATA_VERSION = 2  // 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 Storage flag for non-uniqued, otherwise unowned, metadata.
51   bool IsDistinctInContext : 1;
52   // TODO: expose remaining bits to subclasses.
53
54   unsigned short SubclassData16;
55   unsigned SubclassData32;
56
57 public:
58   enum MetadataKind {
59     GenericMDNodeKind,
60     MDNodeFwdDeclKind,
61     ConstantAsMetadataKind,
62     LocalAsMetadataKind,
63     MDStringKind
64   };
65
66 protected:
67   Metadata(unsigned ID)
68       : SubclassID(ID), IsDistinctInContext(false), SubclassData16(0),
69         SubclassData32(0) {}
70   ~Metadata() {}
71
72   /// \brief Store this in a big non-uniqued untyped bucket.
73   bool isStoredDistinctInContext() const { return IsDistinctInContext; }
74
75   /// \brief Default handling of a changed operand, which asserts.
76   ///
77   /// If subclasses pass themselves in as owners to a tracking node reference,
78   /// they must provide an implementation of this method.
79   void handleChangedOperand(void *, Metadata *) {
80     llvm_unreachable("Unimplemented in Metadata subclass");
81   }
82
83 public:
84   unsigned getMetadataID() const { return SubclassID; }
85
86   /// \brief User-friendly dump.
87   void dump() const;
88   void print(raw_ostream &OS) const;
89   void printAsOperand(raw_ostream &OS, bool PrintType = true,
90                       const Module *M = nullptr) const;
91 };
92
93 #define HANDLE_METADATA(CLASS) class CLASS;
94 #include "llvm/IR/Metadata.def"
95
96 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
97   MD.print(OS);
98   return OS;
99 }
100
101 /// \brief Metadata wrapper in the Value hierarchy.
102 ///
103 /// A member of the \a Value hierarchy to represent a reference to metadata.
104 /// This allows, e.g., instrinsics to have metadata as operands.
105 ///
106 /// Notably, this is the only thing in either hierarchy that is allowed to
107 /// reference \a LocalAsMetadata.
108 class MetadataAsValue : public Value {
109   friend class ReplaceableMetadataImpl;
110   friend class LLVMContextImpl;
111
112   Metadata *MD;
113
114   MetadataAsValue(Type *Ty, Metadata *MD);
115   ~MetadataAsValue();
116
117 public:
118   static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
119   static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
120   Metadata *getMetadata() const { return MD; }
121
122   static bool classof(const Value *V) {
123     return V->getValueID() == MetadataAsValueVal;
124   }
125
126 private:
127   void handleChangedMetadata(Metadata *MD);
128   void track();
129   void untrack();
130 };
131
132 /// \brief Shared implementation of use-lists for replaceable metadata.
133 ///
134 /// Most metadata cannot be RAUW'ed.  This is a shared implementation of
135 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
136 /// and \a TempMDNode).
137 class ReplaceableMetadataImpl {
138   friend class MetadataTracking;
139
140 public:
141   typedef MetadataTracking::OwnerTy OwnerTy;
142
143 private:
144   SmallDenseMap<void *, OwnerTy, 4> UseMap;
145
146 public:
147   ~ReplaceableMetadataImpl() {
148     assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
149   }
150
151   /// \brief Replace all uses of this with MD.
152   ///
153   /// Replace all uses of this with \c MD, which is allowed to be null.
154   void replaceAllUsesWith(Metadata *MD);
155
156   /// \brief Resolve all uses of this.
157   ///
158   /// Resolve all uses of this, turning off RAUW permanently.  If \c
159   /// ResolveUsers, call \a GenericMDNode::resolve() on any users whose last
160   /// operand is resolved.
161   void resolveAllUses(bool ResolveUsers = true);
162
163 private:
164   void addRef(void *Ref, OwnerTy Owner);
165   void dropRef(void *Ref);
166   void moveRef(void *Ref, void *New, const Metadata &MD);
167
168   static ReplaceableMetadataImpl *get(Metadata &MD);
169 };
170
171 /// \brief Value wrapper in the Metadata hierarchy.
172 ///
173 /// This is a custom value handle that allows other metadata to refer to
174 /// classes in the Value hierarchy.
175 ///
176 /// Because of full uniquing support, each value is only wrapped by a single \a
177 /// ValueAsMetadata object, so the lookup maps are far more efficient than
178 /// those using ValueHandleBase.
179 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
180   friend class ReplaceableMetadataImpl;
181   friend class LLVMContextImpl;
182
183   Value *V;
184
185 protected:
186   ValueAsMetadata(LLVMContext &Context, unsigned ID, Value *V)
187       : Metadata(ID), V(V) {
188     assert(V && "Expected valid value");
189   }
190   ~ValueAsMetadata() {}
191
192 public:
193   static ValueAsMetadata *get(Value *V);
194   static ConstantAsMetadata *getConstant(Value *C) {
195     return cast<ConstantAsMetadata>(get(C));
196   }
197   static LocalAsMetadata *getLocal(Value *Local) {
198     return cast<LocalAsMetadata>(get(Local));
199   }
200
201   static ValueAsMetadata *getIfExists(Value *V);
202   static ConstantAsMetadata *getConstantIfExists(Value *C) {
203     return cast_or_null<ConstantAsMetadata>(getIfExists(C));
204   }
205   static LocalAsMetadata *getLocalIfExists(Value *Local) {
206     return cast_or_null<LocalAsMetadata>(getIfExists(Local));
207   }
208
209   Value *getValue() const { return V; }
210   Type *getType() const { return V->getType(); }
211   LLVMContext &getContext() const { return V->getContext(); }
212
213   static void handleDeletion(Value *V);
214   static void handleRAUW(Value *From, Value *To);
215
216 protected:
217   /// \brief Handle collisions after \a Value::replaceAllUsesWith().
218   ///
219   /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
220   /// \a Value gets RAUW'ed and the target already exists, this is used to
221   /// merge the two metadata nodes.
222   void replaceAllUsesWith(Metadata *MD) {
223     ReplaceableMetadataImpl::replaceAllUsesWith(MD);
224   }
225
226 public:
227   static bool classof(const Metadata *MD) {
228     return MD->getMetadataID() == LocalAsMetadataKind ||
229            MD->getMetadataID() == ConstantAsMetadataKind;
230   }
231 };
232
233 class ConstantAsMetadata : public ValueAsMetadata {
234   friend class ValueAsMetadata;
235
236   ConstantAsMetadata(LLVMContext &Context, Constant *C)
237       : ValueAsMetadata(Context, ConstantAsMetadataKind, C) {}
238
239 public:
240   static ConstantAsMetadata *get(Constant *C) {
241     return ValueAsMetadata::getConstant(C);
242   }
243   static ConstantAsMetadata *getIfExists(Constant *C) {
244     return ValueAsMetadata::getConstantIfExists(C);
245   }
246
247   Constant *getValue() const {
248     return cast<Constant>(ValueAsMetadata::getValue());
249   }
250
251   static bool classof(const Metadata *MD) {
252     return MD->getMetadataID() == ConstantAsMetadataKind;
253   }
254 };
255
256 class LocalAsMetadata : public ValueAsMetadata {
257   friend class ValueAsMetadata;
258
259   LocalAsMetadata(LLVMContext &Context, Value *Local)
260       : ValueAsMetadata(Context, LocalAsMetadataKind, Local) {
261     assert(!isa<Constant>(Local) && "Expected local value");
262   }
263
264 public:
265   static LocalAsMetadata *get(Value *Local) {
266     return ValueAsMetadata::getLocal(Local);
267   }
268   static LocalAsMetadata *getIfExists(Value *Local) {
269     return ValueAsMetadata::getLocalIfExists(Local);
270   }
271
272   static bool classof(const Metadata *MD) {
273     return MD->getMetadataID() == LocalAsMetadataKind;
274   }
275 };
276
277 /// \brief Transitional API for extracting constants from Metadata.
278 ///
279 /// This namespace contains transitional functions for metadata that points to
280 /// \a Constants.
281 ///
282 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
283 /// operands could refer to any \a Value.  There's was a lot of code like this:
284 ///
285 /// \code
286 ///     MDNode *N = ...;
287 ///     auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
288 /// \endcode
289 ///
290 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
291 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
292 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
293 /// cast in the \a Value hierarchy.  Besides creating boiler-plate, this
294 /// requires subtle control flow changes.
295 ///
296 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
297 /// so that metadata can refer to numbers without traversing a bridge to the \a
298 /// Value hierarchy.  In this final state, the code above would look like this:
299 ///
300 /// \code
301 ///     MDNode *N = ...;
302 ///     auto *MI = dyn_cast<MDInt>(N->getOperand(2));
303 /// \endcode
304 ///
305 /// The API in this namespace supports the transition.  \a MDInt doesn't exist
306 /// yet, and even once it does, changing each metadata schema to use it is its
307 /// own mini-project.  In the meantime this API prevents us from introducing
308 /// complex and bug-prone control flow that will disappear in the end.  In
309 /// particular, the above code looks like this:
310 ///
311 /// \code
312 ///     MDNode *N = ...;
313 ///     auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
314 /// \endcode
315 ///
316 /// The full set of provided functions includes:
317 ///
318 ///   mdconst::hasa                <=> isa
319 ///   mdconst::extract             <=> cast
320 ///   mdconst::extract_or_null     <=> cast_or_null
321 ///   mdconst::dyn_extract         <=> dyn_cast
322 ///   mdconst::dyn_extract_or_null <=> dyn_cast_or_null
323 ///
324 /// The target of the cast must be a subclass of \a Constant.
325 namespace mdconst {
326
327 namespace detail {
328 template <class T> T &make();
329 template <class T, class Result> struct HasDereference {
330   typedef char Yes[1];
331   typedef char No[2];
332   template <size_t N> struct SFINAE {};
333
334   template <class U, class V>
335   static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
336   template <class U, class V> static No &hasDereference(...);
337
338   static const bool value =
339       sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
340 };
341 template <class V, class M> struct IsValidPointer {
342   static const bool value = std::is_base_of<Constant, V>::value &&
343                             HasDereference<M, const Metadata &>::value;
344 };
345 template <class V, class M> struct IsValidReference {
346   static const bool value = std::is_base_of<Constant, V>::value &&
347                             std::is_convertible<M, const Metadata &>::value;
348 };
349 } // end namespace detail
350
351 /// \brief Check whether Metadata has a Value.
352 ///
353 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
354 /// type \c X.
355 template <class X, class Y>
356 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
357 hasa(Y &&MD) {
358   assert(MD && "Null pointer sent into hasa");
359   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
360     return isa<X>(V->getValue());
361   return false;
362 }
363 template <class X, class Y>
364 inline
365     typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
366     hasa(Y &MD) {
367   return hasa(&MD);
368 }
369
370 /// \brief Extract a Value from Metadata.
371 ///
372 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
373 template <class X, class Y>
374 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
375 extract(Y &&MD) {
376   return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
377 }
378 template <class X, class Y>
379 inline
380     typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
381     extract(Y &MD) {
382   return extract(&MD);
383 }
384
385 /// \brief Extract a Value from Metadata, allowing null.
386 ///
387 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
388 /// from \c MD, allowing \c MD to be null.
389 template <class X, class Y>
390 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
391 extract_or_null(Y &&MD) {
392   if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
393     return cast<X>(V->getValue());
394   return nullptr;
395 }
396
397 /// \brief Extract a Value from Metadata, if any.
398 ///
399 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
400 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
401 /// Value it does contain is of the wrong subclass.
402 template <class X, class Y>
403 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
404 dyn_extract(Y &&MD) {
405   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
406     return dyn_cast<X>(V->getValue());
407   return nullptr;
408 }
409
410 /// \brief Extract a Value from Metadata, if any, allowing null.
411 ///
412 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
413 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
414 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
415 template <class X, class Y>
416 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
417 dyn_extract_or_null(Y &&MD) {
418   if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
419     return dyn_cast<X>(V->getValue());
420   return nullptr;
421 }
422
423 } // end namespace mdconst
424
425 //===----------------------------------------------------------------------===//
426 /// \brief A single uniqued string.
427 ///
428 /// These are used to efficiently contain a byte sequence for metadata.
429 /// MDString is always unnamed.
430 class MDString : public Metadata {
431   friend class StringMapEntry<MDString>;
432
433   MDString(const MDString &) LLVM_DELETED_FUNCTION;
434   MDString &operator=(MDString &&) LLVM_DELETED_FUNCTION;
435   MDString &operator=(const MDString &) LLVM_DELETED_FUNCTION;
436
437   StringMapEntry<MDString> *Entry;
438   MDString() : Metadata(MDStringKind), Entry(nullptr) {}
439   MDString(MDString &&) : Metadata(MDStringKind) {}
440
441 public:
442   static MDString *get(LLVMContext &Context, StringRef Str);
443   static MDString *get(LLVMContext &Context, const char *Str) {
444     return get(Context, Str ? StringRef(Str) : StringRef());
445   }
446
447   StringRef getString() const;
448
449   unsigned getLength() const { return (unsigned)getString().size(); }
450
451   typedef StringRef::iterator iterator;
452
453   /// \brief Pointer to the first byte of the string.
454   iterator begin() const { return getString().begin(); }
455
456   /// \brief Pointer to one byte past the end of the string.
457   iterator end() const { return getString().end(); }
458
459   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
460   static bool classof(const Metadata *MD) {
461     return MD->getMetadataID() == MDStringKind;
462   }
463 };
464
465 /// \brief A collection of metadata nodes that might be associated with a
466 /// memory access used by the alias-analysis infrastructure.
467 struct AAMDNodes {
468   explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
469                      MDNode *N = nullptr)
470       : TBAA(T), Scope(S), NoAlias(N) {}
471
472   bool operator==(const AAMDNodes &A) const {
473     return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
474   }
475
476   bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
477
478   LLVM_EXPLICIT operator bool() const { return TBAA || Scope || NoAlias; }
479
480   /// \brief The tag for type-based alias analysis.
481   MDNode *TBAA;
482
483   /// \brief The tag for alias scope specification (used with noalias).
484   MDNode *Scope;
485
486   /// \brief The tag specifying the noalias scope.
487   MDNode *NoAlias;
488 };
489
490 // Specialize DenseMapInfo for AAMDNodes.
491 template<>
492 struct DenseMapInfo<AAMDNodes> {
493   static inline AAMDNodes getEmptyKey() {
494     return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
495   }
496   static inline AAMDNodes getTombstoneKey() {
497     return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
498   }
499   static unsigned getHashValue(const AAMDNodes &Val) {
500     return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
501            DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
502            DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
503   }
504   static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
505     return LHS == RHS;
506   }
507 };
508
509 /// \brief Tracking metadata reference owned by Metadata.
510 ///
511 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
512 /// of \a Metadata, which has the option of registering itself for callbacks to
513 /// re-unique itself.
514 ///
515 /// In particular, this is used by \a MDNode.
516 class MDOperand {
517   MDOperand(MDOperand &&) LLVM_DELETED_FUNCTION;
518   MDOperand(const MDOperand &) LLVM_DELETED_FUNCTION;
519   MDOperand &operator=(MDOperand &&) LLVM_DELETED_FUNCTION;
520   MDOperand &operator=(const MDOperand &) LLVM_DELETED_FUNCTION;
521
522   Metadata *MD;
523
524 public:
525   MDOperand() : MD(nullptr) {}
526   ~MDOperand() { untrack(); }
527
528   Metadata *get() const { return MD; }
529   operator Metadata *() const { return get(); }
530   Metadata *operator->() const { return get(); }
531   Metadata &operator*() const { return *get(); }
532
533   void reset() {
534     untrack();
535     MD = nullptr;
536   }
537   void reset(Metadata *MD, Metadata *Owner) {
538     untrack();
539     this->MD = MD;
540     track(Owner);
541   }
542
543 private:
544   void track(Metadata *Owner) {
545     if (MD) {
546       if (Owner)
547         MetadataTracking::track(this, *MD, *Owner);
548       else
549         MetadataTracking::track(MD);
550     }
551   }
552   void untrack() {
553     assert(static_cast<void *>(this) == &MD && "Expected same address");
554     if (MD)
555       MetadataTracking::untrack(MD);
556   }
557 };
558
559 template <> struct simplify_type<MDOperand> {
560   typedef Metadata *SimpleType;
561   static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
562 };
563
564 template <> struct simplify_type<const MDOperand> {
565   typedef Metadata *SimpleType;
566   static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
567 };
568
569 //===----------------------------------------------------------------------===//
570 /// \brief Tuple of metadata.
571 class MDNode : public Metadata {
572   MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
573   void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
574   void *operator new(size_t) LLVM_DELETED_FUNCTION;
575
576   LLVMContext &Context;
577   unsigned NumOperands;
578
579 protected:
580   unsigned MDNodeSubclassData;
581
582   void *operator new(size_t Size, unsigned NumOps);
583
584   /// \brief Required by std, but never called.
585   void operator delete(void *Mem);
586
587   /// \brief Required by std, but never called.
588   void operator delete(void *, unsigned) {
589     llvm_unreachable("Constructor throws?");
590   }
591
592   /// \brief Required by std, but never called.
593   void operator delete(void *, unsigned, bool) {
594     llvm_unreachable("Constructor throws?");
595   }
596
597   MDNode(LLVMContext &Context, unsigned ID, ArrayRef<Metadata *> MDs);
598   ~MDNode() { dropAllReferences(); }
599
600   void dropAllReferences();
601   void storeDistinctInContext();
602
603   static MDNode *getMDNode(LLVMContext &C, ArrayRef<Metadata *> MDs,
604                            bool Insert = true);
605
606   MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
607   MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
608
609 public:
610   static MDNode *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
611     return getMDNode(Context, MDs, true);
612   }
613   static MDNode *getWhenValsUnresolved(LLVMContext &Context,
614                                        ArrayRef<Metadata *> MDs) {
615     // TODO: Remove this.
616     return get(Context, MDs);
617   }
618
619   static MDNode *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
620     return getMDNode(Context, MDs, false);
621   }
622
623   /// \brief Return a temporary MDNode
624   ///
625   /// For use in constructing cyclic MDNode structures. A temporary MDNode is
626   /// not uniqued, may be RAUW'd, and must be manually deleted with
627   /// deleteTemporary.
628   static MDNodeFwdDecl *getTemporary(LLVMContext &Context,
629                                      ArrayRef<Metadata *> MDs);
630
631   /// \brief Deallocate a node created by getTemporary.
632   ///
633   /// The node must not have any users.
634   static void deleteTemporary(MDNode *N);
635
636   LLVMContext &getContext() const { return Context; }
637
638   /// \brief Replace a specific operand.
639   void replaceOperandWith(unsigned I, Metadata *New);
640
641   /// \brief Check if node is fully resolved.
642   bool isResolved() const;
643
644 protected:
645   /// \brief Set an operand.
646   ///
647   /// Sets the operand directly, without worrying about uniquing.
648   void setOperand(unsigned I, Metadata *New);
649
650 public:
651   typedef const MDOperand *op_iterator;
652   typedef iterator_range<op_iterator> op_range;
653
654   op_iterator op_begin() const {
655     return const_cast<MDNode *>(this)->mutable_begin();
656   }
657   op_iterator op_end() const {
658     return const_cast<MDNode *>(this)->mutable_end();
659   }
660   op_range operands() const { return op_range(op_begin(), op_end()); }
661
662   const MDOperand &getOperand(unsigned I) const {
663     assert(I < NumOperands && "Out of range");
664     return op_begin()[I];
665   }
666
667   /// \brief Return number of MDNode operands.
668   unsigned getNumOperands() const { return NumOperands; }
669
670   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
671   static bool classof(const Metadata *MD) {
672     return MD->getMetadataID() == GenericMDNodeKind ||
673            MD->getMetadataID() == MDNodeFwdDeclKind;
674   }
675
676   /// \brief Check whether MDNode is a vtable access.
677   bool isTBAAVtableAccess() const;
678
679   /// \brief Methods for metadata merging.
680   static MDNode *concatenate(MDNode *A, MDNode *B);
681   static MDNode *intersect(MDNode *A, MDNode *B);
682   static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
683   static AAMDNodes getMostGenericAA(const AAMDNodes &A, const AAMDNodes &B);
684   static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
685   static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
686 };
687
688 /// \brief Generic metadata node.
689 ///
690 /// Generic metadata nodes, with opt-out support for uniquing.
691 ///
692 /// Although nodes are uniqued by default, \a GenericMDNode has no support for
693 /// RAUW.  If an operand change (due to RAUW or otherwise) causes a uniquing
694 /// collision, the uniquing bit is dropped.
695 ///
696 /// TODO: Make uniquing opt-out (status: mandatory, sometimes dropped).
697 /// TODO: Drop support for RAUW.
698 class GenericMDNode : public MDNode {
699   friend class Metadata;
700   friend class MDNode;
701   friend class LLVMContextImpl;
702   friend class ReplaceableMetadataImpl;
703
704   /// \brief Support RAUW as long as one of its arguments is replaceable.
705   ///
706   /// If an operand is an \a MDNodeFwdDecl (or a replaceable \a GenericMDNode),
707   /// support RAUW to support uniquing as forward declarations are resolved.
708   /// As soon as operands have been resolved, drop support.
709   ///
710   /// FIXME: Save memory by storing this in a pointer union with the
711   /// LLVMContext, and adding an LLVMContext reference to RMI.
712   std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses;
713
714   GenericMDNode(LLVMContext &C, ArrayRef<Metadata *> Vals);
715   ~GenericMDNode();
716
717   void setHash(unsigned Hash) { MDNodeSubclassData = Hash; }
718
719 public:
720   /// \brief Get the hash, if any.
721   unsigned getHash() const { return MDNodeSubclassData; }
722
723   static bool classof(const Metadata *MD) {
724     return MD->getMetadataID() == GenericMDNodeKind;
725   }
726
727   /// \brief Check whether any operands are forward declarations.
728   ///
729   /// Returns \c true as long as any operands (or their operands, etc.) are \a
730   /// MDNodeFwdDecl.
731   ///
732   /// As forward declarations are resolved, their containers should get
733   /// resolved automatically.  However, if this (or one of its operands) is
734   /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
735   bool isResolved() const { return !ReplaceableUses; }
736
737   /// \brief Resolve cycles.
738   ///
739   /// Once all forward declarations have been resolved, force cycles to be
740   /// resolved.
741   ///
742   /// \pre No operands (or operands' operands, etc.) are \a MDNodeFwdDecl.
743   void resolveCycles();
744
745 private:
746   void handleChangedOperand(void *Ref, Metadata *New);
747
748   bool hasUnresolvedOperands() const { return SubclassData32; }
749   void incrementUnresolvedOperands() { ++SubclassData32; }
750   void decrementUnresolvedOperands() { --SubclassData32; }
751   void resolve();
752 };
753
754 /// \brief Forward declaration of metadata.
755 ///
756 /// Forward declaration of metadata, in the form of a metadata node.  Unlike \a
757 /// GenericMDNode, this class has support for RAUW and is suitable for forward
758 /// references.
759 class MDNodeFwdDecl : public MDNode, ReplaceableMetadataImpl {
760   friend class Metadata;
761   friend class MDNode;
762   friend class ReplaceableMetadataImpl;
763
764   MDNodeFwdDecl(LLVMContext &C, ArrayRef<Metadata *> Vals)
765       : MDNode(C, MDNodeFwdDeclKind, Vals) {}
766   ~MDNodeFwdDecl() {}
767
768 public:
769   static bool classof(const Metadata *MD) {
770     return MD->getMetadataID() == MDNodeFwdDeclKind;
771   }
772
773   using ReplaceableMetadataImpl::replaceAllUsesWith;
774 };
775
776 //===----------------------------------------------------------------------===//
777 /// \brief A tuple of MDNodes.
778 ///
779 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
780 /// to modules, have names, and contain lists of MDNodes.
781 ///
782 /// TODO: Inherit from Metadata.
783 class NamedMDNode : public ilist_node<NamedMDNode> {
784   friend class SymbolTableListTraits<NamedMDNode, Module>;
785   friend struct ilist_traits<NamedMDNode>;
786   friend class LLVMContextImpl;
787   friend class Module;
788   NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION;
789
790   std::string Name;
791   Module *Parent;
792   void *Operands; // SmallVector<TrackingMDRef, 4>
793
794   void setParent(Module *M) { Parent = M; }
795
796   explicit NamedMDNode(const Twine &N);
797
798   template<class T1, class T2>
799   class op_iterator_impl :
800       public std::iterator<std::bidirectional_iterator_tag, T2> {
801     const NamedMDNode *Node;
802     unsigned Idx;
803     op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
804
805     friend class NamedMDNode;
806
807   public:
808     op_iterator_impl() : Node(nullptr), Idx(0) { }
809
810     bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
811     bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
812     op_iterator_impl &operator++() {
813       ++Idx;
814       return *this;
815     }
816     op_iterator_impl operator++(int) {
817       op_iterator_impl tmp(*this);
818       operator++();
819       return tmp;
820     }
821     op_iterator_impl &operator--() {
822       --Idx;
823       return *this;
824     }
825     op_iterator_impl operator--(int) {
826       op_iterator_impl tmp(*this);
827       operator--();
828       return tmp;
829     }
830
831     T1 operator*() const { return Node->getOperand(Idx); }
832   };
833
834 public:
835   /// \brief Drop all references and remove the node from parent module.
836   void eraseFromParent();
837
838   /// \brief Remove all uses and clear node vector.
839   void dropAllReferences();
840
841   ~NamedMDNode();
842
843   /// \brief Get the module that holds this named metadata collection.
844   inline Module *getParent() { return Parent; }
845   inline const Module *getParent() const { return Parent; }
846
847   MDNode *getOperand(unsigned i) const;
848   unsigned getNumOperands() const;
849   void addOperand(MDNode *M);
850   StringRef getName() const;
851   void print(raw_ostream &ROS) const;
852   void dump() const;
853
854   // ---------------------------------------------------------------------------
855   // Operand Iterator interface...
856   //
857   typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
858   op_iterator op_begin() { return op_iterator(this, 0); }
859   op_iterator op_end()   { return op_iterator(this, getNumOperands()); }
860
861   typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
862   const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
863   const_op_iterator op_end()   const { return const_op_iterator(this, getNumOperands()); }
864
865   inline iterator_range<op_iterator>  operands() {
866     return iterator_range<op_iterator>(op_begin(), op_end());
867   }
868   inline iterator_range<const_op_iterator> operands() const {
869     return iterator_range<const_op_iterator>(op_begin(), op_end());
870   }
871 };
872
873 } // end llvm namespace
874
875 #endif