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