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