DebugInfo: Remove constructors for DIRef<>
[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() {}
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() {}
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() {}
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() {}
415
416 public:
417   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
418
419   /// \brief Return the raw underlying file.
420   ///
421   /// An \a MDFile is an \a MDScope, but it doesn't point at a separate file
422   /// (it\em is the file).  If \c this is an \a MDFile, we need to return \c
423   /// this.  Otherwise, return the first operand, which is where all other
424   /// subclasses store their file pointer.
425   Metadata *getRawFile() const {
426     return isa<MDFile>(this) ? const_cast<MDScope *>(this)
427                              : static_cast<Metadata *>(getOperand(0));
428   }
429
430   MDScopeRef getRef() const { return MDScopeRef::get(this); }
431
432   static bool classof(const Metadata *MD) {
433     switch (MD->getMetadataID()) {
434     default:
435       return false;
436     case MDBasicTypeKind:
437     case MDDerivedTypeKind:
438     case MDCompositeTypeKind:
439     case MDSubroutineTypeKind:
440     case MDFileKind:
441     case MDCompileUnitKind:
442     case MDSubprogramKind:
443     case MDLexicalBlockKind:
444     case MDLexicalBlockFileKind:
445     case MDNamespaceKind:
446       return true;
447     }
448   }
449 };
450
451 /// \brief File.
452 ///
453 /// TODO: Merge with directory/file node (including users).
454 /// TODO: Canonicalize paths on creation.
455 class MDFile : public MDScope {
456   friend class LLVMContextImpl;
457   friend class MDNode;
458
459   MDFile(LLVMContext &C, StorageType Storage, ArrayRef<Metadata *> Ops)
460       : MDScope(C, MDFileKind, Storage, dwarf::DW_TAG_file_type, Ops) {}
461   ~MDFile() {}
462
463   static MDFile *getImpl(LLVMContext &Context, StringRef Filename,
464                          StringRef Directory, StorageType Storage,
465                          bool ShouldCreate = true) {
466     return getImpl(Context, getCanonicalMDString(Context, Filename),
467                    getCanonicalMDString(Context, Directory), Storage,
468                    ShouldCreate);
469   }
470   static MDFile *getImpl(LLVMContext &Context, MDString *Filename,
471                          MDString *Directory, StorageType Storage,
472                          bool ShouldCreate = true);
473
474   TempMDFile cloneImpl() const {
475     return getTemporary(getContext(), getFilename(), getDirectory());
476   }
477
478 public:
479   DEFINE_MDNODE_GET(MDFile, (StringRef Filename, StringRef Directory),
480                     (Filename, Directory))
481   DEFINE_MDNODE_GET(MDFile, (MDString * Filename, MDString *Directory),
482                     (Filename, Directory))
483
484   TempMDFile clone() const { return cloneImpl(); }
485
486   StringRef getFilename() const { return getStringOperand(0); }
487   StringRef getDirectory() const { return getStringOperand(1); }
488
489   MDString *getRawFilename() const { return getOperandAs<MDString>(0); }
490   MDString *getRawDirectory() const { return getOperandAs<MDString>(1); }
491
492   static bool classof(const Metadata *MD) {
493     return MD->getMetadataID() == MDFileKind;
494   }
495 };
496
497 /// \brief Base class for types.
498 ///
499 /// TODO: Remove the hardcoded name and context, since many types don't use
500 /// them.
501 /// TODO: Split up flags.
502 class MDType : public MDScope {
503   unsigned Line;
504   unsigned Flags;
505   uint64_t SizeInBits;
506   uint64_t AlignInBits;
507   uint64_t OffsetInBits;
508
509 protected:
510   MDType(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
511          unsigned Line, uint64_t SizeInBits, uint64_t AlignInBits,
512          uint64_t OffsetInBits, unsigned Flags, ArrayRef<Metadata *> Ops)
513       : MDScope(C, ID, Storage, Tag, Ops), Line(Line), Flags(Flags),
514         SizeInBits(SizeInBits), AlignInBits(AlignInBits),
515         OffsetInBits(OffsetInBits) {}
516   ~MDType() {}
517
518 public:
519   TempMDType clone() const {
520     return TempMDType(cast<MDType>(MDNode::clone().release()));
521   }
522
523   unsigned getLine() const { return Line; }
524   uint64_t getSizeInBits() const { return SizeInBits; }
525   uint64_t getAlignInBits() const { return AlignInBits; }
526   uint64_t getOffsetInBits() const { return OffsetInBits; }
527   unsigned getFlags() const { return Flags; }
528
529   MDScopeRef getScope() const { return MDScopeRef(getRawScope()); }
530   StringRef getName() const { return getStringOperand(2); }
531
532
533   Metadata *getRawScope() const { return getOperand(1); }
534   MDString *getRawName() const { return getOperandAs<MDString>(2); }
535
536   void setFlags(unsigned NewFlags) {
537     assert(!isUniqued() && "Cannot set flags on uniqued nodes");
538     Flags = NewFlags;
539   }
540
541   bool isPrivate() const {
542     return (getFlags() & FlagAccessibility) == FlagPrivate;
543   }
544   bool isProtected() const {
545     return (getFlags() & FlagAccessibility) == FlagProtected;
546   }
547   bool isPublic() const {
548     return (getFlags() & FlagAccessibility) == FlagPublic;
549   }
550   bool isForwardDecl() const { return getFlags() & FlagFwdDecl; }
551   bool isAppleBlockExtension() const { return getFlags() & FlagAppleBlock; }
552   bool isBlockByrefStruct() const { return getFlags() & FlagBlockByrefStruct; }
553   bool isVirtual() const { return getFlags() & FlagVirtual; }
554   bool isArtificial() const { return getFlags() & FlagArtificial; }
555   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
556   bool isObjcClassComplete() const {
557     return getFlags() & FlagObjcClassComplete;
558   }
559   bool isVector() const { return getFlags() & FlagVector; }
560   bool isStaticMember() const { return getFlags() & FlagStaticMember; }
561   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
562   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
563
564   MDTypeRef getRef() const { return MDTypeRef::get(this); }
565
566   static bool classof(const Metadata *MD) {
567     switch (MD->getMetadataID()) {
568     default:
569       return false;
570     case MDBasicTypeKind:
571     case MDDerivedTypeKind:
572     case MDCompositeTypeKind:
573     case MDSubroutineTypeKind:
574       return true;
575     }
576   }
577 };
578
579 /// \brief Basic type.
580 ///
581 /// TODO: Split out DW_TAG_unspecified_type.
582 /// TODO: Drop unused accessors.
583 class MDBasicType : public MDType {
584   friend class LLVMContextImpl;
585   friend class MDNode;
586
587   unsigned Encoding;
588
589   MDBasicType(LLVMContext &C, StorageType Storage, unsigned Tag,
590               uint64_t SizeInBits, uint64_t AlignInBits, unsigned Encoding,
591               ArrayRef<Metadata *> Ops)
592       : MDType(C, MDBasicTypeKind, Storage, Tag, 0, SizeInBits, AlignInBits, 0,
593                0, Ops),
594         Encoding(Encoding) {}
595   ~MDBasicType() {}
596
597   static MDBasicType *getImpl(LLVMContext &Context, unsigned Tag,
598                               StringRef Name, uint64_t SizeInBits,
599                               uint64_t AlignInBits, unsigned Encoding,
600                               StorageType Storage, bool ShouldCreate = true) {
601     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
602                    SizeInBits, AlignInBits, Encoding, Storage, ShouldCreate);
603   }
604   static MDBasicType *getImpl(LLVMContext &Context, unsigned Tag,
605                               MDString *Name, uint64_t SizeInBits,
606                               uint64_t AlignInBits, unsigned Encoding,
607                               StorageType Storage, bool ShouldCreate = true);
608
609   TempMDBasicType cloneImpl() const {
610     return getTemporary(getContext(), getTag(), getName(), getSizeInBits(),
611                         getAlignInBits(), getEncoding());
612   }
613
614 public:
615   DEFINE_MDNODE_GET(MDBasicType, (unsigned Tag, StringRef Name),
616                     (Tag, Name, 0, 0, 0))
617   DEFINE_MDNODE_GET(MDBasicType,
618                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
619                      uint64_t AlignInBits, unsigned Encoding),
620                     (Tag, Name, SizeInBits, AlignInBits, Encoding))
621   DEFINE_MDNODE_GET(MDBasicType,
622                     (unsigned Tag, MDString *Name, uint64_t SizeInBits,
623                      uint64_t AlignInBits, unsigned Encoding),
624                     (Tag, Name, SizeInBits, AlignInBits, Encoding))
625
626   TempMDBasicType clone() const { return cloneImpl(); }
627
628   unsigned getEncoding() const { return Encoding; }
629
630   static bool classof(const Metadata *MD) {
631     return MD->getMetadataID() == MDBasicTypeKind;
632   }
633 };
634
635 /// \brief Base class for MDDerivedType and MDCompositeType.
636 ///
637 /// TODO: Delete; they're not really related.
638 class MDDerivedTypeBase : public MDType {
639 protected:
640   MDDerivedTypeBase(LLVMContext &C, unsigned ID, StorageType Storage,
641                     unsigned Tag, unsigned Line, uint64_t SizeInBits,
642                     uint64_t AlignInBits, uint64_t OffsetInBits, unsigned Flags,
643                     ArrayRef<Metadata *> Ops)
644       : MDType(C, ID, Storage, Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
645                Flags, Ops) {}
646   ~MDDerivedTypeBase() {}
647
648 public:
649   MDTypeRef getBaseType() const { return MDTypeRef(getRawBaseType()); }
650   Metadata *getRawBaseType() const { return getOperand(3); }
651
652   static bool classof(const Metadata *MD) {
653     return MD->getMetadataID() == MDDerivedTypeKind ||
654            MD->getMetadataID() == MDCompositeTypeKind ||
655            MD->getMetadataID() == MDSubroutineTypeKind;
656   }
657 };
658
659 /// \brief Derived types.
660 ///
661 /// This includes qualified types, pointers, references, friends, typedefs, and
662 /// class members.
663 ///
664 /// TODO: Split out members (inheritance, fields, methods, etc.).
665 class MDDerivedType : public MDDerivedTypeBase {
666   friend class LLVMContextImpl;
667   friend class MDNode;
668
669   MDDerivedType(LLVMContext &C, StorageType Storage, unsigned Tag,
670                 unsigned Line, uint64_t SizeInBits, uint64_t AlignInBits,
671                 uint64_t OffsetInBits, unsigned Flags, ArrayRef<Metadata *> Ops)
672       : MDDerivedTypeBase(C, MDDerivedTypeKind, Storage, Tag, Line, SizeInBits,
673                           AlignInBits, OffsetInBits, Flags, Ops) {}
674   ~MDDerivedType() {}
675
676   static MDDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
677                                 StringRef Name, MDFile *File, unsigned Line,
678                                 MDScopeRef Scope, MDTypeRef BaseType,
679                                 uint64_t SizeInBits, uint64_t AlignInBits,
680                                 uint64_t OffsetInBits, unsigned Flags,
681                                 Metadata *ExtraData, StorageType Storage,
682                                 bool ShouldCreate = true) {
683     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
684                    Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits,
685                    Flags, ExtraData, Storage, ShouldCreate);
686   }
687   static MDDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
688                                 MDString *Name, Metadata *File, unsigned Line,
689                                 Metadata *Scope, Metadata *BaseType,
690                                 uint64_t SizeInBits, uint64_t AlignInBits,
691                                 uint64_t OffsetInBits, unsigned Flags,
692                                 Metadata *ExtraData, StorageType Storage,
693                                 bool ShouldCreate = true);
694
695   TempMDDerivedType cloneImpl() const {
696     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
697                         getScope(), getBaseType(), getSizeInBits(),
698                         getAlignInBits(), getOffsetInBits(), getFlags(),
699                         getExtraData());
700   }
701
702 public:
703   DEFINE_MDNODE_GET(MDDerivedType,
704                     (unsigned Tag, MDString *Name, Metadata *File,
705                      unsigned Line, Metadata *Scope, Metadata *BaseType,
706                      uint64_t SizeInBits, uint64_t AlignInBits,
707                      uint64_t OffsetInBits, unsigned Flags,
708                      Metadata *ExtraData = nullptr),
709                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
710                      AlignInBits, OffsetInBits, Flags, ExtraData))
711   DEFINE_MDNODE_GET(MDDerivedType,
712                     (unsigned Tag, StringRef Name, MDFile *File, unsigned Line,
713                      MDScopeRef Scope, MDTypeRef BaseType, uint64_t SizeInBits,
714                      uint64_t AlignInBits, uint64_t OffsetInBits,
715                      unsigned Flags, Metadata *ExtraData = nullptr),
716                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
717                      AlignInBits, OffsetInBits, Flags, ExtraData))
718
719   TempMDDerivedType clone() const { return cloneImpl(); }
720
721   /// \brief Get extra data associated with this derived type.
722   ///
723   /// Class type for pointer-to-members, objective-c property node for ivars,
724   /// or global constant wrapper for static members.
725   ///
726   /// TODO: Separate out types that need this extra operand: pointer-to-member
727   /// types and member fields (static members and ivars).
728   Metadata *getExtraData() const { return getRawExtraData(); }
729   Metadata *getRawExtraData() const { return getOperand(4); }
730
731   static bool classof(const Metadata *MD) {
732     return MD->getMetadataID() == MDDerivedTypeKind;
733   }
734 };
735
736 /// \brief Base class for MDCompositeType and MDSubroutineType.
737 ///
738 /// TODO: Delete; they're not really related.
739 class MDCompositeTypeBase : public MDDerivedTypeBase {
740   unsigned RuntimeLang;
741
742 protected:
743   MDCompositeTypeBase(LLVMContext &C, unsigned ID, StorageType Storage,
744                       unsigned Tag, unsigned Line, unsigned RuntimeLang,
745                       uint64_t SizeInBits, uint64_t AlignInBits,
746                       uint64_t OffsetInBits, unsigned Flags,
747                       ArrayRef<Metadata *> Ops)
748       : MDDerivedTypeBase(C, ID, Storage, Tag, Line, SizeInBits, AlignInBits,
749                           OffsetInBits, Flags, Ops),
750         RuntimeLang(RuntimeLang) {}
751   ~MDCompositeTypeBase() {}
752
753 public:
754   DebugNodeArray getElements() const {
755     return cast_or_null<MDTuple>(getRawElements());
756   }
757   MDTypeRef getVTableHolder() const { return MDTypeRef(getRawVTableHolder()); }
758   MDTemplateParameterArray getTemplateParams() const {
759     return cast_or_null<MDTuple>(getRawTemplateParams());
760   }
761   StringRef getIdentifier() const { return getStringOperand(7); }
762   unsigned getRuntimeLang() const { return RuntimeLang; }
763
764   Metadata *getRawElements() const { return getOperand(4); }
765   Metadata *getRawVTableHolder() const { return getOperand(5); }
766   Metadata *getRawTemplateParams() const { return getOperand(6); }
767   MDString *getRawIdentifier() const { return getOperandAs<MDString>(7); }
768
769   /// \brief Replace operands.
770   ///
771   /// If this \a isUniqued() and not \a isResolved(), on a uniquing collision
772   /// this will be RAUW'ed and deleted.  Use a \a TrackingMDRef to keep track
773   /// of its movement if necessary.
774   /// @{
775   void replaceElements(DebugNodeArray Elements) {
776 #ifndef NDEBUG
777     for (DebugNode *Op : getElements())
778       assert(std::find(Elements->op_begin(), Elements->op_end(), Op) &&
779              "Lost a member during member list replacement");
780 #endif
781     replaceOperandWith(4, Elements.get());
782   }
783   void replaceVTableHolder(MDTypeRef VTableHolder) {
784     replaceOperandWith(5, VTableHolder);
785   }
786   void replaceTemplateParams(MDTemplateParameterArray TemplateParams) {
787     replaceOperandWith(6, TemplateParams.get());
788   }
789   /// @}
790
791   static bool classof(const Metadata *MD) {
792     return MD->getMetadataID() == MDCompositeTypeKind ||
793            MD->getMetadataID() == MDSubroutineTypeKind;
794   }
795 };
796
797 /// \brief Composite types.
798 ///
799 /// TODO: Detach from DerivedTypeBase (split out MDEnumType?).
800 /// TODO: Create a custom, unrelated node for DW_TAG_array_type.
801 class MDCompositeType : public MDCompositeTypeBase {
802   friend class LLVMContextImpl;
803   friend class MDNode;
804
805   MDCompositeType(LLVMContext &C, StorageType Storage, unsigned Tag,
806                   unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits,
807                   uint64_t AlignInBits, uint64_t OffsetInBits, unsigned Flags,
808                   ArrayRef<Metadata *> Ops)
809       : MDCompositeTypeBase(C, MDCompositeTypeKind, Storage, Tag, Line,
810                             RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
811                             Flags, Ops) {}
812   ~MDCompositeType() {}
813
814   static MDCompositeType *
815   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, Metadata *File,
816           unsigned Line, MDScopeRef Scope, MDTypeRef BaseType,
817           uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
818           uint64_t Flags, DebugNodeArray Elements, unsigned RuntimeLang,
819           MDTypeRef VTableHolder, MDTemplateParameterArray TemplateParams,
820           StringRef Identifier, StorageType Storage, bool ShouldCreate = true) {
821     return getImpl(
822         Context, Tag, getCanonicalMDString(Context, Name), File, Line, Scope,
823         BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements.get(),
824         RuntimeLang, VTableHolder, TemplateParams.get(),
825         getCanonicalMDString(Context, Identifier), Storage, ShouldCreate);
826   }
827   static MDCompositeType *
828   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
829           unsigned Line, Metadata *Scope, Metadata *BaseType,
830           uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
831           unsigned Flags, Metadata *Elements, unsigned RuntimeLang,
832           Metadata *VTableHolder, Metadata *TemplateParams,
833           MDString *Identifier, StorageType Storage, bool ShouldCreate = true);
834
835   TempMDCompositeType cloneImpl() const {
836     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
837                         getScope(), getBaseType(), getSizeInBits(),
838                         getAlignInBits(), getOffsetInBits(), getFlags(),
839                         getElements(), getRuntimeLang(), getVTableHolder(),
840                         getTemplateParams(), getIdentifier());
841   }
842
843 public:
844   DEFINE_MDNODE_GET(MDCompositeType,
845                     (unsigned Tag, StringRef Name, MDFile *File, unsigned Line,
846                      MDScopeRef Scope, MDTypeRef BaseType, uint64_t SizeInBits,
847                      uint64_t AlignInBits, uint64_t OffsetInBits,
848                      unsigned Flags, DebugNodeArray Elements,
849                      unsigned RuntimeLang, MDTypeRef VTableHolder,
850                      MDTemplateParameterArray TemplateParams = nullptr,
851                      StringRef Identifier = ""),
852                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
853                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
854                      VTableHolder, TemplateParams, Identifier))
855   DEFINE_MDNODE_GET(MDCompositeType,
856                     (unsigned Tag, MDString *Name, Metadata *File,
857                      unsigned Line, Metadata *Scope, Metadata *BaseType,
858                      uint64_t SizeInBits, uint64_t AlignInBits,
859                      uint64_t OffsetInBits, unsigned Flags, Metadata *Elements,
860                      unsigned RuntimeLang, Metadata *VTableHolder,
861                      Metadata *TemplateParams = nullptr,
862                      MDString *Identifier = nullptr),
863                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
864                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
865                      VTableHolder, TemplateParams, Identifier))
866
867   TempMDCompositeType clone() const { return cloneImpl(); }
868
869   static bool classof(const Metadata *MD) {
870     return MD->getMetadataID() == MDCompositeTypeKind;
871   }
872 };
873
874 template <class T> TypedDebugNodeRef<T> TypedDebugNodeRef<T>::get(const T *N) {
875   if (N)
876     if (auto *Composite = dyn_cast<MDCompositeType>(N))
877       if (auto *S = Composite->getRawIdentifier())
878         return TypedDebugNodeRef<T>(S);
879   return TypedDebugNodeRef<T>(N);
880 }
881
882 /// \brief Type array for a subprogram.
883 ///
884 /// TODO: Detach from CompositeType, and fold the array of types in directly
885 /// as operands.
886 class MDSubroutineType : public MDCompositeTypeBase {
887   friend class LLVMContextImpl;
888   friend class MDNode;
889
890   MDSubroutineType(LLVMContext &C, StorageType Storage, unsigned Flags,
891                    ArrayRef<Metadata *> Ops)
892       : MDCompositeTypeBase(C, MDSubroutineTypeKind, Storage,
893                             dwarf::DW_TAG_subroutine_type, 0, 0, 0, 0, 0, Flags,
894                             Ops) {}
895   ~MDSubroutineType() {}
896
897   static MDSubroutineType *getImpl(LLVMContext &Context, unsigned Flags,
898                                    MDTypeRefArray TypeArray,
899                                    StorageType Storage,
900                                    bool ShouldCreate = true) {
901     return getImpl(Context, Flags, TypeArray.get(), Storage, ShouldCreate);
902   }
903   static MDSubroutineType *getImpl(LLVMContext &Context, unsigned Flags,
904                                    Metadata *TypeArray, StorageType Storage,
905                                    bool ShouldCreate = true);
906
907   TempMDSubroutineType cloneImpl() const {
908     return getTemporary(getContext(), getFlags(), getTypeArray());
909   }
910
911 public:
912   DEFINE_MDNODE_GET(MDSubroutineType,
913                     (unsigned Flags, MDTypeRefArray TypeArray),
914                     (Flags, TypeArray))
915   DEFINE_MDNODE_GET(MDSubroutineType, (unsigned Flags, Metadata *TypeArray),
916                     (Flags, TypeArray))
917
918   TempMDSubroutineType clone() const { return cloneImpl(); }
919
920   MDTypeRefArray getTypeArray() const {
921     return cast_or_null<MDTuple>(getRawTypeArray());
922   }
923   Metadata *getRawTypeArray() const { return getRawElements(); }
924
925   static bool classof(const Metadata *MD) {
926     return MD->getMetadataID() == MDSubroutineTypeKind;
927   }
928 };
929
930 /// \brief Compile unit.
931 class MDCompileUnit : public MDScope {
932   friend class LLVMContextImpl;
933   friend class MDNode;
934
935   unsigned SourceLanguage;
936   bool IsOptimized;
937   unsigned RuntimeVersion;
938   unsigned EmissionKind;
939
940   MDCompileUnit(LLVMContext &C, StorageType Storage, unsigned SourceLanguage,
941                 bool IsOptimized, unsigned RuntimeVersion,
942                 unsigned EmissionKind, ArrayRef<Metadata *> Ops)
943       : MDScope(C, MDCompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
944         SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
945         RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind) {}
946   ~MDCompileUnit() {}
947
948   static MDCompileUnit *
949   getImpl(LLVMContext &Context, unsigned SourceLanguage, MDFile *File,
950           StringRef Producer, bool IsOptimized, StringRef Flags,
951           unsigned RuntimeVersion, StringRef SplitDebugFilename,
952           unsigned EmissionKind, MDCompositeTypeArray EnumTypes,
953           MDTypeArray RetainedTypes, MDSubprogramArray Subprograms,
954           MDGlobalVariableArray GlobalVariables,
955           MDImportedEntityArray ImportedEntities, StorageType Storage,
956           bool ShouldCreate = true) {
957     return getImpl(
958         Context, SourceLanguage, File, getCanonicalMDString(Context, Producer),
959         IsOptimized, getCanonicalMDString(Context, Flags), RuntimeVersion,
960         getCanonicalMDString(Context, SplitDebugFilename), EmissionKind,
961         EnumTypes.get(), RetainedTypes.get(), Subprograms.get(),
962         GlobalVariables.get(), ImportedEntities.get(), Storage, ShouldCreate);
963   }
964   static MDCompileUnit *
965   getImpl(LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
966           MDString *Producer, bool IsOptimized, MDString *Flags,
967           unsigned RuntimeVersion, MDString *SplitDebugFilename,
968           unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
969           Metadata *Subprograms, Metadata *GlobalVariables,
970           Metadata *ImportedEntities, StorageType Storage,
971           bool ShouldCreate = true);
972
973   TempMDCompileUnit cloneImpl() const {
974     return getTemporary(
975         getContext(), getSourceLanguage(), getFile(), getProducer(),
976         isOptimized(), getFlags(), getRuntimeVersion(), getSplitDebugFilename(),
977         getEmissionKind(), getEnumTypes(), getRetainedTypes(), getSubprograms(),
978         getGlobalVariables(), getImportedEntities());
979   }
980
981 public:
982   DEFINE_MDNODE_GET(MDCompileUnit,
983                     (unsigned SourceLanguage, MDFile *File, StringRef Producer,
984                      bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
985                      StringRef SplitDebugFilename, unsigned EmissionKind,
986                      MDCompositeTypeArray EnumTypes, MDTypeArray RetainedTypes,
987                      MDSubprogramArray Subprograms,
988                      MDGlobalVariableArray GlobalVariables,
989                      MDImportedEntityArray ImportedEntities),
990                     (SourceLanguage, File, Producer, IsOptimized, Flags,
991                      RuntimeVersion, SplitDebugFilename, EmissionKind,
992                      EnumTypes, RetainedTypes, Subprograms, GlobalVariables,
993                      ImportedEntities))
994   DEFINE_MDNODE_GET(MDCompileUnit,
995                     (unsigned SourceLanguage, Metadata *File,
996                      MDString *Producer, bool IsOptimized, MDString *Flags,
997                      unsigned RuntimeVersion, MDString *SplitDebugFilename,
998                      unsigned EmissionKind, Metadata *EnumTypes,
999                      Metadata *RetainedTypes, Metadata *Subprograms,
1000                      Metadata *GlobalVariables, Metadata *ImportedEntities),
1001                     (SourceLanguage, File, Producer, IsOptimized, Flags,
1002                      RuntimeVersion, SplitDebugFilename, EmissionKind,
1003                      EnumTypes, RetainedTypes, Subprograms, GlobalVariables,
1004                      ImportedEntities))
1005
1006   TempMDCompileUnit clone() const { return cloneImpl(); }
1007
1008   unsigned getSourceLanguage() const { return SourceLanguage; }
1009   bool isOptimized() const { return IsOptimized; }
1010   unsigned getRuntimeVersion() const { return RuntimeVersion; }
1011   unsigned getEmissionKind() const { return EmissionKind; }
1012   StringRef getProducer() const { return getStringOperand(1); }
1013   StringRef getFlags() const { return getStringOperand(2); }
1014   StringRef getSplitDebugFilename() const { return getStringOperand(3); }
1015   MDCompositeTypeArray getEnumTypes() const {
1016     return cast_or_null<MDTuple>(getRawEnumTypes());
1017   }
1018   MDTypeArray getRetainedTypes() const {
1019     return cast_or_null<MDTuple>(getRawRetainedTypes());
1020   }
1021   MDSubprogramArray getSubprograms() const {
1022     return cast_or_null<MDTuple>(getRawSubprograms());
1023   }
1024   MDGlobalVariableArray getGlobalVariables() const {
1025     return cast_or_null<MDTuple>(getRawGlobalVariables());
1026   }
1027   MDImportedEntityArray getImportedEntities() const {
1028     return cast_or_null<MDTuple>(getRawImportedEntities());
1029   }
1030
1031   MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
1032   MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
1033   MDString *getRawSplitDebugFilename() const {
1034     return getOperandAs<MDString>(3);
1035   }
1036   Metadata *getRawEnumTypes() const { return getOperand(4); }
1037   Metadata *getRawRetainedTypes() const { return getOperand(5); }
1038   Metadata *getRawSubprograms() const { return getOperand(6); }
1039   Metadata *getRawGlobalVariables() const { return getOperand(7); }
1040   Metadata *getRawImportedEntities() const { return getOperand(8); }
1041
1042   /// \brief Replace arrays.
1043   ///
1044   /// If this \a isUniqued() and not \a isResolved(), it will be RAUW'ed and
1045   /// deleted on a uniquing collision.  In practice, uniquing collisions on \a
1046   /// MDCompileUnit should be fairly rare.
1047   /// @{
1048   void replaceSubprograms(MDSubprogramArray N) {
1049     replaceOperandWith(6, N.get());
1050   }
1051   void replaceGlobalVariables(MDGlobalVariableArray N) {
1052     replaceOperandWith(7, N.get());
1053   }
1054   /// @}
1055
1056   static bool classof(const Metadata *MD) {
1057     return MD->getMetadataID() == MDCompileUnitKind;
1058   }
1059 };
1060
1061 /// \brief A scope for locals.
1062 ///
1063 /// A legal scope for lexical blocks, local variables, and debug info
1064 /// locations.  Subclasses are \a MDSubprogram, \a MDLexicalBlock, and \a
1065 /// MDLexicalBlockFile.
1066 class MDLocalScope : public MDScope {
1067 protected:
1068   MDLocalScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1069                ArrayRef<Metadata *> Ops)
1070       : MDScope(C, ID, Storage, Tag, Ops) {}
1071   ~MDLocalScope() {}
1072
1073 public:
1074   /// \brief Get the subprogram for this scope.
1075   ///
1076   /// Return this if it's an \a MDSubprogram; otherwise, look up the scope
1077   /// chain.
1078   MDSubprogram *getSubprogram() const;
1079
1080   static bool classof(const Metadata *MD) {
1081     return MD->getMetadataID() == MDSubprogramKind ||
1082            MD->getMetadataID() == MDLexicalBlockKind ||
1083            MD->getMetadataID() == MDLexicalBlockFileKind;
1084   }
1085 };
1086
1087 /// \brief Debug location.
1088 ///
1089 /// A debug location in source code, used for debug info and otherwise.
1090 class MDLocation : public MDNode {
1091   friend class LLVMContextImpl;
1092   friend class MDNode;
1093
1094   MDLocation(LLVMContext &C, StorageType Storage, unsigned Line,
1095              unsigned Column, ArrayRef<Metadata *> MDs);
1096   ~MDLocation() { dropAllReferences(); }
1097
1098   static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
1099                              unsigned Column, Metadata *Scope,
1100                              Metadata *InlinedAt, StorageType Storage,
1101                              bool ShouldCreate = true);
1102   static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
1103                              unsigned Column, MDLocalScope *Scope,
1104                              MDLocation *InlinedAt, StorageType Storage,
1105                              bool ShouldCreate = true) {
1106     return getImpl(Context, Line, Column, static_cast<Metadata *>(Scope),
1107                    static_cast<Metadata *>(InlinedAt), Storage, ShouldCreate);
1108   }
1109
1110   TempMDLocation cloneImpl() const {
1111     return getTemporary(getContext(), getLine(), getColumn(), getScope(),
1112                         getInlinedAt());
1113   }
1114
1115   // Disallow replacing operands.
1116   void replaceOperandWith(unsigned I, Metadata *New) = delete;
1117
1118 public:
1119   DEFINE_MDNODE_GET(MDLocation,
1120                     (unsigned Line, unsigned Column, Metadata *Scope,
1121                      Metadata *InlinedAt = nullptr),
1122                     (Line, Column, Scope, InlinedAt))
1123   DEFINE_MDNODE_GET(MDLocation,
1124                     (unsigned Line, unsigned Column, MDLocalScope *Scope,
1125                      MDLocation *InlinedAt = nullptr),
1126                     (Line, Column, Scope, InlinedAt))
1127
1128   /// \brief Return a (temporary) clone of this.
1129   TempMDLocation clone() const { return cloneImpl(); }
1130
1131   unsigned getLine() const { return SubclassData32; }
1132   unsigned getColumn() const { return SubclassData16; }
1133   MDLocalScope *getScope() const {
1134     return cast<MDLocalScope>(getRawScope());
1135   }
1136   MDLocation *getInlinedAt() const {
1137     return cast_or_null<MDLocation>(getRawInlinedAt());
1138   }
1139
1140   /// \brief Get the scope where this is inlined.
1141   ///
1142   /// Walk through \a getInlinedAt() and return \a getScope() from the deepest
1143   /// location.
1144   MDLocalScope *getInlinedAtScope() const {
1145     if (auto *IA = getInlinedAt())
1146       return IA->getInlinedAtScope();
1147     return getScope();
1148   }
1149
1150   Metadata *getRawScope() const { return getOperand(0); }
1151   Metadata *getRawInlinedAt() const {
1152     if (getNumOperands() == 2)
1153       return getOperand(1);
1154     return nullptr;
1155   }
1156
1157   static bool classof(const Metadata *MD) {
1158     return MD->getMetadataID() == MDLocationKind;
1159   }
1160 };
1161
1162 /// \brief Subprogram description.
1163 ///
1164 /// TODO: Remove DisplayName.  It's always equal to Name.
1165 /// TODO: Split up flags.
1166 class MDSubprogram : public MDLocalScope {
1167   friend class LLVMContextImpl;
1168   friend class MDNode;
1169
1170   unsigned Line;
1171   unsigned ScopeLine;
1172   unsigned Virtuality;
1173   unsigned VirtualIndex;
1174   unsigned Flags;
1175   bool IsLocalToUnit;
1176   bool IsDefinition;
1177   bool IsOptimized;
1178
1179   MDSubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
1180                unsigned ScopeLine, unsigned Virtuality, unsigned VirtualIndex,
1181                unsigned Flags, bool IsLocalToUnit, bool IsDefinition,
1182                bool IsOptimized, ArrayRef<Metadata *> Ops)
1183       : MDLocalScope(C, MDSubprogramKind, Storage, dwarf::DW_TAG_subprogram,
1184                      Ops),
1185         Line(Line), ScopeLine(ScopeLine), Virtuality(Virtuality),
1186         VirtualIndex(VirtualIndex), Flags(Flags), IsLocalToUnit(IsLocalToUnit),
1187         IsDefinition(IsDefinition), IsOptimized(IsOptimized) {}
1188   ~MDSubprogram() {}
1189
1190   static MDSubprogram *
1191   getImpl(LLVMContext &Context, MDScopeRef Scope, StringRef Name,
1192           StringRef LinkageName, MDFile *File, unsigned Line,
1193           MDSubroutineType *Type, bool IsLocalToUnit, bool IsDefinition,
1194           unsigned ScopeLine, MDTypeRef ContainingType, unsigned Virtuality,
1195           unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1196           ConstantAsMetadata *Function, MDTemplateParameterArray TemplateParams,
1197           MDSubprogram *Declaration, MDLocalVariableArray Variables,
1198           StorageType Storage, bool ShouldCreate = true) {
1199     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1200                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1201                    IsLocalToUnit, IsDefinition, ScopeLine, ContainingType,
1202                    Virtuality, VirtualIndex, Flags, IsOptimized, Function,
1203                    TemplateParams.get(), Declaration, Variables.get(), Storage,
1204                    ShouldCreate);
1205   }
1206   static MDSubprogram *
1207   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1208           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1209           bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1210           Metadata *ContainingType, unsigned Virtuality, unsigned VirtualIndex,
1211           unsigned Flags, bool IsOptimized, Metadata *Function,
1212           Metadata *TemplateParams, Metadata *Declaration, Metadata *Variables,
1213           StorageType Storage, bool ShouldCreate = true);
1214
1215   TempMDSubprogram cloneImpl() const {
1216     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1217                         getFile(), getLine(), getType(), isLocalToUnit(),
1218                         isDefinition(), getScopeLine(), getContainingType(),
1219                         getVirtuality(), getVirtualIndex(), getFlags(),
1220                         isOptimized(), getFunction(), getTemplateParams(),
1221                         getDeclaration(), getVariables());
1222   }
1223
1224 public:
1225   DEFINE_MDNODE_GET(MDSubprogram,
1226                     (MDScopeRef Scope, StringRef Name, StringRef LinkageName,
1227                      MDFile *File, unsigned Line, MDSubroutineType *Type,
1228                      bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1229                      MDTypeRef ContainingType, unsigned Virtuality,
1230                      unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1231                      ConstantAsMetadata *Function = nullptr,
1232                      MDTemplateParameterArray TemplateParams = nullptr,
1233                      MDSubprogram *Declaration = nullptr,
1234                      MDLocalVariableArray Variables = nullptr),
1235                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1236                      IsDefinition, ScopeLine, ContainingType, Virtuality,
1237                      VirtualIndex, Flags, IsOptimized, Function, TemplateParams,
1238                      Declaration, Variables))
1239   DEFINE_MDNODE_GET(
1240       MDSubprogram,
1241       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
1242        unsigned Line, Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
1243        unsigned ScopeLine, Metadata *ContainingType, unsigned Virtuality,
1244        unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1245        Metadata *Function = nullptr, Metadata *TemplateParams = nullptr,
1246        Metadata *Declaration = nullptr, Metadata *Variables = nullptr),
1247       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
1248        ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized,
1249        Function, TemplateParams, Declaration, Variables))
1250
1251   TempMDSubprogram clone() const { return cloneImpl(); }
1252
1253 public:
1254   unsigned getLine() const { return Line; }
1255   unsigned getVirtuality() const { return Virtuality; }
1256   unsigned getVirtualIndex() const { return VirtualIndex; }
1257   unsigned getScopeLine() const { return ScopeLine; }
1258   unsigned getFlags() const { return Flags; }
1259   bool isLocalToUnit() const { return IsLocalToUnit; }
1260   bool isDefinition() const { return IsDefinition; }
1261   bool isOptimized() const { return IsOptimized; }
1262
1263   unsigned isArtificial() const { return getFlags() & FlagArtificial; }
1264   bool isPrivate() const {
1265     return (getFlags() & FlagAccessibility) == FlagPrivate;
1266   }
1267   bool isProtected() const {
1268     return (getFlags() & FlagAccessibility) == FlagProtected;
1269   }
1270   bool isPublic() const {
1271     return (getFlags() & FlagAccessibility) == FlagPublic;
1272   }
1273   bool isExplicit() const { return getFlags() & FlagExplicit; }
1274   bool isPrototyped() const { return getFlags() & FlagPrototyped; }
1275
1276   /// \brief Check if this is reference-qualified.
1277   ///
1278   /// Return true if this subprogram is a C++11 reference-qualified non-static
1279   /// member function (void foo() &).
1280   unsigned isLValueReference() const {
1281     return getFlags() & FlagLValueReference;
1282   }
1283
1284   /// \brief Check if this is rvalue-reference-qualified.
1285   ///
1286   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
1287   /// non-static member function (void foo() &&).
1288   unsigned isRValueReference() const {
1289     return getFlags() & FlagRValueReference;
1290   }
1291
1292   MDScopeRef getScope() const { return MDScopeRef(getRawScope()); }
1293
1294   StringRef getName() const { return getStringOperand(2); }
1295   StringRef getDisplayName() const { return getStringOperand(3); }
1296   StringRef getLinkageName() const { return getStringOperand(4); }
1297
1298   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1299   MDString *getRawLinkageName() const { return getOperandAs<MDString>(4); }
1300
1301   MDSubroutineType *getType() const {
1302     return cast_or_null<MDSubroutineType>(getRawType());
1303   }
1304   MDTypeRef getContainingType() const {
1305     return MDTypeRef(getRawContainingType());
1306   }
1307
1308   ConstantAsMetadata *getFunction() const {
1309     return cast_or_null<ConstantAsMetadata>(getRawFunction());
1310   }
1311   MDTemplateParameterArray getTemplateParams() const {
1312     return cast_or_null<MDTuple>(getRawTemplateParams());
1313   }
1314   MDSubprogram *getDeclaration() const {
1315     return cast_or_null<MDSubprogram>(getRawDeclaration());
1316   }
1317   MDLocalVariableArray getVariables() const {
1318     return cast_or_null<MDTuple>(getRawVariables());
1319   }
1320
1321   Metadata *getRawScope() const { return getOperand(1); }
1322   Metadata *getRawType() const { return getOperand(5); }
1323   Metadata *getRawContainingType() const { return getOperand(6); }
1324   Metadata *getRawFunction() const { return getOperand(7); }
1325   Metadata *getRawTemplateParams() const { return getOperand(8); }
1326   Metadata *getRawDeclaration() const { return getOperand(9); }
1327   Metadata *getRawVariables() const { return getOperand(10); }
1328
1329   /// \brief Replace the function.
1330   ///
1331   /// If \a isUniqued() and not \a isResolved(), this could node will be
1332   /// RAUW'ed and deleted out from under the caller.  Use a \a TrackingMDRef if
1333   /// that's a problem.
1334   /// @{
1335   void replaceFunction(Function *F);
1336   void replaceFunction(ConstantAsMetadata *MD) { replaceOperandWith(7, MD); }
1337   void replaceFunction(std::nullptr_t) { replaceOperandWith(7, nullptr); }
1338   /// @}
1339
1340   static bool classof(const Metadata *MD) {
1341     return MD->getMetadataID() == MDSubprogramKind;
1342   }
1343 };
1344
1345 class MDLexicalBlockBase : public MDLocalScope {
1346 protected:
1347   MDLexicalBlockBase(LLVMContext &C, unsigned ID, StorageType Storage,
1348                      ArrayRef<Metadata *> Ops)
1349       : MDLocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
1350   ~MDLexicalBlockBase() {}
1351
1352 public:
1353   MDLocalScope *getScope() const { return cast<MDLocalScope>(getRawScope()); }
1354
1355   Metadata *getRawScope() const { return getOperand(1); }
1356
1357   static bool classof(const Metadata *MD) {
1358     return MD->getMetadataID() == MDLexicalBlockKind ||
1359            MD->getMetadataID() == MDLexicalBlockFileKind;
1360   }
1361 };
1362
1363 class MDLexicalBlock : public MDLexicalBlockBase {
1364   friend class LLVMContextImpl;
1365   friend class MDNode;
1366
1367   unsigned Line;
1368   unsigned Column;
1369
1370   MDLexicalBlock(LLVMContext &C, StorageType Storage, unsigned Line,
1371                  unsigned Column, ArrayRef<Metadata *> Ops)
1372       : MDLexicalBlockBase(C, MDLexicalBlockKind, Storage, Ops), Line(Line),
1373         Column(Column) {}
1374   ~MDLexicalBlock() {}
1375
1376   static MDLexicalBlock *getImpl(LLVMContext &Context, MDLocalScope *Scope,
1377                                  MDFile *File, unsigned Line, unsigned Column,
1378                                  StorageType Storage,
1379                                  bool ShouldCreate = true) {
1380     return getImpl(Context, static_cast<Metadata *>(Scope),
1381                    static_cast<Metadata *>(File), Line, Column, Storage,
1382                    ShouldCreate);
1383   }
1384
1385   static MDLexicalBlock *getImpl(LLVMContext &Context, Metadata *Scope,
1386                                  Metadata *File, unsigned Line, unsigned Column,
1387                                  StorageType Storage, bool ShouldCreate = true);
1388
1389   TempMDLexicalBlock cloneImpl() const {
1390     return getTemporary(getContext(), getScope(), getFile(), getLine(),
1391                         getColumn());
1392   }
1393
1394 public:
1395   DEFINE_MDNODE_GET(MDLexicalBlock, (MDLocalScope * Scope, MDFile *File,
1396                                      unsigned Line, unsigned Column),
1397                     (Scope, File, Line, Column))
1398   DEFINE_MDNODE_GET(MDLexicalBlock, (Metadata * Scope, Metadata *File,
1399                                      unsigned Line, unsigned Column),
1400                     (Scope, File, Line, Column))
1401
1402   TempMDLexicalBlock clone() const { return cloneImpl(); }
1403
1404   unsigned getLine() const { return Line; }
1405   unsigned getColumn() const { return Column; }
1406
1407   static bool classof(const Metadata *MD) {
1408     return MD->getMetadataID() == MDLexicalBlockKind;
1409   }
1410 };
1411
1412 class MDLexicalBlockFile : public MDLexicalBlockBase {
1413   friend class LLVMContextImpl;
1414   friend class MDNode;
1415
1416   unsigned Discriminator;
1417
1418   MDLexicalBlockFile(LLVMContext &C, StorageType Storage,
1419                      unsigned Discriminator, ArrayRef<Metadata *> Ops)
1420       : MDLexicalBlockBase(C, MDLexicalBlockFileKind, Storage, Ops),
1421         Discriminator(Discriminator) {}
1422   ~MDLexicalBlockFile() {}
1423
1424   static MDLexicalBlockFile *getImpl(LLVMContext &Context, MDLocalScope *Scope,
1425                                      MDFile *File, unsigned Discriminator,
1426                                      StorageType Storage,
1427                                      bool ShouldCreate = true) {
1428     return getImpl(Context, static_cast<Metadata *>(Scope),
1429                    static_cast<Metadata *>(File), Discriminator, Storage,
1430                    ShouldCreate);
1431   }
1432
1433   static MDLexicalBlockFile *getImpl(LLVMContext &Context, Metadata *Scope,
1434                                      Metadata *File, unsigned Discriminator,
1435                                      StorageType Storage,
1436                                      bool ShouldCreate = true);
1437
1438   TempMDLexicalBlockFile cloneImpl() const {
1439     return getTemporary(getContext(), getScope(), getFile(),
1440                         getDiscriminator());
1441   }
1442
1443 public:
1444   DEFINE_MDNODE_GET(MDLexicalBlockFile, (MDLocalScope * Scope, MDFile *File,
1445                                          unsigned Discriminator),
1446                     (Scope, File, Discriminator))
1447   DEFINE_MDNODE_GET(MDLexicalBlockFile,
1448                     (Metadata * Scope, Metadata *File, unsigned Discriminator),
1449                     (Scope, File, Discriminator))
1450
1451   TempMDLexicalBlockFile clone() const { return cloneImpl(); }
1452
1453   unsigned getDiscriminator() const { return Discriminator; }
1454
1455   static bool classof(const Metadata *MD) {
1456     return MD->getMetadataID() == MDLexicalBlockFileKind;
1457   }
1458 };
1459
1460 class MDNamespace : public MDScope {
1461   friend class LLVMContextImpl;
1462   friend class MDNode;
1463
1464   unsigned Line;
1465
1466   MDNamespace(LLVMContext &Context, StorageType Storage, unsigned Line,
1467               ArrayRef<Metadata *> Ops)
1468       : MDScope(Context, MDNamespaceKind, Storage, dwarf::DW_TAG_namespace,
1469                 Ops),
1470         Line(Line) {}
1471   ~MDNamespace() {}
1472
1473   static MDNamespace *getImpl(LLVMContext &Context, MDScope *Scope,
1474                               MDFile *File, StringRef Name, unsigned Line,
1475                               StorageType Storage, bool ShouldCreate = true) {
1476     return getImpl(Context, Scope, File, getCanonicalMDString(Context, Name),
1477                    Line, Storage, ShouldCreate);
1478   }
1479   static MDNamespace *getImpl(LLVMContext &Context, Metadata *Scope,
1480                               Metadata *File, MDString *Name, unsigned Line,
1481                               StorageType Storage, bool ShouldCreate = true);
1482
1483   TempMDNamespace cloneImpl() const {
1484     return getTemporary(getContext(), getScope(), getFile(), getName(),
1485                         getLine());
1486   }
1487
1488 public:
1489   DEFINE_MDNODE_GET(MDNamespace, (MDScope * Scope, MDFile *File, StringRef Name,
1490                                   unsigned Line),
1491                     (Scope, File, Name, Line))
1492   DEFINE_MDNODE_GET(MDNamespace, (Metadata * Scope, Metadata *File,
1493                                   MDString *Name, unsigned Line),
1494                     (Scope, File, Name, Line))
1495
1496   TempMDNamespace clone() const { return cloneImpl(); }
1497
1498   unsigned getLine() const { return Line; }
1499   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
1500   StringRef getName() const { return getStringOperand(2); }
1501
1502   Metadata *getRawScope() const { return getOperand(1); }
1503   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1504
1505   static bool classof(const Metadata *MD) {
1506     return MD->getMetadataID() == MDNamespaceKind;
1507   }
1508 };
1509
1510 /// \brief Base class for template parameters.
1511 class MDTemplateParameter : public DebugNode {
1512 protected:
1513   MDTemplateParameter(LLVMContext &Context, unsigned ID, StorageType Storage,
1514                       unsigned Tag, ArrayRef<Metadata *> Ops)
1515       : DebugNode(Context, ID, Storage, Tag, Ops) {}
1516   ~MDTemplateParameter() {}
1517
1518 public:
1519   StringRef getName() const { return getStringOperand(0); }
1520   MDTypeRef getType() const { return MDTypeRef(getRawType()); }
1521
1522   MDString *getRawName() const { return getOperandAs<MDString>(0); }
1523   Metadata *getRawType() const { return getOperand(1); }
1524
1525   static bool classof(const Metadata *MD) {
1526     return MD->getMetadataID() == MDTemplateTypeParameterKind ||
1527            MD->getMetadataID() == MDTemplateValueParameterKind;
1528   }
1529 };
1530
1531 class MDTemplateTypeParameter : public MDTemplateParameter {
1532   friend class LLVMContextImpl;
1533   friend class MDNode;
1534
1535   MDTemplateTypeParameter(LLVMContext &Context, StorageType Storage,
1536                           ArrayRef<Metadata *> Ops)
1537       : MDTemplateParameter(Context, MDTemplateTypeParameterKind, Storage,
1538                             dwarf::DW_TAG_template_type_parameter, Ops) {}
1539   ~MDTemplateTypeParameter() {}
1540
1541   static MDTemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
1542                                           MDTypeRef Type, StorageType Storage,
1543                                           bool ShouldCreate = true) {
1544     return getImpl(Context, getCanonicalMDString(Context, Name), Type, Storage,
1545                    ShouldCreate);
1546   }
1547   static MDTemplateTypeParameter *getImpl(LLVMContext &Context, MDString *Name,
1548                                           Metadata *Type, StorageType Storage,
1549                                           bool ShouldCreate = true);
1550
1551   TempMDTemplateTypeParameter cloneImpl() const {
1552     return getTemporary(getContext(), getName(), getType());
1553   }
1554
1555 public:
1556   DEFINE_MDNODE_GET(MDTemplateTypeParameter, (StringRef Name, MDTypeRef Type),
1557                     (Name, Type))
1558   DEFINE_MDNODE_GET(MDTemplateTypeParameter, (MDString * Name, Metadata *Type),
1559                     (Name, Type))
1560
1561   TempMDTemplateTypeParameter clone() const { return cloneImpl(); }
1562
1563   static bool classof(const Metadata *MD) {
1564     return MD->getMetadataID() == MDTemplateTypeParameterKind;
1565   }
1566 };
1567
1568 class MDTemplateValueParameter : public MDTemplateParameter {
1569   friend class LLVMContextImpl;
1570   friend class MDNode;
1571
1572   MDTemplateValueParameter(LLVMContext &Context, StorageType Storage,
1573                            unsigned Tag, ArrayRef<Metadata *> Ops)
1574       : MDTemplateParameter(Context, MDTemplateValueParameterKind, Storage, Tag,
1575                             Ops) {}
1576   ~MDTemplateValueParameter() {}
1577
1578   static MDTemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
1579                                            StringRef Name, MDTypeRef Type,
1580                                            Metadata *Value, StorageType Storage,
1581                                            bool ShouldCreate = true) {
1582     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), Type,
1583                    Value, Storage, ShouldCreate);
1584   }
1585   static MDTemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
1586                                            MDString *Name, Metadata *Type,
1587                                            Metadata *Value, StorageType Storage,
1588                                            bool ShouldCreate = true);
1589
1590   TempMDTemplateValueParameter cloneImpl() const {
1591     return getTemporary(getContext(), getTag(), getName(), getType(),
1592                         getValue());
1593   }
1594
1595 public:
1596   DEFINE_MDNODE_GET(MDTemplateValueParameter, (unsigned Tag, StringRef Name,
1597                                                MDTypeRef Type, Metadata *Value),
1598                     (Tag, Name, Type, Value))
1599   DEFINE_MDNODE_GET(MDTemplateValueParameter, (unsigned Tag, MDString *Name,
1600                                                Metadata *Type, Metadata *Value),
1601                     (Tag, Name, Type, Value))
1602
1603   TempMDTemplateValueParameter clone() const { return cloneImpl(); }
1604
1605   Metadata *getValue() const { return getOperand(2); }
1606
1607   static bool classof(const Metadata *MD) {
1608     return MD->getMetadataID() == MDTemplateValueParameterKind;
1609   }
1610 };
1611
1612 /// \brief Base class for variables.
1613 ///
1614 /// TODO: Hardcode to DW_TAG_variable.
1615 class MDVariable : public DebugNode {
1616   unsigned Line;
1617
1618 protected:
1619   MDVariable(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1620              unsigned Line, ArrayRef<Metadata *> Ops)
1621       : DebugNode(C, ID, Storage, Tag, Ops), Line(Line) {}
1622   ~MDVariable() {}
1623
1624 public:
1625   unsigned getLine() const { return Line; }
1626   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
1627   StringRef getName() const { return getStringOperand(1); }
1628   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
1629   MDTypeRef getType() const { return MDTypeRef(getRawType()); }
1630
1631   Metadata *getRawScope() const { return getOperand(0); }
1632   MDString *getRawName() const { return getOperandAs<MDString>(1); }
1633   Metadata *getRawFile() const { return getOperand(2); }
1634   Metadata *getRawType() const { return getOperand(3); }
1635
1636   static bool classof(const Metadata *MD) {
1637     return MD->getMetadataID() == MDLocalVariableKind ||
1638            MD->getMetadataID() == MDGlobalVariableKind;
1639   }
1640 };
1641
1642 /// \brief Global variables.
1643 ///
1644 /// TODO: Remove DisplayName.  It's always equal to Name.
1645 class MDGlobalVariable : public MDVariable {
1646   friend class LLVMContextImpl;
1647   friend class MDNode;
1648
1649   bool IsLocalToUnit;
1650   bool IsDefinition;
1651
1652   MDGlobalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
1653                    bool IsLocalToUnit, bool IsDefinition,
1654                    ArrayRef<Metadata *> Ops)
1655       : MDVariable(C, MDGlobalVariableKind, Storage, dwarf::DW_TAG_variable,
1656                    Line, Ops),
1657         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition) {}
1658   ~MDGlobalVariable() {}
1659
1660   static MDGlobalVariable *
1661   getImpl(LLVMContext &Context, MDScope *Scope, StringRef Name,
1662           StringRef LinkageName, MDFile *File, unsigned Line, MDTypeRef Type,
1663           bool IsLocalToUnit, bool IsDefinition, ConstantAsMetadata *Variable,
1664           MDDerivedType *StaticDataMemberDeclaration, StorageType Storage,
1665           bool ShouldCreate = true) {
1666     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1667                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1668                    IsLocalToUnit, IsDefinition, Variable,
1669                    StaticDataMemberDeclaration, Storage, ShouldCreate);
1670   }
1671   static MDGlobalVariable *
1672   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1673           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1674           bool IsLocalToUnit, bool IsDefinition, Metadata *Variable,
1675           Metadata *StaticDataMemberDeclaration, StorageType Storage,
1676           bool ShouldCreate = true);
1677
1678   TempMDGlobalVariable cloneImpl() const {
1679     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1680                         getFile(), getLine(), getType(), isLocalToUnit(),
1681                         isDefinition(), getVariable(),
1682                         getStaticDataMemberDeclaration());
1683   }
1684
1685 public:
1686   DEFINE_MDNODE_GET(MDGlobalVariable,
1687                     (MDScope * Scope, StringRef Name, StringRef LinkageName,
1688                      MDFile *File, unsigned Line, MDTypeRef Type,
1689                      bool IsLocalToUnit, bool IsDefinition,
1690                      ConstantAsMetadata *Variable,
1691                      MDDerivedType *StaticDataMemberDeclaration),
1692                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1693                      IsDefinition, Variable, StaticDataMemberDeclaration))
1694   DEFINE_MDNODE_GET(MDGlobalVariable,
1695                     (Metadata * Scope, MDString *Name, MDString *LinkageName,
1696                      Metadata *File, unsigned Line, Metadata *Type,
1697                      bool IsLocalToUnit, bool IsDefinition, Metadata *Variable,
1698                      Metadata *StaticDataMemberDeclaration),
1699                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1700                      IsDefinition, Variable, StaticDataMemberDeclaration))
1701
1702   TempMDGlobalVariable clone() const { return cloneImpl(); }
1703
1704   bool isLocalToUnit() const { return IsLocalToUnit; }
1705   bool isDefinition() const { return IsDefinition; }
1706   StringRef getDisplayName() const { return getStringOperand(4); }
1707   StringRef getLinkageName() const { return getStringOperand(5); }
1708   ConstantAsMetadata *getVariable() const {
1709     return cast_or_null<ConstantAsMetadata>(getRawVariable());
1710   }
1711   MDDerivedType *getStaticDataMemberDeclaration() const {
1712     return cast_or_null<MDDerivedType>(getRawStaticDataMemberDeclaration());
1713   }
1714
1715   MDString *getRawLinkageName() const { return getOperandAs<MDString>(5); }
1716   Metadata *getRawVariable() const { return getOperand(6); }
1717   Metadata *getRawStaticDataMemberDeclaration() const { return getOperand(7); }
1718
1719   static bool classof(const Metadata *MD) {
1720     return MD->getMetadataID() == MDGlobalVariableKind;
1721   }
1722 };
1723
1724 /// \brief Local variable.
1725 ///
1726 /// TODO: Split between arguments and otherwise.
1727 /// TODO: Use \c DW_TAG_variable instead of fake tags.
1728 /// TODO: Split up flags.
1729 class MDLocalVariable : public MDVariable {
1730   friend class LLVMContextImpl;
1731   friend class MDNode;
1732
1733   unsigned Arg;
1734   unsigned Flags;
1735
1736   MDLocalVariable(LLVMContext &C, StorageType Storage, unsigned Tag,
1737                   unsigned Line, unsigned Arg, unsigned Flags,
1738                   ArrayRef<Metadata *> Ops)
1739       : MDVariable(C, MDLocalVariableKind, Storage, Tag, Line, Ops), Arg(Arg),
1740         Flags(Flags) {}
1741   ~MDLocalVariable() {}
1742
1743   static MDLocalVariable *getImpl(LLVMContext &Context, unsigned Tag,
1744                                   MDScope *Scope, StringRef Name, MDFile *File,
1745                                   unsigned Line, MDTypeRef Type, unsigned Arg,
1746                                   unsigned Flags, MDLocation *InlinedAt,
1747                                   StorageType Storage,
1748                                   bool ShouldCreate = true) {
1749     return getImpl(Context, Tag, Scope, getCanonicalMDString(Context, Name),
1750                    File, Line, Type, Arg, Flags, InlinedAt, Storage,
1751                    ShouldCreate);
1752   }
1753   static MDLocalVariable *getImpl(LLVMContext &Context, unsigned Tag,
1754                                   Metadata *Scope, MDString *Name,
1755                                   Metadata *File, unsigned Line, Metadata *Type,
1756                                   unsigned Arg, unsigned Flags,
1757                                   Metadata *InlinedAt, StorageType Storage,
1758                                   bool ShouldCreate = true);
1759
1760   TempMDLocalVariable cloneImpl() const {
1761     return getTemporary(getContext(), getTag(), getScope(), getName(),
1762                         getFile(), getLine(), getType(), getArg(), getFlags(),
1763                         getInlinedAt());
1764   }
1765
1766 public:
1767   DEFINE_MDNODE_GET(MDLocalVariable,
1768                     (unsigned Tag, MDLocalScope *Scope, StringRef Name,
1769                      MDFile *File, unsigned Line, MDTypeRef Type, unsigned Arg,
1770                      unsigned Flags, MDLocation *InlinedAt = nullptr),
1771                     (Tag, Scope, Name, File, Line, Type, Arg, Flags, InlinedAt))
1772   DEFINE_MDNODE_GET(MDLocalVariable,
1773                     (unsigned Tag, Metadata *Scope, MDString *Name,
1774                      Metadata *File, unsigned Line, Metadata *Type,
1775                      unsigned Arg, unsigned Flags,
1776                      Metadata *InlinedAt = nullptr),
1777                     (Tag, Scope, Name, File, Line, Type, Arg, Flags, InlinedAt))
1778
1779   TempMDLocalVariable clone() const { return cloneImpl(); }
1780
1781   /// \brief Get the local scope for this variable.
1782   ///
1783   /// Variables must be defined in a local scope.
1784   MDLocalScope *getScope() const {
1785     return cast<MDLocalScope>(MDVariable::getScope());
1786   }
1787
1788   unsigned getArg() const { return Arg; }
1789   unsigned getFlags() const { return Flags; }
1790   MDLocation *getInlinedAt() const {
1791     return cast_or_null<MDLocation>(getRawInlinedAt());
1792   }
1793
1794   Metadata *getRawInlinedAt() const { return getOperand(4); }
1795
1796   bool isArtificial() const { return getFlags() & FlagArtificial; }
1797   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
1798
1799   /// \brief Check that a location is valid for this variable.
1800   ///
1801   /// Check that \c DL has the same inlined-at location as this variable,
1802   /// making them valid for the same \a DbgInfoIntrinsic.
1803   bool isValidLocationForIntrinsic(const MDLocation *DL) const {
1804     return getInlinedAt() == (DL ? DL->getInlinedAt() : nullptr);
1805   }
1806
1807   /// \brief Get an inlined version of this variable.
1808   ///
1809   /// Returns a version of this with \a getAlinedAt() set to \c InlinedAt.
1810   MDLocalVariable *withInline(MDLocation *InlinedAt) const {
1811     if (InlinedAt == getInlinedAt())
1812       return const_cast<MDLocalVariable *>(this);
1813     auto Temp = clone();
1814     Temp->replaceOperandWith(4, InlinedAt);
1815     return replaceWithUniqued(std::move(Temp));
1816   }
1817   MDLocalVariable *withoutInline() const { return withInline(nullptr); }
1818
1819   static bool classof(const Metadata *MD) {
1820     return MD->getMetadataID() == MDLocalVariableKind;
1821   }
1822 };
1823
1824 /// \brief DWARF expression.
1825 ///
1826 /// TODO: Co-allocate the expression elements.
1827 /// TODO: Separate from MDNode, or otherwise drop Distinct and Temporary
1828 /// storage types.
1829 class MDExpression : public MDNode {
1830   friend class LLVMContextImpl;
1831   friend class MDNode;
1832
1833   std::vector<uint64_t> Elements;
1834
1835   MDExpression(LLVMContext &C, StorageType Storage, ArrayRef<uint64_t> Elements)
1836       : MDNode(C, MDExpressionKind, Storage, None),
1837         Elements(Elements.begin(), Elements.end()) {}
1838   ~MDExpression() {}
1839
1840   static MDExpression *getImpl(LLVMContext &Context,
1841                                ArrayRef<uint64_t> Elements, StorageType Storage,
1842                                bool ShouldCreate = true);
1843
1844   TempMDExpression cloneImpl() const {
1845     return getTemporary(getContext(), getElements());
1846   }
1847
1848 public:
1849   DEFINE_MDNODE_GET(MDExpression, (ArrayRef<uint64_t> Elements), (Elements))
1850
1851   TempMDExpression clone() const { return cloneImpl(); }
1852
1853   ArrayRef<uint64_t> getElements() const { return Elements; }
1854
1855   unsigned getNumElements() const { return Elements.size(); }
1856   uint64_t getElement(unsigned I) const {
1857     assert(I < Elements.size() && "Index out of range");
1858     return Elements[I];
1859   }
1860
1861   /// \brief Return whether this is a piece of an aggregate variable.
1862   bool isBitPiece() const;
1863
1864   /// \brief Return the offset of this piece in bits.
1865   uint64_t getBitPieceOffset() const;
1866
1867   /// \brief Return the size of this piece in bits.
1868   uint64_t getBitPieceSize() const;
1869
1870   typedef ArrayRef<uint64_t>::iterator element_iterator;
1871   element_iterator elements_begin() const { return getElements().begin(); }
1872   element_iterator elements_end() const { return getElements().end(); }
1873
1874   /// \brief A lightweight wrapper around an expression operand.
1875   ///
1876   /// TODO: Store arguments directly and change \a MDExpression to store a
1877   /// range of these.
1878   class ExprOperand {
1879     const uint64_t *Op;
1880
1881   public:
1882     explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
1883
1884     const uint64_t *get() const { return Op; }
1885
1886     /// \brief Get the operand code.
1887     uint64_t getOp() const { return *Op; }
1888
1889     /// \brief Get an argument to the operand.
1890     ///
1891     /// Never returns the operand itself.
1892     uint64_t getArg(unsigned I) const { return Op[I + 1]; }
1893
1894     unsigned getNumArgs() const { return getSize() - 1; }
1895
1896     /// \brief Return the size of the operand.
1897     ///
1898     /// Return the number of elements in the operand (1 + args).
1899     unsigned getSize() const;
1900   };
1901
1902   /// \brief An iterator for expression operands.
1903   class expr_op_iterator
1904       : public std::iterator<std::input_iterator_tag, ExprOperand> {
1905     ExprOperand Op;
1906
1907   public:
1908     explicit expr_op_iterator(element_iterator I) : Op(I) {}
1909
1910     element_iterator getBase() const { return Op.get(); }
1911     const ExprOperand &operator*() const { return Op; }
1912     const ExprOperand *operator->() const { return &Op; }
1913
1914     expr_op_iterator &operator++() {
1915       increment();
1916       return *this;
1917     }
1918     expr_op_iterator operator++(int) {
1919       expr_op_iterator T(*this);
1920       increment();
1921       return T;
1922     }
1923
1924     /// \brief Get the next iterator.
1925     ///
1926     /// \a std::next() doesn't work because this is technically an
1927     /// input_iterator, but it's a perfectly valid operation.  This is an
1928     /// accessor to provide the same functionality.
1929     expr_op_iterator getNext() const { return ++expr_op_iterator(*this); }
1930
1931     bool operator==(const expr_op_iterator &X) const {
1932       return getBase() == X.getBase();
1933     }
1934     bool operator!=(const expr_op_iterator &X) const {
1935       return getBase() != X.getBase();
1936     }
1937
1938   private:
1939     void increment() { Op = ExprOperand(getBase() + Op.getSize()); }
1940   };
1941
1942   /// \brief Visit the elements via ExprOperand wrappers.
1943   ///
1944   /// These range iterators visit elements through \a ExprOperand wrappers.
1945   /// This is not guaranteed to be a valid range unless \a isValid() gives \c
1946   /// true.
1947   ///
1948   /// \pre \a isValid() gives \c true.
1949   /// @{
1950   expr_op_iterator expr_op_begin() const {
1951     return expr_op_iterator(elements_begin());
1952   }
1953   expr_op_iterator expr_op_end() const {
1954     return expr_op_iterator(elements_end());
1955   }
1956   /// @}
1957
1958   bool isValid() const;
1959
1960   static bool classof(const Metadata *MD) {
1961     return MD->getMetadataID() == MDExpressionKind;
1962   }
1963 };
1964
1965 class MDObjCProperty : public DebugNode {
1966   friend class LLVMContextImpl;
1967   friend class MDNode;
1968
1969   unsigned Line;
1970   unsigned Attributes;
1971
1972   MDObjCProperty(LLVMContext &C, StorageType Storage, unsigned Line,
1973                  unsigned Attributes, ArrayRef<Metadata *> Ops)
1974       : DebugNode(C, MDObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property,
1975                   Ops),
1976         Line(Line), Attributes(Attributes) {}
1977   ~MDObjCProperty() {}
1978
1979   static MDObjCProperty *
1980   getImpl(LLVMContext &Context, StringRef Name, MDFile *File, unsigned Line,
1981           StringRef GetterName, StringRef SetterName, unsigned Attributes,
1982           MDType *Type, StorageType Storage, bool ShouldCreate = true) {
1983     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
1984                    getCanonicalMDString(Context, GetterName),
1985                    getCanonicalMDString(Context, SetterName), Attributes, Type,
1986                    Storage, ShouldCreate);
1987   }
1988   static MDObjCProperty *getImpl(LLVMContext &Context, MDString *Name,
1989                                  Metadata *File, unsigned Line,
1990                                  MDString *GetterName, MDString *SetterName,
1991                                  unsigned Attributes, Metadata *Type,
1992                                  StorageType Storage, bool ShouldCreate = true);
1993
1994   TempMDObjCProperty cloneImpl() const {
1995     return getTemporary(getContext(), getName(), getFile(), getLine(),
1996                         getGetterName(), getSetterName(), getAttributes(),
1997                         getType());
1998   }
1999
2000 public:
2001   DEFINE_MDNODE_GET(MDObjCProperty,
2002                     (StringRef Name, MDFile *File, unsigned Line,
2003                      StringRef GetterName, StringRef SetterName,
2004                      unsigned Attributes, MDType *Type),
2005                     (Name, File, Line, GetterName, SetterName, Attributes,
2006                      Type))
2007   DEFINE_MDNODE_GET(MDObjCProperty,
2008                     (MDString * Name, Metadata *File, unsigned Line,
2009                      MDString *GetterName, MDString *SetterName,
2010                      unsigned Attributes, Metadata *Type),
2011                     (Name, File, Line, GetterName, SetterName, Attributes,
2012                      Type))
2013
2014   TempMDObjCProperty clone() const { return cloneImpl(); }
2015
2016   unsigned getLine() const { return Line; }
2017   unsigned getAttributes() const { return Attributes; }
2018   StringRef getName() const { return getStringOperand(0); }
2019   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
2020   StringRef getGetterName() const { return getStringOperand(2); }
2021   StringRef getSetterName() const { return getStringOperand(3); }
2022   MDType *getType() const { return cast_or_null<MDType>(getRawType()); }
2023
2024   MDString *getRawName() const { return getOperandAs<MDString>(0); }
2025   Metadata *getRawFile() const { return getOperand(1); }
2026   MDString *getRawGetterName() const { return getOperandAs<MDString>(2); }
2027   MDString *getRawSetterName() const { return getOperandAs<MDString>(3); }
2028   Metadata *getRawType() const { return getOperand(4); }
2029
2030   static bool classof(const Metadata *MD) {
2031     return MD->getMetadataID() == MDObjCPropertyKind;
2032   }
2033 };
2034
2035 class MDImportedEntity : public DebugNode {
2036   friend class LLVMContextImpl;
2037   friend class MDNode;
2038
2039   unsigned Line;
2040
2041   MDImportedEntity(LLVMContext &C, StorageType Storage, unsigned Tag,
2042                    unsigned Line, ArrayRef<Metadata *> Ops)
2043       : DebugNode(C, MDImportedEntityKind, Storage, Tag, Ops), Line(Line) {}
2044   ~MDImportedEntity() {}
2045
2046   static MDImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2047                                    MDScope *Scope, DebugNodeRef Entity,
2048                                    unsigned Line, StringRef Name,
2049                                    StorageType Storage,
2050                                    bool ShouldCreate = true) {
2051     return getImpl(Context, Tag, Scope, Entity, Line,
2052                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
2053   }
2054   static MDImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2055                                    Metadata *Scope, Metadata *Entity,
2056                                    unsigned Line, MDString *Name,
2057                                    StorageType Storage,
2058                                    bool ShouldCreate = true);
2059
2060   TempMDImportedEntity cloneImpl() const {
2061     return getTemporary(getContext(), getTag(), getScope(), getEntity(),
2062                         getLine(), getName());
2063   }
2064
2065 public:
2066   DEFINE_MDNODE_GET(MDImportedEntity,
2067                     (unsigned Tag, MDScope *Scope, DebugNodeRef Entity,
2068                      unsigned Line, StringRef Name = ""),
2069                     (Tag, Scope, Entity, Line, Name))
2070   DEFINE_MDNODE_GET(MDImportedEntity,
2071                     (unsigned Tag, Metadata *Scope, Metadata *Entity,
2072                      unsigned Line, MDString *Name),
2073                     (Tag, Scope, Entity, Line, Name))
2074
2075   TempMDImportedEntity clone() const { return cloneImpl(); }
2076
2077   unsigned getLine() const { return Line; }
2078   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
2079   DebugNodeRef getEntity() const { return DebugNodeRef(getRawEntity()); }
2080   StringRef getName() const { return getStringOperand(2); }
2081
2082   Metadata *getRawScope() const { return getOperand(0); }
2083   Metadata *getRawEntity() const { return getOperand(1); }
2084   MDString *getRawName() const { return getOperandAs<MDString>(2); }
2085
2086   static bool classof(const Metadata *MD) {
2087     return MD->getMetadataID() == MDImportedEntityKind;
2088   }
2089 };
2090
2091 } // end namespace llvm
2092
2093 #undef DEFINE_MDNODE_GET_UNPACK_IMPL
2094 #undef DEFINE_MDNODE_GET_UNPACK
2095 #undef DEFINE_MDNODE_GET
2096
2097 #endif