DebugInfo: Migrate DISubprogram::describes() to new hierarchy, 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   static bool classof(const Metadata *MD) {
750     return MD->getMetadataID() == MDDerivedTypeKind;
751   }
752 };
753
754 /// \brief Base class for MDCompositeType and MDSubroutineType.
755 ///
756 /// TODO: Delete; they're not really related.
757 class MDCompositeTypeBase : public MDDerivedTypeBase {
758   unsigned RuntimeLang;
759
760 protected:
761   MDCompositeTypeBase(LLVMContext &C, unsigned ID, StorageType Storage,
762                       unsigned Tag, unsigned Line, unsigned RuntimeLang,
763                       uint64_t SizeInBits, uint64_t AlignInBits,
764                       uint64_t OffsetInBits, unsigned Flags,
765                       ArrayRef<Metadata *> Ops)
766       : MDDerivedTypeBase(C, ID, Storage, Tag, Line, SizeInBits, AlignInBits,
767                           OffsetInBits, Flags, Ops),
768         RuntimeLang(RuntimeLang) {}
769   ~MDCompositeTypeBase() = default;
770
771 public:
772   DebugNodeArray getElements() const {
773     return cast_or_null<MDTuple>(getRawElements());
774   }
775   MDTypeRef getVTableHolder() const { return MDTypeRef(getRawVTableHolder()); }
776   MDTemplateParameterArray getTemplateParams() const {
777     return cast_or_null<MDTuple>(getRawTemplateParams());
778   }
779   StringRef getIdentifier() const { return getStringOperand(7); }
780   unsigned getRuntimeLang() const { return RuntimeLang; }
781
782   Metadata *getRawElements() const { return getOperand(4); }
783   Metadata *getRawVTableHolder() const { return getOperand(5); }
784   Metadata *getRawTemplateParams() const { return getOperand(6); }
785   MDString *getRawIdentifier() const { return getOperandAs<MDString>(7); }
786
787   /// \brief Replace operands.
788   ///
789   /// If this \a isUniqued() and not \a isResolved(), on a uniquing collision
790   /// this will be RAUW'ed and deleted.  Use a \a TrackingMDRef to keep track
791   /// of its movement if necessary.
792   /// @{
793   void replaceElements(DebugNodeArray Elements) {
794 #ifndef NDEBUG
795     for (DebugNode *Op : getElements())
796       assert(std::find(Elements->op_begin(), Elements->op_end(), Op) &&
797              "Lost a member during member list replacement");
798 #endif
799     replaceOperandWith(4, Elements.get());
800   }
801   void replaceVTableHolder(MDTypeRef VTableHolder) {
802     replaceOperandWith(5, VTableHolder);
803   }
804   void replaceTemplateParams(MDTemplateParameterArray TemplateParams) {
805     replaceOperandWith(6, TemplateParams.get());
806   }
807   /// @}
808
809   static bool classof(const Metadata *MD) {
810     return MD->getMetadataID() == MDCompositeTypeKind ||
811            MD->getMetadataID() == MDSubroutineTypeKind;
812   }
813 };
814
815 /// \brief Composite types.
816 ///
817 /// TODO: Detach from DerivedTypeBase (split out MDEnumType?).
818 /// TODO: Create a custom, unrelated node for DW_TAG_array_type.
819 class MDCompositeType : public MDCompositeTypeBase {
820   friend class LLVMContextImpl;
821   friend class MDNode;
822
823   MDCompositeType(LLVMContext &C, StorageType Storage, unsigned Tag,
824                   unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits,
825                   uint64_t AlignInBits, uint64_t OffsetInBits, unsigned Flags,
826                   ArrayRef<Metadata *> Ops)
827       : MDCompositeTypeBase(C, MDCompositeTypeKind, Storage, Tag, Line,
828                             RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
829                             Flags, Ops) {}
830   ~MDCompositeType() = default;
831
832   static MDCompositeType *
833   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, Metadata *File,
834           unsigned Line, MDScopeRef Scope, MDTypeRef BaseType,
835           uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
836           uint64_t Flags, DebugNodeArray Elements, unsigned RuntimeLang,
837           MDTypeRef VTableHolder, MDTemplateParameterArray TemplateParams,
838           StringRef Identifier, StorageType Storage, bool ShouldCreate = true) {
839     return getImpl(
840         Context, Tag, getCanonicalMDString(Context, Name), File, Line, Scope,
841         BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements.get(),
842         RuntimeLang, VTableHolder, TemplateParams.get(),
843         getCanonicalMDString(Context, Identifier), Storage, ShouldCreate);
844   }
845   static MDCompositeType *
846   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
847           unsigned Line, Metadata *Scope, Metadata *BaseType,
848           uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
849           unsigned Flags, Metadata *Elements, unsigned RuntimeLang,
850           Metadata *VTableHolder, Metadata *TemplateParams,
851           MDString *Identifier, StorageType Storage, bool ShouldCreate = true);
852
853   TempMDCompositeType cloneImpl() const {
854     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
855                         getScope(), getBaseType(), getSizeInBits(),
856                         getAlignInBits(), getOffsetInBits(), getFlags(),
857                         getElements(), getRuntimeLang(), getVTableHolder(),
858                         getTemplateParams(), getIdentifier());
859   }
860
861 public:
862   DEFINE_MDNODE_GET(MDCompositeType,
863                     (unsigned Tag, StringRef Name, MDFile *File, unsigned Line,
864                      MDScopeRef Scope, MDTypeRef BaseType, uint64_t SizeInBits,
865                      uint64_t AlignInBits, uint64_t OffsetInBits,
866                      unsigned Flags, DebugNodeArray Elements,
867                      unsigned RuntimeLang, MDTypeRef VTableHolder,
868                      MDTemplateParameterArray TemplateParams = nullptr,
869                      StringRef Identifier = ""),
870                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
871                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
872                      VTableHolder, TemplateParams, Identifier))
873   DEFINE_MDNODE_GET(MDCompositeType,
874                     (unsigned Tag, MDString *Name, Metadata *File,
875                      unsigned Line, Metadata *Scope, Metadata *BaseType,
876                      uint64_t SizeInBits, uint64_t AlignInBits,
877                      uint64_t OffsetInBits, unsigned Flags, Metadata *Elements,
878                      unsigned RuntimeLang, Metadata *VTableHolder,
879                      Metadata *TemplateParams = nullptr,
880                      MDString *Identifier = nullptr),
881                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
882                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
883                      VTableHolder, TemplateParams, Identifier))
884
885   TempMDCompositeType clone() const { return cloneImpl(); }
886
887   static bool classof(const Metadata *MD) {
888     return MD->getMetadataID() == MDCompositeTypeKind;
889   }
890 };
891
892 template <class T> TypedDebugNodeRef<T> TypedDebugNodeRef<T>::get(const T *N) {
893   if (N)
894     if (auto *Composite = dyn_cast<MDCompositeType>(N))
895       if (auto *S = Composite->getRawIdentifier())
896         return TypedDebugNodeRef<T>(S);
897   return TypedDebugNodeRef<T>(N);
898 }
899
900 /// \brief Type array for a subprogram.
901 ///
902 /// TODO: Detach from CompositeType, and fold the array of types in directly
903 /// as operands.
904 class MDSubroutineType : public MDCompositeTypeBase {
905   friend class LLVMContextImpl;
906   friend class MDNode;
907
908   MDSubroutineType(LLVMContext &C, StorageType Storage, unsigned Flags,
909                    ArrayRef<Metadata *> Ops)
910       : MDCompositeTypeBase(C, MDSubroutineTypeKind, Storage,
911                             dwarf::DW_TAG_subroutine_type, 0, 0, 0, 0, 0, Flags,
912                             Ops) {}
913   ~MDSubroutineType() = default;
914
915   static MDSubroutineType *getImpl(LLVMContext &Context, unsigned Flags,
916                                    MDTypeRefArray TypeArray,
917                                    StorageType Storage,
918                                    bool ShouldCreate = true) {
919     return getImpl(Context, Flags, TypeArray.get(), Storage, ShouldCreate);
920   }
921   static MDSubroutineType *getImpl(LLVMContext &Context, unsigned Flags,
922                                    Metadata *TypeArray, StorageType Storage,
923                                    bool ShouldCreate = true);
924
925   TempMDSubroutineType cloneImpl() const {
926     return getTemporary(getContext(), getFlags(), getTypeArray());
927   }
928
929 public:
930   DEFINE_MDNODE_GET(MDSubroutineType,
931                     (unsigned Flags, MDTypeRefArray TypeArray),
932                     (Flags, TypeArray))
933   DEFINE_MDNODE_GET(MDSubroutineType, (unsigned Flags, Metadata *TypeArray),
934                     (Flags, TypeArray))
935
936   TempMDSubroutineType clone() const { return cloneImpl(); }
937
938   MDTypeRefArray getTypeArray() const {
939     return cast_or_null<MDTuple>(getRawTypeArray());
940   }
941   Metadata *getRawTypeArray() const { return getRawElements(); }
942
943   static bool classof(const Metadata *MD) {
944     return MD->getMetadataID() == MDSubroutineTypeKind;
945   }
946 };
947
948 /// \brief Compile unit.
949 class MDCompileUnit : public MDScope {
950   friend class LLVMContextImpl;
951   friend class MDNode;
952
953   unsigned SourceLanguage;
954   bool IsOptimized;
955   unsigned RuntimeVersion;
956   unsigned EmissionKind;
957
958   MDCompileUnit(LLVMContext &C, StorageType Storage, unsigned SourceLanguage,
959                 bool IsOptimized, unsigned RuntimeVersion,
960                 unsigned EmissionKind, ArrayRef<Metadata *> Ops)
961       : MDScope(C, MDCompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
962         SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
963         RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind) {}
964   ~MDCompileUnit() = default;
965
966   static MDCompileUnit *
967   getImpl(LLVMContext &Context, unsigned SourceLanguage, MDFile *File,
968           StringRef Producer, bool IsOptimized, StringRef Flags,
969           unsigned RuntimeVersion, StringRef SplitDebugFilename,
970           unsigned EmissionKind, MDCompositeTypeArray EnumTypes,
971           MDTypeArray RetainedTypes, MDSubprogramArray Subprograms,
972           MDGlobalVariableArray GlobalVariables,
973           MDImportedEntityArray ImportedEntities, StorageType Storage,
974           bool ShouldCreate = true) {
975     return getImpl(
976         Context, SourceLanguage, File, getCanonicalMDString(Context, Producer),
977         IsOptimized, getCanonicalMDString(Context, Flags), RuntimeVersion,
978         getCanonicalMDString(Context, SplitDebugFilename), EmissionKind,
979         EnumTypes.get(), RetainedTypes.get(), Subprograms.get(),
980         GlobalVariables.get(), ImportedEntities.get(), Storage, ShouldCreate);
981   }
982   static MDCompileUnit *
983   getImpl(LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
984           MDString *Producer, bool IsOptimized, MDString *Flags,
985           unsigned RuntimeVersion, MDString *SplitDebugFilename,
986           unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
987           Metadata *Subprograms, Metadata *GlobalVariables,
988           Metadata *ImportedEntities, StorageType Storage,
989           bool ShouldCreate = true);
990
991   TempMDCompileUnit cloneImpl() const {
992     return getTemporary(
993         getContext(), getSourceLanguage(), getFile(), getProducer(),
994         isOptimized(), getFlags(), getRuntimeVersion(), getSplitDebugFilename(),
995         getEmissionKind(), getEnumTypes(), getRetainedTypes(), getSubprograms(),
996         getGlobalVariables(), getImportedEntities());
997   }
998
999 public:
1000   DEFINE_MDNODE_GET(MDCompileUnit,
1001                     (unsigned SourceLanguage, MDFile *File, StringRef Producer,
1002                      bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
1003                      StringRef SplitDebugFilename, unsigned EmissionKind,
1004                      MDCompositeTypeArray EnumTypes, MDTypeArray RetainedTypes,
1005                      MDSubprogramArray Subprograms,
1006                      MDGlobalVariableArray GlobalVariables,
1007                      MDImportedEntityArray ImportedEntities),
1008                     (SourceLanguage, File, Producer, IsOptimized, Flags,
1009                      RuntimeVersion, SplitDebugFilename, EmissionKind,
1010                      EnumTypes, RetainedTypes, Subprograms, GlobalVariables,
1011                      ImportedEntities))
1012   DEFINE_MDNODE_GET(MDCompileUnit,
1013                     (unsigned SourceLanguage, Metadata *File,
1014                      MDString *Producer, bool IsOptimized, MDString *Flags,
1015                      unsigned RuntimeVersion, MDString *SplitDebugFilename,
1016                      unsigned EmissionKind, Metadata *EnumTypes,
1017                      Metadata *RetainedTypes, Metadata *Subprograms,
1018                      Metadata *GlobalVariables, Metadata *ImportedEntities),
1019                     (SourceLanguage, File, Producer, IsOptimized, Flags,
1020                      RuntimeVersion, SplitDebugFilename, EmissionKind,
1021                      EnumTypes, RetainedTypes, Subprograms, GlobalVariables,
1022                      ImportedEntities))
1023
1024   TempMDCompileUnit clone() const { return cloneImpl(); }
1025
1026   unsigned getSourceLanguage() const { return SourceLanguage; }
1027   bool isOptimized() const { return IsOptimized; }
1028   unsigned getRuntimeVersion() const { return RuntimeVersion; }
1029   unsigned getEmissionKind() const { return EmissionKind; }
1030   StringRef getProducer() const { return getStringOperand(1); }
1031   StringRef getFlags() const { return getStringOperand(2); }
1032   StringRef getSplitDebugFilename() const { return getStringOperand(3); }
1033   MDCompositeTypeArray getEnumTypes() const {
1034     return cast_or_null<MDTuple>(getRawEnumTypes());
1035   }
1036   MDTypeArray getRetainedTypes() const {
1037     return cast_or_null<MDTuple>(getRawRetainedTypes());
1038   }
1039   MDSubprogramArray getSubprograms() const {
1040     return cast_or_null<MDTuple>(getRawSubprograms());
1041   }
1042   MDGlobalVariableArray getGlobalVariables() const {
1043     return cast_or_null<MDTuple>(getRawGlobalVariables());
1044   }
1045   MDImportedEntityArray getImportedEntities() const {
1046     return cast_or_null<MDTuple>(getRawImportedEntities());
1047   }
1048
1049   MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
1050   MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
1051   MDString *getRawSplitDebugFilename() const {
1052     return getOperandAs<MDString>(3);
1053   }
1054   Metadata *getRawEnumTypes() const { return getOperand(4); }
1055   Metadata *getRawRetainedTypes() const { return getOperand(5); }
1056   Metadata *getRawSubprograms() const { return getOperand(6); }
1057   Metadata *getRawGlobalVariables() const { return getOperand(7); }
1058   Metadata *getRawImportedEntities() const { return getOperand(8); }
1059
1060   /// \brief Replace arrays.
1061   ///
1062   /// If this \a isUniqued() and not \a isResolved(), it will be RAUW'ed and
1063   /// deleted on a uniquing collision.  In practice, uniquing collisions on \a
1064   /// MDCompileUnit should be fairly rare.
1065   /// @{
1066   void replaceSubprograms(MDSubprogramArray N) {
1067     replaceOperandWith(6, N.get());
1068   }
1069   void replaceGlobalVariables(MDGlobalVariableArray N) {
1070     replaceOperandWith(7, N.get());
1071   }
1072   /// @}
1073
1074   static bool classof(const Metadata *MD) {
1075     return MD->getMetadataID() == MDCompileUnitKind;
1076   }
1077 };
1078
1079 /// \brief A scope for locals.
1080 ///
1081 /// A legal scope for lexical blocks, local variables, and debug info
1082 /// locations.  Subclasses are \a MDSubprogram, \a MDLexicalBlock, and \a
1083 /// MDLexicalBlockFile.
1084 class MDLocalScope : public MDScope {
1085 protected:
1086   MDLocalScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1087                ArrayRef<Metadata *> Ops)
1088       : MDScope(C, ID, Storage, Tag, Ops) {}
1089   ~MDLocalScope() = default;
1090
1091 public:
1092   /// \brief Get the subprogram for this scope.
1093   ///
1094   /// Return this if it's an \a MDSubprogram; otherwise, look up the scope
1095   /// chain.
1096   MDSubprogram *getSubprogram() const;
1097
1098   static bool classof(const Metadata *MD) {
1099     return MD->getMetadataID() == MDSubprogramKind ||
1100            MD->getMetadataID() == MDLexicalBlockKind ||
1101            MD->getMetadataID() == MDLexicalBlockFileKind;
1102   }
1103 };
1104
1105 /// \brief Debug location.
1106 ///
1107 /// A debug location in source code, used for debug info and otherwise.
1108 class MDLocation : public MDNode {
1109   friend class LLVMContextImpl;
1110   friend class MDNode;
1111
1112   MDLocation(LLVMContext &C, StorageType Storage, unsigned Line,
1113              unsigned Column, ArrayRef<Metadata *> MDs);
1114   ~MDLocation() { dropAllReferences(); }
1115
1116   static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
1117                              unsigned Column, Metadata *Scope,
1118                              Metadata *InlinedAt, StorageType Storage,
1119                              bool ShouldCreate = true);
1120   static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
1121                              unsigned Column, MDLocalScope *Scope,
1122                              MDLocation *InlinedAt, StorageType Storage,
1123                              bool ShouldCreate = true) {
1124     return getImpl(Context, Line, Column, static_cast<Metadata *>(Scope),
1125                    static_cast<Metadata *>(InlinedAt), Storage, ShouldCreate);
1126   }
1127
1128   TempMDLocation cloneImpl() const {
1129     return getTemporary(getContext(), getLine(), getColumn(), getScope(),
1130                         getInlinedAt());
1131   }
1132
1133   // Disallow replacing operands.
1134   void replaceOperandWith(unsigned I, Metadata *New) = delete;
1135
1136 public:
1137   DEFINE_MDNODE_GET(MDLocation,
1138                     (unsigned Line, unsigned Column, Metadata *Scope,
1139                      Metadata *InlinedAt = nullptr),
1140                     (Line, Column, Scope, InlinedAt))
1141   DEFINE_MDNODE_GET(MDLocation,
1142                     (unsigned Line, unsigned Column, MDLocalScope *Scope,
1143                      MDLocation *InlinedAt = nullptr),
1144                     (Line, Column, Scope, InlinedAt))
1145
1146   /// \brief Return a (temporary) clone of this.
1147   TempMDLocation clone() const { return cloneImpl(); }
1148
1149   unsigned getLine() const { return SubclassData32; }
1150   unsigned getColumn() const { return SubclassData16; }
1151   MDLocalScope *getScope() const {
1152     return cast<MDLocalScope>(getRawScope());
1153   }
1154   MDLocation *getInlinedAt() const {
1155     return cast_or_null<MDLocation>(getRawInlinedAt());
1156   }
1157
1158   MDFile *getFile() const { return getScope()->getFile(); }
1159   StringRef getFilename() const { return getScope()->getFilename(); }
1160   StringRef getDirectory() const { return getScope()->getDirectory(); }
1161
1162   /// \brief Get the scope where this is inlined.
1163   ///
1164   /// Walk through \a getInlinedAt() and return \a getScope() from the deepest
1165   /// location.
1166   MDLocalScope *getInlinedAtScope() const {
1167     if (auto *IA = getInlinedAt())
1168       return IA->getInlinedAtScope();
1169     return getScope();
1170   }
1171
1172   /// \brief Check whether this can be discriminated from another location.
1173   ///
1174   /// Check \c this can be discriminated from \c RHS in a linetable entry.
1175   /// Scope and inlined-at chains are not recorded in the linetable, so they
1176   /// cannot be used to distinguish basic blocks.
1177   ///
1178   /// The current implementation is weaker than it should be, since it just
1179   /// checks filename and line.
1180   ///
1181   /// FIXME: Add a check for getDiscriminator().
1182   /// FIXME: Add a check for getColumn().
1183   /// FIXME: Change the getFilename() check to getFile() (or add one for
1184   /// getDirectory()).
1185   bool canDiscriminate(const MDLocation &RHS) const {
1186     return getFilename() != RHS.getFilename() || getLine() != RHS.getLine();
1187   }
1188
1189   Metadata *getRawScope() const { return getOperand(0); }
1190   Metadata *getRawInlinedAt() const {
1191     if (getNumOperands() == 2)
1192       return getOperand(1);
1193     return nullptr;
1194   }
1195
1196   static bool classof(const Metadata *MD) {
1197     return MD->getMetadataID() == MDLocationKind;
1198   }
1199 };
1200
1201 /// \brief Subprogram description.
1202 ///
1203 /// TODO: Remove DisplayName.  It's always equal to Name.
1204 /// TODO: Split up flags.
1205 class MDSubprogram : public MDLocalScope {
1206   friend class LLVMContextImpl;
1207   friend class MDNode;
1208
1209   unsigned Line;
1210   unsigned ScopeLine;
1211   unsigned Virtuality;
1212   unsigned VirtualIndex;
1213   unsigned Flags;
1214   bool IsLocalToUnit;
1215   bool IsDefinition;
1216   bool IsOptimized;
1217
1218   MDSubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
1219                unsigned ScopeLine, unsigned Virtuality, unsigned VirtualIndex,
1220                unsigned Flags, bool IsLocalToUnit, bool IsDefinition,
1221                bool IsOptimized, ArrayRef<Metadata *> Ops)
1222       : MDLocalScope(C, MDSubprogramKind, Storage, dwarf::DW_TAG_subprogram,
1223                      Ops),
1224         Line(Line), ScopeLine(ScopeLine), Virtuality(Virtuality),
1225         VirtualIndex(VirtualIndex), Flags(Flags), IsLocalToUnit(IsLocalToUnit),
1226         IsDefinition(IsDefinition), IsOptimized(IsOptimized) {}
1227   ~MDSubprogram() = default;
1228
1229   static MDSubprogram *
1230   getImpl(LLVMContext &Context, MDScopeRef Scope, StringRef Name,
1231           StringRef LinkageName, MDFile *File, unsigned Line,
1232           MDSubroutineType *Type, bool IsLocalToUnit, bool IsDefinition,
1233           unsigned ScopeLine, MDTypeRef ContainingType, unsigned Virtuality,
1234           unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1235           Constant *Function, MDTemplateParameterArray TemplateParams,
1236           MDSubprogram *Declaration, MDLocalVariableArray Variables,
1237           StorageType Storage, bool ShouldCreate = true) {
1238     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1239                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1240                    IsLocalToUnit, IsDefinition, ScopeLine, ContainingType,
1241                    Virtuality, VirtualIndex, Flags, IsOptimized,
1242                    Function ? ConstantAsMetadata::get(Function) : nullptr,
1243                    TemplateParams.get(), Declaration, Variables.get(), Storage,
1244                    ShouldCreate);
1245   }
1246   static MDSubprogram *
1247   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1248           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1249           bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1250           Metadata *ContainingType, unsigned Virtuality, unsigned VirtualIndex,
1251           unsigned Flags, bool IsOptimized, Metadata *Function,
1252           Metadata *TemplateParams, Metadata *Declaration, Metadata *Variables,
1253           StorageType Storage, bool ShouldCreate = true);
1254
1255   TempMDSubprogram cloneImpl() const {
1256     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1257                         getFile(), getLine(), getType(), isLocalToUnit(),
1258                         isDefinition(), getScopeLine(), getContainingType(),
1259                         getVirtuality(), getVirtualIndex(), getFlags(),
1260                         isOptimized(), getFunctionConstant(),
1261                         getTemplateParams(), getDeclaration(), getVariables());
1262   }
1263
1264 public:
1265   DEFINE_MDNODE_GET(MDSubprogram,
1266                     (MDScopeRef Scope, StringRef Name, StringRef LinkageName,
1267                      MDFile *File, unsigned Line, MDSubroutineType *Type,
1268                      bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1269                      MDTypeRef ContainingType, unsigned Virtuality,
1270                      unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1271                      Constant *Function = nullptr,
1272                      MDTemplateParameterArray TemplateParams = nullptr,
1273                      MDSubprogram *Declaration = nullptr,
1274                      MDLocalVariableArray Variables = nullptr),
1275                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1276                      IsDefinition, ScopeLine, ContainingType, Virtuality,
1277                      VirtualIndex, Flags, IsOptimized, Function, TemplateParams,
1278                      Declaration, Variables))
1279   DEFINE_MDNODE_GET(
1280       MDSubprogram,
1281       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
1282        unsigned Line, Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
1283        unsigned ScopeLine, Metadata *ContainingType, unsigned Virtuality,
1284        unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1285        Metadata *Function = nullptr, Metadata *TemplateParams = nullptr,
1286        Metadata *Declaration = nullptr, Metadata *Variables = nullptr),
1287       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
1288        ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized,
1289        Function, TemplateParams, Declaration, Variables))
1290
1291   TempMDSubprogram clone() const { return cloneImpl(); }
1292
1293 public:
1294   unsigned getLine() const { return Line; }
1295   unsigned getVirtuality() const { return Virtuality; }
1296   unsigned getVirtualIndex() const { return VirtualIndex; }
1297   unsigned getScopeLine() const { return ScopeLine; }
1298   unsigned getFlags() const { return Flags; }
1299   bool isLocalToUnit() const { return IsLocalToUnit; }
1300   bool isDefinition() const { return IsDefinition; }
1301   bool isOptimized() const { return IsOptimized; }
1302
1303   unsigned isArtificial() const { return getFlags() & FlagArtificial; }
1304   bool isPrivate() const {
1305     return (getFlags() & FlagAccessibility) == FlagPrivate;
1306   }
1307   bool isProtected() const {
1308     return (getFlags() & FlagAccessibility) == FlagProtected;
1309   }
1310   bool isPublic() const {
1311     return (getFlags() & FlagAccessibility) == FlagPublic;
1312   }
1313   bool isExplicit() const { return getFlags() & FlagExplicit; }
1314   bool isPrototyped() const { return getFlags() & FlagPrototyped; }
1315
1316   /// \brief Check if this is reference-qualified.
1317   ///
1318   /// Return true if this subprogram is a C++11 reference-qualified non-static
1319   /// member function (void foo() &).
1320   unsigned isLValueReference() const {
1321     return getFlags() & FlagLValueReference;
1322   }
1323
1324   /// \brief Check if this is rvalue-reference-qualified.
1325   ///
1326   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
1327   /// non-static member function (void foo() &&).
1328   unsigned isRValueReference() const {
1329     return getFlags() & FlagRValueReference;
1330   }
1331
1332   MDScopeRef getScope() const { return MDScopeRef(getRawScope()); }
1333
1334   StringRef getName() const { return getStringOperand(2); }
1335   StringRef getDisplayName() const { return getStringOperand(3); }
1336   StringRef getLinkageName() const { return getStringOperand(4); }
1337
1338   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1339   MDString *getRawLinkageName() const { return getOperandAs<MDString>(4); }
1340
1341   MDSubroutineType *getType() const {
1342     return cast_or_null<MDSubroutineType>(getRawType());
1343   }
1344   MDTypeRef getContainingType() const {
1345     return MDTypeRef(getRawContainingType());
1346   }
1347
1348   Constant *getFunctionConstant() const {
1349     if (auto *C = cast_or_null<ConstantAsMetadata>(getRawFunction()))
1350       return C->getValue();
1351     return nullptr;
1352   }
1353   MDTemplateParameterArray getTemplateParams() const {
1354     return cast_or_null<MDTuple>(getRawTemplateParams());
1355   }
1356   MDSubprogram *getDeclaration() const {
1357     return cast_or_null<MDSubprogram>(getRawDeclaration());
1358   }
1359   MDLocalVariableArray getVariables() const {
1360     return cast_or_null<MDTuple>(getRawVariables());
1361   }
1362
1363   Metadata *getRawScope() const { return getOperand(1); }
1364   Metadata *getRawType() const { return getOperand(5); }
1365   Metadata *getRawContainingType() const { return getOperand(6); }
1366   Metadata *getRawFunction() const { return getOperand(7); }
1367   Metadata *getRawTemplateParams() const { return getOperand(8); }
1368   Metadata *getRawDeclaration() const { return getOperand(9); }
1369   Metadata *getRawVariables() const { return getOperand(10); }
1370
1371   /// \brief Get a pointer to the function this subprogram describes.
1372   ///
1373   /// This dyn_casts \a getFunctionConstant() to \a Function.
1374   ///
1375   /// FIXME: Should this be looking through bitcasts?
1376   Function *getFunction() const;
1377
1378   /// \brief Replace the function.
1379   ///
1380   /// If \a isUniqued() and not \a isResolved(), this could node will be
1381   /// RAUW'ed and deleted out from under the caller.  Use a \a TrackingMDRef if
1382   /// that's a problem.
1383   /// @{
1384   void replaceFunction(Function *F);
1385   void replaceFunction(ConstantAsMetadata *MD) { replaceOperandWith(7, MD); }
1386   void replaceFunction(std::nullptr_t) { replaceOperandWith(7, nullptr); }
1387   /// @}
1388
1389   /// \brief Check if this subprogram decribes the given function.
1390   ///
1391   /// FIXME: Should this be looking through bitcasts?
1392   bool describes(const Function *F) const;
1393
1394   static bool classof(const Metadata *MD) {
1395     return MD->getMetadataID() == MDSubprogramKind;
1396   }
1397 };
1398
1399 class MDLexicalBlockBase : public MDLocalScope {
1400 protected:
1401   MDLexicalBlockBase(LLVMContext &C, unsigned ID, StorageType Storage,
1402                      ArrayRef<Metadata *> Ops)
1403       : MDLocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
1404   ~MDLexicalBlockBase() = default;
1405
1406 public:
1407   MDLocalScope *getScope() const { return cast<MDLocalScope>(getRawScope()); }
1408
1409   Metadata *getRawScope() const { return getOperand(1); }
1410
1411   static bool classof(const Metadata *MD) {
1412     return MD->getMetadataID() == MDLexicalBlockKind ||
1413            MD->getMetadataID() == MDLexicalBlockFileKind;
1414   }
1415 };
1416
1417 class MDLexicalBlock : public MDLexicalBlockBase {
1418   friend class LLVMContextImpl;
1419   friend class MDNode;
1420
1421   unsigned Line;
1422   unsigned Column;
1423
1424   MDLexicalBlock(LLVMContext &C, StorageType Storage, unsigned Line,
1425                  unsigned Column, ArrayRef<Metadata *> Ops)
1426       : MDLexicalBlockBase(C, MDLexicalBlockKind, Storage, Ops), Line(Line),
1427         Column(Column) {}
1428   ~MDLexicalBlock() = default;
1429
1430   static MDLexicalBlock *getImpl(LLVMContext &Context, MDLocalScope *Scope,
1431                                  MDFile *File, unsigned Line, unsigned Column,
1432                                  StorageType Storage,
1433                                  bool ShouldCreate = true) {
1434     return getImpl(Context, static_cast<Metadata *>(Scope),
1435                    static_cast<Metadata *>(File), Line, Column, Storage,
1436                    ShouldCreate);
1437   }
1438
1439   static MDLexicalBlock *getImpl(LLVMContext &Context, Metadata *Scope,
1440                                  Metadata *File, unsigned Line, unsigned Column,
1441                                  StorageType Storage, bool ShouldCreate = true);
1442
1443   TempMDLexicalBlock cloneImpl() const {
1444     return getTemporary(getContext(), getScope(), getFile(), getLine(),
1445                         getColumn());
1446   }
1447
1448 public:
1449   DEFINE_MDNODE_GET(MDLexicalBlock, (MDLocalScope * Scope, MDFile *File,
1450                                      unsigned Line, unsigned Column),
1451                     (Scope, File, Line, Column))
1452   DEFINE_MDNODE_GET(MDLexicalBlock, (Metadata * Scope, Metadata *File,
1453                                      unsigned Line, unsigned Column),
1454                     (Scope, File, Line, Column))
1455
1456   TempMDLexicalBlock clone() const { return cloneImpl(); }
1457
1458   unsigned getLine() const { return Line; }
1459   unsigned getColumn() const { return Column; }
1460
1461   static bool classof(const Metadata *MD) {
1462     return MD->getMetadataID() == MDLexicalBlockKind;
1463   }
1464 };
1465
1466 class MDLexicalBlockFile : public MDLexicalBlockBase {
1467   friend class LLVMContextImpl;
1468   friend class MDNode;
1469
1470   unsigned Discriminator;
1471
1472   MDLexicalBlockFile(LLVMContext &C, StorageType Storage,
1473                      unsigned Discriminator, ArrayRef<Metadata *> Ops)
1474       : MDLexicalBlockBase(C, MDLexicalBlockFileKind, Storage, Ops),
1475         Discriminator(Discriminator) {}
1476   ~MDLexicalBlockFile() = default;
1477
1478   static MDLexicalBlockFile *getImpl(LLVMContext &Context, MDLocalScope *Scope,
1479                                      MDFile *File, unsigned Discriminator,
1480                                      StorageType Storage,
1481                                      bool ShouldCreate = true) {
1482     return getImpl(Context, static_cast<Metadata *>(Scope),
1483                    static_cast<Metadata *>(File), Discriminator, Storage,
1484                    ShouldCreate);
1485   }
1486
1487   static MDLexicalBlockFile *getImpl(LLVMContext &Context, Metadata *Scope,
1488                                      Metadata *File, unsigned Discriminator,
1489                                      StorageType Storage,
1490                                      bool ShouldCreate = true);
1491
1492   TempMDLexicalBlockFile cloneImpl() const {
1493     return getTemporary(getContext(), getScope(), getFile(),
1494                         getDiscriminator());
1495   }
1496
1497 public:
1498   DEFINE_MDNODE_GET(MDLexicalBlockFile, (MDLocalScope * Scope, MDFile *File,
1499                                          unsigned Discriminator),
1500                     (Scope, File, Discriminator))
1501   DEFINE_MDNODE_GET(MDLexicalBlockFile,
1502                     (Metadata * Scope, Metadata *File, unsigned Discriminator),
1503                     (Scope, File, Discriminator))
1504
1505   TempMDLexicalBlockFile clone() const { return cloneImpl(); }
1506
1507   unsigned getDiscriminator() const { return Discriminator; }
1508
1509   static bool classof(const Metadata *MD) {
1510     return MD->getMetadataID() == MDLexicalBlockFileKind;
1511   }
1512 };
1513
1514 class MDNamespace : public MDScope {
1515   friend class LLVMContextImpl;
1516   friend class MDNode;
1517
1518   unsigned Line;
1519
1520   MDNamespace(LLVMContext &Context, StorageType Storage, unsigned Line,
1521               ArrayRef<Metadata *> Ops)
1522       : MDScope(Context, MDNamespaceKind, Storage, dwarf::DW_TAG_namespace,
1523                 Ops),
1524         Line(Line) {}
1525   ~MDNamespace() = default;
1526
1527   static MDNamespace *getImpl(LLVMContext &Context, MDScope *Scope,
1528                               MDFile *File, StringRef Name, unsigned Line,
1529                               StorageType Storage, bool ShouldCreate = true) {
1530     return getImpl(Context, Scope, File, getCanonicalMDString(Context, Name),
1531                    Line, Storage, ShouldCreate);
1532   }
1533   static MDNamespace *getImpl(LLVMContext &Context, Metadata *Scope,
1534                               Metadata *File, MDString *Name, unsigned Line,
1535                               StorageType Storage, bool ShouldCreate = true);
1536
1537   TempMDNamespace cloneImpl() const {
1538     return getTemporary(getContext(), getScope(), getFile(), getName(),
1539                         getLine());
1540   }
1541
1542 public:
1543   DEFINE_MDNODE_GET(MDNamespace, (MDScope * Scope, MDFile *File, StringRef Name,
1544                                   unsigned Line),
1545                     (Scope, File, Name, Line))
1546   DEFINE_MDNODE_GET(MDNamespace, (Metadata * Scope, Metadata *File,
1547                                   MDString *Name, unsigned Line),
1548                     (Scope, File, Name, Line))
1549
1550   TempMDNamespace clone() const { return cloneImpl(); }
1551
1552   unsigned getLine() const { return Line; }
1553   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
1554   StringRef getName() const { return getStringOperand(2); }
1555
1556   Metadata *getRawScope() const { return getOperand(1); }
1557   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1558
1559   static bool classof(const Metadata *MD) {
1560     return MD->getMetadataID() == MDNamespaceKind;
1561   }
1562 };
1563
1564 /// \brief Base class for template parameters.
1565 class MDTemplateParameter : public DebugNode {
1566 protected:
1567   MDTemplateParameter(LLVMContext &Context, unsigned ID, StorageType Storage,
1568                       unsigned Tag, ArrayRef<Metadata *> Ops)
1569       : DebugNode(Context, ID, Storage, Tag, Ops) {}
1570   ~MDTemplateParameter() = default;
1571
1572 public:
1573   StringRef getName() const { return getStringOperand(0); }
1574   MDTypeRef getType() const { return MDTypeRef(getRawType()); }
1575
1576   MDString *getRawName() const { return getOperandAs<MDString>(0); }
1577   Metadata *getRawType() const { return getOperand(1); }
1578
1579   static bool classof(const Metadata *MD) {
1580     return MD->getMetadataID() == MDTemplateTypeParameterKind ||
1581            MD->getMetadataID() == MDTemplateValueParameterKind;
1582   }
1583 };
1584
1585 class MDTemplateTypeParameter : public MDTemplateParameter {
1586   friend class LLVMContextImpl;
1587   friend class MDNode;
1588
1589   MDTemplateTypeParameter(LLVMContext &Context, StorageType Storage,
1590                           ArrayRef<Metadata *> Ops)
1591       : MDTemplateParameter(Context, MDTemplateTypeParameterKind, Storage,
1592                             dwarf::DW_TAG_template_type_parameter, Ops) {}
1593   ~MDTemplateTypeParameter() = default;
1594
1595   static MDTemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
1596                                           MDTypeRef Type, StorageType Storage,
1597                                           bool ShouldCreate = true) {
1598     return getImpl(Context, getCanonicalMDString(Context, Name), Type, Storage,
1599                    ShouldCreate);
1600   }
1601   static MDTemplateTypeParameter *getImpl(LLVMContext &Context, MDString *Name,
1602                                           Metadata *Type, StorageType Storage,
1603                                           bool ShouldCreate = true);
1604
1605   TempMDTemplateTypeParameter cloneImpl() const {
1606     return getTemporary(getContext(), getName(), getType());
1607   }
1608
1609 public:
1610   DEFINE_MDNODE_GET(MDTemplateTypeParameter, (StringRef Name, MDTypeRef Type),
1611                     (Name, Type))
1612   DEFINE_MDNODE_GET(MDTemplateTypeParameter, (MDString * Name, Metadata *Type),
1613                     (Name, Type))
1614
1615   TempMDTemplateTypeParameter clone() const { return cloneImpl(); }
1616
1617   static bool classof(const Metadata *MD) {
1618     return MD->getMetadataID() == MDTemplateTypeParameterKind;
1619   }
1620 };
1621
1622 class MDTemplateValueParameter : public MDTemplateParameter {
1623   friend class LLVMContextImpl;
1624   friend class MDNode;
1625
1626   MDTemplateValueParameter(LLVMContext &Context, StorageType Storage,
1627                            unsigned Tag, ArrayRef<Metadata *> Ops)
1628       : MDTemplateParameter(Context, MDTemplateValueParameterKind, Storage, Tag,
1629                             Ops) {}
1630   ~MDTemplateValueParameter() = default;
1631
1632   static MDTemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
1633                                            StringRef Name, MDTypeRef Type,
1634                                            Metadata *Value, StorageType Storage,
1635                                            bool ShouldCreate = true) {
1636     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), Type,
1637                    Value, Storage, ShouldCreate);
1638   }
1639   static MDTemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
1640                                            MDString *Name, Metadata *Type,
1641                                            Metadata *Value, StorageType Storage,
1642                                            bool ShouldCreate = true);
1643
1644   TempMDTemplateValueParameter cloneImpl() const {
1645     return getTemporary(getContext(), getTag(), getName(), getType(),
1646                         getValue());
1647   }
1648
1649 public:
1650   DEFINE_MDNODE_GET(MDTemplateValueParameter, (unsigned Tag, StringRef Name,
1651                                                MDTypeRef Type, Metadata *Value),
1652                     (Tag, Name, Type, Value))
1653   DEFINE_MDNODE_GET(MDTemplateValueParameter, (unsigned Tag, MDString *Name,
1654                                                Metadata *Type, Metadata *Value),
1655                     (Tag, Name, Type, Value))
1656
1657   TempMDTemplateValueParameter clone() const { return cloneImpl(); }
1658
1659   Metadata *getValue() const { return getOperand(2); }
1660
1661   static bool classof(const Metadata *MD) {
1662     return MD->getMetadataID() == MDTemplateValueParameterKind;
1663   }
1664 };
1665
1666 /// \brief Base class for variables.
1667 ///
1668 /// TODO: Hardcode to DW_TAG_variable.
1669 class MDVariable : public DebugNode {
1670   unsigned Line;
1671
1672 protected:
1673   MDVariable(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1674              unsigned Line, ArrayRef<Metadata *> Ops)
1675       : DebugNode(C, ID, Storage, Tag, Ops), Line(Line) {}
1676   ~MDVariable() = default;
1677
1678 public:
1679   unsigned getLine() const { return Line; }
1680   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
1681   StringRef getName() const { return getStringOperand(1); }
1682   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
1683   MDTypeRef getType() const { return MDTypeRef(getRawType()); }
1684
1685   StringRef getFilename() const {
1686     if (auto *F = getFile())
1687       return F->getFilename();
1688     return "";
1689   }
1690   StringRef getDirectory() const {
1691     if (auto *F = getFile())
1692       return F->getDirectory();
1693     return "";
1694   }
1695
1696   Metadata *getRawScope() const { return getOperand(0); }
1697   MDString *getRawName() const { return getOperandAs<MDString>(1); }
1698   Metadata *getRawFile() const { return getOperand(2); }
1699   Metadata *getRawType() const { return getOperand(3); }
1700
1701   static bool classof(const Metadata *MD) {
1702     return MD->getMetadataID() == MDLocalVariableKind ||
1703            MD->getMetadataID() == MDGlobalVariableKind;
1704   }
1705 };
1706
1707 /// \brief Global variables.
1708 ///
1709 /// TODO: Remove DisplayName.  It's always equal to Name.
1710 class MDGlobalVariable : public MDVariable {
1711   friend class LLVMContextImpl;
1712   friend class MDNode;
1713
1714   bool IsLocalToUnit;
1715   bool IsDefinition;
1716
1717   MDGlobalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
1718                    bool IsLocalToUnit, bool IsDefinition,
1719                    ArrayRef<Metadata *> Ops)
1720       : MDVariable(C, MDGlobalVariableKind, Storage, dwarf::DW_TAG_variable,
1721                    Line, Ops),
1722         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition) {}
1723   ~MDGlobalVariable() = default;
1724
1725   static MDGlobalVariable *
1726   getImpl(LLVMContext &Context, MDScope *Scope, StringRef Name,
1727           StringRef LinkageName, MDFile *File, unsigned Line, MDTypeRef Type,
1728           bool IsLocalToUnit, bool IsDefinition, Constant *Variable,
1729           MDDerivedType *StaticDataMemberDeclaration, StorageType Storage,
1730           bool ShouldCreate = true) {
1731     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1732                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1733                    IsLocalToUnit, IsDefinition,
1734                    Variable ? ConstantAsMetadata::get(Variable) : nullptr,
1735                    StaticDataMemberDeclaration, Storage, ShouldCreate);
1736   }
1737   static MDGlobalVariable *
1738   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1739           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1740           bool IsLocalToUnit, bool IsDefinition, Metadata *Variable,
1741           Metadata *StaticDataMemberDeclaration, StorageType Storage,
1742           bool ShouldCreate = true);
1743
1744   TempMDGlobalVariable cloneImpl() const {
1745     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1746                         getFile(), getLine(), getType(), isLocalToUnit(),
1747                         isDefinition(), getVariable(),
1748                         getStaticDataMemberDeclaration());
1749   }
1750
1751 public:
1752   DEFINE_MDNODE_GET(MDGlobalVariable,
1753                     (MDScope * Scope, StringRef Name, StringRef LinkageName,
1754                      MDFile *File, unsigned Line, MDTypeRef Type,
1755                      bool IsLocalToUnit, bool IsDefinition, Constant *Variable,
1756                      MDDerivedType *StaticDataMemberDeclaration),
1757                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1758                      IsDefinition, Variable, StaticDataMemberDeclaration))
1759   DEFINE_MDNODE_GET(MDGlobalVariable,
1760                     (Metadata * Scope, MDString *Name, MDString *LinkageName,
1761                      Metadata *File, unsigned Line, Metadata *Type,
1762                      bool IsLocalToUnit, bool IsDefinition, Metadata *Variable,
1763                      Metadata *StaticDataMemberDeclaration),
1764                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1765                      IsDefinition, Variable, StaticDataMemberDeclaration))
1766
1767   TempMDGlobalVariable clone() const { return cloneImpl(); }
1768
1769   bool isLocalToUnit() const { return IsLocalToUnit; }
1770   bool isDefinition() const { return IsDefinition; }
1771   StringRef getDisplayName() const { return getStringOperand(4); }
1772   StringRef getLinkageName() const { return getStringOperand(5); }
1773   Constant *getVariable() const {
1774     if (auto *C = cast_or_null<ConstantAsMetadata>(getRawVariable()))
1775       return dyn_cast<Constant>(C->getValue());
1776     return nullptr;
1777   }
1778   MDDerivedType *getStaticDataMemberDeclaration() const {
1779     return cast_or_null<MDDerivedType>(getRawStaticDataMemberDeclaration());
1780   }
1781
1782   MDString *getRawLinkageName() const { return getOperandAs<MDString>(5); }
1783   Metadata *getRawVariable() const { return getOperand(6); }
1784   Metadata *getRawStaticDataMemberDeclaration() const { return getOperand(7); }
1785
1786   static bool classof(const Metadata *MD) {
1787     return MD->getMetadataID() == MDGlobalVariableKind;
1788   }
1789 };
1790
1791 /// \brief Local variable.
1792 ///
1793 /// TODO: Split between arguments and otherwise.
1794 /// TODO: Use \c DW_TAG_variable instead of fake tags.
1795 /// TODO: Split up flags.
1796 class MDLocalVariable : public MDVariable {
1797   friend class LLVMContextImpl;
1798   friend class MDNode;
1799
1800   unsigned Arg;
1801   unsigned Flags;
1802
1803   MDLocalVariable(LLVMContext &C, StorageType Storage, unsigned Tag,
1804                   unsigned Line, unsigned Arg, unsigned Flags,
1805                   ArrayRef<Metadata *> Ops)
1806       : MDVariable(C, MDLocalVariableKind, Storage, Tag, Line, Ops), Arg(Arg),
1807         Flags(Flags) {}
1808   ~MDLocalVariable() = default;
1809
1810   static MDLocalVariable *getImpl(LLVMContext &Context, unsigned Tag,
1811                                   MDScope *Scope, StringRef Name, MDFile *File,
1812                                   unsigned Line, MDTypeRef Type, unsigned Arg,
1813                                   unsigned Flags, MDLocation *InlinedAt,
1814                                   StorageType Storage,
1815                                   bool ShouldCreate = true) {
1816     return getImpl(Context, Tag, Scope, getCanonicalMDString(Context, Name),
1817                    File, Line, Type, Arg, Flags, InlinedAt, Storage,
1818                    ShouldCreate);
1819   }
1820   static MDLocalVariable *getImpl(LLVMContext &Context, unsigned Tag,
1821                                   Metadata *Scope, MDString *Name,
1822                                   Metadata *File, unsigned Line, Metadata *Type,
1823                                   unsigned Arg, unsigned Flags,
1824                                   Metadata *InlinedAt, StorageType Storage,
1825                                   bool ShouldCreate = true);
1826
1827   TempMDLocalVariable cloneImpl() const {
1828     return getTemporary(getContext(), getTag(), getScope(), getName(),
1829                         getFile(), getLine(), getType(), getArg(), getFlags(),
1830                         getInlinedAt());
1831   }
1832
1833 public:
1834   DEFINE_MDNODE_GET(MDLocalVariable,
1835                     (unsigned Tag, MDLocalScope *Scope, StringRef Name,
1836                      MDFile *File, unsigned Line, MDTypeRef Type, unsigned Arg,
1837                      unsigned Flags, MDLocation *InlinedAt = nullptr),
1838                     (Tag, Scope, Name, File, Line, Type, Arg, Flags, InlinedAt))
1839   DEFINE_MDNODE_GET(MDLocalVariable,
1840                     (unsigned Tag, Metadata *Scope, MDString *Name,
1841                      Metadata *File, unsigned Line, Metadata *Type,
1842                      unsigned Arg, unsigned Flags,
1843                      Metadata *InlinedAt = nullptr),
1844                     (Tag, Scope, Name, File, Line, Type, Arg, Flags, InlinedAt))
1845
1846   TempMDLocalVariable clone() const { return cloneImpl(); }
1847
1848   /// \brief Get the local scope for this variable.
1849   ///
1850   /// Variables must be defined in a local scope.
1851   MDLocalScope *getScope() const {
1852     return cast<MDLocalScope>(MDVariable::getScope());
1853   }
1854
1855   unsigned getArg() const { return Arg; }
1856   unsigned getFlags() const { return Flags; }
1857   MDLocation *getInlinedAt() const {
1858     return cast_or_null<MDLocation>(getRawInlinedAt());
1859   }
1860
1861   Metadata *getRawInlinedAt() const { return getOperand(4); }
1862
1863   bool isArtificial() const { return getFlags() & FlagArtificial; }
1864   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
1865
1866   /// \brief Check that a location is valid for this variable.
1867   ///
1868   /// Check that \c DL has the same inlined-at location as this variable,
1869   /// making them valid for the same \a DbgInfoIntrinsic.
1870   bool isValidLocationForIntrinsic(const MDLocation *DL) const {
1871     return getInlinedAt() == (DL ? DL->getInlinedAt() : nullptr);
1872   }
1873
1874   /// \brief Get an inlined version of this variable.
1875   ///
1876   /// Returns a version of this with \a getAlinedAt() set to \c InlinedAt.
1877   MDLocalVariable *withInline(MDLocation *InlinedAt) const {
1878     if (InlinedAt == getInlinedAt())
1879       return const_cast<MDLocalVariable *>(this);
1880     auto Temp = clone();
1881     Temp->replaceOperandWith(4, InlinedAt);
1882     return replaceWithUniqued(std::move(Temp));
1883   }
1884   MDLocalVariable *withoutInline() const { return withInline(nullptr); }
1885
1886   static bool classof(const Metadata *MD) {
1887     return MD->getMetadataID() == MDLocalVariableKind;
1888   }
1889 };
1890
1891 /// \brief DWARF expression.
1892 ///
1893 /// TODO: Co-allocate the expression elements.
1894 /// TODO: Separate from MDNode, or otherwise drop Distinct and Temporary
1895 /// storage types.
1896 class MDExpression : public MDNode {
1897   friend class LLVMContextImpl;
1898   friend class MDNode;
1899
1900   std::vector<uint64_t> Elements;
1901
1902   MDExpression(LLVMContext &C, StorageType Storage, ArrayRef<uint64_t> Elements)
1903       : MDNode(C, MDExpressionKind, Storage, None),
1904         Elements(Elements.begin(), Elements.end()) {}
1905   ~MDExpression() = default;
1906
1907   static MDExpression *getImpl(LLVMContext &Context,
1908                                ArrayRef<uint64_t> Elements, StorageType Storage,
1909                                bool ShouldCreate = true);
1910
1911   TempMDExpression cloneImpl() const {
1912     return getTemporary(getContext(), getElements());
1913   }
1914
1915 public:
1916   DEFINE_MDNODE_GET(MDExpression, (ArrayRef<uint64_t> Elements), (Elements))
1917
1918   TempMDExpression clone() const { return cloneImpl(); }
1919
1920   ArrayRef<uint64_t> getElements() const { return Elements; }
1921
1922   unsigned getNumElements() const { return Elements.size(); }
1923   uint64_t getElement(unsigned I) const {
1924     assert(I < Elements.size() && "Index out of range");
1925     return Elements[I];
1926   }
1927
1928   /// \brief Return whether this is a piece of an aggregate variable.
1929   bool isBitPiece() const;
1930
1931   /// \brief Return the offset of this piece in bits.
1932   uint64_t getBitPieceOffset() const;
1933
1934   /// \brief Return the size of this piece in bits.
1935   uint64_t getBitPieceSize() const;
1936
1937   typedef ArrayRef<uint64_t>::iterator element_iterator;
1938   element_iterator elements_begin() const { return getElements().begin(); }
1939   element_iterator elements_end() const { return getElements().end(); }
1940
1941   /// \brief A lightweight wrapper around an expression operand.
1942   ///
1943   /// TODO: Store arguments directly and change \a MDExpression to store a
1944   /// range of these.
1945   class ExprOperand {
1946     const uint64_t *Op;
1947
1948   public:
1949     explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
1950
1951     const uint64_t *get() const { return Op; }
1952
1953     /// \brief Get the operand code.
1954     uint64_t getOp() const { return *Op; }
1955
1956     /// \brief Get an argument to the operand.
1957     ///
1958     /// Never returns the operand itself.
1959     uint64_t getArg(unsigned I) const { return Op[I + 1]; }
1960
1961     unsigned getNumArgs() const { return getSize() - 1; }
1962
1963     /// \brief Return the size of the operand.
1964     ///
1965     /// Return the number of elements in the operand (1 + args).
1966     unsigned getSize() const;
1967   };
1968
1969   /// \brief An iterator for expression operands.
1970   class expr_op_iterator
1971       : public std::iterator<std::input_iterator_tag, ExprOperand> {
1972     ExprOperand Op;
1973
1974   public:
1975     explicit expr_op_iterator(element_iterator I) : Op(I) {}
1976
1977     element_iterator getBase() const { return Op.get(); }
1978     const ExprOperand &operator*() const { return Op; }
1979     const ExprOperand *operator->() const { return &Op; }
1980
1981     expr_op_iterator &operator++() {
1982       increment();
1983       return *this;
1984     }
1985     expr_op_iterator operator++(int) {
1986       expr_op_iterator T(*this);
1987       increment();
1988       return T;
1989     }
1990
1991     /// \brief Get the next iterator.
1992     ///
1993     /// \a std::next() doesn't work because this is technically an
1994     /// input_iterator, but it's a perfectly valid operation.  This is an
1995     /// accessor to provide the same functionality.
1996     expr_op_iterator getNext() const { return ++expr_op_iterator(*this); }
1997
1998     bool operator==(const expr_op_iterator &X) const {
1999       return getBase() == X.getBase();
2000     }
2001     bool operator!=(const expr_op_iterator &X) const {
2002       return getBase() != X.getBase();
2003     }
2004
2005   private:
2006     void increment() { Op = ExprOperand(getBase() + Op.getSize()); }
2007   };
2008
2009   /// \brief Visit the elements via ExprOperand wrappers.
2010   ///
2011   /// These range iterators visit elements through \a ExprOperand wrappers.
2012   /// This is not guaranteed to be a valid range unless \a isValid() gives \c
2013   /// true.
2014   ///
2015   /// \pre \a isValid() gives \c true.
2016   /// @{
2017   expr_op_iterator expr_op_begin() const {
2018     return expr_op_iterator(elements_begin());
2019   }
2020   expr_op_iterator expr_op_end() const {
2021     return expr_op_iterator(elements_end());
2022   }
2023   /// @}
2024
2025   bool isValid() const;
2026
2027   static bool classof(const Metadata *MD) {
2028     return MD->getMetadataID() == MDExpressionKind;
2029   }
2030 };
2031
2032 class MDObjCProperty : public DebugNode {
2033   friend class LLVMContextImpl;
2034   friend class MDNode;
2035
2036   unsigned Line;
2037   unsigned Attributes;
2038
2039   MDObjCProperty(LLVMContext &C, StorageType Storage, unsigned Line,
2040                  unsigned Attributes, ArrayRef<Metadata *> Ops)
2041       : DebugNode(C, MDObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property,
2042                   Ops),
2043         Line(Line), Attributes(Attributes) {}
2044   ~MDObjCProperty() = default;
2045
2046   static MDObjCProperty *
2047   getImpl(LLVMContext &Context, StringRef Name, MDFile *File, unsigned Line,
2048           StringRef GetterName, StringRef SetterName, unsigned Attributes,
2049           MDType *Type, StorageType Storage, bool ShouldCreate = true) {
2050     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
2051                    getCanonicalMDString(Context, GetterName),
2052                    getCanonicalMDString(Context, SetterName), Attributes, Type,
2053                    Storage, ShouldCreate);
2054   }
2055   static MDObjCProperty *getImpl(LLVMContext &Context, MDString *Name,
2056                                  Metadata *File, unsigned Line,
2057                                  MDString *GetterName, MDString *SetterName,
2058                                  unsigned Attributes, Metadata *Type,
2059                                  StorageType Storage, bool ShouldCreate = true);
2060
2061   TempMDObjCProperty cloneImpl() const {
2062     return getTemporary(getContext(), getName(), getFile(), getLine(),
2063                         getGetterName(), getSetterName(), getAttributes(),
2064                         getType());
2065   }
2066
2067 public:
2068   DEFINE_MDNODE_GET(MDObjCProperty,
2069                     (StringRef Name, MDFile *File, unsigned Line,
2070                      StringRef GetterName, StringRef SetterName,
2071                      unsigned Attributes, MDType *Type),
2072                     (Name, File, Line, GetterName, SetterName, Attributes,
2073                      Type))
2074   DEFINE_MDNODE_GET(MDObjCProperty,
2075                     (MDString * Name, Metadata *File, unsigned Line,
2076                      MDString *GetterName, MDString *SetterName,
2077                      unsigned Attributes, Metadata *Type),
2078                     (Name, File, Line, GetterName, SetterName, Attributes,
2079                      Type))
2080
2081   TempMDObjCProperty clone() const { return cloneImpl(); }
2082
2083   unsigned getLine() const { return Line; }
2084   unsigned getAttributes() const { return Attributes; }
2085   StringRef getName() const { return getStringOperand(0); }
2086   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
2087   StringRef getGetterName() const { return getStringOperand(2); }
2088   StringRef getSetterName() const { return getStringOperand(3); }
2089   MDType *getType() const { return cast_or_null<MDType>(getRawType()); }
2090
2091   StringRef getFilename() const {
2092     if (auto *F = getFile())
2093       return F->getFilename();
2094     return "";
2095   }
2096   StringRef getDirectory() const {
2097     if (auto *F = getFile())
2098       return F->getDirectory();
2099     return "";
2100   }
2101
2102   MDString *getRawName() const { return getOperandAs<MDString>(0); }
2103   Metadata *getRawFile() const { return getOperand(1); }
2104   MDString *getRawGetterName() const { return getOperandAs<MDString>(2); }
2105   MDString *getRawSetterName() const { return getOperandAs<MDString>(3); }
2106   Metadata *getRawType() const { return getOperand(4); }
2107
2108   static bool classof(const Metadata *MD) {
2109     return MD->getMetadataID() == MDObjCPropertyKind;
2110   }
2111 };
2112
2113 class MDImportedEntity : public DebugNode {
2114   friend class LLVMContextImpl;
2115   friend class MDNode;
2116
2117   unsigned Line;
2118
2119   MDImportedEntity(LLVMContext &C, StorageType Storage, unsigned Tag,
2120                    unsigned Line, ArrayRef<Metadata *> Ops)
2121       : DebugNode(C, MDImportedEntityKind, Storage, Tag, Ops), Line(Line) {}
2122   ~MDImportedEntity() = default;
2123
2124   static MDImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2125                                    MDScope *Scope, DebugNodeRef Entity,
2126                                    unsigned Line, StringRef Name,
2127                                    StorageType Storage,
2128                                    bool ShouldCreate = true) {
2129     return getImpl(Context, Tag, Scope, Entity, Line,
2130                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
2131   }
2132   static MDImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2133                                    Metadata *Scope, Metadata *Entity,
2134                                    unsigned Line, MDString *Name,
2135                                    StorageType Storage,
2136                                    bool ShouldCreate = true);
2137
2138   TempMDImportedEntity cloneImpl() const {
2139     return getTemporary(getContext(), getTag(), getScope(), getEntity(),
2140                         getLine(), getName());
2141   }
2142
2143 public:
2144   DEFINE_MDNODE_GET(MDImportedEntity,
2145                     (unsigned Tag, MDScope *Scope, DebugNodeRef Entity,
2146                      unsigned Line, StringRef Name = ""),
2147                     (Tag, Scope, Entity, Line, Name))
2148   DEFINE_MDNODE_GET(MDImportedEntity,
2149                     (unsigned Tag, Metadata *Scope, Metadata *Entity,
2150                      unsigned Line, MDString *Name),
2151                     (Tag, Scope, Entity, Line, Name))
2152
2153   TempMDImportedEntity clone() const { return cloneImpl(); }
2154
2155   unsigned getLine() const { return Line; }
2156   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
2157   DebugNodeRef getEntity() const { return DebugNodeRef(getRawEntity()); }
2158   StringRef getName() const { return getStringOperand(2); }
2159
2160   Metadata *getRawScope() const { return getOperand(0); }
2161   Metadata *getRawEntity() const { return getOperand(1); }
2162   MDString *getRawName() const { return getOperandAs<MDString>(2); }
2163
2164   static bool classof(const Metadata *MD) {
2165     return MD->getMetadataID() == MDImportedEntityKind;
2166   }
2167 };
2168
2169 } // end namespace llvm
2170
2171 #undef DEFINE_MDNODE_GET_UNPACK_IMPL
2172 #undef DEFINE_MDNODE_GET_UNPACK
2173 #undef DEFINE_MDNODE_GET
2174
2175 #endif