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