DebugInfo: Remove DITypedArray<>, replace with typedefs
[oota-llvm.git] / include / llvm / IR / DebugInfoMetadata.h
1 //===- llvm/IR/DebugInfoMetadata.h - Debug info metadata --------*- 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 // Declarations for metadata specific to debug info.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_IR_DEBUGINFOMETADATA_H
15 #define LLVM_IR_DEBUGINFOMETADATA_H
16
17 #include "llvm/IR/Metadata.h"
18 #include "llvm/Support/Dwarf.h"
19
20 // Helper macros for defining get() overrides.
21 #define DEFINE_MDNODE_GET_UNPACK_IMPL(...) __VA_ARGS__
22 #define DEFINE_MDNODE_GET_UNPACK(ARGS) DEFINE_MDNODE_GET_UNPACK_IMPL ARGS
23 #define DEFINE_MDNODE_GET(CLASS, FORMAL, ARGS)                                 \
24   static CLASS *get(LLVMContext &Context, DEFINE_MDNODE_GET_UNPACK(FORMAL)) {  \
25     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued);          \
26   }                                                                            \
27   static CLASS *getIfExists(LLVMContext &Context,                              \
28                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
29     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued,           \
30                    /* ShouldCreate */ false);                                  \
31   }                                                                            \
32   static CLASS *getDistinct(LLVMContext &Context,                              \
33                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
34     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Distinct);         \
35   }                                                                            \
36   static Temp##CLASS getTemporary(LLVMContext &Context,                        \
37                                   DEFINE_MDNODE_GET_UNPACK(FORMAL)) {          \
38     return Temp##CLASS(                                                        \
39         getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Temporary));          \
40   }
41
42 namespace llvm {
43
44 /// \brief Pointer union between a subclass of DebugNode and MDString.
45 ///
46 /// \a MDCompositeType can be referenced via an \a MDString unique identifier.
47 /// This class allows some type safety in the face of that, requiring either a
48 /// node of a particular type or an \a MDString.
49 template <class T> class TypedDebugNodeRef {
50   const Metadata *MD = nullptr;
51
52 public:
53   TypedDebugNodeRef(std::nullptr_t) {}
54
55   /// \brief Construct from a raw pointer.
56   explicit TypedDebugNodeRef(const Metadata *MD) : MD(MD) {
57     assert((!MD || isa<MDString>(MD) || isa<T>(MD)) && "Expected valid ref");
58   }
59
60   template <class U>
61   TypedDebugNodeRef(
62       const TypedDebugNodeRef<U> &X,
63       typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
64           nullptr)
65       : MD(X) {}
66
67   operator Metadata *() const { return const_cast<Metadata *>(MD); }
68
69   bool operator==(const TypedDebugNodeRef<T> &X) const { return MD == X.MD; };
70   bool operator!=(const TypedDebugNodeRef<T> &X) const { return MD != X.MD; };
71
72   /// \brief Create a reference.
73   ///
74   /// Get a reference to \c N, using an \a MDString reference if available.
75   static TypedDebugNodeRef get(const T *N);
76
77   template <class MapTy> T *resolve(const MapTy &Map) const {
78     if (!MD)
79       return nullptr;
80
81     if (auto *Typed = dyn_cast<T>(MD))
82       return const_cast<T *>(Typed);
83
84     auto *S = cast<MDString>(MD);
85     auto I = Map.find(S);
86     assert(I != Map.end() && "Missing identifier in type map");
87     return cast<T>(I->second);
88   }
89 };
90
91 typedef TypedDebugNodeRef<DebugNode> DebugNodeRef;
92 typedef TypedDebugNodeRef<MDScope> MDScopeRef;
93 typedef TypedDebugNodeRef<MDType> MDTypeRef;
94
95 class MDTypeRefArray {
96   const MDTuple *N = nullptr;
97
98 public:
99   MDTypeRefArray(const MDTuple *N) : N(N) {}
100   operator MDTuple *() const { return const_cast<MDTuple *>(N); }
101   MDTuple *operator->() const { return const_cast<MDTuple *>(N); }
102   MDTuple &operator*() const { return *const_cast<MDTuple *>(N); }
103
104   // FIXME: Fix callers and remove condition on N.
105   unsigned size() const { return N ? N->getNumOperands() : 0u; }
106   MDTypeRef operator[](unsigned I) const { return MDTypeRef(N->getOperand(I)); }
107
108   class iterator : std::iterator<std::input_iterator_tag, MDTypeRef,
109                                  std::ptrdiff_t, void, MDTypeRef> {
110     MDNode::op_iterator I = nullptr;
111
112   public:
113     iterator() = default;
114     explicit iterator(MDNode::op_iterator I) : I(I) {}
115     MDTypeRef operator*() const { return MDTypeRef(*I); }
116     iterator &operator++() {
117       ++I;
118       return *this;
119     }
120     iterator operator++(int) {
121       iterator Temp(*this);
122       ++I;
123       return Temp;
124     }
125     bool operator==(const iterator &X) const { return I == X.I; }
126     bool operator!=(const iterator &X) const { return I != X.I; }
127   };
128
129   // FIXME: Fix callers and remove condition on N.
130   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
131   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
132 };
133
134 /// \brief Tagged DWARF-like metadata node.
135 ///
136 /// A metadata node with a DWARF tag (i.e., a constant named \c DW_TAG_*,
137 /// defined in llvm/Support/Dwarf.h).  Called \a DebugNode because it's
138 /// potentially used for non-DWARF output.
139 class DebugNode : public MDNode {
140   friend class LLVMContextImpl;
141   friend class MDNode;
142
143 protected:
144   DebugNode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
145             ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
146       : MDNode(C, ID, Storage, Ops1, Ops2) {
147     assert(Tag < 1u << 16);
148     SubclassData16 = Tag;
149   }
150   ~DebugNode() {}
151
152   template <class Ty> Ty *getOperandAs(unsigned I) const {
153     return cast_or_null<Ty>(getOperand(I));
154   }
155
156   StringRef getStringOperand(unsigned I) const {
157     if (auto *S = getOperandAs<MDString>(I))
158       return S->getString();
159     return StringRef();
160   }
161
162   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
163     if (S.empty())
164       return nullptr;
165     return MDString::get(Context, S);
166   }
167
168 public:
169   unsigned getTag() const { return SubclassData16; }
170
171   /// \brief Debug info flags.
172   ///
173   /// The three accessibility flags are mutually exclusive and rolled together
174   /// in the first two bits.
175   enum DIFlags {
176 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = ID,
177 #include "llvm/IR/DebugInfoFlags.def"
178     FlagAccessibility = FlagPrivate | FlagProtected | FlagPublic
179   };
180
181   static unsigned getFlag(StringRef Flag);
182   static const char *getFlagString(unsigned Flag);
183
184   /// \brief Split up a flags bitfield.
185   ///
186   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
187   /// any remaining (unrecognized) bits.
188   static unsigned splitFlags(unsigned Flags,
189                              SmallVectorImpl<unsigned> &SplitFlags);
190
191   DebugNodeRef getRef() const { return DebugNodeRef::get(this); }
192
193   static bool classof(const Metadata *MD) {
194     switch (MD->getMetadataID()) {
195     default:
196       return false;
197     case GenericDebugNodeKind:
198     case MDSubrangeKind:
199     case MDEnumeratorKind:
200     case MDBasicTypeKind:
201     case MDDerivedTypeKind:
202     case MDCompositeTypeKind:
203     case MDSubroutineTypeKind:
204     case MDFileKind:
205     case MDCompileUnitKind:
206     case MDSubprogramKind:
207     case MDLexicalBlockKind:
208     case MDLexicalBlockFileKind:
209     case MDNamespaceKind:
210     case MDTemplateTypeParameterKind:
211     case MDTemplateValueParameterKind:
212     case MDGlobalVariableKind:
213     case MDLocalVariableKind:
214     case MDObjCPropertyKind:
215     case MDImportedEntityKind:
216       return true;
217     }
218   }
219 };
220
221 template <class T>
222 struct simplify_type<const TypedDebugNodeRef<T>> {
223   typedef Metadata *SimpleType;
224   static SimpleType getSimplifiedValue(const TypedDebugNodeRef<T> &MD) {
225     return MD;
226   }
227 };
228
229 template <class T>
230 struct simplify_type<TypedDebugNodeRef<T>>
231     : simplify_type<const TypedDebugNodeRef<T>> {};
232
233 /// \brief Generic tagged DWARF-like metadata node.
234 ///
235 /// An un-specialized DWARF-like metadata node.  The first operand is a
236 /// (possibly empty) null-separated \a MDString header that contains arbitrary
237 /// fields.  The remaining operands are \a dwarf_operands(), and are pointers
238 /// to other metadata.
239 class GenericDebugNode : public DebugNode {
240   friend class LLVMContextImpl;
241   friend class MDNode;
242
243   GenericDebugNode(LLVMContext &C, StorageType Storage, unsigned Hash,
244                    unsigned Tag, ArrayRef<Metadata *> Ops1,
245                    ArrayRef<Metadata *> Ops2)
246       : DebugNode(C, GenericDebugNodeKind, Storage, Tag, Ops1, Ops2) {
247     setHash(Hash);
248   }
249   ~GenericDebugNode() { dropAllReferences(); }
250
251   void setHash(unsigned Hash) { SubclassData32 = Hash; }
252   void recalculateHash();
253
254   static GenericDebugNode *getImpl(LLVMContext &Context, unsigned Tag,
255                                    StringRef Header,
256                                    ArrayRef<Metadata *> DwarfOps,
257                                    StorageType Storage,
258                                    bool ShouldCreate = true) {
259     return getImpl(Context, Tag, getCanonicalMDString(Context, Header),
260                    DwarfOps, Storage, ShouldCreate);
261   }
262
263   static GenericDebugNode *getImpl(LLVMContext &Context, unsigned Tag,
264                                    MDString *Header,
265                                    ArrayRef<Metadata *> DwarfOps,
266                                    StorageType Storage,
267                                    bool ShouldCreate = true);
268
269   TempGenericDebugNode cloneImpl() const {
270     return getTemporary(
271         getContext(), getTag(), getHeader(),
272         SmallVector<Metadata *, 4>(dwarf_op_begin(), dwarf_op_end()));
273   }
274
275 public:
276   unsigned getHash() const { return SubclassData32; }
277
278   DEFINE_MDNODE_GET(GenericDebugNode, (unsigned Tag, StringRef Header,
279                                        ArrayRef<Metadata *> DwarfOps),
280                     (Tag, Header, DwarfOps))
281   DEFINE_MDNODE_GET(GenericDebugNode, (unsigned Tag, MDString *Header,
282                                        ArrayRef<Metadata *> DwarfOps),
283                     (Tag, Header, DwarfOps))
284
285   /// \brief Return a (temporary) clone of this.
286   TempGenericDebugNode clone() const { return cloneImpl(); }
287
288   unsigned getTag() const { return SubclassData16; }
289   StringRef getHeader() const { return getStringOperand(0); }
290
291   op_iterator dwarf_op_begin() const { return op_begin() + 1; }
292   op_iterator dwarf_op_end() const { return op_end(); }
293   op_range dwarf_operands() const {
294     return op_range(dwarf_op_begin(), dwarf_op_end());
295   }
296
297   unsigned getNumDwarfOperands() const { return getNumOperands() - 1; }
298   const MDOperand &getDwarfOperand(unsigned I) const {
299     return getOperand(I + 1);
300   }
301   void replaceDwarfOperandWith(unsigned I, Metadata *New) {
302     replaceOperandWith(I + 1, New);
303   }
304
305   static bool classof(const Metadata *MD) {
306     return MD->getMetadataID() == GenericDebugNodeKind;
307   }
308 };
309
310 /// \brief Array subrange.
311 ///
312 /// TODO: Merge into node for DW_TAG_array_type, which should have a custom
313 /// type.
314 class MDSubrange : public DebugNode {
315   friend class LLVMContextImpl;
316   friend class MDNode;
317
318   int64_t Count;
319   int64_t LowerBound;
320
321   MDSubrange(LLVMContext &C, StorageType Storage, int64_t Count,
322              int64_t LowerBound)
323       : DebugNode(C, MDSubrangeKind, Storage, dwarf::DW_TAG_subrange_type,
324                   None),
325         Count(Count), LowerBound(LowerBound) {}
326   ~MDSubrange() {}
327
328   static MDSubrange *getImpl(LLVMContext &Context, int64_t Count,
329                              int64_t LowerBound, StorageType Storage,
330                              bool ShouldCreate = true);
331
332   TempMDSubrange cloneImpl() const {
333     return getTemporary(getContext(), getCount(), getLowerBound());
334   }
335
336 public:
337   DEFINE_MDNODE_GET(MDSubrange, (int64_t Count, int64_t LowerBound = 0),
338                     (Count, LowerBound))
339
340   TempMDSubrange clone() const { return cloneImpl(); }
341
342   int64_t getLowerBound() const { return LowerBound; }
343   int64_t getCount() const { return Count; }
344
345   static bool classof(const Metadata *MD) {
346     return MD->getMetadataID() == MDSubrangeKind;
347   }
348 };
349
350 /// \brief Enumeration value.
351 ///
352 /// TODO: Add a pointer to the context (DW_TAG_enumeration_type) once that no
353 /// longer creates a type cycle.
354 class MDEnumerator : public DebugNode {
355   friend class LLVMContextImpl;
356   friend class MDNode;
357
358   int64_t Value;
359
360   MDEnumerator(LLVMContext &C, StorageType Storage, int64_t Value,
361                ArrayRef<Metadata *> Ops)
362       : DebugNode(C, MDEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops),
363         Value(Value) {}
364   ~MDEnumerator() {}
365
366   static MDEnumerator *getImpl(LLVMContext &Context, int64_t Value,
367                                StringRef Name, StorageType Storage,
368                                bool ShouldCreate = true) {
369     return getImpl(Context, Value, getCanonicalMDString(Context, Name), Storage,
370                    ShouldCreate);
371   }
372   static MDEnumerator *getImpl(LLVMContext &Context, int64_t Value,
373                                MDString *Name, StorageType Storage,
374                                bool ShouldCreate = true);
375
376   TempMDEnumerator cloneImpl() const {
377     return getTemporary(getContext(), getValue(), getName());
378   }
379
380 public:
381   DEFINE_MDNODE_GET(MDEnumerator, (int64_t Value, StringRef Name),
382                     (Value, Name))
383   DEFINE_MDNODE_GET(MDEnumerator, (int64_t Value, MDString *Name),
384                     (Value, Name))
385
386   TempMDEnumerator clone() const { return cloneImpl(); }
387
388   int64_t getValue() const { return Value; }
389   StringRef getName() const { return getStringOperand(0); }
390
391   MDString *getRawName() const { return getOperandAs<MDString>(0); }
392
393   static bool classof(const Metadata *MD) {
394     return MD->getMetadataID() == MDEnumeratorKind;
395   }
396 };
397
398 /// \brief Base class for scope-like contexts.
399 ///
400 /// Base class for lexical scopes and types (which are also declaration
401 /// contexts).
402 ///
403 /// TODO: Separate the concepts of declaration contexts and lexical scopes.
404 class MDScope : public DebugNode {
405 protected:
406   MDScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
407           ArrayRef<Metadata *> Ops)
408       : DebugNode(C, ID, Storage, Tag, Ops) {}
409   ~MDScope() {}
410
411 public:
412   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
413
414   /// \brief Return the raw underlying file.
415   ///
416   /// An \a MDFile is an \a MDScope, but it doesn't point at a separate file
417   /// (it\em is the file).  If \c this is an \a MDFile, we need to return \c
418   /// this.  Otherwise, return the first operand, which is where all other
419   /// subclasses store their file pointer.
420   Metadata *getRawFile() const {
421     return isa<MDFile>(this) ? const_cast<MDScope *>(this)
422                              : static_cast<Metadata *>(getOperand(0));
423   }
424
425   MDScopeRef getRef() const { return MDScopeRef::get(this); }
426
427   static bool classof(const Metadata *MD) {
428     switch (MD->getMetadataID()) {
429     default:
430       return false;
431     case MDBasicTypeKind:
432     case MDDerivedTypeKind:
433     case MDCompositeTypeKind:
434     case MDSubroutineTypeKind:
435     case MDFileKind:
436     case MDCompileUnitKind:
437     case MDSubprogramKind:
438     case MDLexicalBlockKind:
439     case MDLexicalBlockFileKind:
440     case MDNamespaceKind:
441       return true;
442     }
443   }
444 };
445
446 /// \brief File.
447 ///
448 /// TODO: Merge with directory/file node (including users).
449 /// TODO: Canonicalize paths on creation.
450 class MDFile : public MDScope {
451   friend class LLVMContextImpl;
452   friend class MDNode;
453
454   MDFile(LLVMContext &C, StorageType Storage, ArrayRef<Metadata *> Ops)
455       : MDScope(C, MDFileKind, Storage, dwarf::DW_TAG_file_type, Ops) {}
456   ~MDFile() {}
457
458   static MDFile *getImpl(LLVMContext &Context, StringRef Filename,
459                          StringRef Directory, StorageType Storage,
460                          bool ShouldCreate = true) {
461     return getImpl(Context, getCanonicalMDString(Context, Filename),
462                    getCanonicalMDString(Context, Directory), Storage,
463                    ShouldCreate);
464   }
465   static MDFile *getImpl(LLVMContext &Context, MDString *Filename,
466                          MDString *Directory, StorageType Storage,
467                          bool ShouldCreate = true);
468
469   TempMDFile cloneImpl() const {
470     return getTemporary(getContext(), getFilename(), getDirectory());
471   }
472
473 public:
474   DEFINE_MDNODE_GET(MDFile, (StringRef Filename, StringRef Directory),
475                     (Filename, Directory))
476   DEFINE_MDNODE_GET(MDFile, (MDString * Filename, MDString *Directory),
477                     (Filename, Directory))
478
479   TempMDFile clone() const { return cloneImpl(); }
480
481   StringRef getFilename() const { return getStringOperand(0); }
482   StringRef getDirectory() const { return getStringOperand(1); }
483
484   MDString *getRawFilename() const { return getOperandAs<MDString>(0); }
485   MDString *getRawDirectory() const { return getOperandAs<MDString>(1); }
486
487   static bool classof(const Metadata *MD) {
488     return MD->getMetadataID() == MDFileKind;
489   }
490 };
491
492 /// \brief Base class for types.
493 ///
494 /// TODO: Remove the hardcoded name and context, since many types don't use
495 /// them.
496 /// TODO: Split up flags.
497 class MDType : public MDScope {
498   unsigned Line;
499   unsigned Flags;
500   uint64_t SizeInBits;
501   uint64_t AlignInBits;
502   uint64_t OffsetInBits;
503
504 protected:
505   MDType(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
506          unsigned Line, uint64_t SizeInBits, uint64_t AlignInBits,
507          uint64_t OffsetInBits, unsigned Flags, ArrayRef<Metadata *> Ops)
508       : MDScope(C, ID, Storage, Tag, Ops), Line(Line), Flags(Flags),
509         SizeInBits(SizeInBits), AlignInBits(AlignInBits),
510         OffsetInBits(OffsetInBits) {}
511   ~MDType() {}
512
513 public:
514   TempMDType clone() const {
515     return TempMDType(cast<MDType>(MDNode::clone().release()));
516   }
517
518   unsigned getLine() const { return Line; }
519   uint64_t getSizeInBits() const { return SizeInBits; }
520   uint64_t getAlignInBits() const { return AlignInBits; }
521   uint64_t getOffsetInBits() const { return OffsetInBits; }
522   unsigned getFlags() const { return Flags; }
523
524   MDScopeRef getScope() const { return MDScopeRef(getRawScope()); }
525   StringRef getName() const { return getStringOperand(2); }
526
527
528   Metadata *getRawScope() const { return getOperand(1); }
529   MDString *getRawName() const { return getOperandAs<MDString>(2); }
530
531   void setFlags(unsigned NewFlags) {
532     assert(!isUniqued() && "Cannot set flags on uniqued nodes");
533     Flags = NewFlags;
534   }
535
536   bool isPrivate() const {
537     return (getFlags() & FlagAccessibility) == FlagPrivate;
538   }
539   bool isProtected() const {
540     return (getFlags() & FlagAccessibility) == FlagProtected;
541   }
542   bool isPublic() const {
543     return (getFlags() & FlagAccessibility) == FlagPublic;
544   }
545   bool isForwardDecl() const { return getFlags() & FlagFwdDecl; }
546   bool isAppleBlockExtension() const { return getFlags() & FlagAppleBlock; }
547   bool isBlockByrefStruct() const { return getFlags() & FlagBlockByrefStruct; }
548   bool isVirtual() const { return getFlags() & FlagVirtual; }
549   bool isArtificial() const { return getFlags() & FlagArtificial; }
550   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
551   bool isObjcClassComplete() const {
552     return getFlags() & FlagObjcClassComplete;
553   }
554   bool isVector() const { return getFlags() & FlagVector; }
555   bool isStaticMember() const { return getFlags() & FlagStaticMember; }
556   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
557   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
558
559   MDTypeRef getRef() const { return MDTypeRef::get(this); }
560
561   static bool classof(const Metadata *MD) {
562     switch (MD->getMetadataID()) {
563     default:
564       return false;
565     case MDBasicTypeKind:
566     case MDDerivedTypeKind:
567     case MDCompositeTypeKind:
568     case MDSubroutineTypeKind:
569       return true;
570     }
571   }
572 };
573
574 /// \brief Basic type.
575 ///
576 /// TODO: Split out DW_TAG_unspecified_type.
577 /// TODO: Drop unused accessors.
578 class MDBasicType : public MDType {
579   friend class LLVMContextImpl;
580   friend class MDNode;
581
582   unsigned Encoding;
583
584   MDBasicType(LLVMContext &C, StorageType Storage, unsigned Tag,
585               uint64_t SizeInBits, uint64_t AlignInBits, unsigned Encoding,
586               ArrayRef<Metadata *> Ops)
587       : MDType(C, MDBasicTypeKind, Storage, Tag, 0, SizeInBits, AlignInBits, 0,
588                0, Ops),
589         Encoding(Encoding) {}
590   ~MDBasicType() {}
591
592   static MDBasicType *getImpl(LLVMContext &Context, unsigned Tag,
593                               StringRef Name, uint64_t SizeInBits,
594                               uint64_t AlignInBits, unsigned Encoding,
595                               StorageType Storage, bool ShouldCreate = true) {
596     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
597                    SizeInBits, AlignInBits, Encoding, Storage, ShouldCreate);
598   }
599   static MDBasicType *getImpl(LLVMContext &Context, unsigned Tag,
600                               MDString *Name, uint64_t SizeInBits,
601                               uint64_t AlignInBits, unsigned Encoding,
602                               StorageType Storage, bool ShouldCreate = true);
603
604   TempMDBasicType cloneImpl() const {
605     return getTemporary(getContext(), getTag(), getName(), getSizeInBits(),
606                         getAlignInBits(), getEncoding());
607   }
608
609 public:
610   DEFINE_MDNODE_GET(MDBasicType, (unsigned Tag, StringRef Name),
611                     (Tag, Name, 0, 0, 0))
612   DEFINE_MDNODE_GET(MDBasicType,
613                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
614                      uint64_t AlignInBits, unsigned Encoding),
615                     (Tag, Name, SizeInBits, AlignInBits, Encoding))
616   DEFINE_MDNODE_GET(MDBasicType,
617                     (unsigned Tag, MDString *Name, uint64_t SizeInBits,
618                      uint64_t AlignInBits, unsigned Encoding),
619                     (Tag, Name, SizeInBits, AlignInBits, Encoding))
620
621   TempMDBasicType clone() const { return cloneImpl(); }
622
623   unsigned getEncoding() const { return Encoding; }
624
625   static bool classof(const Metadata *MD) {
626     return MD->getMetadataID() == MDBasicTypeKind;
627   }
628 };
629
630 /// \brief Base class for MDDerivedType and MDCompositeType.
631 ///
632 /// TODO: Delete; they're not really related.
633 class MDDerivedTypeBase : public MDType {
634 protected:
635   MDDerivedTypeBase(LLVMContext &C, unsigned ID, StorageType Storage,
636                     unsigned Tag, unsigned Line, uint64_t SizeInBits,
637                     uint64_t AlignInBits, uint64_t OffsetInBits, unsigned Flags,
638                     ArrayRef<Metadata *> Ops)
639       : MDType(C, ID, Storage, Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
640                Flags, Ops) {}
641   ~MDDerivedTypeBase() {}
642
643 public:
644   MDTypeRef getBaseType() const { return MDTypeRef(getRawBaseType()); }
645   Metadata *getRawBaseType() const { return getOperand(3); }
646
647   static bool classof(const Metadata *MD) {
648     return MD->getMetadataID() == MDDerivedTypeKind ||
649            MD->getMetadataID() == MDCompositeTypeKind ||
650            MD->getMetadataID() == MDSubroutineTypeKind;
651   }
652 };
653
654 /// \brief Derived types.
655 ///
656 /// This includes qualified types, pointers, references, friends, typedefs, and
657 /// class members.
658 ///
659 /// TODO: Split out members (inheritance, fields, methods, etc.).
660 class MDDerivedType : public MDDerivedTypeBase {
661   friend class LLVMContextImpl;
662   friend class MDNode;
663
664   MDDerivedType(LLVMContext &C, StorageType Storage, unsigned Tag,
665                 unsigned Line, uint64_t SizeInBits, uint64_t AlignInBits,
666                 uint64_t OffsetInBits, unsigned Flags, ArrayRef<Metadata *> Ops)
667       : MDDerivedTypeBase(C, MDDerivedTypeKind, Storage, Tag, Line, SizeInBits,
668                           AlignInBits, OffsetInBits, Flags, Ops) {}
669   ~MDDerivedType() {}
670
671   static MDDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
672                                 StringRef Name, MDFile *File, unsigned Line,
673                                 MDScopeRef Scope, MDTypeRef BaseType,
674                                 uint64_t SizeInBits, uint64_t AlignInBits,
675                                 uint64_t OffsetInBits, unsigned Flags,
676                                 Metadata *ExtraData, StorageType Storage,
677                                 bool ShouldCreate = true) {
678     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
679                    Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits,
680                    Flags, ExtraData, Storage, ShouldCreate);
681   }
682   static MDDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
683                                 MDString *Name, Metadata *File, unsigned Line,
684                                 Metadata *Scope, Metadata *BaseType,
685                                 uint64_t SizeInBits, uint64_t AlignInBits,
686                                 uint64_t OffsetInBits, unsigned Flags,
687                                 Metadata *ExtraData, StorageType Storage,
688                                 bool ShouldCreate = true);
689
690   TempMDDerivedType cloneImpl() const {
691     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
692                         getScope(), getBaseType(), getSizeInBits(),
693                         getAlignInBits(), getOffsetInBits(), getFlags(),
694                         getExtraData());
695   }
696
697 public:
698   DEFINE_MDNODE_GET(MDDerivedType,
699                     (unsigned Tag, MDString *Name, Metadata *File,
700                      unsigned Line, Metadata *Scope, Metadata *BaseType,
701                      uint64_t SizeInBits, uint64_t AlignInBits,
702                      uint64_t OffsetInBits, unsigned Flags,
703                      Metadata *ExtraData = nullptr),
704                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
705                      AlignInBits, OffsetInBits, Flags, ExtraData))
706   DEFINE_MDNODE_GET(MDDerivedType,
707                     (unsigned Tag, StringRef Name, MDFile *File, unsigned Line,
708                      MDScopeRef Scope, MDTypeRef BaseType, uint64_t SizeInBits,
709                      uint64_t AlignInBits, uint64_t OffsetInBits,
710                      unsigned Flags, Metadata *ExtraData = nullptr),
711                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
712                      AlignInBits, OffsetInBits, Flags, ExtraData))
713
714   TempMDDerivedType clone() const { return cloneImpl(); }
715
716   /// \brief Get extra data associated with this derived type.
717   ///
718   /// Class type for pointer-to-members, objective-c property node for ivars,
719   /// or global constant wrapper for static members.
720   ///
721   /// TODO: Separate out types that need this extra operand: pointer-to-member
722   /// types and member fields (static members and ivars).
723   Metadata *getExtraData() const { return getRawExtraData(); }
724   Metadata *getRawExtraData() const { return getOperand(4); }
725
726   static bool classof(const Metadata *MD) {
727     return MD->getMetadataID() == MDDerivedTypeKind;
728   }
729 };
730
731 /// \brief Base class for MDCompositeType and MDSubroutineType.
732 ///
733 /// TODO: Delete; they're not really related.
734 class MDCompositeTypeBase : public MDDerivedTypeBase {
735   unsigned RuntimeLang;
736
737 protected:
738   MDCompositeTypeBase(LLVMContext &C, unsigned ID, StorageType Storage,
739                       unsigned Tag, unsigned Line, unsigned RuntimeLang,
740                       uint64_t SizeInBits, uint64_t AlignInBits,
741                       uint64_t OffsetInBits, unsigned Flags,
742                       ArrayRef<Metadata *> Ops)
743       : MDDerivedTypeBase(C, ID, Storage, Tag, Line, SizeInBits, AlignInBits,
744                           OffsetInBits, Flags, Ops),
745         RuntimeLang(RuntimeLang) {}
746   ~MDCompositeTypeBase() {}
747
748 public:
749   MDTuple *getElements() const {
750     return cast_or_null<MDTuple>(getRawElements());
751   }
752   MDTypeRef getVTableHolder() const { return MDTypeRef(getRawVTableHolder()); }
753   MDTemplateParameterArray getTemplateParams() const {
754     return cast_or_null<MDTuple>(getRawTemplateParams());
755   }
756   StringRef getIdentifier() const { return getStringOperand(7); }
757   unsigned getRuntimeLang() const { return RuntimeLang; }
758
759   Metadata *getRawElements() const { return getOperand(4); }
760   Metadata *getRawVTableHolder() const { return getOperand(5); }
761   Metadata *getRawTemplateParams() const { return getOperand(6); }
762   MDString *getRawIdentifier() const { return getOperandAs<MDString>(7); }
763
764   /// \brief Replace operands.
765   ///
766   /// If this \a isUniqued() and not \a isResolved(), on a uniquing collision
767   /// this will be RAUW'ed and deleted.  Use a \a TrackingMDRef to keep track
768   /// of its movement if necessary.
769   /// @{
770   void replaceElements(MDTuple *Elements) {
771 #ifndef NDEBUG
772     if (auto *Old = cast_or_null<MDTuple>(getElements()))
773       for (const auto &Op : Old->operands())
774         assert(std::find(Elements->op_begin(), Elements->op_end(), Op) &&
775                "Lost a member during member list replacement");
776 #endif
777     replaceOperandWith(4, Elements);
778   }
779   void replaceVTableHolder(MDTypeRef VTableHolder) {
780     replaceOperandWith(5, VTableHolder);
781   }
782   void replaceTemplateParams(MDTemplateParameterArray TemplateParams) {
783     replaceOperandWith(6, TemplateParams);
784   }
785   /// @}
786
787   static bool classof(const Metadata *MD) {
788     return MD->getMetadataID() == MDCompositeTypeKind ||
789            MD->getMetadataID() == MDSubroutineTypeKind;
790   }
791 };
792
793 /// \brief Composite types.
794 ///
795 /// TODO: Detach from DerivedTypeBase (split out MDEnumType?).
796 /// TODO: Create a custom, unrelated node for DW_TAG_array_type.
797 class MDCompositeType : public MDCompositeTypeBase {
798   friend class LLVMContextImpl;
799   friend class MDNode;
800
801   MDCompositeType(LLVMContext &C, StorageType Storage, unsigned Tag,
802                   unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits,
803                   uint64_t AlignInBits, uint64_t OffsetInBits, unsigned Flags,
804                   ArrayRef<Metadata *> Ops)
805       : MDCompositeTypeBase(C, MDCompositeTypeKind, Storage, Tag, Line,
806                             RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
807                             Flags, Ops) {}
808   ~MDCompositeType() {}
809
810   static MDCompositeType *
811   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, Metadata *File,
812           unsigned Line, MDScopeRef Scope, MDTypeRef BaseType,
813           uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
814           uint64_t Flags, MDTuple *Elements, unsigned RuntimeLang,
815           MDTypeRef VTableHolder, MDTemplateParameterArray TemplateParams,
816           StringRef Identifier, StorageType Storage, bool ShouldCreate = true) {
817     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
818                    Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits,
819                    Flags, Elements, RuntimeLang, VTableHolder, TemplateParams,
820                    getCanonicalMDString(Context, Identifier), Storage,
821                    ShouldCreate);
822   }
823   static MDCompositeType *
824   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
825           unsigned Line, Metadata *Scope, Metadata *BaseType,
826           uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
827           unsigned Flags, Metadata *Elements, unsigned RuntimeLang,
828           Metadata *VTableHolder, Metadata *TemplateParams,
829           MDString *Identifier, StorageType Storage, bool ShouldCreate = true);
830
831   TempMDCompositeType cloneImpl() const {
832     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
833                         getScope(), getBaseType(), getSizeInBits(),
834                         getAlignInBits(), getOffsetInBits(), getFlags(),
835                         getElements(), getRuntimeLang(), getVTableHolder(),
836                         getTemplateParams(), getIdentifier());
837   }
838
839 public:
840   DEFINE_MDNODE_GET(MDCompositeType,
841                     (unsigned Tag, StringRef Name, MDFile *File, unsigned Line,
842                      MDScopeRef Scope, MDTypeRef BaseType, uint64_t SizeInBits,
843                      uint64_t AlignInBits, uint64_t OffsetInBits,
844                      unsigned Flags, MDTuple *Elements, unsigned RuntimeLang,
845                      MDTypeRef VTableHolder,
846                      MDTemplateParameterArray TemplateParams = nullptr,
847                      StringRef Identifier = ""),
848                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
849                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
850                      VTableHolder, TemplateParams, Identifier))
851   DEFINE_MDNODE_GET(MDCompositeType,
852                     (unsigned Tag, MDString *Name, Metadata *File,
853                      unsigned Line, Metadata *Scope, Metadata *BaseType,
854                      uint64_t SizeInBits, uint64_t AlignInBits,
855                      uint64_t OffsetInBits, unsigned Flags, Metadata *Elements,
856                      unsigned RuntimeLang, Metadata *VTableHolder,
857                      Metadata *TemplateParams = nullptr,
858                      MDString *Identifier = nullptr),
859                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
860                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
861                      VTableHolder, TemplateParams, Identifier))
862
863   TempMDCompositeType clone() const { return cloneImpl(); }
864
865   static bool classof(const Metadata *MD) {
866     return MD->getMetadataID() == MDCompositeTypeKind;
867   }
868 };
869
870 template <class T> TypedDebugNodeRef<T> TypedDebugNodeRef<T>::get(const T *N) {
871   if (N)
872     if (auto *Composite = dyn_cast<MDCompositeType>(N))
873       if (auto *S = Composite->getRawIdentifier())
874         return TypedDebugNodeRef<T>(S);
875   return TypedDebugNodeRef<T>(N);
876 }
877
878 /// \brief Type array for a subprogram.
879 ///
880 /// TODO: Detach from CompositeType, and fold the array of types in directly
881 /// as operands.
882 class MDSubroutineType : public MDCompositeTypeBase {
883   friend class LLVMContextImpl;
884   friend class MDNode;
885
886   MDSubroutineType(LLVMContext &C, StorageType Storage, unsigned Flags,
887                    ArrayRef<Metadata *> Ops)
888       : MDCompositeTypeBase(C, MDSubroutineTypeKind, Storage,
889                             dwarf::DW_TAG_subroutine_type, 0, 0, 0, 0, 0, Flags,
890                             Ops) {}
891   ~MDSubroutineType() {}
892
893   static MDSubroutineType *getImpl(LLVMContext &Context, unsigned Flags,
894                                    Metadata *TypeArray, StorageType Storage,
895                                    bool ShouldCreate = true);
896
897   TempMDSubroutineType cloneImpl() const {
898     return getTemporary(getContext(), getFlags(), getTypeArray());
899   }
900
901 public:
902   DEFINE_MDNODE_GET(MDSubroutineType, (unsigned Flags, Metadata *TypeArray),
903                     (Flags, TypeArray))
904
905   TempMDSubroutineType clone() const { return cloneImpl(); }
906
907   MDTypeRefArray getTypeArray() const { return getElements(); }
908   Metadata *getRawTypeArray() const { return getRawElements(); }
909
910   static bool classof(const Metadata *MD) {
911     return MD->getMetadataID() == MDSubroutineTypeKind;
912   }
913 };
914
915 /// \brief Compile unit.
916 class MDCompileUnit : public MDScope {
917   friend class LLVMContextImpl;
918   friend class MDNode;
919
920   unsigned SourceLanguage;
921   bool IsOptimized;
922   unsigned RuntimeVersion;
923   unsigned EmissionKind;
924
925   MDCompileUnit(LLVMContext &C, StorageType Storage, unsigned SourceLanguage,
926                 bool IsOptimized, unsigned RuntimeVersion,
927                 unsigned EmissionKind, ArrayRef<Metadata *> Ops)
928       : MDScope(C, MDCompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
929         SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
930         RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind) {}
931   ~MDCompileUnit() {}
932
933   static MDCompileUnit *
934   getImpl(LLVMContext &Context, unsigned SourceLanguage, MDFile *File,
935           StringRef Producer, bool IsOptimized, StringRef Flags,
936           unsigned RuntimeVersion, StringRef SplitDebugFilename,
937           unsigned EmissionKind, MDTuple *EnumTypes, MDTuple *RetainedTypes,
938           MDTuple *Subprograms, MDTuple *GlobalVariables,
939           MDTuple *ImportedEntities, StorageType Storage,
940           bool ShouldCreate = true) {
941     return getImpl(Context, SourceLanguage, File,
942                    getCanonicalMDString(Context, Producer), IsOptimized,
943                    getCanonicalMDString(Context, Flags), RuntimeVersion,
944                    getCanonicalMDString(Context, SplitDebugFilename),
945                    EmissionKind, EnumTypes, RetainedTypes, Subprograms,
946                    GlobalVariables, ImportedEntities, Storage, ShouldCreate);
947   }
948   static MDCompileUnit *
949   getImpl(LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
950           MDString *Producer, bool IsOptimized, MDString *Flags,
951           unsigned RuntimeVersion, MDString *SplitDebugFilename,
952           unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
953           Metadata *Subprograms, Metadata *GlobalVariables,
954           Metadata *ImportedEntities, StorageType Storage,
955           bool ShouldCreate = true);
956
957   TempMDCompileUnit cloneImpl() const {
958     return getTemporary(
959         getContext(), getSourceLanguage(), getFile(), getProducer(),
960         isOptimized(), getFlags(), getRuntimeVersion(), getSplitDebugFilename(),
961         getEmissionKind(), getEnumTypes(), getRetainedTypes(), getSubprograms(),
962         getGlobalVariables(), getImportedEntities());
963   }
964
965 public:
966   DEFINE_MDNODE_GET(MDCompileUnit,
967                     (unsigned SourceLanguage, MDFile *File, StringRef Producer,
968                      bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
969                      StringRef SplitDebugFilename, unsigned EmissionKind,
970                      MDTuple *EnumTypes, MDTuple *RetainedTypes,
971                      MDTuple *Subprograms, MDTuple *GlobalVariables,
972                      MDTuple *ImportedEntities),
973                     (SourceLanguage, File, Producer, IsOptimized, Flags,
974                      RuntimeVersion, SplitDebugFilename, EmissionKind,
975                      EnumTypes, RetainedTypes, Subprograms, GlobalVariables,
976                      ImportedEntities))
977   DEFINE_MDNODE_GET(MDCompileUnit,
978                     (unsigned SourceLanguage, Metadata *File,
979                      MDString *Producer, bool IsOptimized, MDString *Flags,
980                      unsigned RuntimeVersion, MDString *SplitDebugFilename,
981                      unsigned EmissionKind, Metadata *EnumTypes,
982                      Metadata *RetainedTypes, Metadata *Subprograms,
983                      Metadata *GlobalVariables, Metadata *ImportedEntities),
984                     (SourceLanguage, File, Producer, IsOptimized, Flags,
985                      RuntimeVersion, SplitDebugFilename, EmissionKind,
986                      EnumTypes, RetainedTypes, Subprograms, GlobalVariables,
987                      ImportedEntities))
988
989   TempMDCompileUnit clone() const { return cloneImpl(); }
990
991   unsigned getSourceLanguage() const { return SourceLanguage; }
992   bool isOptimized() const { return IsOptimized; }
993   unsigned getRuntimeVersion() const { return RuntimeVersion; }
994   unsigned getEmissionKind() const { return EmissionKind; }
995   StringRef getProducer() const { return getStringOperand(1); }
996   StringRef getFlags() const { return getStringOperand(2); }
997   StringRef getSplitDebugFilename() const { return getStringOperand(3); }
998   MDCompositeTypeArray getEnumTypes() const {
999     return cast_or_null<MDTuple>(getRawEnumTypes());
1000   }
1001   MDTypeArray getRetainedTypes() const {
1002     return cast_or_null<MDTuple>(getRawRetainedTypes());
1003   }
1004   MDSubprogramArray getSubprograms() const {
1005     return cast_or_null<MDTuple>(getRawSubprograms());
1006   }
1007   MDGlobalVariableArray getGlobalVariables() const {
1008     return cast_or_null<MDTuple>(getRawGlobalVariables());
1009   }
1010   MDImportedEntityArray getImportedEntities() const {
1011     return cast_or_null<MDTuple>(getRawImportedEntities());
1012   }
1013
1014   MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
1015   MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
1016   MDString *getRawSplitDebugFilename() const {
1017     return getOperandAs<MDString>(3);
1018   }
1019   Metadata *getRawEnumTypes() const { return getOperand(4); }
1020   Metadata *getRawRetainedTypes() const { return getOperand(5); }
1021   Metadata *getRawSubprograms() const { return getOperand(6); }
1022   Metadata *getRawGlobalVariables() const { return getOperand(7); }
1023   Metadata *getRawImportedEntities() const { return getOperand(8); }
1024
1025   /// \brief Replace arrays.
1026   ///
1027   /// If this \a isUniqued() and not \a isResolved(), it will be RAUW'ed and
1028   /// deleted on a uniquing collision.  In practice, uniquing collisions on \a
1029   /// MDCompileUnit should be fairly rare.
1030   /// @{
1031   void replaceSubprograms(MDTuple *N) { replaceOperandWith(6, N); }
1032   void replaceGlobalVariables(MDTuple *N) { replaceOperandWith(7, N); }
1033   /// @}
1034
1035   static bool classof(const Metadata *MD) {
1036     return MD->getMetadataID() == MDCompileUnitKind;
1037   }
1038 };
1039
1040 /// \brief A scope for locals.
1041 ///
1042 /// A legal scope for lexical blocks, local variables, and debug info
1043 /// locations.  Subclasses are \a MDSubprogram, \a MDLexicalBlock, and \a
1044 /// MDLexicalBlockFile.
1045 class MDLocalScope : public MDScope {
1046 protected:
1047   MDLocalScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1048                ArrayRef<Metadata *> Ops)
1049       : MDScope(C, ID, Storage, Tag, Ops) {}
1050   ~MDLocalScope() {}
1051
1052 public:
1053   /// \brief Get the subprogram for this scope.
1054   ///
1055   /// Return this if it's an \a MDSubprogram; otherwise, look up the scope
1056   /// chain.
1057   MDSubprogram *getSubprogram() const;
1058
1059   static bool classof(const Metadata *MD) {
1060     return MD->getMetadataID() == MDSubprogramKind ||
1061            MD->getMetadataID() == MDLexicalBlockKind ||
1062            MD->getMetadataID() == MDLexicalBlockFileKind;
1063   }
1064 };
1065
1066 /// \brief Debug location.
1067 ///
1068 /// A debug location in source code, used for debug info and otherwise.
1069 class MDLocation : public MDNode {
1070   friend class LLVMContextImpl;
1071   friend class MDNode;
1072
1073   MDLocation(LLVMContext &C, StorageType Storage, unsigned Line,
1074              unsigned Column, ArrayRef<Metadata *> MDs);
1075   ~MDLocation() { dropAllReferences(); }
1076
1077   static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
1078                              unsigned Column, Metadata *Scope,
1079                              Metadata *InlinedAt, StorageType Storage,
1080                              bool ShouldCreate = true);
1081   static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
1082                              unsigned Column, MDLocalScope *Scope,
1083                              MDLocation *InlinedAt, StorageType Storage,
1084                              bool ShouldCreate = true) {
1085     return getImpl(Context, Line, Column, static_cast<Metadata *>(Scope),
1086                    static_cast<Metadata *>(InlinedAt), Storage, ShouldCreate);
1087   }
1088
1089   TempMDLocation cloneImpl() const {
1090     return getTemporary(getContext(), getLine(), getColumn(), getScope(),
1091                         getInlinedAt());
1092   }
1093
1094   // Disallow replacing operands.
1095   void replaceOperandWith(unsigned I, Metadata *New) = delete;
1096
1097 public:
1098   DEFINE_MDNODE_GET(MDLocation,
1099                     (unsigned Line, unsigned Column, Metadata *Scope,
1100                      Metadata *InlinedAt = nullptr),
1101                     (Line, Column, Scope, InlinedAt))
1102   DEFINE_MDNODE_GET(MDLocation,
1103                     (unsigned Line, unsigned Column, MDLocalScope *Scope,
1104                      MDLocation *InlinedAt = nullptr),
1105                     (Line, Column, Scope, InlinedAt))
1106
1107   /// \brief Return a (temporary) clone of this.
1108   TempMDLocation clone() const { return cloneImpl(); }
1109
1110   unsigned getLine() const { return SubclassData32; }
1111   unsigned getColumn() const { return SubclassData16; }
1112   MDLocalScope *getScope() const {
1113     return cast<MDLocalScope>(getRawScope());
1114   }
1115   MDLocation *getInlinedAt() const {
1116     return cast_or_null<MDLocation>(getRawInlinedAt());
1117   }
1118
1119   /// \brief Get the scope where this is inlined.
1120   ///
1121   /// Walk through \a getInlinedAt() and return \a getScope() from the deepest
1122   /// location.
1123   MDLocalScope *getInlinedAtScope() const {
1124     if (auto *IA = getInlinedAt())
1125       return IA->getInlinedAtScope();
1126     return getScope();
1127   }
1128
1129   Metadata *getRawScope() const { return getOperand(0); }
1130   Metadata *getRawInlinedAt() const {
1131     if (getNumOperands() == 2)
1132       return getOperand(1);
1133     return nullptr;
1134   }
1135
1136   static bool classof(const Metadata *MD) {
1137     return MD->getMetadataID() == MDLocationKind;
1138   }
1139 };
1140
1141 /// \brief Subprogram description.
1142 ///
1143 /// TODO: Remove DisplayName.  It's always equal to Name.
1144 /// TODO: Split up flags.
1145 class MDSubprogram : public MDLocalScope {
1146   friend class LLVMContextImpl;
1147   friend class MDNode;
1148
1149   unsigned Line;
1150   unsigned ScopeLine;
1151   unsigned Virtuality;
1152   unsigned VirtualIndex;
1153   unsigned Flags;
1154   bool IsLocalToUnit;
1155   bool IsDefinition;
1156   bool IsOptimized;
1157
1158   MDSubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
1159                unsigned ScopeLine, unsigned Virtuality, unsigned VirtualIndex,
1160                unsigned Flags, bool IsLocalToUnit, bool IsDefinition,
1161                bool IsOptimized, ArrayRef<Metadata *> Ops)
1162       : MDLocalScope(C, MDSubprogramKind, Storage, dwarf::DW_TAG_subprogram,
1163                      Ops),
1164         Line(Line), ScopeLine(ScopeLine), Virtuality(Virtuality),
1165         VirtualIndex(VirtualIndex), Flags(Flags), IsLocalToUnit(IsLocalToUnit),
1166         IsDefinition(IsDefinition), IsOptimized(IsOptimized) {}
1167   ~MDSubprogram() {}
1168
1169   static MDSubprogram *
1170   getImpl(LLVMContext &Context, MDScopeRef Scope, StringRef Name,
1171           StringRef LinkageName, MDFile *File, unsigned Line,
1172           MDSubroutineType *Type, bool IsLocalToUnit, bool IsDefinition,
1173           unsigned ScopeLine, MDTypeRef ContainingType, unsigned Virtuality,
1174           unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1175           ConstantAsMetadata *Function, MDTemplateParameterArray TemplateParams,
1176           MDSubprogram *Declaration, MDLocalVariableArray Variables,
1177           StorageType Storage, bool ShouldCreate = true) {
1178     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1179                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1180                    IsLocalToUnit, IsDefinition, ScopeLine, ContainingType,
1181                    Virtuality, VirtualIndex, Flags, IsOptimized, Function,
1182                    TemplateParams, Declaration, Variables, Storage,
1183                    ShouldCreate);
1184   }
1185   static MDSubprogram *
1186   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1187           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1188           bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1189           Metadata *ContainingType, unsigned Virtuality, unsigned VirtualIndex,
1190           unsigned Flags, bool IsOptimized, Metadata *Function,
1191           Metadata *TemplateParams, Metadata *Declaration, Metadata *Variables,
1192           StorageType Storage, bool ShouldCreate = true);
1193
1194   TempMDSubprogram cloneImpl() const {
1195     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1196                         getFile(), getLine(), getType(), isLocalToUnit(),
1197                         isDefinition(), getScopeLine(), getContainingType(),
1198                         getVirtuality(), getVirtualIndex(), getFlags(),
1199                         isOptimized(), getFunction(), getTemplateParams(),
1200                         getDeclaration(), getVariables());
1201   }
1202
1203 public:
1204   DEFINE_MDNODE_GET(MDSubprogram,
1205                     (MDScopeRef Scope, StringRef Name, StringRef LinkageName,
1206                      MDFile *File, unsigned Line, MDSubroutineType *Type,
1207                      bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1208                      MDTypeRef ContainingType, unsigned Virtuality,
1209                      unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1210                      ConstantAsMetadata *Function = nullptr,
1211                      MDTemplateParameterArray TemplateParams = nullptr,
1212                      MDSubprogram *Declaration = nullptr,
1213                      MDLocalVariableArray Variables = nullptr),
1214                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1215                      IsDefinition, ScopeLine, ContainingType, Virtuality,
1216                      VirtualIndex, Flags, IsOptimized, Function, TemplateParams,
1217                      Declaration, Variables))
1218   DEFINE_MDNODE_GET(
1219       MDSubprogram,
1220       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
1221        unsigned Line, Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
1222        unsigned ScopeLine, Metadata *ContainingType, unsigned Virtuality,
1223        unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1224        Metadata *Function = nullptr, Metadata *TemplateParams = nullptr,
1225        Metadata *Declaration = nullptr, Metadata *Variables = nullptr),
1226       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
1227        ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized,
1228        Function, TemplateParams, Declaration, Variables))
1229
1230   TempMDSubprogram clone() const { return cloneImpl(); }
1231
1232 public:
1233   unsigned getLine() const { return Line; }
1234   unsigned getVirtuality() const { return Virtuality; }
1235   unsigned getVirtualIndex() const { return VirtualIndex; }
1236   unsigned getScopeLine() const { return ScopeLine; }
1237   unsigned getFlags() const { return Flags; }
1238   bool isLocalToUnit() const { return IsLocalToUnit; }
1239   bool isDefinition() const { return IsDefinition; }
1240   bool isOptimized() const { return IsOptimized; }
1241
1242   unsigned isArtificial() const { return getFlags() & FlagArtificial; }
1243   bool isPrivate() const {
1244     return (getFlags() & FlagAccessibility) == FlagPrivate;
1245   }
1246   bool isProtected() const {
1247     return (getFlags() & FlagAccessibility) == FlagProtected;
1248   }
1249   bool isPublic() const {
1250     return (getFlags() & FlagAccessibility) == FlagPublic;
1251   }
1252   bool isExplicit() const { return getFlags() & FlagExplicit; }
1253   bool isPrototyped() const { return getFlags() & FlagPrototyped; }
1254
1255   /// \brief Check if this is reference-qualified.
1256   ///
1257   /// Return true if this subprogram is a C++11 reference-qualified non-static
1258   /// member function (void foo() &).
1259   unsigned isLValueReference() const {
1260     return getFlags() & FlagLValueReference;
1261   }
1262
1263   /// \brief Check if this is rvalue-reference-qualified.
1264   ///
1265   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
1266   /// non-static member function (void foo() &&).
1267   unsigned isRValueReference() const {
1268     return getFlags() & FlagRValueReference;
1269   }
1270
1271   MDScopeRef getScope() const { return MDScopeRef(getRawScope()); }
1272
1273   StringRef getName() const { return getStringOperand(2); }
1274   StringRef getDisplayName() const { return getStringOperand(3); }
1275   StringRef getLinkageName() const { return getStringOperand(4); }
1276
1277   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1278   MDString *getRawLinkageName() const { return getOperandAs<MDString>(4); }
1279
1280   MDSubroutineType *getType() const {
1281     return cast_or_null<MDSubroutineType>(getRawType());
1282   }
1283   MDTypeRef getContainingType() const {
1284     return MDTypeRef(getRawContainingType());
1285   }
1286
1287   ConstantAsMetadata *getFunction() const {
1288     return cast_or_null<ConstantAsMetadata>(getRawFunction());
1289   }
1290   MDTemplateParameterArray getTemplateParams() const {
1291     return cast_or_null<MDTuple>(getRawTemplateParams());
1292   }
1293   MDSubprogram *getDeclaration() const {
1294     return cast_or_null<MDSubprogram>(getRawDeclaration());
1295   }
1296   MDLocalVariableArray getVariables() const {
1297     return cast_or_null<MDTuple>(getRawVariables());
1298   }
1299
1300   Metadata *getRawScope() const { return getOperand(1); }
1301   Metadata *getRawType() const { return getOperand(5); }
1302   Metadata *getRawContainingType() const { return getOperand(6); }
1303   Metadata *getRawFunction() const { return getOperand(7); }
1304   Metadata *getRawTemplateParams() const { return getOperand(8); }
1305   Metadata *getRawDeclaration() const { return getOperand(9); }
1306   Metadata *getRawVariables() const { return getOperand(10); }
1307
1308   /// \brief Replace the function.
1309   ///
1310   /// If \a isUniqued() and not \a isResolved(), this could node will be
1311   /// RAUW'ed and deleted out from under the caller.  Use a \a TrackingMDRef if
1312   /// that's a problem.
1313   /// @{
1314   void replaceFunction(Function *F);
1315   void replaceFunction(ConstantAsMetadata *MD) { replaceOperandWith(7, MD); }
1316   void replaceFunction(std::nullptr_t) { replaceOperandWith(7, nullptr); }
1317   /// @}
1318
1319   static bool classof(const Metadata *MD) {
1320     return MD->getMetadataID() == MDSubprogramKind;
1321   }
1322 };
1323
1324 class MDLexicalBlockBase : public MDLocalScope {
1325 protected:
1326   MDLexicalBlockBase(LLVMContext &C, unsigned ID, StorageType Storage,
1327                      ArrayRef<Metadata *> Ops)
1328       : MDLocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
1329   ~MDLexicalBlockBase() {}
1330
1331 public:
1332   MDLocalScope *getScope() const { return cast<MDLocalScope>(getRawScope()); }
1333
1334   Metadata *getRawScope() const { return getOperand(1); }
1335
1336   static bool classof(const Metadata *MD) {
1337     return MD->getMetadataID() == MDLexicalBlockKind ||
1338            MD->getMetadataID() == MDLexicalBlockFileKind;
1339   }
1340 };
1341
1342 class MDLexicalBlock : public MDLexicalBlockBase {
1343   friend class LLVMContextImpl;
1344   friend class MDNode;
1345
1346   unsigned Line;
1347   unsigned Column;
1348
1349   MDLexicalBlock(LLVMContext &C, StorageType Storage, unsigned Line,
1350                  unsigned Column, ArrayRef<Metadata *> Ops)
1351       : MDLexicalBlockBase(C, MDLexicalBlockKind, Storage, Ops), Line(Line),
1352         Column(Column) {}
1353   ~MDLexicalBlock() {}
1354
1355   static MDLexicalBlock *getImpl(LLVMContext &Context, MDLocalScope *Scope,
1356                                  MDFile *File, unsigned Line, unsigned Column,
1357                                  StorageType Storage,
1358                                  bool ShouldCreate = true) {
1359     return getImpl(Context, static_cast<Metadata *>(Scope),
1360                    static_cast<Metadata *>(File), Line, Column, Storage,
1361                    ShouldCreate);
1362   }
1363
1364   static MDLexicalBlock *getImpl(LLVMContext &Context, Metadata *Scope,
1365                                  Metadata *File, unsigned Line, unsigned Column,
1366                                  StorageType Storage, bool ShouldCreate = true);
1367
1368   TempMDLexicalBlock cloneImpl() const {
1369     return getTemporary(getContext(), getScope(), getFile(), getLine(),
1370                         getColumn());
1371   }
1372
1373 public:
1374   DEFINE_MDNODE_GET(MDLexicalBlock, (MDLocalScope * Scope, MDFile *File,
1375                                      unsigned Line, unsigned Column),
1376                     (Scope, File, Line, Column))
1377   DEFINE_MDNODE_GET(MDLexicalBlock, (Metadata * Scope, Metadata *File,
1378                                      unsigned Line, unsigned Column),
1379                     (Scope, File, Line, Column))
1380
1381   TempMDLexicalBlock clone() const { return cloneImpl(); }
1382
1383   unsigned getLine() const { return Line; }
1384   unsigned getColumn() const { return Column; }
1385
1386   static bool classof(const Metadata *MD) {
1387     return MD->getMetadataID() == MDLexicalBlockKind;
1388   }
1389 };
1390
1391 class MDLexicalBlockFile : public MDLexicalBlockBase {
1392   friend class LLVMContextImpl;
1393   friend class MDNode;
1394
1395   unsigned Discriminator;
1396
1397   MDLexicalBlockFile(LLVMContext &C, StorageType Storage,
1398                      unsigned Discriminator, ArrayRef<Metadata *> Ops)
1399       : MDLexicalBlockBase(C, MDLexicalBlockFileKind, Storage, Ops),
1400         Discriminator(Discriminator) {}
1401   ~MDLexicalBlockFile() {}
1402
1403   static MDLexicalBlockFile *getImpl(LLVMContext &Context, MDLocalScope *Scope,
1404                                      MDFile *File, unsigned Discriminator,
1405                                      StorageType Storage,
1406                                      bool ShouldCreate = true) {
1407     return getImpl(Context, static_cast<Metadata *>(Scope),
1408                    static_cast<Metadata *>(File), Discriminator, Storage,
1409                    ShouldCreate);
1410   }
1411
1412   static MDLexicalBlockFile *getImpl(LLVMContext &Context, Metadata *Scope,
1413                                      Metadata *File, unsigned Discriminator,
1414                                      StorageType Storage,
1415                                      bool ShouldCreate = true);
1416
1417   TempMDLexicalBlockFile cloneImpl() const {
1418     return getTemporary(getContext(), getScope(), getFile(),
1419                         getDiscriminator());
1420   }
1421
1422 public:
1423   DEFINE_MDNODE_GET(MDLexicalBlockFile, (MDLocalScope * Scope, MDFile *File,
1424                                          unsigned Discriminator),
1425                     (Scope, File, Discriminator))
1426   DEFINE_MDNODE_GET(MDLexicalBlockFile,
1427                     (Metadata * Scope, Metadata *File, unsigned Discriminator),
1428                     (Scope, File, Discriminator))
1429
1430   TempMDLexicalBlockFile clone() const { return cloneImpl(); }
1431
1432   unsigned getDiscriminator() const { return Discriminator; }
1433
1434   static bool classof(const Metadata *MD) {
1435     return MD->getMetadataID() == MDLexicalBlockFileKind;
1436   }
1437 };
1438
1439 class MDNamespace : public MDScope {
1440   friend class LLVMContextImpl;
1441   friend class MDNode;
1442
1443   unsigned Line;
1444
1445   MDNamespace(LLVMContext &Context, StorageType Storage, unsigned Line,
1446               ArrayRef<Metadata *> Ops)
1447       : MDScope(Context, MDNamespaceKind, Storage, dwarf::DW_TAG_namespace,
1448                 Ops),
1449         Line(Line) {}
1450   ~MDNamespace() {}
1451
1452   static MDNamespace *getImpl(LLVMContext &Context, MDScope *Scope,
1453                               MDFile *File, StringRef Name, unsigned Line,
1454                               StorageType Storage, bool ShouldCreate = true) {
1455     return getImpl(Context, Scope, File, getCanonicalMDString(Context, Name),
1456                    Line, Storage, ShouldCreate);
1457   }
1458   static MDNamespace *getImpl(LLVMContext &Context, Metadata *Scope,
1459                               Metadata *File, MDString *Name, unsigned Line,
1460                               StorageType Storage, bool ShouldCreate = true);
1461
1462   TempMDNamespace cloneImpl() const {
1463     return getTemporary(getContext(), getScope(), getFile(), getName(),
1464                         getLine());
1465   }
1466
1467 public:
1468   DEFINE_MDNODE_GET(MDNamespace, (MDScope * Scope, MDFile *File, StringRef Name,
1469                                   unsigned Line),
1470                     (Scope, File, Name, Line))
1471   DEFINE_MDNODE_GET(MDNamespace, (Metadata * Scope, Metadata *File,
1472                                   MDString *Name, unsigned Line),
1473                     (Scope, File, Name, Line))
1474
1475   TempMDNamespace clone() const { return cloneImpl(); }
1476
1477   unsigned getLine() const { return Line; }
1478   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
1479   StringRef getName() const { return getStringOperand(2); }
1480
1481   Metadata *getRawScope() const { return getOperand(1); }
1482   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1483
1484   static bool classof(const Metadata *MD) {
1485     return MD->getMetadataID() == MDNamespaceKind;
1486   }
1487 };
1488
1489 /// \brief Base class for template parameters.
1490 class MDTemplateParameter : public DebugNode {
1491 protected:
1492   MDTemplateParameter(LLVMContext &Context, unsigned ID, StorageType Storage,
1493                       unsigned Tag, ArrayRef<Metadata *> Ops)
1494       : DebugNode(Context, ID, Storage, Tag, Ops) {}
1495   ~MDTemplateParameter() {}
1496
1497 public:
1498   StringRef getName() const { return getStringOperand(0); }
1499   MDTypeRef getType() const { return MDTypeRef(getRawType()); }
1500
1501   MDString *getRawName() const { return getOperandAs<MDString>(0); }
1502   Metadata *getRawType() const { return getOperand(1); }
1503
1504   static bool classof(const Metadata *MD) {
1505     return MD->getMetadataID() == MDTemplateTypeParameterKind ||
1506            MD->getMetadataID() == MDTemplateValueParameterKind;
1507   }
1508 };
1509
1510 class MDTemplateTypeParameter : public MDTemplateParameter {
1511   friend class LLVMContextImpl;
1512   friend class MDNode;
1513
1514   MDTemplateTypeParameter(LLVMContext &Context, StorageType Storage,
1515                           ArrayRef<Metadata *> Ops)
1516       : MDTemplateParameter(Context, MDTemplateTypeParameterKind, Storage,
1517                             dwarf::DW_TAG_template_type_parameter, Ops) {}
1518   ~MDTemplateTypeParameter() {}
1519
1520   static MDTemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
1521                                           MDTypeRef Type, StorageType Storage,
1522                                           bool ShouldCreate = true) {
1523     return getImpl(Context, getCanonicalMDString(Context, Name), Type, Storage,
1524                    ShouldCreate);
1525   }
1526   static MDTemplateTypeParameter *getImpl(LLVMContext &Context, MDString *Name,
1527                                           Metadata *Type, StorageType Storage,
1528                                           bool ShouldCreate = true);
1529
1530   TempMDTemplateTypeParameter cloneImpl() const {
1531     return getTemporary(getContext(), getName(), getType());
1532   }
1533
1534 public:
1535   DEFINE_MDNODE_GET(MDTemplateTypeParameter, (StringRef Name, MDTypeRef Type),
1536                     (Name, Type))
1537   DEFINE_MDNODE_GET(MDTemplateTypeParameter, (MDString * Name, Metadata *Type),
1538                     (Name, Type))
1539
1540   TempMDTemplateTypeParameter clone() const { return cloneImpl(); }
1541
1542   static bool classof(const Metadata *MD) {
1543     return MD->getMetadataID() == MDTemplateTypeParameterKind;
1544   }
1545 };
1546
1547 class MDTemplateValueParameter : public MDTemplateParameter {
1548   friend class LLVMContextImpl;
1549   friend class MDNode;
1550
1551   MDTemplateValueParameter(LLVMContext &Context, StorageType Storage,
1552                            unsigned Tag, ArrayRef<Metadata *> Ops)
1553       : MDTemplateParameter(Context, MDTemplateValueParameterKind, Storage, Tag,
1554                             Ops) {}
1555   ~MDTemplateValueParameter() {}
1556
1557   static MDTemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
1558                                            StringRef Name, MDTypeRef Type,
1559                                            Metadata *Value, StorageType Storage,
1560                                            bool ShouldCreate = true) {
1561     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), Type,
1562                    Value, Storage, ShouldCreate);
1563   }
1564   static MDTemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
1565                                            MDString *Name, Metadata *Type,
1566                                            Metadata *Value, StorageType Storage,
1567                                            bool ShouldCreate = true);
1568
1569   TempMDTemplateValueParameter cloneImpl() const {
1570     return getTemporary(getContext(), getTag(), getName(), getType(),
1571                         getValue());
1572   }
1573
1574 public:
1575   DEFINE_MDNODE_GET(MDTemplateValueParameter, (unsigned Tag, StringRef Name,
1576                                                MDTypeRef Type, Metadata *Value),
1577                     (Tag, Name, Type, Value))
1578   DEFINE_MDNODE_GET(MDTemplateValueParameter, (unsigned Tag, MDString *Name,
1579                                                Metadata *Type, Metadata *Value),
1580                     (Tag, Name, Type, Value))
1581
1582   TempMDTemplateValueParameter clone() const { return cloneImpl(); }
1583
1584   Metadata *getValue() const { return getOperand(2); }
1585
1586   static bool classof(const Metadata *MD) {
1587     return MD->getMetadataID() == MDTemplateValueParameterKind;
1588   }
1589 };
1590
1591 /// \brief Base class for variables.
1592 ///
1593 /// TODO: Hardcode to DW_TAG_variable.
1594 class MDVariable : public DebugNode {
1595   unsigned Line;
1596
1597 protected:
1598   MDVariable(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1599              unsigned Line, ArrayRef<Metadata *> Ops)
1600       : DebugNode(C, ID, Storage, Tag, Ops), Line(Line) {}
1601   ~MDVariable() {}
1602
1603 public:
1604   unsigned getLine() const { return Line; }
1605   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
1606   StringRef getName() const { return getStringOperand(1); }
1607   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
1608   MDTypeRef getType() const { return MDTypeRef(getRawType()); }
1609
1610   Metadata *getRawScope() const { return getOperand(0); }
1611   MDString *getRawName() const { return getOperandAs<MDString>(1); }
1612   Metadata *getRawFile() const { return getOperand(2); }
1613   Metadata *getRawType() const { return getOperand(3); }
1614
1615   static bool classof(const Metadata *MD) {
1616     return MD->getMetadataID() == MDLocalVariableKind ||
1617            MD->getMetadataID() == MDGlobalVariableKind;
1618   }
1619 };
1620
1621 /// \brief Global variables.
1622 ///
1623 /// TODO: Remove DisplayName.  It's always equal to Name.
1624 class MDGlobalVariable : public MDVariable {
1625   friend class LLVMContextImpl;
1626   friend class MDNode;
1627
1628   bool IsLocalToUnit;
1629   bool IsDefinition;
1630
1631   MDGlobalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
1632                    bool IsLocalToUnit, bool IsDefinition,
1633                    ArrayRef<Metadata *> Ops)
1634       : MDVariable(C, MDGlobalVariableKind, Storage, dwarf::DW_TAG_variable,
1635                    Line, Ops),
1636         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition) {}
1637   ~MDGlobalVariable() {}
1638
1639   static MDGlobalVariable *
1640   getImpl(LLVMContext &Context, MDScope *Scope, StringRef Name,
1641           StringRef LinkageName, MDFile *File, unsigned Line, MDTypeRef Type,
1642           bool IsLocalToUnit, bool IsDefinition, ConstantAsMetadata *Variable,
1643           MDDerivedType *StaticDataMemberDeclaration, StorageType Storage,
1644           bool ShouldCreate = true) {
1645     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1646                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1647                    IsLocalToUnit, IsDefinition, Variable,
1648                    StaticDataMemberDeclaration, Storage, ShouldCreate);
1649   }
1650   static MDGlobalVariable *
1651   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1652           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1653           bool IsLocalToUnit, bool IsDefinition, Metadata *Variable,
1654           Metadata *StaticDataMemberDeclaration, StorageType Storage,
1655           bool ShouldCreate = true);
1656
1657   TempMDGlobalVariable cloneImpl() const {
1658     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1659                         getFile(), getLine(), getType(), isLocalToUnit(),
1660                         isDefinition(), getVariable(),
1661                         getStaticDataMemberDeclaration());
1662   }
1663
1664 public:
1665   DEFINE_MDNODE_GET(MDGlobalVariable,
1666                     (MDScope * Scope, StringRef Name, StringRef LinkageName,
1667                      MDFile *File, unsigned Line, MDTypeRef Type,
1668                      bool IsLocalToUnit, bool IsDefinition,
1669                      ConstantAsMetadata *Variable,
1670                      MDDerivedType *StaticDataMemberDeclaration),
1671                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1672                      IsDefinition, Variable, StaticDataMemberDeclaration))
1673   DEFINE_MDNODE_GET(MDGlobalVariable,
1674                     (Metadata * Scope, MDString *Name, MDString *LinkageName,
1675                      Metadata *File, unsigned Line, Metadata *Type,
1676                      bool IsLocalToUnit, bool IsDefinition, Metadata *Variable,
1677                      Metadata *StaticDataMemberDeclaration),
1678                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1679                      IsDefinition, Variable, StaticDataMemberDeclaration))
1680
1681   TempMDGlobalVariable clone() const { return cloneImpl(); }
1682
1683   bool isLocalToUnit() const { return IsLocalToUnit; }
1684   bool isDefinition() const { return IsDefinition; }
1685   StringRef getDisplayName() const { return getStringOperand(4); }
1686   StringRef getLinkageName() const { return getStringOperand(5); }
1687   ConstantAsMetadata *getVariable() const {
1688     return cast_or_null<ConstantAsMetadata>(getRawVariable());
1689   }
1690   MDDerivedType *getStaticDataMemberDeclaration() const {
1691     return cast_or_null<MDDerivedType>(getRawStaticDataMemberDeclaration());
1692   }
1693
1694   MDString *getRawLinkageName() const { return getOperandAs<MDString>(5); }
1695   Metadata *getRawVariable() const { return getOperand(6); }
1696   Metadata *getRawStaticDataMemberDeclaration() const { return getOperand(7); }
1697
1698   static bool classof(const Metadata *MD) {
1699     return MD->getMetadataID() == MDGlobalVariableKind;
1700   }
1701 };
1702
1703 /// \brief Local variable.
1704 ///
1705 /// TODO: Split between arguments and otherwise.
1706 /// TODO: Use \c DW_TAG_variable instead of fake tags.
1707 /// TODO: Split up flags.
1708 class MDLocalVariable : public MDVariable {
1709   friend class LLVMContextImpl;
1710   friend class MDNode;
1711
1712   unsigned Arg;
1713   unsigned Flags;
1714
1715   MDLocalVariable(LLVMContext &C, StorageType Storage, unsigned Tag,
1716                   unsigned Line, unsigned Arg, unsigned Flags,
1717                   ArrayRef<Metadata *> Ops)
1718       : MDVariable(C, MDLocalVariableKind, Storage, Tag, Line, Ops), Arg(Arg),
1719         Flags(Flags) {}
1720   ~MDLocalVariable() {}
1721
1722   static MDLocalVariable *getImpl(LLVMContext &Context, unsigned Tag,
1723                                   MDScope *Scope, StringRef Name, MDFile *File,
1724                                   unsigned Line, MDTypeRef Type, unsigned Arg,
1725                                   unsigned Flags, MDLocation *InlinedAt,
1726                                   StorageType Storage,
1727                                   bool ShouldCreate = true) {
1728     return getImpl(Context, Tag, Scope, getCanonicalMDString(Context, Name),
1729                    File, Line, Type, Arg, Flags, InlinedAt, Storage,
1730                    ShouldCreate);
1731   }
1732   static MDLocalVariable *getImpl(LLVMContext &Context, unsigned Tag,
1733                                   Metadata *Scope, MDString *Name,
1734                                   Metadata *File, unsigned Line, Metadata *Type,
1735                                   unsigned Arg, unsigned Flags,
1736                                   Metadata *InlinedAt, StorageType Storage,
1737                                   bool ShouldCreate = true);
1738
1739   TempMDLocalVariable cloneImpl() const {
1740     return getTemporary(getContext(), getTag(), getScope(), getName(),
1741                         getFile(), getLine(), getType(), getArg(), getFlags(),
1742                         getInlinedAt());
1743   }
1744
1745 public:
1746   DEFINE_MDNODE_GET(MDLocalVariable,
1747                     (unsigned Tag, MDLocalScope *Scope, StringRef Name,
1748                      MDFile *File, unsigned Line, MDTypeRef Type, unsigned Arg,
1749                      unsigned Flags, MDLocation *InlinedAt = nullptr),
1750                     (Tag, Scope, Name, File, Line, Type, Arg, Flags, InlinedAt))
1751   DEFINE_MDNODE_GET(MDLocalVariable,
1752                     (unsigned Tag, Metadata *Scope, MDString *Name,
1753                      Metadata *File, unsigned Line, Metadata *Type,
1754                      unsigned Arg, unsigned Flags,
1755                      Metadata *InlinedAt = nullptr),
1756                     (Tag, Scope, Name, File, Line, Type, Arg, Flags, InlinedAt))
1757
1758   TempMDLocalVariable clone() const { return cloneImpl(); }
1759
1760   /// \brief Get the local scope for this variable.
1761   ///
1762   /// Variables must be defined in a local scope.
1763   MDLocalScope *getScope() const {
1764     return cast<MDLocalScope>(MDVariable::getScope());
1765   }
1766
1767   unsigned getArg() const { return Arg; }
1768   unsigned getFlags() const { return Flags; }
1769   MDLocation *getInlinedAt() const {
1770     return cast_or_null<MDLocation>(getRawInlinedAt());
1771   }
1772
1773   Metadata *getRawInlinedAt() const { return getOperand(4); }
1774
1775   bool isArtificial() const { return getFlags() & FlagArtificial; }
1776   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
1777
1778   /// \brief Check that a location is valid for this variable.
1779   ///
1780   /// Check that \c DL has the same inlined-at location as this variable,
1781   /// making them valid for the same \a DbgInfoIntrinsic.
1782   bool isValidLocationForIntrinsic(const MDLocation *DL) const {
1783     return getInlinedAt() == (DL ? DL->getInlinedAt() : nullptr);
1784   }
1785
1786   /// \brief Get an inlined version of this variable.
1787   ///
1788   /// Returns a version of this with \a getAlinedAt() set to \c InlinedAt.
1789   MDLocalVariable *withInline(MDLocation *InlinedAt) const {
1790     if (InlinedAt == getInlinedAt())
1791       return const_cast<MDLocalVariable *>(this);
1792     auto Temp = clone();
1793     Temp->replaceOperandWith(4, InlinedAt);
1794     return replaceWithUniqued(std::move(Temp));
1795   }
1796   MDLocalVariable *withoutInline() const { return withInline(nullptr); }
1797
1798   static bool classof(const Metadata *MD) {
1799     return MD->getMetadataID() == MDLocalVariableKind;
1800   }
1801 };
1802
1803 /// \brief DWARF expression.
1804 ///
1805 /// TODO: Co-allocate the expression elements.
1806 /// TODO: Separate from MDNode, or otherwise drop Distinct and Temporary
1807 /// storage types.
1808 class MDExpression : public MDNode {
1809   friend class LLVMContextImpl;
1810   friend class MDNode;
1811
1812   std::vector<uint64_t> Elements;
1813
1814   MDExpression(LLVMContext &C, StorageType Storage, ArrayRef<uint64_t> Elements)
1815       : MDNode(C, MDExpressionKind, Storage, None),
1816         Elements(Elements.begin(), Elements.end()) {}
1817   ~MDExpression() {}
1818
1819   static MDExpression *getImpl(LLVMContext &Context,
1820                                ArrayRef<uint64_t> Elements, StorageType Storage,
1821                                bool ShouldCreate = true);
1822
1823   TempMDExpression cloneImpl() const {
1824     return getTemporary(getContext(), getElements());
1825   }
1826
1827 public:
1828   DEFINE_MDNODE_GET(MDExpression, (ArrayRef<uint64_t> Elements), (Elements))
1829
1830   TempMDExpression clone() const { return cloneImpl(); }
1831
1832   ArrayRef<uint64_t> getElements() const { return Elements; }
1833
1834   unsigned getNumElements() const { return Elements.size(); }
1835   uint64_t getElement(unsigned I) const {
1836     assert(I < Elements.size() && "Index out of range");
1837     return Elements[I];
1838   }
1839
1840   /// \brief Return whether this is a piece of an aggregate variable.
1841   bool isBitPiece() const;
1842
1843   /// \brief Return the offset of this piece in bits.
1844   uint64_t getBitPieceOffset() const;
1845
1846   /// \brief Return the size of this piece in bits.
1847   uint64_t getBitPieceSize() const;
1848
1849   typedef ArrayRef<uint64_t>::iterator element_iterator;
1850   element_iterator elements_begin() const { return getElements().begin(); }
1851   element_iterator elements_end() const { return getElements().end(); }
1852
1853   /// \brief A lightweight wrapper around an expression operand.
1854   ///
1855   /// TODO: Store arguments directly and change \a MDExpression to store a
1856   /// range of these.
1857   class ExprOperand {
1858     const uint64_t *Op;
1859
1860   public:
1861     explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
1862
1863     const uint64_t *get() const { return Op; }
1864
1865     /// \brief Get the operand code.
1866     uint64_t getOp() const { return *Op; }
1867
1868     /// \brief Get an argument to the operand.
1869     ///
1870     /// Never returns the operand itself.
1871     uint64_t getArg(unsigned I) const { return Op[I + 1]; }
1872
1873     unsigned getNumArgs() const { return getSize() - 1; }
1874
1875     /// \brief Return the size of the operand.
1876     ///
1877     /// Return the number of elements in the operand (1 + args).
1878     unsigned getSize() const;
1879   };
1880
1881   /// \brief An iterator for expression operands.
1882   class expr_op_iterator
1883       : public std::iterator<std::input_iterator_tag, ExprOperand> {
1884     ExprOperand Op;
1885
1886   public:
1887     explicit expr_op_iterator(element_iterator I) : Op(I) {}
1888
1889     element_iterator getBase() const { return Op.get(); }
1890     const ExprOperand &operator*() const { return Op; }
1891     const ExprOperand *operator->() const { return &Op; }
1892
1893     expr_op_iterator &operator++() {
1894       increment();
1895       return *this;
1896     }
1897     expr_op_iterator operator++(int) {
1898       expr_op_iterator T(*this);
1899       increment();
1900       return T;
1901     }
1902
1903     /// \brief Get the next iterator.
1904     ///
1905     /// \a std::next() doesn't work because this is technically an
1906     /// input_iterator, but it's a perfectly valid operation.  This is an
1907     /// accessor to provide the same functionality.
1908     expr_op_iterator getNext() const { return ++expr_op_iterator(*this); }
1909
1910     bool operator==(const expr_op_iterator &X) const {
1911       return getBase() == X.getBase();
1912     }
1913     bool operator!=(const expr_op_iterator &X) const {
1914       return getBase() != X.getBase();
1915     }
1916
1917   private:
1918     void increment() { Op = ExprOperand(getBase() + Op.getSize()); }
1919   };
1920
1921   /// \brief Visit the elements via ExprOperand wrappers.
1922   ///
1923   /// These range iterators visit elements through \a ExprOperand wrappers.
1924   /// This is not guaranteed to be a valid range unless \a isValid() gives \c
1925   /// true.
1926   ///
1927   /// \pre \a isValid() gives \c true.
1928   /// @{
1929   expr_op_iterator expr_op_begin() const {
1930     return expr_op_iterator(elements_begin());
1931   }
1932   expr_op_iterator expr_op_end() const {
1933     return expr_op_iterator(elements_end());
1934   }
1935   /// @}
1936
1937   bool isValid() const;
1938
1939   static bool classof(const Metadata *MD) {
1940     return MD->getMetadataID() == MDExpressionKind;
1941   }
1942 };
1943
1944 class MDObjCProperty : public DebugNode {
1945   friend class LLVMContextImpl;
1946   friend class MDNode;
1947
1948   unsigned Line;
1949   unsigned Attributes;
1950
1951   MDObjCProperty(LLVMContext &C, StorageType Storage, unsigned Line,
1952                  unsigned Attributes, ArrayRef<Metadata *> Ops)
1953       : DebugNode(C, MDObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property,
1954                   Ops),
1955         Line(Line), Attributes(Attributes) {}
1956   ~MDObjCProperty() {}
1957
1958   static MDObjCProperty *
1959   getImpl(LLVMContext &Context, StringRef Name, MDFile *File, unsigned Line,
1960           StringRef GetterName, StringRef SetterName, unsigned Attributes,
1961           MDType *Type, StorageType Storage, bool ShouldCreate = true) {
1962     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
1963                    getCanonicalMDString(Context, GetterName),
1964                    getCanonicalMDString(Context, SetterName), Attributes, Type,
1965                    Storage, ShouldCreate);
1966   }
1967   static MDObjCProperty *getImpl(LLVMContext &Context, MDString *Name,
1968                                  Metadata *File, unsigned Line,
1969                                  MDString *GetterName, MDString *SetterName,
1970                                  unsigned Attributes, Metadata *Type,
1971                                  StorageType Storage, bool ShouldCreate = true);
1972
1973   TempMDObjCProperty cloneImpl() const {
1974     return getTemporary(getContext(), getName(), getFile(), getLine(),
1975                         getGetterName(), getSetterName(), getAttributes(),
1976                         getType());
1977   }
1978
1979 public:
1980   DEFINE_MDNODE_GET(MDObjCProperty,
1981                     (StringRef Name, MDFile *File, unsigned Line,
1982                      StringRef GetterName, StringRef SetterName,
1983                      unsigned Attributes, MDType *Type),
1984                     (Name, File, Line, GetterName, SetterName, Attributes,
1985                      Type))
1986   DEFINE_MDNODE_GET(MDObjCProperty,
1987                     (MDString * Name, Metadata *File, unsigned Line,
1988                      MDString *GetterName, MDString *SetterName,
1989                      unsigned Attributes, Metadata *Type),
1990                     (Name, File, Line, GetterName, SetterName, Attributes,
1991                      Type))
1992
1993   TempMDObjCProperty clone() const { return cloneImpl(); }
1994
1995   unsigned getLine() const { return Line; }
1996   unsigned getAttributes() const { return Attributes; }
1997   StringRef getName() const { return getStringOperand(0); }
1998   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
1999   StringRef getGetterName() const { return getStringOperand(2); }
2000   StringRef getSetterName() const { return getStringOperand(3); }
2001   MDType *getType() const { return cast_or_null<MDType>(getRawType()); }
2002
2003   MDString *getRawName() const { return getOperandAs<MDString>(0); }
2004   Metadata *getRawFile() const { return getOperand(1); }
2005   MDString *getRawGetterName() const { return getOperandAs<MDString>(2); }
2006   MDString *getRawSetterName() const { return getOperandAs<MDString>(3); }
2007   Metadata *getRawType() const { return getOperand(4); }
2008
2009   static bool classof(const Metadata *MD) {
2010     return MD->getMetadataID() == MDObjCPropertyKind;
2011   }
2012 };
2013
2014 class MDImportedEntity : public DebugNode {
2015   friend class LLVMContextImpl;
2016   friend class MDNode;
2017
2018   unsigned Line;
2019
2020   MDImportedEntity(LLVMContext &C, StorageType Storage, unsigned Tag,
2021                    unsigned Line, ArrayRef<Metadata *> Ops)
2022       : DebugNode(C, MDImportedEntityKind, Storage, Tag, Ops), Line(Line) {}
2023   ~MDImportedEntity() {}
2024
2025   static MDImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2026                                    MDScope *Scope, DebugNodeRef Entity,
2027                                    unsigned Line, StringRef Name,
2028                                    StorageType Storage,
2029                                    bool ShouldCreate = true) {
2030     return getImpl(Context, Tag, Scope, Entity, Line,
2031                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
2032   }
2033   static MDImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2034                                    Metadata *Scope, Metadata *Entity,
2035                                    unsigned Line, MDString *Name,
2036                                    StorageType Storage,
2037                                    bool ShouldCreate = true);
2038
2039   TempMDImportedEntity cloneImpl() const {
2040     return getTemporary(getContext(), getTag(), getScope(), getEntity(),
2041                         getLine(), getName());
2042   }
2043
2044 public:
2045   DEFINE_MDNODE_GET(MDImportedEntity,
2046                     (unsigned Tag, MDScope *Scope, DebugNodeRef Entity,
2047                      unsigned Line, StringRef Name = ""),
2048                     (Tag, Scope, Entity, Line, Name))
2049   DEFINE_MDNODE_GET(MDImportedEntity,
2050                     (unsigned Tag, Metadata *Scope, Metadata *Entity,
2051                      unsigned Line, MDString *Name),
2052                     (Tag, Scope, Entity, Line, Name))
2053
2054   TempMDImportedEntity clone() const { return cloneImpl(); }
2055
2056   unsigned getLine() const { return Line; }
2057   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
2058   DebugNodeRef getEntity() const { return DebugNodeRef(getRawEntity()); }
2059   StringRef getName() const { return getStringOperand(2); }
2060
2061   Metadata *getRawScope() const { return getOperand(0); }
2062   Metadata *getRawEntity() const { return getOperand(1); }
2063   MDString *getRawName() const { return getOperandAs<MDString>(2); }
2064
2065   static bool classof(const Metadata *MD) {
2066     return MD->getMetadataID() == MDImportedEntityKind;
2067   }
2068 };
2069
2070 } // end namespace llvm
2071
2072 #undef DEFINE_MDNODE_GET_UNPACK_IMPL
2073 #undef DEFINE_MDNODE_GET_UNPACK
2074 #undef DEFINE_MDNODE_GET
2075
2076 #endif