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