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