]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/include/llvm/IR/Metadata.h
MFC r355940:
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / include / llvm / IR / Metadata.h
1 //===- llvm/IR/Metadata.h - Metadata definitions ----------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// @file
10 /// This file contains the declarations for metadata subclasses.
11 /// They represent the different flavors of metadata that live in LLVM.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_IR_METADATA_H
16 #define LLVM_IR_METADATA_H
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/DenseMapInfo.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/PointerUnion.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/ilist_node.h"
27 #include "llvm/ADT/iterator_range.h"
28 #include "llvm/IR/Constant.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Support/CBindingWrapping.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include <cassert>
35 #include <cstddef>
36 #include <cstdint>
37 #include <iterator>
38 #include <memory>
39 #include <string>
40 #include <type_traits>
41 #include <utility>
42
43 namespace llvm {
44
45 class Module;
46 class ModuleSlotTracker;
47 class raw_ostream;
48 class Type;
49
50 enum LLVMConstants : uint32_t {
51   DEBUG_METADATA_VERSION = 3 // Current debug info version number.
52 };
53
54 /// Root of the metadata hierarchy.
55 ///
56 /// This is a root class for typeless data in the IR.
57 class Metadata {
58   friend class ReplaceableMetadataImpl;
59
60   /// RTTI.
61   const unsigned char SubclassID;
62
63 protected:
64   /// Active type of storage.
65   enum StorageType { Uniqued, Distinct, Temporary };
66
67   /// Storage flag for non-uniqued, otherwise unowned, metadata.
68   unsigned char Storage : 7;
69   // TODO: expose remaining bits to subclasses.
70
71   unsigned char ImplicitCode : 1;
72
73   unsigned short SubclassData16 = 0;
74   unsigned SubclassData32 = 0;
75
76 public:
77   enum MetadataKind {
78 #define HANDLE_METADATA_LEAF(CLASS) CLASS##Kind,
79 #include "llvm/IR/Metadata.def"
80   };
81
82 protected:
83   Metadata(unsigned ID, StorageType Storage)
84       : SubclassID(ID), Storage(Storage), ImplicitCode(false) {
85     static_assert(sizeof(*this) == 8, "Metadata fields poorly packed");
86   }
87
88   ~Metadata() = default;
89
90   /// Default handling of a changed operand, which asserts.
91   ///
92   /// If subclasses pass themselves in as owners to a tracking node reference,
93   /// they must provide an implementation of this method.
94   void handleChangedOperand(void *, Metadata *) {
95     llvm_unreachable("Unimplemented in Metadata subclass");
96   }
97
98 public:
99   unsigned getMetadataID() const { return SubclassID; }
100
101   /// User-friendly dump.
102   ///
103   /// If \c M is provided, metadata nodes will be numbered canonically;
104   /// otherwise, pointer addresses are substituted.
105   ///
106   /// Note: this uses an explicit overload instead of default arguments so that
107   /// the nullptr version is easy to call from a debugger.
108   ///
109   /// @{
110   void dump() const;
111   void dump(const Module *M) const;
112   /// @}
113
114   /// Print.
115   ///
116   /// Prints definition of \c this.
117   ///
118   /// If \c M is provided, metadata nodes will be numbered canonically;
119   /// otherwise, pointer addresses are substituted.
120   /// @{
121   void print(raw_ostream &OS, const Module *M = nullptr,
122              bool IsForDebug = false) const;
123   void print(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr,
124              bool IsForDebug = false) const;
125   /// @}
126
127   /// Print as operand.
128   ///
129   /// Prints reference of \c this.
130   ///
131   /// If \c M is provided, metadata nodes will be numbered canonically;
132   /// otherwise, pointer addresses are substituted.
133   /// @{
134   void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
135   void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
136                       const Module *M = nullptr) const;
137   /// @}
138 };
139
140 // Create wrappers for C Binding types (see CBindingWrapping.h).
141 DEFINE_ISA_CONVERSION_FUNCTIONS(Metadata, LLVMMetadataRef)
142
143 // Specialized opaque metadata conversions.
144 inline Metadata **unwrap(LLVMMetadataRef *MDs) {
145   return reinterpret_cast<Metadata**>(MDs);
146 }
147
148 #define HANDLE_METADATA(CLASS) class CLASS;
149 #include "llvm/IR/Metadata.def"
150
151 // Provide specializations of isa so that we don't need definitions of
152 // subclasses to see if the metadata is a subclass.
153 #define HANDLE_METADATA_LEAF(CLASS)                                            \
154   template <> struct isa_impl<CLASS, Metadata> {                               \
155     static inline bool doit(const Metadata &MD) {                              \
156       return MD.getMetadataID() == Metadata::CLASS##Kind;                      \
157     }                                                                          \
158   };
159 #include "llvm/IR/Metadata.def"
160
161 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
162   MD.print(OS);
163   return OS;
164 }
165
166 /// Metadata wrapper in the Value hierarchy.
167 ///
168 /// A member of the \a Value hierarchy to represent a reference to metadata.
169 /// This allows, e.g., instrinsics to have metadata as operands.
170 ///
171 /// Notably, this is the only thing in either hierarchy that is allowed to
172 /// reference \a LocalAsMetadata.
173 class MetadataAsValue : public Value {
174   friend class ReplaceableMetadataImpl;
175   friend class LLVMContextImpl;
176
177   Metadata *MD;
178
179   MetadataAsValue(Type *Ty, Metadata *MD);
180
181   /// Drop use of metadata (during teardown).
182   void dropUse() { MD = nullptr; }
183
184 public:
185   ~MetadataAsValue();
186
187   static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
188   static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
189
190   Metadata *getMetadata() const { return MD; }
191
192   static bool classof(const Value *V) {
193     return V->getValueID() == MetadataAsValueVal;
194   }
195
196 private:
197   void handleChangedMetadata(Metadata *MD);
198   void track();
199   void untrack();
200 };
201
202 /// API for tracking metadata references through RAUW and deletion.
203 ///
204 /// Shared API for updating \a Metadata pointers in subclasses that support
205 /// RAUW.
206 ///
207 /// This API is not meant to be used directly.  See \a TrackingMDRef for a
208 /// user-friendly tracking reference.
209 class MetadataTracking {
210 public:
211   /// Track the reference to metadata.
212   ///
213   /// Register \c MD with \c *MD, if the subclass supports tracking.  If \c *MD
214   /// gets RAUW'ed, \c MD will be updated to the new address.  If \c *MD gets
215   /// deleted, \c MD will be set to \c nullptr.
216   ///
217   /// If tracking isn't supported, \c *MD will not change.
218   ///
219   /// \return true iff tracking is supported by \c MD.
220   static bool track(Metadata *&MD) {
221     return track(&MD, *MD, static_cast<Metadata *>(nullptr));
222   }
223
224   /// Track the reference to metadata for \a Metadata.
225   ///
226   /// As \a track(Metadata*&), but with support for calling back to \c Owner to
227   /// tell it that its operand changed.  This could trigger \c Owner being
228   /// re-uniqued.
229   static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
230     return track(Ref, MD, &Owner);
231   }
232
233   /// Track the reference to metadata for \a MetadataAsValue.
234   ///
235   /// As \a track(Metadata*&), but with support for calling back to \c Owner to
236   /// tell it that its operand changed.  This could trigger \c Owner being
237   /// re-uniqued.
238   static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
239     return track(Ref, MD, &Owner);
240   }
241
242   /// Stop tracking a reference to metadata.
243   ///
244   /// Stops \c *MD from tracking \c MD.
245   static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
246   static void untrack(void *Ref, Metadata &MD);
247
248   /// Move tracking from one reference to another.
249   ///
250   /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
251   /// except that ownership callbacks are maintained.
252   ///
253   /// Note: it is an error if \c *MD does not equal \c New.
254   ///
255   /// \return true iff tracking is supported by \c MD.
256   static bool retrack(Metadata *&MD, Metadata *&New) {
257     return retrack(&MD, *MD, &New);
258   }
259   static bool retrack(void *Ref, Metadata &MD, void *New);
260
261   /// Check whether metadata is replaceable.
262   static bool isReplaceable(const Metadata &MD);
263
264   using OwnerTy = PointerUnion<MetadataAsValue *, Metadata *>;
265
266 private:
267   /// Track a reference to metadata for an owner.
268   ///
269   /// Generalized version of tracking.
270   static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
271 };
272
273 /// Shared implementation of use-lists for replaceable metadata.
274 ///
275 /// Most metadata cannot be RAUW'ed.  This is a shared implementation of
276 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
277 /// and \a TempMDNode).
278 class ReplaceableMetadataImpl {
279   friend class MetadataTracking;
280
281 public:
282   using OwnerTy = MetadataTracking::OwnerTy;
283
284 private:
285   LLVMContext &Context;
286   uint64_t NextIndex = 0;
287   SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
288
289 public:
290   ReplaceableMetadataImpl(LLVMContext &Context) : Context(Context) {}
291
292   ~ReplaceableMetadataImpl() {
293     assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
294   }
295
296   LLVMContext &getContext() const { return Context; }
297
298   /// Replace all uses of this with MD.
299   ///
300   /// Replace all uses of this with \c MD, which is allowed to be null.
301   void replaceAllUsesWith(Metadata *MD);
302
303   /// Resolve all uses of this.
304   ///
305   /// Resolve all uses of this, turning off RAUW permanently.  If \c
306   /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
307   /// is resolved.
308   void resolveAllUses(bool ResolveUsers = true);
309
310 private:
311   void addRef(void *Ref, OwnerTy Owner);
312   void dropRef(void *Ref);
313   void moveRef(void *Ref, void *New, const Metadata &MD);
314
315   /// Lazily construct RAUW support on MD.
316   ///
317   /// If this is an unresolved MDNode, RAUW support will be created on-demand.
318   /// ValueAsMetadata always has RAUW support.
319   static ReplaceableMetadataImpl *getOrCreate(Metadata &MD);
320
321   /// Get RAUW support on MD, if it exists.
322   static ReplaceableMetadataImpl *getIfExists(Metadata &MD);
323
324   /// Check whether this node will support RAUW.
325   ///
326   /// Returns \c true unless getOrCreate() would return null.
327   static bool isReplaceable(const Metadata &MD);
328 };
329
330 /// Value wrapper in the Metadata hierarchy.
331 ///
332 /// This is a custom value handle that allows other metadata to refer to
333 /// classes in the Value hierarchy.
334 ///
335 /// Because of full uniquing support, each value is only wrapped by a single \a
336 /// ValueAsMetadata object, so the lookup maps are far more efficient than
337 /// those using ValueHandleBase.
338 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
339   friend class ReplaceableMetadataImpl;
340   friend class LLVMContextImpl;
341
342   Value *V;
343
344   /// Drop users without RAUW (during teardown).
345   void dropUsers() {
346     ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
347   }
348
349 protected:
350   ValueAsMetadata(unsigned ID, Value *V)
351       : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
352     assert(V && "Expected valid value");
353   }
354
355   ~ValueAsMetadata() = default;
356
357 public:
358   static ValueAsMetadata *get(Value *V);
359
360   static ConstantAsMetadata *getConstant(Value *C) {
361     return cast<ConstantAsMetadata>(get(C));
362   }
363
364   static LocalAsMetadata *getLocal(Value *Local) {
365     return cast<LocalAsMetadata>(get(Local));
366   }
367
368   static ValueAsMetadata *getIfExists(Value *V);
369
370   static ConstantAsMetadata *getConstantIfExists(Value *C) {
371     return cast_or_null<ConstantAsMetadata>(getIfExists(C));
372   }
373
374   static LocalAsMetadata *getLocalIfExists(Value *Local) {
375     return cast_or_null<LocalAsMetadata>(getIfExists(Local));
376   }
377
378   Value *getValue() const { return V; }
379   Type *getType() const { return V->getType(); }
380   LLVMContext &getContext() const { return V->getContext(); }
381
382   static void handleDeletion(Value *V);
383   static void handleRAUW(Value *From, Value *To);
384
385 protected:
386   /// Handle collisions after \a Value::replaceAllUsesWith().
387   ///
388   /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
389   /// \a Value gets RAUW'ed and the target already exists, this is used to
390   /// merge the two metadata nodes.
391   void replaceAllUsesWith(Metadata *MD) {
392     ReplaceableMetadataImpl::replaceAllUsesWith(MD);
393   }
394
395 public:
396   static bool classof(const Metadata *MD) {
397     return MD->getMetadataID() == LocalAsMetadataKind ||
398            MD->getMetadataID() == ConstantAsMetadataKind;
399   }
400 };
401
402 class ConstantAsMetadata : public ValueAsMetadata {
403   friend class ValueAsMetadata;
404
405   ConstantAsMetadata(Constant *C)
406       : ValueAsMetadata(ConstantAsMetadataKind, C) {}
407
408 public:
409   static ConstantAsMetadata *get(Constant *C) {
410     return ValueAsMetadata::getConstant(C);
411   }
412
413   static ConstantAsMetadata *getIfExists(Constant *C) {
414     return ValueAsMetadata::getConstantIfExists(C);
415   }
416
417   Constant *getValue() const {
418     return cast<Constant>(ValueAsMetadata::getValue());
419   }
420
421   static bool classof(const Metadata *MD) {
422     return MD->getMetadataID() == ConstantAsMetadataKind;
423   }
424 };
425
426 class LocalAsMetadata : public ValueAsMetadata {
427   friend class ValueAsMetadata;
428
429   LocalAsMetadata(Value *Local)
430       : ValueAsMetadata(LocalAsMetadataKind, Local) {
431     assert(!isa<Constant>(Local) && "Expected local value");
432   }
433
434 public:
435   static LocalAsMetadata *get(Value *Local) {
436     return ValueAsMetadata::getLocal(Local);
437   }
438
439   static LocalAsMetadata *getIfExists(Value *Local) {
440     return ValueAsMetadata::getLocalIfExists(Local);
441   }
442
443   static bool classof(const Metadata *MD) {
444     return MD->getMetadataID() == LocalAsMetadataKind;
445   }
446 };
447
448 /// Transitional API for extracting constants from Metadata.
449 ///
450 /// This namespace contains transitional functions for metadata that points to
451 /// \a Constants.
452 ///
453 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
454 /// operands could refer to any \a Value.  There's was a lot of code like this:
455 ///
456 /// \code
457 ///     MDNode *N = ...;
458 ///     auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
459 /// \endcode
460 ///
461 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
462 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
463 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
464 /// cast in the \a Value hierarchy.  Besides creating boiler-plate, this
465 /// requires subtle control flow changes.
466 ///
467 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
468 /// so that metadata can refer to numbers without traversing a bridge to the \a
469 /// Value hierarchy.  In this final state, the code above would look like this:
470 ///
471 /// \code
472 ///     MDNode *N = ...;
473 ///     auto *MI = dyn_cast<MDInt>(N->getOperand(2));
474 /// \endcode
475 ///
476 /// The API in this namespace supports the transition.  \a MDInt doesn't exist
477 /// yet, and even once it does, changing each metadata schema to use it is its
478 /// own mini-project.  In the meantime this API prevents us from introducing
479 /// complex and bug-prone control flow that will disappear in the end.  In
480 /// particular, the above code looks like this:
481 ///
482 /// \code
483 ///     MDNode *N = ...;
484 ///     auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
485 /// \endcode
486 ///
487 /// The full set of provided functions includes:
488 ///
489 ///   mdconst::hasa                <=> isa
490 ///   mdconst::extract             <=> cast
491 ///   mdconst::extract_or_null     <=> cast_or_null
492 ///   mdconst::dyn_extract         <=> dyn_cast
493 ///   mdconst::dyn_extract_or_null <=> dyn_cast_or_null
494 ///
495 /// The target of the cast must be a subclass of \a Constant.
496 namespace mdconst {
497
498 namespace detail {
499
500 template <class T> T &make();
501 template <class T, class Result> struct HasDereference {
502   using Yes = char[1];
503   using No = char[2];
504   template <size_t N> struct SFINAE {};
505
506   template <class U, class V>
507   static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
508   template <class U, class V> static No &hasDereference(...);
509
510   static const bool value =
511       sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
512 };
513 template <class V, class M> struct IsValidPointer {
514   static const bool value = std::is_base_of<Constant, V>::value &&
515                             HasDereference<M, const Metadata &>::value;
516 };
517 template <class V, class M> struct IsValidReference {
518   static const bool value = std::is_base_of<Constant, V>::value &&
519                             std::is_convertible<M, const Metadata &>::value;
520 };
521
522 } // end namespace detail
523
524 /// Check whether Metadata has a Value.
525 ///
526 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
527 /// type \c X.
528 template <class X, class Y>
529 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
530 hasa(Y &&MD) {
531   assert(MD && "Null pointer sent into hasa");
532   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
533     return isa<X>(V->getValue());
534   return false;
535 }
536 template <class X, class Y>
537 inline
538     typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
539     hasa(Y &MD) {
540   return hasa(&MD);
541 }
542
543 /// Extract a Value from Metadata.
544 ///
545 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
546 template <class X, class Y>
547 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
548 extract(Y &&MD) {
549   return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
550 }
551 template <class X, class Y>
552 inline
553     typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
554     extract(Y &MD) {
555   return extract(&MD);
556 }
557
558 /// Extract a Value from Metadata, allowing null.
559 ///
560 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
561 /// from \c MD, allowing \c MD to be null.
562 template <class X, class Y>
563 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
564 extract_or_null(Y &&MD) {
565   if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
566     return cast<X>(V->getValue());
567   return nullptr;
568 }
569
570 /// Extract a Value from Metadata, if any.
571 ///
572 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
573 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
574 /// Value it does contain is of the wrong subclass.
575 template <class X, class Y>
576 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
577 dyn_extract(Y &&MD) {
578   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
579     return dyn_cast<X>(V->getValue());
580   return nullptr;
581 }
582
583 /// Extract a Value from Metadata, if any, allowing null.
584 ///
585 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
586 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
587 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
588 template <class X, class Y>
589 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
590 dyn_extract_or_null(Y &&MD) {
591   if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
592     return dyn_cast<X>(V->getValue());
593   return nullptr;
594 }
595
596 } // end namespace mdconst
597
598 //===----------------------------------------------------------------------===//
599 /// A single uniqued string.
600 ///
601 /// These are used to efficiently contain a byte sequence for metadata.
602 /// MDString is always unnamed.
603 class MDString : public Metadata {
604   friend class StringMapEntry<MDString>;
605
606   StringMapEntry<MDString> *Entry = nullptr;
607
608   MDString() : Metadata(MDStringKind, Uniqued) {}
609
610 public:
611   MDString(const MDString &) = delete;
612   MDString &operator=(MDString &&) = delete;
613   MDString &operator=(const MDString &) = delete;
614
615   static MDString *get(LLVMContext &Context, StringRef Str);
616   static MDString *get(LLVMContext &Context, const char *Str) {
617     return get(Context, Str ? StringRef(Str) : StringRef());
618   }
619
620   StringRef getString() const;
621
622   unsigned getLength() const { return (unsigned)getString().size(); }
623
624   using iterator = StringRef::iterator;
625
626   /// Pointer to the first byte of the string.
627   iterator begin() const { return getString().begin(); }
628
629   /// Pointer to one byte past the end of the string.
630   iterator end() const { return getString().end(); }
631
632   const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
633   const unsigned char *bytes_end() const { return getString().bytes_end(); }
634
635   /// Methods for support type inquiry through isa, cast, and dyn_cast.
636   static bool classof(const Metadata *MD) {
637     return MD->getMetadataID() == MDStringKind;
638   }
639 };
640
641 /// A collection of metadata nodes that might be associated with a
642 /// memory access used by the alias-analysis infrastructure.
643 struct AAMDNodes {
644   explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
645                      MDNode *N = nullptr)
646       : TBAA(T), Scope(S), NoAlias(N) {}
647
648   bool operator==(const AAMDNodes &A) const {
649     return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
650   }
651
652   bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
653
654   explicit operator bool() const { return TBAA || Scope || NoAlias; }
655
656   /// The tag for type-based alias analysis.
657   MDNode *TBAA;
658
659   /// The tag for alias scope specification (used with noalias).
660   MDNode *Scope;
661
662   /// The tag specifying the noalias scope.
663   MDNode *NoAlias;
664
665   /// Given two sets of AAMDNodes that apply to the same pointer,
666   /// give the best AAMDNodes that are compatible with both (i.e. a set of
667   /// nodes whose allowable aliasing conclusions are a subset of those
668   /// allowable by both of the inputs). However, for efficiency
669   /// reasons, do not create any new MDNodes.
670   AAMDNodes intersect(const AAMDNodes &Other) {
671     AAMDNodes Result;
672     Result.TBAA = Other.TBAA == TBAA ? TBAA : nullptr;
673     Result.Scope = Other.Scope == Scope ? Scope : nullptr;
674     Result.NoAlias = Other.NoAlias == NoAlias ? NoAlias : nullptr;
675     return Result;
676   }
677 };
678
679 // Specialize DenseMapInfo for AAMDNodes.
680 template<>
681 struct DenseMapInfo<AAMDNodes> {
682   static inline AAMDNodes getEmptyKey() {
683     return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
684                      nullptr, nullptr);
685   }
686
687   static inline AAMDNodes getTombstoneKey() {
688     return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
689                      nullptr, nullptr);
690   }
691
692   static unsigned getHashValue(const AAMDNodes &Val) {
693     return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
694            DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
695            DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
696   }
697
698   static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
699     return LHS == RHS;
700   }
701 };
702
703 /// Tracking metadata reference owned by Metadata.
704 ///
705 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
706 /// of \a Metadata, which has the option of registering itself for callbacks to
707 /// re-unique itself.
708 ///
709 /// In particular, this is used by \a MDNode.
710 class MDOperand {
711   Metadata *MD = nullptr;
712
713 public:
714   MDOperand() = default;
715   MDOperand(MDOperand &&) = delete;
716   MDOperand(const MDOperand &) = delete;
717   MDOperand &operator=(MDOperand &&) = delete;
718   MDOperand &operator=(const MDOperand &) = delete;
719   ~MDOperand() { untrack(); }
720
721   Metadata *get() const { return MD; }
722   operator Metadata *() const { return get(); }
723   Metadata *operator->() const { return get(); }
724   Metadata &operator*() const { return *get(); }
725
726   void reset() {
727     untrack();
728     MD = nullptr;
729   }
730   void reset(Metadata *MD, Metadata *Owner) {
731     untrack();
732     this->MD = MD;
733     track(Owner);
734   }
735
736 private:
737   void track(Metadata *Owner) {
738     if (MD) {
739       if (Owner)
740         MetadataTracking::track(this, *MD, *Owner);
741       else
742         MetadataTracking::track(MD);
743     }
744   }
745
746   void untrack() {
747     assert(static_cast<void *>(this) == &MD && "Expected same address");
748     if (MD)
749       MetadataTracking::untrack(MD);
750   }
751 };
752
753 template <> struct simplify_type<MDOperand> {
754   using SimpleType = Metadata *;
755
756   static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
757 };
758
759 template <> struct simplify_type<const MDOperand> {
760   using SimpleType = Metadata *;
761
762   static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
763 };
764
765 /// Pointer to the context, with optional RAUW support.
766 ///
767 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
768 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
769 class ContextAndReplaceableUses {
770   PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
771
772 public:
773   ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
774   ContextAndReplaceableUses(
775       std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
776       : Ptr(ReplaceableUses.release()) {
777     assert(getReplaceableUses() && "Expected non-null replaceable uses");
778   }
779   ContextAndReplaceableUses() = delete;
780   ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
781   ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
782   ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
783   ContextAndReplaceableUses &
784   operator=(const ContextAndReplaceableUses &) = delete;
785   ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
786
787   operator LLVMContext &() { return getContext(); }
788
789   /// Whether this contains RAUW support.
790   bool hasReplaceableUses() const {
791     return Ptr.is<ReplaceableMetadataImpl *>();
792   }
793
794   LLVMContext &getContext() const {
795     if (hasReplaceableUses())
796       return getReplaceableUses()->getContext();
797     return *Ptr.get<LLVMContext *>();
798   }
799
800   ReplaceableMetadataImpl *getReplaceableUses() const {
801     if (hasReplaceableUses())
802       return Ptr.get<ReplaceableMetadataImpl *>();
803     return nullptr;
804   }
805
806   /// Ensure that this has RAUW support, and then return it.
807   ReplaceableMetadataImpl *getOrCreateReplaceableUses() {
808     if (!hasReplaceableUses())
809       makeReplaceable(llvm::make_unique<ReplaceableMetadataImpl>(getContext()));
810     return getReplaceableUses();
811   }
812
813   /// Assign RAUW support to this.
814   ///
815   /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
816   /// not be null).
817   void
818   makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
819     assert(ReplaceableUses && "Expected non-null replaceable uses");
820     assert(&ReplaceableUses->getContext() == &getContext() &&
821            "Expected same context");
822     delete getReplaceableUses();
823     Ptr = ReplaceableUses.release();
824   }
825
826   /// Drop RAUW support.
827   ///
828   /// Cede ownership of RAUW support, returning it.
829   std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
830     assert(hasReplaceableUses() && "Expected to own replaceable uses");
831     std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
832         getReplaceableUses());
833     Ptr = &ReplaceableUses->getContext();
834     return ReplaceableUses;
835   }
836 };
837
838 struct TempMDNodeDeleter {
839   inline void operator()(MDNode *Node) const;
840 };
841
842 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
843   using Temp##CLASS = std::unique_ptr<CLASS, TempMDNodeDeleter>;
844 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
845 #include "llvm/IR/Metadata.def"
846
847 /// Metadata node.
848 ///
849 /// Metadata nodes can be uniqued, like constants, or distinct.  Temporary
850 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
851 /// until forward references are known.  The basic metadata node is an \a
852 /// MDTuple.
853 ///
854 /// There is limited support for RAUW at construction time.  At construction
855 /// time, if any operand is a temporary node (or an unresolved uniqued node,
856 /// which indicates a transitive temporary operand), the node itself will be
857 /// unresolved.  As soon as all operands become resolved, it will drop RAUW
858 /// support permanently.
859 ///
860 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
861 /// to be called on some member of the cycle once all temporary nodes have been
862 /// replaced.
863 class MDNode : public Metadata {
864   friend class ReplaceableMetadataImpl;
865   friend class LLVMContextImpl;
866
867   unsigned NumOperands;
868   unsigned NumUnresolved;
869
870   ContextAndReplaceableUses Context;
871
872 protected:
873   MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
874          ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
875   ~MDNode() = default;
876
877   void *operator new(size_t Size, unsigned NumOps);
878   void operator delete(void *Mem);
879
880   /// Required by std, but never called.
881   void operator delete(void *, unsigned) {
882     llvm_unreachable("Constructor throws?");
883   }
884
885   /// Required by std, but never called.
886   void operator delete(void *, unsigned, bool) {
887     llvm_unreachable("Constructor throws?");
888   }
889
890   void dropAllReferences();
891
892   MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
893   MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
894
895   using mutable_op_range = iterator_range<MDOperand *>;
896
897   mutable_op_range mutable_operands() {
898     return mutable_op_range(mutable_begin(), mutable_end());
899   }
900
901 public:
902   MDNode(const MDNode &) = delete;
903   void operator=(const MDNode &) = delete;
904   void *operator new(size_t) = delete;
905
906   static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
907   static inline MDTuple *getIfExists(LLVMContext &Context,
908                                      ArrayRef<Metadata *> MDs);
909   static inline MDTuple *getDistinct(LLVMContext &Context,
910                                      ArrayRef<Metadata *> MDs);
911   static inline TempMDTuple getTemporary(LLVMContext &Context,
912                                          ArrayRef<Metadata *> MDs);
913
914   /// Create a (temporary) clone of this.
915   TempMDNode clone() const;
916
917   /// Deallocate a node created by getTemporary.
918   ///
919   /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
920   /// references will be reset.
921   static void deleteTemporary(MDNode *N);
922
923   LLVMContext &getContext() const { return Context.getContext(); }
924
925   /// Replace a specific operand.
926   void replaceOperandWith(unsigned I, Metadata *New);
927
928   /// Check if node is fully resolved.
929   ///
930   /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
931   /// this always returns \c true.
932   ///
933   /// If \a isUniqued(), returns \c true if this has already dropped RAUW
934   /// support (because all operands are resolved).
935   ///
936   /// As forward declarations are resolved, their containers should get
937   /// resolved automatically.  However, if this (or one of its operands) is
938   /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
939   bool isResolved() const { return !isTemporary() && !NumUnresolved; }
940
941   bool isUniqued() const { return Storage == Uniqued; }
942   bool isDistinct() const { return Storage == Distinct; }
943   bool isTemporary() const { return Storage == Temporary; }
944
945   /// RAUW a temporary.
946   ///
947   /// \pre \a isTemporary() must be \c true.
948   void replaceAllUsesWith(Metadata *MD) {
949     assert(isTemporary() && "Expected temporary node");
950     if (Context.hasReplaceableUses())
951       Context.getReplaceableUses()->replaceAllUsesWith(MD);
952   }
953
954   /// Resolve cycles.
955   ///
956   /// Once all forward declarations have been resolved, force cycles to be
957   /// resolved.
958   ///
959   /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
960   void resolveCycles();
961
962   /// Resolve a unique, unresolved node.
963   void resolve();
964
965   /// Replace a temporary node with a permanent one.
966   ///
967   /// Try to create a uniqued version of \c N -- in place, if possible -- and
968   /// return it.  If \c N cannot be uniqued, return a distinct node instead.
969   template <class T>
970   static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
971   replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
972     return cast<T>(N.release()->replaceWithPermanentImpl());
973   }
974
975   /// Replace a temporary node with a uniqued one.
976   ///
977   /// Create a uniqued version of \c N -- in place, if possible -- and return
978   /// it.  Takes ownership of the temporary node.
979   ///
980   /// \pre N does not self-reference.
981   template <class T>
982   static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
983   replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
984     return cast<T>(N.release()->replaceWithUniquedImpl());
985   }
986
987   /// Replace a temporary node with a distinct one.
988   ///
989   /// Create a distinct version of \c N -- in place, if possible -- and return
990   /// it.  Takes ownership of the temporary node.
991   template <class T>
992   static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
993   replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
994     return cast<T>(N.release()->replaceWithDistinctImpl());
995   }
996
997 private:
998   MDNode *replaceWithPermanentImpl();
999   MDNode *replaceWithUniquedImpl();
1000   MDNode *replaceWithDistinctImpl();
1001
1002 protected:
1003   /// Set an operand.
1004   ///
1005   /// Sets the operand directly, without worrying about uniquing.
1006   void setOperand(unsigned I, Metadata *New);
1007
1008   void storeDistinctInContext();
1009   template <class T, class StoreT>
1010   static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
1011   template <class T> static T *storeImpl(T *N, StorageType Storage);
1012
1013 private:
1014   void handleChangedOperand(void *Ref, Metadata *New);
1015
1016   /// Drop RAUW support, if any.
1017   void dropReplaceableUses();
1018
1019   void resolveAfterOperandChange(Metadata *Old, Metadata *New);
1020   void decrementUnresolvedOperandCount();
1021   void countUnresolvedOperands();
1022
1023   /// Mutate this to be "uniqued".
1024   ///
1025   /// Mutate this so that \a isUniqued().
1026   /// \pre \a isTemporary().
1027   /// \pre already added to uniquing set.
1028   void makeUniqued();
1029
1030   /// Mutate this to be "distinct".
1031   ///
1032   /// Mutate this so that \a isDistinct().
1033   /// \pre \a isTemporary().
1034   void makeDistinct();
1035
1036   void deleteAsSubclass();
1037   MDNode *uniquify();
1038   void eraseFromStore();
1039
1040   template <class NodeTy> struct HasCachedHash;
1041   template <class NodeTy>
1042   static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
1043     N->recalculateHash();
1044   }
1045   template <class NodeTy>
1046   static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
1047   template <class NodeTy>
1048   static void dispatchResetHash(NodeTy *N, std::true_type) {
1049     N->setHash(0);
1050   }
1051   template <class NodeTy>
1052   static void dispatchResetHash(NodeTy *, std::false_type) {}
1053
1054 public:
1055   using op_iterator = const MDOperand *;
1056   using op_range = iterator_range<op_iterator>;
1057
1058   op_iterator op_begin() const {
1059     return const_cast<MDNode *>(this)->mutable_begin();
1060   }
1061
1062   op_iterator op_end() const {
1063     return const_cast<MDNode *>(this)->mutable_end();
1064   }
1065
1066   op_range operands() const { return op_range(op_begin(), op_end()); }
1067
1068   const MDOperand &getOperand(unsigned I) const {
1069     assert(I < NumOperands && "Out of range");
1070     return op_begin()[I];
1071   }
1072
1073   /// Return number of MDNode operands.
1074   unsigned getNumOperands() const { return NumOperands; }
1075
1076   /// Methods for support type inquiry through isa, cast, and dyn_cast:
1077   static bool classof(const Metadata *MD) {
1078     switch (MD->getMetadataID()) {
1079     default:
1080       return false;
1081 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1082   case CLASS##Kind:                                                            \
1083     return true;
1084 #include "llvm/IR/Metadata.def"
1085     }
1086   }
1087
1088   /// Check whether MDNode is a vtable access.
1089   bool isTBAAVtableAccess() const;
1090
1091   /// Methods for metadata merging.
1092   static MDNode *concatenate(MDNode *A, MDNode *B);
1093   static MDNode *intersect(MDNode *A, MDNode *B);
1094   static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
1095   static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
1096   static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
1097   static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
1098   static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B);
1099 };
1100
1101 /// Tuple of metadata.
1102 ///
1103 /// This is the simple \a MDNode arbitrary tuple.  Nodes are uniqued by
1104 /// default based on their operands.
1105 class MDTuple : public MDNode {
1106   friend class LLVMContextImpl;
1107   friend class MDNode;
1108
1109   MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1110           ArrayRef<Metadata *> Vals)
1111       : MDNode(C, MDTupleKind, Storage, Vals) {
1112     setHash(Hash);
1113   }
1114
1115   ~MDTuple() { dropAllReferences(); }
1116
1117   void setHash(unsigned Hash) { SubclassData32 = Hash; }
1118   void recalculateHash();
1119
1120   static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
1121                           StorageType Storage, bool ShouldCreate = true);
1122
1123   TempMDTuple cloneImpl() const {
1124     return getTemporary(getContext(),
1125                         SmallVector<Metadata *, 4>(op_begin(), op_end()));
1126   }
1127
1128 public:
1129   /// Get the hash, if any.
1130   unsigned getHash() const { return SubclassData32; }
1131
1132   static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1133     return getImpl(Context, MDs, Uniqued);
1134   }
1135
1136   static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1137     return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1138   }
1139
1140   /// Return a distinct node.
1141   ///
1142   /// Return a distinct node -- i.e., a node that is not uniqued.
1143   static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1144     return getImpl(Context, MDs, Distinct);
1145   }
1146
1147   /// Return a temporary node.
1148   ///
1149   /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1150   /// not uniqued, may be RAUW'd, and must be manually deleted with
1151   /// deleteTemporary.
1152   static TempMDTuple getTemporary(LLVMContext &Context,
1153                                   ArrayRef<Metadata *> MDs) {
1154     return TempMDTuple(getImpl(Context, MDs, Temporary));
1155   }
1156
1157   /// Return a (temporary) clone of this.
1158   TempMDTuple clone() const { return cloneImpl(); }
1159
1160   static bool classof(const Metadata *MD) {
1161     return MD->getMetadataID() == MDTupleKind;
1162   }
1163 };
1164
1165 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1166   return MDTuple::get(Context, MDs);
1167 }
1168
1169 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1170   return MDTuple::getIfExists(Context, MDs);
1171 }
1172
1173 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1174   return MDTuple::getDistinct(Context, MDs);
1175 }
1176
1177 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1178                                  ArrayRef<Metadata *> MDs) {
1179   return MDTuple::getTemporary(Context, MDs);
1180 }
1181
1182 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1183   MDNode::deleteTemporary(Node);
1184 }
1185
1186 /// Typed iterator through MDNode operands.
1187 ///
1188 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1189 /// particular Metadata subclass.
1190 template <class T>
1191 class TypedMDOperandIterator
1192     : public std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void,
1193                            T *> {
1194   MDNode::op_iterator I = nullptr;
1195
1196 public:
1197   TypedMDOperandIterator() = default;
1198   explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1199
1200   T *operator*() const { return cast_or_null<T>(*I); }
1201
1202   TypedMDOperandIterator &operator++() {
1203     ++I;
1204     return *this;
1205   }
1206
1207   TypedMDOperandIterator operator++(int) {
1208     TypedMDOperandIterator Temp(*this);
1209     ++I;
1210     return Temp;
1211   }
1212
1213   bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1214   bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1215 };
1216
1217 /// Typed, array-like tuple of metadata.
1218 ///
1219 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1220 /// particular type of metadata.
1221 template <class T> class MDTupleTypedArrayWrapper {
1222   const MDTuple *N = nullptr;
1223
1224 public:
1225   MDTupleTypedArrayWrapper() = default;
1226   MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1227
1228   template <class U>
1229   MDTupleTypedArrayWrapper(
1230       const MDTupleTypedArrayWrapper<U> &Other,
1231       typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
1232           nullptr)
1233       : N(Other.get()) {}
1234
1235   template <class U>
1236   explicit MDTupleTypedArrayWrapper(
1237       const MDTupleTypedArrayWrapper<U> &Other,
1238       typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
1239           nullptr)
1240       : N(Other.get()) {}
1241
1242   explicit operator bool() const { return get(); }
1243   explicit operator MDTuple *() const { return get(); }
1244
1245   MDTuple *get() const { return const_cast<MDTuple *>(N); }
1246   MDTuple *operator->() const { return get(); }
1247   MDTuple &operator*() const { return *get(); }
1248
1249   // FIXME: Fix callers and remove condition on N.
1250   unsigned size() const { return N ? N->getNumOperands() : 0u; }
1251   bool empty() const { return N ? N->getNumOperands() == 0 : true; }
1252   T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1253
1254   // FIXME: Fix callers and remove condition on N.
1255   using iterator = TypedMDOperandIterator<T>;
1256
1257   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1258   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1259 };
1260
1261 #define HANDLE_METADATA(CLASS)                                                 \
1262   using CLASS##Array = MDTupleTypedArrayWrapper<CLASS>;
1263 #include "llvm/IR/Metadata.def"
1264
1265 /// Placeholder metadata for operands of distinct MDNodes.
1266 ///
1267 /// This is a lightweight placeholder for an operand of a distinct node.  It's
1268 /// purpose is to help track forward references when creating a distinct node.
1269 /// This allows distinct nodes involved in a cycle to be constructed before
1270 /// their operands without requiring a heavyweight temporary node with
1271 /// full-blown RAUW support.
1272 ///
1273 /// Each placeholder supports only a single MDNode user.  Clients should pass
1274 /// an ID, retrieved via \a getID(), to indicate the "real" operand that this
1275 /// should be replaced with.
1276 ///
1277 /// While it would be possible to implement move operators, they would be
1278 /// fairly expensive.  Leave them unimplemented to discourage their use
1279 /// (clients can use std::deque, std::list, BumpPtrAllocator, etc.).
1280 class DistinctMDOperandPlaceholder : public Metadata {
1281   friend class MetadataTracking;
1282
1283   Metadata **Use = nullptr;
1284
1285 public:
1286   explicit DistinctMDOperandPlaceholder(unsigned ID)
1287       : Metadata(DistinctMDOperandPlaceholderKind, Distinct) {
1288     SubclassData32 = ID;
1289   }
1290
1291   DistinctMDOperandPlaceholder() = delete;
1292   DistinctMDOperandPlaceholder(DistinctMDOperandPlaceholder &&) = delete;
1293   DistinctMDOperandPlaceholder(const DistinctMDOperandPlaceholder &) = delete;
1294
1295   ~DistinctMDOperandPlaceholder() {
1296     if (Use)
1297       *Use = nullptr;
1298   }
1299
1300   unsigned getID() const { return SubclassData32; }
1301
1302   /// Replace the use of this with MD.
1303   void replaceUseWith(Metadata *MD) {
1304     if (!Use)
1305       return;
1306     *Use = MD;
1307
1308     if (*Use)
1309       MetadataTracking::track(*Use);
1310
1311     Metadata *T = cast<Metadata>(this);
1312     MetadataTracking::untrack(T);
1313     assert(!Use && "Use is still being tracked despite being untracked!");
1314   }
1315 };
1316
1317 //===----------------------------------------------------------------------===//
1318 /// A tuple of MDNodes.
1319 ///
1320 /// Despite its name, a NamedMDNode isn't itself an MDNode.
1321 ///
1322 /// NamedMDNodes are named module-level entities that contain lists of MDNodes.
1323 ///
1324 /// It is illegal for a NamedMDNode to appear as an operand of an MDNode.
1325 class NamedMDNode : public ilist_node<NamedMDNode> {
1326   friend class LLVMContextImpl;
1327   friend class Module;
1328
1329   std::string Name;
1330   Module *Parent = nullptr;
1331   void *Operands; // SmallVector<TrackingMDRef, 4>
1332
1333   void setParent(Module *M) { Parent = M; }
1334
1335   explicit NamedMDNode(const Twine &N);
1336
1337   template<class T1, class T2>
1338   class op_iterator_impl :
1339       public std::iterator<std::bidirectional_iterator_tag, T2> {
1340     friend class NamedMDNode;
1341
1342     const NamedMDNode *Node = nullptr;
1343     unsigned Idx = 0;
1344
1345     op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) {}
1346
1347   public:
1348     op_iterator_impl() = default;
1349
1350     bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1351     bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1352
1353     op_iterator_impl &operator++() {
1354       ++Idx;
1355       return *this;
1356     }
1357
1358     op_iterator_impl operator++(int) {
1359       op_iterator_impl tmp(*this);
1360       operator++();
1361       return tmp;
1362     }
1363
1364     op_iterator_impl &operator--() {
1365       --Idx;
1366       return *this;
1367     }
1368
1369     op_iterator_impl operator--(int) {
1370       op_iterator_impl tmp(*this);
1371       operator--();
1372       return tmp;
1373     }
1374
1375     T1 operator*() const { return Node->getOperand(Idx); }
1376   };
1377
1378 public:
1379   NamedMDNode(const NamedMDNode &) = delete;
1380   ~NamedMDNode();
1381
1382   /// Drop all references and remove the node from parent module.
1383   void eraseFromParent();
1384
1385   /// Remove all uses and clear node vector.
1386   void dropAllReferences() { clearOperands(); }
1387   /// Drop all references to this node's operands.
1388   void clearOperands();
1389
1390   /// Get the module that holds this named metadata collection.
1391   inline Module *getParent() { return Parent; }
1392   inline const Module *getParent() const { return Parent; }
1393
1394   MDNode *getOperand(unsigned i) const;
1395   unsigned getNumOperands() const;
1396   void addOperand(MDNode *M);
1397   void setOperand(unsigned I, MDNode *New);
1398   StringRef getName() const;
1399   void print(raw_ostream &ROS, bool IsForDebug = false) const;
1400   void print(raw_ostream &ROS, ModuleSlotTracker &MST,
1401              bool IsForDebug = false) const;
1402   void dump() const;
1403
1404   // ---------------------------------------------------------------------------
1405   // Operand Iterator interface...
1406   //
1407   using op_iterator = op_iterator_impl<MDNode *, MDNode>;
1408
1409   op_iterator op_begin() { return op_iterator(this, 0); }
1410   op_iterator op_end()   { return op_iterator(this, getNumOperands()); }
1411
1412   using const_op_iterator = op_iterator_impl<const MDNode *, MDNode>;
1413
1414   const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1415   const_op_iterator op_end()   const { return const_op_iterator(this, getNumOperands()); }
1416
1417   inline iterator_range<op_iterator>  operands() {
1418     return make_range(op_begin(), op_end());
1419   }
1420   inline iterator_range<const_op_iterator> operands() const {
1421     return make_range(op_begin(), op_end());
1422   }
1423 };
1424
1425 // Create wrappers for C Binding types (see CBindingWrapping.h).
1426 DEFINE_ISA_CONVERSION_FUNCTIONS(NamedMDNode, LLVMNamedMDNodeRef)
1427
1428 } // end namespace llvm
1429
1430 #endif // LLVM_IR_METADATA_H