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