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