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