]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/IR/DebugInfoMetadata.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r308421, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitmaskEnum.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/iterator_range.h"
25 #include "llvm/BinaryFormat/Dwarf.h"
26 #include "llvm/IR/Metadata.h"
27 #include "llvm/Support/Casting.h"
28 #include <cassert>
29 #include <climits>
30 #include <cstddef>
31 #include <cstdint>
32 #include <iterator>
33 #include <type_traits>
34 #include <vector>
35
36 // Helper macros for defining get() overrides.
37 #define DEFINE_MDNODE_GET_UNPACK_IMPL(...) __VA_ARGS__
38 #define DEFINE_MDNODE_GET_UNPACK(ARGS) DEFINE_MDNODE_GET_UNPACK_IMPL ARGS
39 #define DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(CLASS, FORMAL, ARGS)              \
40   static CLASS *getDistinct(LLVMContext &Context,                              \
41                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
42     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Distinct);         \
43   }                                                                            \
44   static Temp##CLASS getTemporary(LLVMContext &Context,                        \
45                                   DEFINE_MDNODE_GET_UNPACK(FORMAL)) {          \
46     return Temp##CLASS(                                                        \
47         getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Temporary));          \
48   }
49 #define DEFINE_MDNODE_GET(CLASS, FORMAL, ARGS)                                 \
50   static CLASS *get(LLVMContext &Context, DEFINE_MDNODE_GET_UNPACK(FORMAL)) {  \
51     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued);          \
52   }                                                                            \
53   static CLASS *getIfExists(LLVMContext &Context,                              \
54                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
55     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued,           \
56                    /* ShouldCreate */ false);                                  \
57   }                                                                            \
58   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(CLASS, FORMAL, ARGS)
59
60 namespace llvm {
61
62 /// Holds a subclass of DINode.
63 ///
64 /// FIXME: This class doesn't currently make much sense.  Previously it was a
65 /// union beteen MDString (for ODR-uniqued types) and things like DIType.  To
66 /// support CodeView work, it wasn't deleted outright when MDString-based type
67 /// references were deleted; we'll soon need a similar concept for CodeView
68 /// DITypeIndex.
69 template <class T> class TypedDINodeRef {
70   const Metadata *MD = nullptr;
71
72 public:
73   TypedDINodeRef() = default;
74   TypedDINodeRef(std::nullptr_t) {}
75   TypedDINodeRef(const T *MD) : MD(MD) {}
76
77   explicit TypedDINodeRef(const Metadata *MD) : MD(MD) {
78     assert((!MD || isa<T>(MD)) && "Expected valid type ref");
79   }
80
81   template <class U>
82   TypedDINodeRef(
83       const TypedDINodeRef<U> &X,
84       typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
85           nullptr)
86       : MD(X) {}
87
88   operator Metadata *() const { return const_cast<Metadata *>(MD); }
89
90   T *resolve() const { return const_cast<T *>(cast_or_null<T>(MD)); }
91
92   bool operator==(const TypedDINodeRef<T> &X) const { return MD == X.MD; }
93   bool operator!=(const TypedDINodeRef<T> &X) const { return MD != X.MD; }
94 };
95
96 using DINodeRef = TypedDINodeRef<DINode>;
97 using DIScopeRef = TypedDINodeRef<DIScope>;
98 using DITypeRef = TypedDINodeRef<DIType>;
99
100 class DITypeRefArray {
101   const MDTuple *N = nullptr;
102
103 public:
104   DITypeRefArray() = default;
105   DITypeRefArray(const MDTuple *N) : N(N) {}
106
107   explicit operator bool() const { return get(); }
108   explicit operator MDTuple *() const { return get(); }
109
110   MDTuple *get() const { return const_cast<MDTuple *>(N); }
111   MDTuple *operator->() const { return get(); }
112   MDTuple &operator*() const { return *get(); }
113
114   // FIXME: Fix callers and remove condition on N.
115   unsigned size() const { return N ? N->getNumOperands() : 0u; }
116   DITypeRef operator[](unsigned I) const { return DITypeRef(N->getOperand(I)); }
117
118   class iterator : std::iterator<std::input_iterator_tag, DITypeRef,
119                                  std::ptrdiff_t, void, DITypeRef> {
120     MDNode::op_iterator I = nullptr;
121
122   public:
123     iterator() = default;
124     explicit iterator(MDNode::op_iterator I) : I(I) {}
125
126     DITypeRef operator*() const { return DITypeRef(*I); }
127
128     iterator &operator++() {
129       ++I;
130       return *this;
131     }
132
133     iterator operator++(int) {
134       iterator Temp(*this);
135       ++I;
136       return Temp;
137     }
138
139     bool operator==(const iterator &X) const { return I == X.I; }
140     bool operator!=(const iterator &X) const { return I != X.I; }
141   };
142
143   // FIXME: Fix callers and remove condition on N.
144   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
145   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
146 };
147
148 /// Tagged DWARF-like metadata node.
149 ///
150 /// A metadata node with a DWARF tag (i.e., a constant named \c DW_TAG_*,
151 /// defined in llvm/BinaryFormat/Dwarf.h).  Called \a DINode because it's
152 /// potentially used for non-DWARF output.
153 class DINode : public MDNode {
154   friend class LLVMContextImpl;
155   friend class MDNode;
156
157 protected:
158   DINode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
159          ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
160       : MDNode(C, ID, Storage, Ops1, Ops2) {
161     assert(Tag < 1u << 16);
162     SubclassData16 = Tag;
163   }
164   ~DINode() = default;
165
166   template <class Ty> Ty *getOperandAs(unsigned I) const {
167     return cast_or_null<Ty>(getOperand(I));
168   }
169
170   StringRef getStringOperand(unsigned I) const {
171     if (auto *S = getOperandAs<MDString>(I))
172       return S->getString();
173     return StringRef();
174   }
175
176   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
177     if (S.empty())
178       return nullptr;
179     return MDString::get(Context, S);
180   }
181
182   /// Allow subclasses to mutate the tag.
183   void setTag(unsigned Tag) { SubclassData16 = Tag; }
184
185 public:
186   unsigned getTag() const { return SubclassData16; }
187
188   /// Debug info flags.
189   ///
190   /// The three accessibility flags are mutually exclusive and rolled together
191   /// in the first two bits.
192   enum DIFlags : uint32_t {
193 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = ID,
194 #define DI_FLAG_LARGEST_NEEDED
195 #include "llvm/IR/DebugInfoFlags.def"
196     FlagAccessibility = FlagPrivate | FlagProtected | FlagPublic,
197     FlagPtrToMemberRep = FlagSingleInheritance | FlagMultipleInheritance |
198                          FlagVirtualInheritance,
199     LLVM_MARK_AS_BITMASK_ENUM(FlagLargest)
200   };
201
202   static DIFlags getFlag(StringRef Flag);
203   static StringRef getFlagString(DIFlags Flag);
204
205   /// Split up a flags bitfield.
206   ///
207   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
208   /// any remaining (unrecognized) bits.
209   static DIFlags splitFlags(DIFlags Flags,
210                             SmallVectorImpl<DIFlags> &SplitFlags);
211
212   static bool classof(const Metadata *MD) {
213     switch (MD->getMetadataID()) {
214     default:
215       return false;
216     case GenericDINodeKind:
217     case DISubrangeKind:
218     case DIEnumeratorKind:
219     case DIBasicTypeKind:
220     case DIDerivedTypeKind:
221     case DICompositeTypeKind:
222     case DISubroutineTypeKind:
223     case DIFileKind:
224     case DICompileUnitKind:
225     case DISubprogramKind:
226     case DILexicalBlockKind:
227     case DILexicalBlockFileKind:
228     case DINamespaceKind:
229     case DITemplateTypeParameterKind:
230     case DITemplateValueParameterKind:
231     case DIGlobalVariableKind:
232     case DILocalVariableKind:
233     case DIObjCPropertyKind:
234     case DIImportedEntityKind:
235     case DIModuleKind:
236       return true;
237     }
238   }
239 };
240
241 template <class T> struct simplify_type<const TypedDINodeRef<T>> {
242   using SimpleType = Metadata *;
243
244   static SimpleType getSimplifiedValue(const TypedDINodeRef<T> &MD) {
245     return MD;
246   }
247 };
248
249 template <class T>
250 struct simplify_type<TypedDINodeRef<T>>
251     : simplify_type<const TypedDINodeRef<T>> {};
252
253 /// Generic tagged DWARF-like metadata node.
254 ///
255 /// An un-specialized DWARF-like metadata node.  The first operand is a
256 /// (possibly empty) null-separated \a MDString header that contains arbitrary
257 /// fields.  The remaining operands are \a dwarf_operands(), and are pointers
258 /// to other metadata.
259 class GenericDINode : public DINode {
260   friend class LLVMContextImpl;
261   friend class MDNode;
262
263   GenericDINode(LLVMContext &C, StorageType Storage, unsigned Hash,
264                 unsigned Tag, ArrayRef<Metadata *> Ops1,
265                 ArrayRef<Metadata *> Ops2)
266       : DINode(C, GenericDINodeKind, Storage, Tag, Ops1, Ops2) {
267     setHash(Hash);
268   }
269   ~GenericDINode() { dropAllReferences(); }
270
271   void setHash(unsigned Hash) { SubclassData32 = Hash; }
272   void recalculateHash();
273
274   static GenericDINode *getImpl(LLVMContext &Context, unsigned Tag,
275                                 StringRef Header, ArrayRef<Metadata *> DwarfOps,
276                                 StorageType Storage, bool ShouldCreate = true) {
277     return getImpl(Context, Tag, getCanonicalMDString(Context, Header),
278                    DwarfOps, Storage, ShouldCreate);
279   }
280
281   static GenericDINode *getImpl(LLVMContext &Context, unsigned Tag,
282                                 MDString *Header, ArrayRef<Metadata *> DwarfOps,
283                                 StorageType Storage, bool ShouldCreate = true);
284
285   TempGenericDINode cloneImpl() const {
286     return getTemporary(
287         getContext(), getTag(), getHeader(),
288         SmallVector<Metadata *, 4>(dwarf_op_begin(), dwarf_op_end()));
289   }
290
291 public:
292   unsigned getHash() const { return SubclassData32; }
293
294   DEFINE_MDNODE_GET(GenericDINode, (unsigned Tag, StringRef Header,
295                                     ArrayRef<Metadata *> DwarfOps),
296                     (Tag, Header, DwarfOps))
297   DEFINE_MDNODE_GET(GenericDINode, (unsigned Tag, MDString *Header,
298                                     ArrayRef<Metadata *> DwarfOps),
299                     (Tag, Header, DwarfOps))
300
301   /// Return a (temporary) clone of this.
302   TempGenericDINode clone() const { return cloneImpl(); }
303
304   unsigned getTag() const { return SubclassData16; }
305   StringRef getHeader() const { return getStringOperand(0); }
306   MDString *getRawHeader() const { return getOperandAs<MDString>(0); }
307
308   op_iterator dwarf_op_begin() const { return op_begin() + 1; }
309   op_iterator dwarf_op_end() const { return op_end(); }
310   op_range dwarf_operands() const {
311     return op_range(dwarf_op_begin(), dwarf_op_end());
312   }
313
314   unsigned getNumDwarfOperands() const { return getNumOperands() - 1; }
315   const MDOperand &getDwarfOperand(unsigned I) const {
316     return getOperand(I + 1);
317   }
318   void replaceDwarfOperandWith(unsigned I, Metadata *New) {
319     replaceOperandWith(I + 1, New);
320   }
321
322   static bool classof(const Metadata *MD) {
323     return MD->getMetadataID() == GenericDINodeKind;
324   }
325 };
326
327 /// Array subrange.
328 ///
329 /// TODO: Merge into node for DW_TAG_array_type, which should have a custom
330 /// type.
331 class DISubrange : public DINode {
332   friend class LLVMContextImpl;
333   friend class MDNode;
334
335   int64_t Count;
336   int64_t LowerBound;
337
338   DISubrange(LLVMContext &C, StorageType Storage, int64_t Count,
339              int64_t LowerBound)
340       : DINode(C, DISubrangeKind, Storage, dwarf::DW_TAG_subrange_type, None),
341         Count(Count), LowerBound(LowerBound) {}
342   ~DISubrange() = default;
343
344   static DISubrange *getImpl(LLVMContext &Context, int64_t Count,
345                              int64_t LowerBound, StorageType Storage,
346                              bool ShouldCreate = true);
347
348   TempDISubrange cloneImpl() const {
349     return getTemporary(getContext(), getCount(), getLowerBound());
350   }
351
352 public:
353   DEFINE_MDNODE_GET(DISubrange, (int64_t Count, int64_t LowerBound = 0),
354                     (Count, LowerBound))
355
356   TempDISubrange clone() const { return cloneImpl(); }
357
358   int64_t getLowerBound() const { return LowerBound; }
359   int64_t getCount() const { return Count; }
360
361   static bool classof(const Metadata *MD) {
362     return MD->getMetadataID() == DISubrangeKind;
363   }
364 };
365
366 /// Enumeration value.
367 ///
368 /// TODO: Add a pointer to the context (DW_TAG_enumeration_type) once that no
369 /// longer creates a type cycle.
370 class DIEnumerator : public DINode {
371   friend class LLVMContextImpl;
372   friend class MDNode;
373
374   int64_t Value;
375
376   DIEnumerator(LLVMContext &C, StorageType Storage, int64_t Value,
377                ArrayRef<Metadata *> Ops)
378       : DINode(C, DIEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops),
379         Value(Value) {}
380   ~DIEnumerator() = default;
381
382   static DIEnumerator *getImpl(LLVMContext &Context, int64_t Value,
383                                StringRef Name, StorageType Storage,
384                                bool ShouldCreate = true) {
385     return getImpl(Context, Value, getCanonicalMDString(Context, Name), Storage,
386                    ShouldCreate);
387   }
388   static DIEnumerator *getImpl(LLVMContext &Context, int64_t Value,
389                                MDString *Name, StorageType Storage,
390                                bool ShouldCreate = true);
391
392   TempDIEnumerator cloneImpl() const {
393     return getTemporary(getContext(), getValue(), getName());
394   }
395
396 public:
397   DEFINE_MDNODE_GET(DIEnumerator, (int64_t Value, StringRef Name),
398                     (Value, Name))
399   DEFINE_MDNODE_GET(DIEnumerator, (int64_t Value, MDString *Name),
400                     (Value, Name))
401
402   TempDIEnumerator clone() const { return cloneImpl(); }
403
404   int64_t getValue() const { return Value; }
405   StringRef getName() const { return getStringOperand(0); }
406
407   MDString *getRawName() const { return getOperandAs<MDString>(0); }
408
409   static bool classof(const Metadata *MD) {
410     return MD->getMetadataID() == DIEnumeratorKind;
411   }
412 };
413
414 /// Base class for scope-like contexts.
415 ///
416 /// Base class for lexical scopes and types (which are also declaration
417 /// contexts).
418 ///
419 /// TODO: Separate the concepts of declaration contexts and lexical scopes.
420 class DIScope : public DINode {
421 protected:
422   DIScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
423           ArrayRef<Metadata *> Ops)
424       : DINode(C, ID, Storage, Tag, Ops) {}
425   ~DIScope() = default;
426
427 public:
428   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
429
430   inline StringRef getFilename() const;
431   inline StringRef getDirectory() const;
432
433   StringRef getName() const;
434   DIScopeRef getScope() const;
435
436   /// Return the raw underlying file.
437   ///
438   /// A \a DIFile is a \a DIScope, but it doesn't point at a separate file (it
439   /// \em is the file).  If \c this is an \a DIFile, we need to return \c this.
440   /// Otherwise, return the first operand, which is where all other subclasses
441   /// store their file pointer.
442   Metadata *getRawFile() const {
443     return isa<DIFile>(this) ? const_cast<DIScope *>(this)
444                              : static_cast<Metadata *>(getOperand(0));
445   }
446
447   static bool classof(const Metadata *MD) {
448     switch (MD->getMetadataID()) {
449     default:
450       return false;
451     case DIBasicTypeKind:
452     case DIDerivedTypeKind:
453     case DICompositeTypeKind:
454     case DISubroutineTypeKind:
455     case DIFileKind:
456     case DICompileUnitKind:
457     case DISubprogramKind:
458     case DILexicalBlockKind:
459     case DILexicalBlockFileKind:
460     case DINamespaceKind:
461     case DIModuleKind:
462       return true;
463     }
464   }
465 };
466
467 /// File.
468 ///
469 /// TODO: Merge with directory/file node (including users).
470 /// TODO: Canonicalize paths on creation.
471 class DIFile : public DIScope {
472   friend class LLVMContextImpl;
473   friend class MDNode;
474
475 public:
476   enum ChecksumKind {
477     CSK_None,
478     CSK_MD5,
479     CSK_SHA1,
480     CSK_Last = CSK_SHA1 // Should be last enumeration.
481   };
482
483 private:
484   ChecksumKind CSKind;
485
486   DIFile(LLVMContext &C, StorageType Storage, ChecksumKind CSK,
487          ArrayRef<Metadata *> Ops)
488       : DIScope(C, DIFileKind, Storage, dwarf::DW_TAG_file_type, Ops),
489         CSKind(CSK) {}
490   ~DIFile() = default;
491
492   static DIFile *getImpl(LLVMContext &Context, StringRef Filename,
493                          StringRef Directory, ChecksumKind CSK, StringRef CS,
494                          StorageType Storage, bool ShouldCreate = true) {
495     return getImpl(Context, getCanonicalMDString(Context, Filename),
496                    getCanonicalMDString(Context, Directory), CSK,
497                    getCanonicalMDString(Context, CS), Storage, ShouldCreate);
498   }
499   static DIFile *getImpl(LLVMContext &Context, MDString *Filename,
500                          MDString *Directory, ChecksumKind CSK, MDString *CS,
501                          StorageType Storage, bool ShouldCreate = true);
502
503   TempDIFile cloneImpl() const {
504     return getTemporary(getContext(), getFilename(), getDirectory(),
505                         getChecksumKind(), getChecksum());
506   }
507
508 public:
509   DEFINE_MDNODE_GET(DIFile, (StringRef Filename, StringRef Directory,
510                              ChecksumKind CSK = CSK_None,
511                              StringRef CS = StringRef()),
512                     (Filename, Directory, CSK, CS))
513   DEFINE_MDNODE_GET(DIFile, (MDString *Filename, MDString *Directory,
514                              ChecksumKind CSK = CSK_None,
515                              MDString *CS = nullptr),
516                     (Filename, Directory, CSK, CS))
517
518   TempDIFile clone() const { return cloneImpl(); }
519
520   StringRef getFilename() const { return getStringOperand(0); }
521   StringRef getDirectory() const { return getStringOperand(1); }
522   StringRef getChecksum() const { return getStringOperand(2); }
523   ChecksumKind getChecksumKind() const { return CSKind; }
524   StringRef getChecksumKindAsString() const;
525
526   MDString *getRawFilename() const { return getOperandAs<MDString>(0); }
527   MDString *getRawDirectory() const { return getOperandAs<MDString>(1); }
528   MDString *getRawChecksum() const { return getOperandAs<MDString>(2); }
529
530   static ChecksumKind getChecksumKind(StringRef CSKindStr);
531
532   static bool classof(const Metadata *MD) {
533     return MD->getMetadataID() == DIFileKind;
534   }
535 };
536
537 StringRef DIScope::getFilename() const {
538   if (auto *F = getFile())
539     return F->getFilename();
540   return "";
541 }
542
543 StringRef DIScope::getDirectory() const {
544   if (auto *F = getFile())
545     return F->getDirectory();
546   return "";
547 }
548
549 /// Base class for types.
550 ///
551 /// TODO: Remove the hardcoded name and context, since many types don't use
552 /// them.
553 /// TODO: Split up flags.
554 class DIType : public DIScope {
555   unsigned Line;
556   DIFlags Flags;
557   uint64_t SizeInBits;
558   uint64_t OffsetInBits;
559   uint32_t AlignInBits;
560
561 protected:
562   DIType(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
563          unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
564          uint64_t OffsetInBits, DIFlags Flags, ArrayRef<Metadata *> Ops)
565       : DIScope(C, ID, Storage, Tag, Ops) {
566     init(Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
567   }
568   ~DIType() = default;
569
570   void init(unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
571             uint64_t OffsetInBits, DIFlags Flags) {
572     this->Line = Line;
573     this->Flags = Flags;
574     this->SizeInBits = SizeInBits;
575     this->AlignInBits = AlignInBits;
576     this->OffsetInBits = OffsetInBits;
577   }
578
579   /// Change fields in place.
580   void mutate(unsigned Tag, unsigned Line, uint64_t SizeInBits,
581               uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags) {
582     assert(isDistinct() && "Only distinct nodes can mutate");
583     setTag(Tag);
584     init(Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
585   }
586
587 public:
588   TempDIType clone() const {
589     return TempDIType(cast<DIType>(MDNode::clone().release()));
590   }
591
592   unsigned getLine() const { return Line; }
593   uint64_t getSizeInBits() const { return SizeInBits; }
594   uint32_t getAlignInBits() const { return AlignInBits; }
595   uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
596   uint64_t getOffsetInBits() const { return OffsetInBits; }
597   DIFlags getFlags() const { return Flags; }
598
599   DIScopeRef getScope() const { return DIScopeRef(getRawScope()); }
600   StringRef getName() const { return getStringOperand(2); }
601
602
603   Metadata *getRawScope() const { return getOperand(1); }
604   MDString *getRawName() const { return getOperandAs<MDString>(2); }
605
606   void setFlags(DIFlags NewFlags) {
607     assert(!isUniqued() && "Cannot set flags on uniqued nodes");
608     Flags = NewFlags;
609   }
610
611   bool isPrivate() const {
612     return (getFlags() & FlagAccessibility) == FlagPrivate;
613   }
614   bool isProtected() const {
615     return (getFlags() & FlagAccessibility) == FlagProtected;
616   }
617   bool isPublic() const {
618     return (getFlags() & FlagAccessibility) == FlagPublic;
619   }
620   bool isForwardDecl() const { return getFlags() & FlagFwdDecl; }
621   bool isAppleBlockExtension() const { return getFlags() & FlagAppleBlock; }
622   bool isBlockByrefStruct() const { return getFlags() & FlagBlockByrefStruct; }
623   bool isVirtual() const { return getFlags() & FlagVirtual; }
624   bool isArtificial() const { return getFlags() & FlagArtificial; }
625   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
626   bool isObjcClassComplete() const {
627     return getFlags() & FlagObjcClassComplete;
628   }
629   bool isVector() const { return getFlags() & FlagVector; }
630   bool isBitField() const { return getFlags() & FlagBitField; }
631   bool isStaticMember() const { return getFlags() & FlagStaticMember; }
632   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
633   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
634
635   static bool classof(const Metadata *MD) {
636     switch (MD->getMetadataID()) {
637     default:
638       return false;
639     case DIBasicTypeKind:
640     case DIDerivedTypeKind:
641     case DICompositeTypeKind:
642     case DISubroutineTypeKind:
643       return true;
644     }
645   }
646 };
647
648 /// Basic type, like 'int' or 'float'.
649 ///
650 /// TODO: Split out DW_TAG_unspecified_type.
651 /// TODO: Drop unused accessors.
652 class DIBasicType : public DIType {
653   friend class LLVMContextImpl;
654   friend class MDNode;
655
656   unsigned Encoding;
657
658   DIBasicType(LLVMContext &C, StorageType Storage, unsigned Tag,
659               uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding,
660               ArrayRef<Metadata *> Ops)
661       : DIType(C, DIBasicTypeKind, Storage, Tag, 0, SizeInBits, AlignInBits, 0,
662                FlagZero, Ops),
663         Encoding(Encoding) {}
664   ~DIBasicType() = default;
665
666   static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
667                               StringRef Name, uint64_t SizeInBits,
668                               uint32_t AlignInBits, unsigned Encoding,
669                               StorageType Storage, bool ShouldCreate = true) {
670     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
671                    SizeInBits, AlignInBits, Encoding, Storage, ShouldCreate);
672   }
673   static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
674                               MDString *Name, uint64_t SizeInBits,
675                               uint32_t AlignInBits, unsigned Encoding,
676                               StorageType Storage, bool ShouldCreate = true);
677
678   TempDIBasicType cloneImpl() const {
679     return getTemporary(getContext(), getTag(), getName(), getSizeInBits(),
680                         getAlignInBits(), getEncoding());
681   }
682
683 public:
684   DEFINE_MDNODE_GET(DIBasicType, (unsigned Tag, StringRef Name),
685                     (Tag, Name, 0, 0, 0))
686   DEFINE_MDNODE_GET(DIBasicType,
687                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
688                      uint32_t AlignInBits, unsigned Encoding),
689                     (Tag, Name, SizeInBits, AlignInBits, Encoding))
690   DEFINE_MDNODE_GET(DIBasicType,
691                     (unsigned Tag, MDString *Name, uint64_t SizeInBits,
692                      uint32_t AlignInBits, unsigned Encoding),
693                     (Tag, Name, SizeInBits, AlignInBits, Encoding))
694
695   TempDIBasicType clone() const { return cloneImpl(); }
696
697   unsigned getEncoding() const { return Encoding; }
698
699   static bool classof(const Metadata *MD) {
700     return MD->getMetadataID() == DIBasicTypeKind;
701   }
702 };
703
704 /// Derived types.
705 ///
706 /// This includes qualified types, pointers, references, friends, typedefs, and
707 /// class members.
708 ///
709 /// TODO: Split out members (inheritance, fields, methods, etc.).
710 class DIDerivedType : public DIType {
711   friend class LLVMContextImpl;
712   friend class MDNode;
713
714   /// \brief The DWARF address space of the memory pointed to or referenced by a
715   /// pointer or reference type respectively.
716   Optional<unsigned> DWARFAddressSpace;
717
718   DIDerivedType(LLVMContext &C, StorageType Storage, unsigned Tag,
719                 unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
720                 uint64_t OffsetInBits, Optional<unsigned> DWARFAddressSpace,
721                 DIFlags Flags, ArrayRef<Metadata *> Ops)
722       : DIType(C, DIDerivedTypeKind, Storage, Tag, Line, SizeInBits,
723                AlignInBits, OffsetInBits, Flags, Ops),
724         DWARFAddressSpace(DWARFAddressSpace) {}
725   ~DIDerivedType() = default;
726
727   static DIDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
728                                 StringRef Name, DIFile *File, unsigned Line,
729                                 DIScopeRef Scope, DITypeRef BaseType,
730                                 uint64_t SizeInBits, uint32_t AlignInBits,
731                                 uint64_t OffsetInBits,
732                                 Optional<unsigned> DWARFAddressSpace,
733                                 DIFlags Flags, Metadata *ExtraData,
734                                 StorageType Storage, bool ShouldCreate = true) {
735     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
736                    Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits,
737                    DWARFAddressSpace, Flags, ExtraData, Storage, ShouldCreate);
738   }
739   static DIDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
740                                 MDString *Name, Metadata *File, unsigned Line,
741                                 Metadata *Scope, Metadata *BaseType,
742                                 uint64_t SizeInBits, uint32_t AlignInBits,
743                                 uint64_t OffsetInBits,
744                                 Optional<unsigned> DWARFAddressSpace,
745                                 DIFlags Flags, Metadata *ExtraData,
746                                 StorageType Storage, bool ShouldCreate = true);
747
748   TempDIDerivedType cloneImpl() const {
749     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
750                         getScope(), getBaseType(), getSizeInBits(),
751                         getAlignInBits(), getOffsetInBits(),
752                         getDWARFAddressSpace(), getFlags(), getExtraData());
753   }
754
755 public:
756   DEFINE_MDNODE_GET(DIDerivedType,
757                     (unsigned Tag, MDString *Name, Metadata *File,
758                      unsigned Line, Metadata *Scope, Metadata *BaseType,
759                      uint64_t SizeInBits, uint32_t AlignInBits,
760                      uint64_t OffsetInBits,
761                      Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
762                      Metadata *ExtraData = nullptr),
763                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
764                      AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
765                      ExtraData))
766   DEFINE_MDNODE_GET(DIDerivedType,
767                     (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
768                      DIScopeRef Scope, DITypeRef BaseType, uint64_t SizeInBits,
769                      uint32_t AlignInBits, uint64_t OffsetInBits,
770                      Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
771                      Metadata *ExtraData = nullptr),
772                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
773                      AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
774                      ExtraData))
775
776   TempDIDerivedType clone() const { return cloneImpl(); }
777
778   /// Get the base type this is derived from.
779   DITypeRef getBaseType() const { return DITypeRef(getRawBaseType()); }
780   Metadata *getRawBaseType() const { return getOperand(3); }
781
782   /// \returns The DWARF address space of the memory pointed to or referenced by
783   /// a pointer or reference type respectively.
784   Optional<unsigned> getDWARFAddressSpace() const { return DWARFAddressSpace; }
785
786   /// Get extra data associated with this derived type.
787   ///
788   /// Class type for pointer-to-members, objective-c property node for ivars,
789   /// or global constant wrapper for static members.
790   ///
791   /// TODO: Separate out types that need this extra operand: pointer-to-member
792   /// types and member fields (static members and ivars).
793   Metadata *getExtraData() const { return getRawExtraData(); }
794   Metadata *getRawExtraData() const { return getOperand(4); }
795
796   /// Get casted version of extra data.
797   /// @{
798   DITypeRef getClassType() const {
799     assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
800     return DITypeRef(getExtraData());
801   }
802
803   DIObjCProperty *getObjCProperty() const {
804     return dyn_cast_or_null<DIObjCProperty>(getExtraData());
805   }
806
807   Constant *getStorageOffsetInBits() const {
808     assert(getTag() == dwarf::DW_TAG_member && isBitField());
809     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
810       return C->getValue();
811     return nullptr;
812   }
813
814   Constant *getConstant() const {
815     assert(getTag() == dwarf::DW_TAG_member && isStaticMember());
816     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
817       return C->getValue();
818     return nullptr;
819   }
820   /// @}
821
822   static bool classof(const Metadata *MD) {
823     return MD->getMetadataID() == DIDerivedTypeKind;
824   }
825 };
826
827 /// Composite types.
828 ///
829 /// TODO: Detach from DerivedTypeBase (split out MDEnumType?).
830 /// TODO: Create a custom, unrelated node for DW_TAG_array_type.
831 class DICompositeType : public DIType {
832   friend class LLVMContextImpl;
833   friend class MDNode;
834
835   unsigned RuntimeLang;
836
837   DICompositeType(LLVMContext &C, StorageType Storage, unsigned Tag,
838                   unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits,
839                   uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
840                   ArrayRef<Metadata *> Ops)
841       : DIType(C, DICompositeTypeKind, Storage, Tag, Line, SizeInBits,
842                AlignInBits, OffsetInBits, Flags, Ops),
843         RuntimeLang(RuntimeLang) {}
844   ~DICompositeType() = default;
845
846   /// Change fields in place.
847   void mutate(unsigned Tag, unsigned Line, unsigned RuntimeLang,
848               uint64_t SizeInBits, uint32_t AlignInBits,
849               uint64_t OffsetInBits, DIFlags Flags) {
850     assert(isDistinct() && "Only distinct nodes can mutate");
851     assert(getRawIdentifier() && "Only ODR-uniqued nodes should mutate");
852     this->RuntimeLang = RuntimeLang;
853     DIType::mutate(Tag, Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
854   }
855
856   static DICompositeType *
857   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, Metadata *File,
858           unsigned Line, DIScopeRef Scope, DITypeRef BaseType,
859           uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
860           DIFlags Flags, DINodeArray Elements, unsigned RuntimeLang,
861           DITypeRef VTableHolder, DITemplateParameterArray TemplateParams,
862           StringRef Identifier, StorageType Storage, bool ShouldCreate = true) {
863     return getImpl(
864         Context, Tag, getCanonicalMDString(Context, Name), File, Line, Scope,
865         BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements.get(),
866         RuntimeLang, VTableHolder, TemplateParams.get(),
867         getCanonicalMDString(Context, Identifier), Storage, ShouldCreate);
868   }
869   static DICompositeType *
870   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
871           unsigned Line, Metadata *Scope, Metadata *BaseType,
872           uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
873           DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
874           Metadata *VTableHolder, Metadata *TemplateParams,
875           MDString *Identifier, StorageType Storage, bool ShouldCreate = true);
876
877   TempDICompositeType cloneImpl() const {
878     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
879                         getScope(), getBaseType(), getSizeInBits(),
880                         getAlignInBits(), getOffsetInBits(), getFlags(),
881                         getElements(), getRuntimeLang(), getVTableHolder(),
882                         getTemplateParams(), getIdentifier());
883   }
884
885 public:
886   DEFINE_MDNODE_GET(DICompositeType,
887                     (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
888                      DIScopeRef Scope, DITypeRef BaseType, uint64_t SizeInBits,
889                      uint32_t AlignInBits, uint64_t OffsetInBits,
890                      DIFlags Flags, DINodeArray Elements, unsigned RuntimeLang,
891                      DITypeRef VTableHolder,
892                      DITemplateParameterArray TemplateParams = nullptr,
893                      StringRef Identifier = ""),
894                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
895                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
896                      VTableHolder, TemplateParams, Identifier))
897   DEFINE_MDNODE_GET(DICompositeType,
898                     (unsigned Tag, MDString *Name, Metadata *File,
899                      unsigned Line, Metadata *Scope, Metadata *BaseType,
900                      uint64_t SizeInBits, uint32_t AlignInBits,
901                      uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements,
902                      unsigned RuntimeLang, Metadata *VTableHolder,
903                      Metadata *TemplateParams = nullptr,
904                      MDString *Identifier = nullptr),
905                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
906                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
907                      VTableHolder, TemplateParams, Identifier))
908
909   TempDICompositeType clone() const { return cloneImpl(); }
910
911   /// Get a DICompositeType with the given ODR identifier.
912   ///
913   /// If \a LLVMContext::isODRUniquingDebugTypes(), gets the mapped
914   /// DICompositeType for the given ODR \c Identifier.  If none exists, creates
915   /// a new node.
916   ///
917   /// Else, returns \c nullptr.
918   static DICompositeType *
919   getODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag,
920              MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
921              Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits,
922              uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements,
923              unsigned RuntimeLang, Metadata *VTableHolder,
924              Metadata *TemplateParams);
925   static DICompositeType *getODRTypeIfExists(LLVMContext &Context,
926                                              MDString &Identifier);
927
928   /// Build a DICompositeType with the given ODR identifier.
929   ///
930   /// Looks up the mapped DICompositeType for the given ODR \c Identifier.  If
931   /// it doesn't exist, creates a new one.  If it does exist and \a
932   /// isForwardDecl(), and the new arguments would be a definition, mutates the
933   /// the type in place.  In either case, returns the type.
934   ///
935   /// If not \a LLVMContext::isODRUniquingDebugTypes(), this function returns
936   /// nullptr.
937   static DICompositeType *
938   buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag,
939                MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
940                Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits,
941                uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements,
942                unsigned RuntimeLang, Metadata *VTableHolder,
943                Metadata *TemplateParams);
944
945   DITypeRef getBaseType() const { return DITypeRef(getRawBaseType()); }
946   DINodeArray getElements() const {
947     return cast_or_null<MDTuple>(getRawElements());
948   }
949   DITypeRef getVTableHolder() const { return DITypeRef(getRawVTableHolder()); }
950   DITemplateParameterArray getTemplateParams() const {
951     return cast_or_null<MDTuple>(getRawTemplateParams());
952   }
953   StringRef getIdentifier() const { return getStringOperand(7); }
954   unsigned getRuntimeLang() const { return RuntimeLang; }
955
956   Metadata *getRawBaseType() const { return getOperand(3); }
957   Metadata *getRawElements() const { return getOperand(4); }
958   Metadata *getRawVTableHolder() const { return getOperand(5); }
959   Metadata *getRawTemplateParams() const { return getOperand(6); }
960   MDString *getRawIdentifier() const { return getOperandAs<MDString>(7); }
961
962   /// Replace operands.
963   ///
964   /// If this \a isUniqued() and not \a isResolved(), on a uniquing collision
965   /// this will be RAUW'ed and deleted.  Use a \a TrackingMDRef to keep track
966   /// of its movement if necessary.
967   /// @{
968   void replaceElements(DINodeArray Elements) {
969 #ifndef NDEBUG
970     for (DINode *Op : getElements())
971       assert(is_contained(Elements->operands(), Op) &&
972              "Lost a member during member list replacement");
973 #endif
974     replaceOperandWith(4, Elements.get());
975   }
976
977   void replaceVTableHolder(DITypeRef VTableHolder) {
978     replaceOperandWith(5, VTableHolder);
979   }
980
981   void replaceTemplateParams(DITemplateParameterArray TemplateParams) {
982     replaceOperandWith(6, TemplateParams.get());
983   }
984   /// @}
985
986   static bool classof(const Metadata *MD) {
987     return MD->getMetadataID() == DICompositeTypeKind;
988   }
989 };
990
991 /// Type array for a subprogram.
992 ///
993 /// TODO: Fold the array of types in directly as operands.
994 class DISubroutineType : public DIType {
995   friend class LLVMContextImpl;
996   friend class MDNode;
997
998   /// The calling convention used with DW_AT_calling_convention. Actually of
999   /// type dwarf::CallingConvention.
1000   uint8_t CC;
1001
1002   DISubroutineType(LLVMContext &C, StorageType Storage, DIFlags Flags,
1003                    uint8_t CC, ArrayRef<Metadata *> Ops)
1004       : DIType(C, DISubroutineTypeKind, Storage, dwarf::DW_TAG_subroutine_type,
1005                0, 0, 0, 0, Flags, Ops),
1006         CC(CC) {}
1007   ~DISubroutineType() = default;
1008
1009   static DISubroutineType *getImpl(LLVMContext &Context, DIFlags Flags,
1010                                    uint8_t CC, DITypeRefArray TypeArray,
1011                                    StorageType Storage,
1012                                    bool ShouldCreate = true) {
1013     return getImpl(Context, Flags, CC, TypeArray.get(), Storage, ShouldCreate);
1014   }
1015   static DISubroutineType *getImpl(LLVMContext &Context, DIFlags Flags,
1016                                    uint8_t CC, Metadata *TypeArray,
1017                                    StorageType Storage,
1018                                    bool ShouldCreate = true);
1019
1020   TempDISubroutineType cloneImpl() const {
1021     return getTemporary(getContext(), getFlags(), getCC(), getTypeArray());
1022   }
1023
1024 public:
1025   DEFINE_MDNODE_GET(DISubroutineType,
1026                     (DIFlags Flags, uint8_t CC, DITypeRefArray TypeArray),
1027                     (Flags, CC, TypeArray))
1028   DEFINE_MDNODE_GET(DISubroutineType,
1029                     (DIFlags Flags, uint8_t CC, Metadata *TypeArray),
1030                     (Flags, CC, TypeArray))
1031
1032   TempDISubroutineType clone() const { return cloneImpl(); }
1033
1034   uint8_t getCC() const { return CC; }
1035
1036   DITypeRefArray getTypeArray() const {
1037     return cast_or_null<MDTuple>(getRawTypeArray());
1038   }
1039
1040   Metadata *getRawTypeArray() const { return getOperand(3); }
1041
1042   static bool classof(const Metadata *MD) {
1043     return MD->getMetadataID() == DISubroutineTypeKind;
1044   }
1045 };
1046
1047 /// Compile unit.
1048 class DICompileUnit : public DIScope {
1049   friend class LLVMContextImpl;
1050   friend class MDNode;
1051
1052 public:
1053   enum DebugEmissionKind : unsigned {
1054     NoDebug = 0,
1055     FullDebug,
1056     LineTablesOnly,
1057     LastEmissionKind = LineTablesOnly
1058   };
1059
1060   static Optional<DebugEmissionKind> getEmissionKind(StringRef Str);
1061   static const char *EmissionKindString(DebugEmissionKind EK);
1062
1063 private:
1064   unsigned SourceLanguage;
1065   bool IsOptimized;
1066   unsigned RuntimeVersion;
1067   unsigned EmissionKind;
1068   uint64_t DWOId;
1069   bool SplitDebugInlining;
1070   bool DebugInfoForProfiling;
1071
1072   DICompileUnit(LLVMContext &C, StorageType Storage, unsigned SourceLanguage,
1073                 bool IsOptimized, unsigned RuntimeVersion,
1074                 unsigned EmissionKind, uint64_t DWOId, bool SplitDebugInlining,
1075                 bool DebugInfoForProfiling, ArrayRef<Metadata *> Ops)
1076       : DIScope(C, DICompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
1077         SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
1078         RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind),
1079         DWOId(DWOId), SplitDebugInlining(SplitDebugInlining),
1080         DebugInfoForProfiling(DebugInfoForProfiling) {
1081     assert(Storage != Uniqued);
1082   }
1083   ~DICompileUnit() = default;
1084
1085   static DICompileUnit *
1086   getImpl(LLVMContext &Context, unsigned SourceLanguage, DIFile *File,
1087           StringRef Producer, bool IsOptimized, StringRef Flags,
1088           unsigned RuntimeVersion, StringRef SplitDebugFilename,
1089           unsigned EmissionKind, DICompositeTypeArray EnumTypes,
1090           DIScopeArray RetainedTypes,
1091           DIGlobalVariableExpressionArray GlobalVariables,
1092           DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
1093           uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
1094           StorageType Storage, bool ShouldCreate = true) {
1095     return getImpl(Context, SourceLanguage, File,
1096                    getCanonicalMDString(Context, Producer), IsOptimized,
1097                    getCanonicalMDString(Context, Flags), RuntimeVersion,
1098                    getCanonicalMDString(Context, SplitDebugFilename),
1099                    EmissionKind, EnumTypes.get(), RetainedTypes.get(),
1100                    GlobalVariables.get(), ImportedEntities.get(), Macros.get(),
1101                    DWOId, SplitDebugInlining, DebugInfoForProfiling, Storage,
1102                    ShouldCreate);
1103   }
1104   static DICompileUnit *
1105   getImpl(LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
1106           MDString *Producer, bool IsOptimized, MDString *Flags,
1107           unsigned RuntimeVersion, MDString *SplitDebugFilename,
1108           unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
1109           Metadata *GlobalVariables, Metadata *ImportedEntities,
1110           Metadata *Macros, uint64_t DWOId, bool SplitDebugInlining,
1111           bool DebugInfoForProfiling, StorageType Storage,
1112           bool ShouldCreate = true);
1113
1114   TempDICompileUnit cloneImpl() const {
1115     return getTemporary(getContext(), getSourceLanguage(), getFile(),
1116                         getProducer(), isOptimized(), getFlags(),
1117                         getRuntimeVersion(), getSplitDebugFilename(),
1118                         getEmissionKind(), getEnumTypes(), getRetainedTypes(),
1119                         getGlobalVariables(), getImportedEntities(),
1120                         getMacros(), DWOId, getSplitDebugInlining(),
1121                         getDebugInfoForProfiling());
1122   }
1123
1124 public:
1125   static void get() = delete;
1126   static void getIfExists() = delete;
1127
1128   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
1129       DICompileUnit,
1130       (unsigned SourceLanguage, DIFile *File, StringRef Producer,
1131        bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
1132        StringRef SplitDebugFilename, DebugEmissionKind EmissionKind,
1133        DICompositeTypeArray EnumTypes, DIScopeArray RetainedTypes,
1134        DIGlobalVariableExpressionArray GlobalVariables,
1135        DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
1136        uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling),
1137       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
1138        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
1139        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
1140        DebugInfoForProfiling))
1141   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
1142       DICompileUnit,
1143       (unsigned SourceLanguage, Metadata *File, MDString *Producer,
1144        bool IsOptimized, MDString *Flags, unsigned RuntimeVersion,
1145        MDString *SplitDebugFilename, unsigned EmissionKind, Metadata *EnumTypes,
1146        Metadata *RetainedTypes, Metadata *GlobalVariables,
1147        Metadata *ImportedEntities, Metadata *Macros, uint64_t DWOId,
1148        bool SplitDebugInlining, bool DebugInfoForProfiling),
1149       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
1150        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
1151        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
1152        DebugInfoForProfiling))
1153
1154   TempDICompileUnit clone() const { return cloneImpl(); }
1155
1156   unsigned getSourceLanguage() const { return SourceLanguage; }
1157   bool isOptimized() const { return IsOptimized; }
1158   unsigned getRuntimeVersion() const { return RuntimeVersion; }
1159   DebugEmissionKind getEmissionKind() const {
1160     return (DebugEmissionKind)EmissionKind;
1161   }
1162   bool getDebugInfoForProfiling() const { return DebugInfoForProfiling; }
1163   StringRef getProducer() const { return getStringOperand(1); }
1164   StringRef getFlags() const { return getStringOperand(2); }
1165   StringRef getSplitDebugFilename() const { return getStringOperand(3); }
1166   DICompositeTypeArray getEnumTypes() const {
1167     return cast_or_null<MDTuple>(getRawEnumTypes());
1168   }
1169   DIScopeArray getRetainedTypes() const {
1170     return cast_or_null<MDTuple>(getRawRetainedTypes());
1171   }
1172   DIGlobalVariableExpressionArray getGlobalVariables() const {
1173     return cast_or_null<MDTuple>(getRawGlobalVariables());
1174   }
1175   DIImportedEntityArray getImportedEntities() const {
1176     return cast_or_null<MDTuple>(getRawImportedEntities());
1177   }
1178   DIMacroNodeArray getMacros() const {
1179     return cast_or_null<MDTuple>(getRawMacros());
1180   }
1181   uint64_t getDWOId() const { return DWOId; }
1182   void setDWOId(uint64_t DwoId) { DWOId = DwoId; }
1183   bool getSplitDebugInlining() const { return SplitDebugInlining; }
1184   void setSplitDebugInlining(bool SplitDebugInlining) {
1185     this->SplitDebugInlining = SplitDebugInlining;
1186   }
1187
1188   MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
1189   MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
1190   MDString *getRawSplitDebugFilename() const {
1191     return getOperandAs<MDString>(3);
1192   }
1193   Metadata *getRawEnumTypes() const { return getOperand(4); }
1194   Metadata *getRawRetainedTypes() const { return getOperand(5); }
1195   Metadata *getRawGlobalVariables() const { return getOperand(6); }
1196   Metadata *getRawImportedEntities() const { return getOperand(7); }
1197   Metadata *getRawMacros() const { return getOperand(8); }
1198
1199   /// Replace arrays.
1200   ///
1201   /// If this \a isUniqued() and not \a isResolved(), it will be RAUW'ed and
1202   /// deleted on a uniquing collision.  In practice, uniquing collisions on \a
1203   /// DICompileUnit should be fairly rare.
1204   /// @{
1205   void replaceEnumTypes(DICompositeTypeArray N) {
1206     replaceOperandWith(4, N.get());
1207   }
1208   void replaceRetainedTypes(DITypeArray N) {
1209     replaceOperandWith(5, N.get());
1210   }
1211   void replaceGlobalVariables(DIGlobalVariableExpressionArray N) {
1212     replaceOperandWith(6, N.get());
1213   }
1214   void replaceImportedEntities(DIImportedEntityArray N) {
1215     replaceOperandWith(7, N.get());
1216   }
1217   void replaceMacros(DIMacroNodeArray N) { replaceOperandWith(8, N.get()); }
1218   /// @}
1219
1220   static bool classof(const Metadata *MD) {
1221     return MD->getMetadataID() == DICompileUnitKind;
1222   }
1223 };
1224
1225 /// A scope for locals.
1226 ///
1227 /// A legal scope for lexical blocks, local variables, and debug info
1228 /// locations.  Subclasses are \a DISubprogram, \a DILexicalBlock, and \a
1229 /// DILexicalBlockFile.
1230 class DILocalScope : public DIScope {
1231 protected:
1232   DILocalScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1233                ArrayRef<Metadata *> Ops)
1234       : DIScope(C, ID, Storage, Tag, Ops) {}
1235   ~DILocalScope() = default;
1236
1237 public:
1238   /// Get the subprogram for this scope.
1239   ///
1240   /// Return this if it's an \a DISubprogram; otherwise, look up the scope
1241   /// chain.
1242   DISubprogram *getSubprogram() const;
1243
1244   /// Get the first non DILexicalBlockFile scope of this scope.
1245   ///
1246   /// Return this if it's not a \a DILexicalBlockFIle; otherwise, look up the
1247   /// scope chain.
1248   DILocalScope *getNonLexicalBlockFileScope() const;
1249
1250   static bool classof(const Metadata *MD) {
1251     return MD->getMetadataID() == DISubprogramKind ||
1252            MD->getMetadataID() == DILexicalBlockKind ||
1253            MD->getMetadataID() == DILexicalBlockFileKind;
1254   }
1255 };
1256
1257 /// Debug location.
1258 ///
1259 /// A debug location in source code, used for debug info and otherwise.
1260 class DILocation : public MDNode {
1261   friend class LLVMContextImpl;
1262   friend class MDNode;
1263
1264   DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
1265              unsigned Column, ArrayRef<Metadata *> MDs);
1266   ~DILocation() { dropAllReferences(); }
1267
1268   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
1269                              unsigned Column, Metadata *Scope,
1270                              Metadata *InlinedAt, StorageType Storage,
1271                              bool ShouldCreate = true);
1272   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
1273                              unsigned Column, DILocalScope *Scope,
1274                              DILocation *InlinedAt, StorageType Storage,
1275                              bool ShouldCreate = true) {
1276     return getImpl(Context, Line, Column, static_cast<Metadata *>(Scope),
1277                    static_cast<Metadata *>(InlinedAt), Storage, ShouldCreate);
1278   }
1279
1280   /// With a given unsigned int \p U, use up to 13 bits to represent it.
1281   /// old_bit 1~5  --> new_bit 1~5
1282   /// old_bit 6~12 --> new_bit 7~13
1283   /// new_bit_6 is 0 if higher bits (7~13) are all 0
1284   static unsigned getPrefixEncodingFromUnsigned(unsigned U) {
1285     U &= 0xfff;
1286     return U > 0x1f ? (((U & 0xfe0) << 1) | (U & 0x1f) | 0x20) : U;
1287   }
1288
1289   /// Reverse transformation as getPrefixEncodingFromUnsigned.
1290   static unsigned getUnsignedFromPrefixEncoding(unsigned U) {
1291     return (U & 0x20) ? (((U >> 1) & 0xfe0) | (U & 0x1f)) : (U & 0x1f);
1292   }
1293
1294   /// Returns the next component stored in discriminator.
1295   static unsigned getNextComponentInDiscriminator(unsigned D) {
1296     if ((D & 1) == 0)
1297       return D >> ((D & 0x40) ? 14 : 7);
1298     else
1299       return D >> 1;
1300   }
1301
1302   TempDILocation cloneImpl() const {
1303     // Get the raw scope/inlinedAt since it is possible to invoke this on
1304     // a DILocation containing temporary metadata.
1305     return getTemporary(getContext(), getLine(), getColumn(), getRawScope(),
1306                         getRawInlinedAt());
1307   }
1308
1309 public:
1310   // Disallow replacing operands.
1311   void replaceOperandWith(unsigned I, Metadata *New) = delete;
1312
1313   DEFINE_MDNODE_GET(DILocation,
1314                     (unsigned Line, unsigned Column, Metadata *Scope,
1315                      Metadata *InlinedAt = nullptr),
1316                     (Line, Column, Scope, InlinedAt))
1317   DEFINE_MDNODE_GET(DILocation,
1318                     (unsigned Line, unsigned Column, DILocalScope *Scope,
1319                      DILocation *InlinedAt = nullptr),
1320                     (Line, Column, Scope, InlinedAt))
1321
1322   /// Return a (temporary) clone of this.
1323   TempDILocation clone() const { return cloneImpl(); }
1324
1325   unsigned getLine() const { return SubclassData32; }
1326   unsigned getColumn() const { return SubclassData16; }
1327   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
1328
1329   DILocation *getInlinedAt() const {
1330     return cast_or_null<DILocation>(getRawInlinedAt());
1331   }
1332
1333   DIFile *getFile() const { return getScope()->getFile(); }
1334   StringRef getFilename() const { return getScope()->getFilename(); }
1335   StringRef getDirectory() const { return getScope()->getDirectory(); }
1336
1337   /// Get the scope where this is inlined.
1338   ///
1339   /// Walk through \a getInlinedAt() and return \a getScope() from the deepest
1340   /// location.
1341   DILocalScope *getInlinedAtScope() const {
1342     if (auto *IA = getInlinedAt())
1343       return IA->getInlinedAtScope();
1344     return getScope();
1345   }
1346
1347   /// Check whether this can be discriminated from another location.
1348   ///
1349   /// Check \c this can be discriminated from \c RHS in a linetable entry.
1350   /// Scope and inlined-at chains are not recorded in the linetable, so they
1351   /// cannot be used to distinguish basic blocks.
1352   bool canDiscriminate(const DILocation &RHS) const {
1353     return getLine() != RHS.getLine() ||
1354            getColumn() != RHS.getColumn() ||
1355            getDiscriminator() != RHS.getDiscriminator() ||
1356            getFilename() != RHS.getFilename() ||
1357            getDirectory() != RHS.getDirectory();
1358   }
1359
1360   /// Get the DWARF discriminator.
1361   ///
1362   /// DWARF discriminators distinguish identical file locations between
1363   /// instructions that are on different basic blocks.
1364   ///
1365   /// There are 3 components stored in discriminator, from lower bits:
1366   ///
1367   /// Base discriminator: assigned by AddDiscriminators pass to identify IRs
1368   ///                     that are defined by the same source line, but
1369   ///                     different basic blocks.
1370   /// Duplication factor: assigned by optimizations that will scale down
1371   ///                     the execution frequency of the original IR.
1372   /// Copy Identifier: assigned by optimizations that clones the IR.
1373   ///                  Each copy of the IR will be assigned an identifier.
1374   ///
1375   /// Encoding:
1376   ///
1377   /// The above 3 components are encoded into a 32bit unsigned integer in
1378   /// order. If the lowest bit is 1, the current component is empty, and the
1379   /// next component will start in the next bit. Otherwise, the the current
1380   /// component is non-empty, and its content starts in the next bit. The
1381   /// length of each components is either 5 bit or 12 bit: if the 7th bit
1382   /// is 0, the bit 2~6 (5 bits) are used to represent the component; if the
1383   /// 7th bit is 1, the bit 2~6 (5 bits) and 8~14 (7 bits) are combined to
1384   /// represent the component.
1385
1386   inline unsigned getDiscriminator() const;
1387
1388   /// Returns a new DILocation with updated \p Discriminator.
1389   inline const DILocation *cloneWithDiscriminator(unsigned Discriminator) const;
1390
1391   /// Returns a new DILocation with updated base discriminator \p BD.
1392   inline const DILocation *setBaseDiscriminator(unsigned BD) const;
1393
1394   /// Returns the duplication factor stored in the discriminator.
1395   inline unsigned getDuplicationFactor() const;
1396
1397   /// Returns the copy identifier stored in the discriminator.
1398   inline unsigned getCopyIdentifier() const;
1399
1400   /// Returns the base discriminator stored in the discriminator.
1401   inline unsigned getBaseDiscriminator() const;
1402
1403   /// Returns a new DILocation with duplication factor \p DF encoded in the
1404   /// discriminator.
1405   inline const DILocation *cloneWithDuplicationFactor(unsigned DF) const;
1406
1407   /// When two instructions are combined into a single instruction we also
1408   /// need to combine the original locations into a single location.
1409   ///
1410   /// When the locations are the same we can use either location. When they
1411   /// differ, we need a third location which is distinct from either. If
1412   /// they have the same file/line but have a different discriminator we
1413   /// could create a location with a new discriminator. If they are from
1414   /// different files/lines the location is ambiguous and can't be
1415   /// represented in a single line entry.  In this case, no location
1416   /// should be set.
1417   ///
1418   /// Currently the function does not create a new location. If the locations
1419   /// are the same, or cannot be discriminated, the first location is returned.
1420   /// Otherwise an empty location will be used.
1421   static const DILocation *getMergedLocation(const DILocation *LocA,
1422                                              const DILocation *LocB) {
1423     if (LocA && LocB && (LocA == LocB || !LocA->canDiscriminate(*LocB)))
1424       return LocA;
1425     return nullptr;
1426   }
1427
1428   /// Returns the base discriminator for a given encoded discriminator \p D.
1429   static unsigned getBaseDiscriminatorFromDiscriminator(unsigned D) {
1430     if ((D & 1) == 0)
1431       return getUnsignedFromPrefixEncoding(D >> 1);
1432     else
1433       return 0;
1434   }
1435
1436   /// Returns the duplication factor for a given encoded discriminator \p D.
1437   static unsigned getDuplicationFactorFromDiscriminator(unsigned D) {
1438     D = getNextComponentInDiscriminator(D);
1439     if (D == 0 || (D & 1))
1440       return 1;
1441     else
1442       return getUnsignedFromPrefixEncoding(D >> 1);
1443   }
1444
1445   /// Returns the copy identifier for a given encoded discriminator \p D.
1446   static unsigned getCopyIdentifierFromDiscriminator(unsigned D) {
1447     return getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(
1448         getNextComponentInDiscriminator(D)));
1449   }
1450
1451
1452   Metadata *getRawScope() const { return getOperand(0); }
1453   Metadata *getRawInlinedAt() const {
1454     if (getNumOperands() == 2)
1455       return getOperand(1);
1456     return nullptr;
1457   }
1458
1459   static bool classof(const Metadata *MD) {
1460     return MD->getMetadataID() == DILocationKind;
1461   }
1462 };
1463
1464 /// Subprogram description.
1465 ///
1466 /// TODO: Remove DisplayName.  It's always equal to Name.
1467 /// TODO: Split up flags.
1468 class DISubprogram : public DILocalScope {
1469   friend class LLVMContextImpl;
1470   friend class MDNode;
1471
1472   unsigned Line;
1473   unsigned ScopeLine;
1474   unsigned VirtualIndex;
1475
1476   /// In the MS ABI, the implicit 'this' parameter is adjusted in the prologue
1477   /// of method overrides from secondary bases by this amount. It may be
1478   /// negative.
1479   int ThisAdjustment;
1480
1481   // Virtuality can only assume three values, so we can pack
1482   // in 2 bits (none/pure/pure_virtual).
1483   unsigned Virtuality : 2;
1484
1485   // These are boolean flags so one bit is enough.
1486   // MSVC starts a new container field every time the base
1487   // type changes so we can't use 'bool' to ensure these bits
1488   // are packed.
1489   unsigned IsLocalToUnit : 1;
1490   unsigned IsDefinition : 1;
1491   unsigned IsOptimized : 1;
1492
1493   unsigned Padding : 3;
1494
1495   DIFlags Flags;
1496
1497   DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
1498                unsigned ScopeLine, unsigned Virtuality, unsigned VirtualIndex,
1499                int ThisAdjustment, DIFlags Flags, bool IsLocalToUnit,
1500                bool IsDefinition, bool IsOptimized, ArrayRef<Metadata *> Ops)
1501       : DILocalScope(C, DISubprogramKind, Storage, dwarf::DW_TAG_subprogram,
1502                      Ops),
1503         Line(Line), ScopeLine(ScopeLine), VirtualIndex(VirtualIndex),
1504         ThisAdjustment(ThisAdjustment), Virtuality(Virtuality),
1505         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition),
1506         IsOptimized(IsOptimized), Flags(Flags) {
1507     static_assert(dwarf::DW_VIRTUALITY_max < 4, "Virtuality out of range");
1508     assert(Virtuality < 4 && "Virtuality out of range");
1509   }
1510   ~DISubprogram() = default;
1511
1512   static DISubprogram *
1513   getImpl(LLVMContext &Context, DIScopeRef Scope, StringRef Name,
1514           StringRef LinkageName, DIFile *File, unsigned Line,
1515           DISubroutineType *Type, bool IsLocalToUnit, bool IsDefinition,
1516           unsigned ScopeLine, DITypeRef ContainingType, unsigned Virtuality,
1517           unsigned VirtualIndex, int ThisAdjustment, DIFlags Flags,
1518           bool IsOptimized, DICompileUnit *Unit,
1519           DITemplateParameterArray TemplateParams, DISubprogram *Declaration,
1520           DILocalVariableArray Variables, DITypeArray ThrownTypes,
1521           StorageType Storage, bool ShouldCreate = true) {
1522     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1523                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1524                    IsLocalToUnit, IsDefinition, ScopeLine, ContainingType,
1525                    Virtuality, VirtualIndex, ThisAdjustment, Flags, IsOptimized,
1526                    Unit, TemplateParams.get(), Declaration, Variables.get(),
1527                    ThrownTypes.get(), Storage, ShouldCreate);
1528   }
1529   static DISubprogram *
1530   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1531           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1532           bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1533           Metadata *ContainingType, unsigned Virtuality, unsigned VirtualIndex,
1534           int ThisAdjustment, DIFlags Flags, bool IsOptimized, Metadata *Unit,
1535           Metadata *TemplateParams, Metadata *Declaration, Metadata *Variables,
1536           Metadata *ThrownTypes, StorageType Storage, bool ShouldCreate = true);
1537
1538   TempDISubprogram cloneImpl() const {
1539     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1540                         getFile(), getLine(), getType(), isLocalToUnit(),
1541                         isDefinition(), getScopeLine(), getContainingType(),
1542                         getVirtuality(), getVirtualIndex(), getThisAdjustment(),
1543                         getFlags(), isOptimized(), getUnit(),
1544                         getTemplateParams(), getDeclaration(), getVariables(),
1545                         getThrownTypes());
1546   }
1547
1548 public:
1549   DEFINE_MDNODE_GET(DISubprogram,
1550                     (DIScopeRef Scope, StringRef Name, StringRef LinkageName,
1551                      DIFile *File, unsigned Line, DISubroutineType *Type,
1552                      bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1553                      DITypeRef ContainingType, unsigned Virtuality,
1554                      unsigned VirtualIndex, int ThisAdjustment, DIFlags Flags,
1555                      bool IsOptimized, DICompileUnit *Unit,
1556                      DITemplateParameterArray TemplateParams = nullptr,
1557                      DISubprogram *Declaration = nullptr,
1558                      DILocalVariableArray Variables = nullptr,
1559                      DITypeArray ThrownTypes = nullptr),
1560                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1561                      IsDefinition, ScopeLine, ContainingType, Virtuality,
1562                      VirtualIndex, ThisAdjustment, Flags, IsOptimized, Unit,
1563                      TemplateParams, Declaration, Variables, ThrownTypes))
1564   DEFINE_MDNODE_GET(
1565       DISubprogram,
1566       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
1567        unsigned Line, Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
1568        unsigned ScopeLine, Metadata *ContainingType, unsigned Virtuality,
1569        unsigned VirtualIndex, int ThisAdjustment, DIFlags Flags,
1570        bool IsOptimized, Metadata *Unit, Metadata *TemplateParams = nullptr,
1571        Metadata *Declaration = nullptr, Metadata *Variables = nullptr,
1572        Metadata *ThrownTypes = nullptr),
1573       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
1574        ScopeLine, ContainingType, Virtuality, VirtualIndex, ThisAdjustment,
1575        Flags, IsOptimized, Unit, TemplateParams, Declaration, Variables,
1576        ThrownTypes))
1577
1578   TempDISubprogram clone() const { return cloneImpl(); }
1579
1580 public:
1581   unsigned getLine() const { return Line; }
1582   unsigned getVirtuality() const { return Virtuality; }
1583   unsigned getVirtualIndex() const { return VirtualIndex; }
1584   int getThisAdjustment() const { return ThisAdjustment; }
1585   unsigned getScopeLine() const { return ScopeLine; }
1586   DIFlags getFlags() const { return Flags; }
1587   bool isLocalToUnit() const { return IsLocalToUnit; }
1588   bool isDefinition() const { return IsDefinition; }
1589   bool isOptimized() const { return IsOptimized; }
1590
1591   bool isArtificial() const { return getFlags() & FlagArtificial; }
1592   bool isPrivate() const {
1593     return (getFlags() & FlagAccessibility) == FlagPrivate;
1594   }
1595   bool isProtected() const {
1596     return (getFlags() & FlagAccessibility) == FlagProtected;
1597   }
1598   bool isPublic() const {
1599     return (getFlags() & FlagAccessibility) == FlagPublic;
1600   }
1601   bool isExplicit() const { return getFlags() & FlagExplicit; }
1602   bool isPrototyped() const { return getFlags() & FlagPrototyped; }
1603   bool isMainSubprogram() const { return getFlags() & FlagMainSubprogram; }
1604
1605   /// Check if this is reference-qualified.
1606   ///
1607   /// Return true if this subprogram is a C++11 reference-qualified non-static
1608   /// member function (void foo() &).
1609   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
1610
1611   /// Check if this is rvalue-reference-qualified.
1612   ///
1613   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
1614   /// non-static member function (void foo() &&).
1615   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
1616
1617   /// Check if this is marked as noreturn.
1618   ///
1619   /// Return true if this subprogram is C++11 noreturn or C11 _Noreturn
1620   bool isNoReturn() const { return getFlags() & FlagNoReturn; }
1621
1622   DIScopeRef getScope() const { return DIScopeRef(getRawScope()); }
1623
1624   StringRef getName() const { return getStringOperand(2); }
1625   StringRef getLinkageName() const { return getStringOperand(3); }
1626
1627   DISubroutineType *getType() const {
1628     return cast_or_null<DISubroutineType>(getRawType());
1629   }
1630   DITypeRef getContainingType() const {
1631     return DITypeRef(getRawContainingType());
1632   }
1633
1634   DICompileUnit *getUnit() const {
1635     return cast_or_null<DICompileUnit>(getRawUnit());
1636   }
1637   void replaceUnit(DICompileUnit *CU) { replaceOperandWith(5, CU); }
1638   DITemplateParameterArray getTemplateParams() const {
1639     return cast_or_null<MDTuple>(getRawTemplateParams());
1640   }
1641   DISubprogram *getDeclaration() const {
1642     return cast_or_null<DISubprogram>(getRawDeclaration());
1643   }
1644   DILocalVariableArray getVariables() const {
1645     return cast_or_null<MDTuple>(getRawVariables());
1646   }
1647   DITypeArray getThrownTypes() const {
1648     return cast_or_null<MDTuple>(getRawThrownTypes());
1649   }
1650
1651   Metadata *getRawScope() const { return getOperand(1); }
1652   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1653   MDString *getRawLinkageName() const { return getOperandAs<MDString>(3); }
1654   Metadata *getRawType() const { return getOperand(4); }
1655   Metadata *getRawUnit() const { return getOperand(5); }
1656   Metadata *getRawDeclaration() const { return getOperand(6); }
1657   Metadata *getRawVariables() const { return getOperand(7); }
1658   Metadata *getRawContainingType() const {
1659     return getNumOperands() > 8 ? getOperandAs<Metadata>(8) : nullptr;
1660   }
1661   Metadata *getRawTemplateParams() const {
1662     return getNumOperands() > 9 ? getOperandAs<Metadata>(9) : nullptr;
1663   }
1664   Metadata *getRawThrownTypes() const {
1665     return getNumOperands() > 10 ? getOperandAs<Metadata>(10) : nullptr;
1666   }
1667
1668   /// Check if this subprogram describes the given function.
1669   ///
1670   /// FIXME: Should this be looking through bitcasts?
1671   bool describes(const Function *F) const;
1672
1673   static bool classof(const Metadata *MD) {
1674     return MD->getMetadataID() == DISubprogramKind;
1675   }
1676 };
1677
1678 class DILexicalBlockBase : public DILocalScope {
1679 protected:
1680   DILexicalBlockBase(LLVMContext &C, unsigned ID, StorageType Storage,
1681                      ArrayRef<Metadata *> Ops)
1682       : DILocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
1683   ~DILexicalBlockBase() = default;
1684
1685 public:
1686   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
1687
1688   Metadata *getRawScope() const { return getOperand(1); }
1689
1690   static bool classof(const Metadata *MD) {
1691     return MD->getMetadataID() == DILexicalBlockKind ||
1692            MD->getMetadataID() == DILexicalBlockFileKind;
1693   }
1694 };
1695
1696 class DILexicalBlock : public DILexicalBlockBase {
1697   friend class LLVMContextImpl;
1698   friend class MDNode;
1699
1700   unsigned Line;
1701   uint16_t Column;
1702
1703   DILexicalBlock(LLVMContext &C, StorageType Storage, unsigned Line,
1704                  unsigned Column, ArrayRef<Metadata *> Ops)
1705       : DILexicalBlockBase(C, DILexicalBlockKind, Storage, Ops), Line(Line),
1706         Column(Column) {
1707     assert(Column < (1u << 16) && "Expected 16-bit column");
1708   }
1709   ~DILexicalBlock() = default;
1710
1711   static DILexicalBlock *getImpl(LLVMContext &Context, DILocalScope *Scope,
1712                                  DIFile *File, unsigned Line, unsigned Column,
1713                                  StorageType Storage,
1714                                  bool ShouldCreate = true) {
1715     return getImpl(Context, static_cast<Metadata *>(Scope),
1716                    static_cast<Metadata *>(File), Line, Column, Storage,
1717                    ShouldCreate);
1718   }
1719
1720   static DILexicalBlock *getImpl(LLVMContext &Context, Metadata *Scope,
1721                                  Metadata *File, unsigned Line, unsigned Column,
1722                                  StorageType Storage, bool ShouldCreate = true);
1723
1724   TempDILexicalBlock cloneImpl() const {
1725     return getTemporary(getContext(), getScope(), getFile(), getLine(),
1726                         getColumn());
1727   }
1728
1729 public:
1730   DEFINE_MDNODE_GET(DILexicalBlock, (DILocalScope * Scope, DIFile *File,
1731                                      unsigned Line, unsigned Column),
1732                     (Scope, File, Line, Column))
1733   DEFINE_MDNODE_GET(DILexicalBlock, (Metadata * Scope, Metadata *File,
1734                                      unsigned Line, unsigned Column),
1735                     (Scope, File, Line, Column))
1736
1737   TempDILexicalBlock clone() const { return cloneImpl(); }
1738
1739   unsigned getLine() const { return Line; }
1740   unsigned getColumn() const { return Column; }
1741
1742   static bool classof(const Metadata *MD) {
1743     return MD->getMetadataID() == DILexicalBlockKind;
1744   }
1745 };
1746
1747 class DILexicalBlockFile : public DILexicalBlockBase {
1748   friend class LLVMContextImpl;
1749   friend class MDNode;
1750
1751   unsigned Discriminator;
1752
1753   DILexicalBlockFile(LLVMContext &C, StorageType Storage,
1754                      unsigned Discriminator, ArrayRef<Metadata *> Ops)
1755       : DILexicalBlockBase(C, DILexicalBlockFileKind, Storage, Ops),
1756         Discriminator(Discriminator) {}
1757   ~DILexicalBlockFile() = default;
1758
1759   static DILexicalBlockFile *getImpl(LLVMContext &Context, DILocalScope *Scope,
1760                                      DIFile *File, unsigned Discriminator,
1761                                      StorageType Storage,
1762                                      bool ShouldCreate = true) {
1763     return getImpl(Context, static_cast<Metadata *>(Scope),
1764                    static_cast<Metadata *>(File), Discriminator, Storage,
1765                    ShouldCreate);
1766   }
1767
1768   static DILexicalBlockFile *getImpl(LLVMContext &Context, Metadata *Scope,
1769                                      Metadata *File, unsigned Discriminator,
1770                                      StorageType Storage,
1771                                      bool ShouldCreate = true);
1772
1773   TempDILexicalBlockFile cloneImpl() const {
1774     return getTemporary(getContext(), getScope(), getFile(),
1775                         getDiscriminator());
1776   }
1777
1778 public:
1779   DEFINE_MDNODE_GET(DILexicalBlockFile, (DILocalScope * Scope, DIFile *File,
1780                                          unsigned Discriminator),
1781                     (Scope, File, Discriminator))
1782   DEFINE_MDNODE_GET(DILexicalBlockFile,
1783                     (Metadata * Scope, Metadata *File, unsigned Discriminator),
1784                     (Scope, File, Discriminator))
1785
1786   TempDILexicalBlockFile clone() const { return cloneImpl(); }
1787
1788   // TODO: Remove these once they're gone from DILexicalBlockBase.
1789   unsigned getLine() const = delete;
1790   unsigned getColumn() const = delete;
1791
1792   unsigned getDiscriminator() const { return Discriminator; }
1793
1794   static bool classof(const Metadata *MD) {
1795     return MD->getMetadataID() == DILexicalBlockFileKind;
1796   }
1797 };
1798
1799 unsigned DILocation::getDiscriminator() const {
1800   if (auto *F = dyn_cast<DILexicalBlockFile>(getScope()))
1801     return F->getDiscriminator();
1802   return 0;
1803 }
1804
1805 const DILocation *
1806 DILocation::cloneWithDiscriminator(unsigned Discriminator) const {
1807   DIScope *Scope = getScope();
1808   // Skip all parent DILexicalBlockFile that already have a discriminator
1809   // assigned. We do not want to have nested DILexicalBlockFiles that have
1810   // mutliple discriminators because only the leaf DILexicalBlockFile's
1811   // dominator will be used.
1812   for (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope);
1813        LBF && LBF->getDiscriminator() != 0;
1814        LBF = dyn_cast<DILexicalBlockFile>(Scope))
1815     Scope = LBF->getScope();
1816   DILexicalBlockFile *NewScope =
1817       DILexicalBlockFile::get(getContext(), Scope, getFile(), Discriminator);
1818   return DILocation::get(getContext(), getLine(), getColumn(), NewScope,
1819                          getInlinedAt());
1820 }
1821
1822 unsigned DILocation::getBaseDiscriminator() const {
1823   return getBaseDiscriminatorFromDiscriminator(getDiscriminator());
1824 }
1825
1826 unsigned DILocation::getDuplicationFactor() const {
1827   return getDuplicationFactorFromDiscriminator(getDiscriminator());
1828 }
1829
1830 unsigned DILocation::getCopyIdentifier() const {
1831   return getCopyIdentifierFromDiscriminator(getDiscriminator());
1832 }
1833
1834 const DILocation *DILocation::setBaseDiscriminator(unsigned D) const {
1835   if (D == 0)
1836     return this;
1837   else
1838     return cloneWithDiscriminator(getPrefixEncodingFromUnsigned(D) << 1);
1839 }
1840
1841 const DILocation *DILocation::cloneWithDuplicationFactor(unsigned DF) const {
1842   DF *= getDuplicationFactor();
1843   if (DF <= 1)
1844     return this;
1845
1846   unsigned BD = getBaseDiscriminator();
1847   unsigned CI = getCopyIdentifier() << (DF > 0x1f ? 14 : 7);
1848   unsigned D = CI | (getPrefixEncodingFromUnsigned(DF) << 1);
1849
1850   if (BD == 0)
1851     D = (D << 1) | 1;
1852   else
1853     D = (D << (BD > 0x1f ? 14 : 7)) | (getPrefixEncodingFromUnsigned(BD) << 1);
1854
1855   return cloneWithDiscriminator(D);
1856 }
1857
1858 class DINamespace : public DIScope {
1859   friend class LLVMContextImpl;
1860   friend class MDNode;
1861
1862   unsigned ExportSymbols : 1;
1863
1864   DINamespace(LLVMContext &Context, StorageType Storage, bool ExportSymbols,
1865               ArrayRef<Metadata *> Ops)
1866       : DIScope(Context, DINamespaceKind, Storage, dwarf::DW_TAG_namespace,
1867                 Ops),
1868         ExportSymbols(ExportSymbols) {}
1869   ~DINamespace() = default;
1870
1871   static DINamespace *getImpl(LLVMContext &Context, DIScope *Scope,
1872                               StringRef Name, bool ExportSymbols,
1873                               StorageType Storage, bool ShouldCreate = true) {
1874     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1875                    ExportSymbols, Storage, ShouldCreate);
1876   }
1877   static DINamespace *getImpl(LLVMContext &Context, Metadata *Scope,
1878                               MDString *Name, bool ExportSymbols,
1879                               StorageType Storage, bool ShouldCreate = true);
1880
1881   TempDINamespace cloneImpl() const {
1882     return getTemporary(getContext(), getScope(), getName(),
1883                         getExportSymbols());
1884   }
1885
1886 public:
1887   DEFINE_MDNODE_GET(DINamespace,
1888                     (DIScope *Scope, StringRef Name, bool ExportSymbols),
1889                     (Scope, Name, ExportSymbols))
1890   DEFINE_MDNODE_GET(DINamespace,
1891                     (Metadata *Scope, MDString *Name, bool ExportSymbols),
1892                     (Scope, Name, ExportSymbols))
1893
1894   TempDINamespace clone() const { return cloneImpl(); }
1895
1896   bool getExportSymbols() const { return ExportSymbols; }
1897   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
1898   StringRef getName() const { return getStringOperand(2); }
1899
1900   Metadata *getRawScope() const { return getOperand(1); }
1901   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1902
1903   static bool classof(const Metadata *MD) {
1904     return MD->getMetadataID() == DINamespaceKind;
1905   }
1906 };
1907
1908 /// A (clang) module that has been imported by the compile unit.
1909 ///
1910 class DIModule : public DIScope {
1911   friend class LLVMContextImpl;
1912   friend class MDNode;
1913
1914   DIModule(LLVMContext &Context, StorageType Storage, ArrayRef<Metadata *> Ops)
1915       : DIScope(Context, DIModuleKind, Storage, dwarf::DW_TAG_module, Ops) {}
1916   ~DIModule() = default;
1917
1918   static DIModule *getImpl(LLVMContext &Context, DIScope *Scope,
1919                            StringRef Name, StringRef ConfigurationMacros,
1920                            StringRef IncludePath, StringRef ISysRoot,
1921                            StorageType Storage, bool ShouldCreate = true) {
1922     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1923                    getCanonicalMDString(Context, ConfigurationMacros),
1924                    getCanonicalMDString(Context, IncludePath),
1925                    getCanonicalMDString(Context, ISysRoot),
1926                    Storage, ShouldCreate);
1927   }
1928   static DIModule *getImpl(LLVMContext &Context, Metadata *Scope,
1929                            MDString *Name, MDString *ConfigurationMacros,
1930                            MDString *IncludePath, MDString *ISysRoot,
1931                            StorageType Storage, bool ShouldCreate = true);
1932
1933   TempDIModule cloneImpl() const {
1934     return getTemporary(getContext(), getScope(), getName(),
1935                         getConfigurationMacros(), getIncludePath(),
1936                         getISysRoot());
1937   }
1938
1939 public:
1940   DEFINE_MDNODE_GET(DIModule, (DIScope *Scope, StringRef Name,
1941                                StringRef ConfigurationMacros, StringRef IncludePath,
1942                                StringRef ISysRoot),
1943                     (Scope, Name, ConfigurationMacros, IncludePath, ISysRoot))
1944   DEFINE_MDNODE_GET(DIModule,
1945                     (Metadata *Scope, MDString *Name, MDString *ConfigurationMacros,
1946                      MDString *IncludePath, MDString *ISysRoot),
1947                     (Scope, Name, ConfigurationMacros, IncludePath, ISysRoot))
1948
1949   TempDIModule clone() const { return cloneImpl(); }
1950
1951   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
1952   StringRef getName() const { return getStringOperand(1); }
1953   StringRef getConfigurationMacros() const { return getStringOperand(2); }
1954   StringRef getIncludePath() const { return getStringOperand(3); }
1955   StringRef getISysRoot() const { return getStringOperand(4); }
1956
1957   Metadata *getRawScope() const { return getOperand(0); }
1958   MDString *getRawName() const { return getOperandAs<MDString>(1); }
1959   MDString *getRawConfigurationMacros() const { return getOperandAs<MDString>(2); }
1960   MDString *getRawIncludePath() const { return getOperandAs<MDString>(3); }
1961   MDString *getRawISysRoot() const { return getOperandAs<MDString>(4); }
1962
1963   static bool classof(const Metadata *MD) {
1964     return MD->getMetadataID() == DIModuleKind;
1965   }
1966 };
1967
1968 /// Base class for template parameters.
1969 class DITemplateParameter : public DINode {
1970 protected:
1971   DITemplateParameter(LLVMContext &Context, unsigned ID, StorageType Storage,
1972                       unsigned Tag, ArrayRef<Metadata *> Ops)
1973       : DINode(Context, ID, Storage, Tag, Ops) {}
1974   ~DITemplateParameter() = default;
1975
1976 public:
1977   StringRef getName() const { return getStringOperand(0); }
1978   DITypeRef getType() const { return DITypeRef(getRawType()); }
1979
1980   MDString *getRawName() const { return getOperandAs<MDString>(0); }
1981   Metadata *getRawType() const { return getOperand(1); }
1982
1983   static bool classof(const Metadata *MD) {
1984     return MD->getMetadataID() == DITemplateTypeParameterKind ||
1985            MD->getMetadataID() == DITemplateValueParameterKind;
1986   }
1987 };
1988
1989 class DITemplateTypeParameter : public DITemplateParameter {
1990   friend class LLVMContextImpl;
1991   friend class MDNode;
1992
1993   DITemplateTypeParameter(LLVMContext &Context, StorageType Storage,
1994                           ArrayRef<Metadata *> Ops)
1995       : DITemplateParameter(Context, DITemplateTypeParameterKind, Storage,
1996                             dwarf::DW_TAG_template_type_parameter, Ops) {}
1997   ~DITemplateTypeParameter() = default;
1998
1999   static DITemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
2000                                           DITypeRef Type, StorageType Storage,
2001                                           bool ShouldCreate = true) {
2002     return getImpl(Context, getCanonicalMDString(Context, Name), Type, Storage,
2003                    ShouldCreate);
2004   }
2005   static DITemplateTypeParameter *getImpl(LLVMContext &Context, MDString *Name,
2006                                           Metadata *Type, StorageType Storage,
2007                                           bool ShouldCreate = true);
2008
2009   TempDITemplateTypeParameter cloneImpl() const {
2010     return getTemporary(getContext(), getName(), getType());
2011   }
2012
2013 public:
2014   DEFINE_MDNODE_GET(DITemplateTypeParameter, (StringRef Name, DITypeRef Type),
2015                     (Name, Type))
2016   DEFINE_MDNODE_GET(DITemplateTypeParameter, (MDString * Name, Metadata *Type),
2017                     (Name, Type))
2018
2019   TempDITemplateTypeParameter clone() const { return cloneImpl(); }
2020
2021   static bool classof(const Metadata *MD) {
2022     return MD->getMetadataID() == DITemplateTypeParameterKind;
2023   }
2024 };
2025
2026 class DITemplateValueParameter : public DITemplateParameter {
2027   friend class LLVMContextImpl;
2028   friend class MDNode;
2029
2030   DITemplateValueParameter(LLVMContext &Context, StorageType Storage,
2031                            unsigned Tag, ArrayRef<Metadata *> Ops)
2032       : DITemplateParameter(Context, DITemplateValueParameterKind, Storage, Tag,
2033                             Ops) {}
2034   ~DITemplateValueParameter() = default;
2035
2036   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
2037                                            StringRef Name, DITypeRef Type,
2038                                            Metadata *Value, StorageType Storage,
2039                                            bool ShouldCreate = true) {
2040     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), Type,
2041                    Value, Storage, ShouldCreate);
2042   }
2043   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
2044                                            MDString *Name, Metadata *Type,
2045                                            Metadata *Value, StorageType Storage,
2046                                            bool ShouldCreate = true);
2047
2048   TempDITemplateValueParameter cloneImpl() const {
2049     return getTemporary(getContext(), getTag(), getName(), getType(),
2050                         getValue());
2051   }
2052
2053 public:
2054   DEFINE_MDNODE_GET(DITemplateValueParameter, (unsigned Tag, StringRef Name,
2055                                                DITypeRef Type, Metadata *Value),
2056                     (Tag, Name, Type, Value))
2057   DEFINE_MDNODE_GET(DITemplateValueParameter, (unsigned Tag, MDString *Name,
2058                                                Metadata *Type, Metadata *Value),
2059                     (Tag, Name, Type, Value))
2060
2061   TempDITemplateValueParameter clone() const { return cloneImpl(); }
2062
2063   Metadata *getValue() const { return getOperand(2); }
2064
2065   static bool classof(const Metadata *MD) {
2066     return MD->getMetadataID() == DITemplateValueParameterKind;
2067   }
2068 };
2069
2070 /// Base class for variables.
2071 class DIVariable : public DINode {
2072   unsigned Line;
2073   uint32_t AlignInBits;
2074
2075 protected:
2076   DIVariable(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Line,
2077              ArrayRef<Metadata *> Ops, uint32_t AlignInBits = 0)
2078       : DINode(C, ID, Storage, dwarf::DW_TAG_variable, Ops), Line(Line),
2079         AlignInBits(AlignInBits) {}
2080   ~DIVariable() = default;
2081
2082 public:
2083   unsigned getLine() const { return Line; }
2084   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
2085   StringRef getName() const { return getStringOperand(1); }
2086   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
2087   DITypeRef getType() const { return DITypeRef(getRawType()); }
2088   uint32_t getAlignInBits() const { return AlignInBits; }
2089   uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
2090
2091   StringRef getFilename() const {
2092     if (auto *F = getFile())
2093       return F->getFilename();
2094     return "";
2095   }
2096
2097   StringRef getDirectory() const {
2098     if (auto *F = getFile())
2099       return F->getDirectory();
2100     return "";
2101   }
2102
2103   Metadata *getRawScope() const { return getOperand(0); }
2104   MDString *getRawName() const { return getOperandAs<MDString>(1); }
2105   Metadata *getRawFile() const { return getOperand(2); }
2106   Metadata *getRawType() const { return getOperand(3); }
2107
2108   static bool classof(const Metadata *MD) {
2109     return MD->getMetadataID() == DILocalVariableKind ||
2110            MD->getMetadataID() == DIGlobalVariableKind;
2111   }
2112 };
2113
2114 /// DWARF expression.
2115 ///
2116 /// This is (almost) a DWARF expression that modifies the location of a
2117 /// variable, or the location of a single piece of a variable, or (when using
2118 /// DW_OP_stack_value) is the constant variable value.
2119 ///
2120 /// TODO: Co-allocate the expression elements.
2121 /// TODO: Separate from MDNode, or otherwise drop Distinct and Temporary
2122 /// storage types.
2123 class DIExpression : public MDNode {
2124   friend class LLVMContextImpl;
2125   friend class MDNode;
2126
2127   std::vector<uint64_t> Elements;
2128
2129   DIExpression(LLVMContext &C, StorageType Storage, ArrayRef<uint64_t> Elements)
2130       : MDNode(C, DIExpressionKind, Storage, None),
2131         Elements(Elements.begin(), Elements.end()) {}
2132   ~DIExpression() = default;
2133
2134   static DIExpression *getImpl(LLVMContext &Context,
2135                                ArrayRef<uint64_t> Elements, StorageType Storage,
2136                                bool ShouldCreate = true);
2137
2138   TempDIExpression cloneImpl() const {
2139     return getTemporary(getContext(), getElements());
2140   }
2141
2142 public:
2143   DEFINE_MDNODE_GET(DIExpression, (ArrayRef<uint64_t> Elements), (Elements))
2144
2145   TempDIExpression clone() const { return cloneImpl(); }
2146
2147   ArrayRef<uint64_t> getElements() const { return Elements; }
2148
2149   unsigned getNumElements() const { return Elements.size(); }
2150
2151   uint64_t getElement(unsigned I) const {
2152     assert(I < Elements.size() && "Index out of range");
2153     return Elements[I];
2154   }
2155
2156   /// Determine whether this represents a standalone constant value.
2157   bool isConstant() const;
2158
2159   using element_iterator = ArrayRef<uint64_t>::iterator;
2160
2161   element_iterator elements_begin() const { return getElements().begin(); }
2162   element_iterator elements_end() const { return getElements().end(); }
2163
2164   /// A lightweight wrapper around an expression operand.
2165   ///
2166   /// TODO: Store arguments directly and change \a DIExpression to store a
2167   /// range of these.
2168   class ExprOperand {
2169     const uint64_t *Op = nullptr;
2170
2171   public:
2172     ExprOperand() = default;
2173     explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
2174
2175     const uint64_t *get() const { return Op; }
2176
2177     /// Get the operand code.
2178     uint64_t getOp() const { return *Op; }
2179
2180     /// Get an argument to the operand.
2181     ///
2182     /// Never returns the operand itself.
2183     uint64_t getArg(unsigned I) const { return Op[I + 1]; }
2184
2185     unsigned getNumArgs() const { return getSize() - 1; }
2186
2187     /// Return the size of the operand.
2188     ///
2189     /// Return the number of elements in the operand (1 + args).
2190     unsigned getSize() const;
2191   };
2192
2193   /// An iterator for expression operands.
2194   class expr_op_iterator
2195       : public std::iterator<std::input_iterator_tag, ExprOperand> {
2196     ExprOperand Op;
2197
2198   public:
2199     expr_op_iterator() = default;
2200     explicit expr_op_iterator(element_iterator I) : Op(I) {}
2201
2202     element_iterator getBase() const { return Op.get(); }
2203     const ExprOperand &operator*() const { return Op; }
2204     const ExprOperand *operator->() const { return &Op; }
2205
2206     expr_op_iterator &operator++() {
2207       increment();
2208       return *this;
2209     }
2210     expr_op_iterator operator++(int) {
2211       expr_op_iterator T(*this);
2212       increment();
2213       return T;
2214     }
2215
2216     /// Get the next iterator.
2217     ///
2218     /// \a std::next() doesn't work because this is technically an
2219     /// input_iterator, but it's a perfectly valid operation.  This is an
2220     /// accessor to provide the same functionality.
2221     expr_op_iterator getNext() const { return ++expr_op_iterator(*this); }
2222
2223     bool operator==(const expr_op_iterator &X) const {
2224       return getBase() == X.getBase();
2225     }
2226     bool operator!=(const expr_op_iterator &X) const {
2227       return getBase() != X.getBase();
2228     }
2229
2230   private:
2231     void increment() { Op = ExprOperand(getBase() + Op.getSize()); }
2232   };
2233
2234   /// Visit the elements via ExprOperand wrappers.
2235   ///
2236   /// These range iterators visit elements through \a ExprOperand wrappers.
2237   /// This is not guaranteed to be a valid range unless \a isValid() gives \c
2238   /// true.
2239   ///
2240   /// \pre \a isValid() gives \c true.
2241   /// @{
2242   expr_op_iterator expr_op_begin() const {
2243     return expr_op_iterator(elements_begin());
2244   }
2245   expr_op_iterator expr_op_end() const {
2246     return expr_op_iterator(elements_end());
2247   }
2248   iterator_range<expr_op_iterator> expr_ops() const {
2249     return {expr_op_begin(), expr_op_end()};
2250   }
2251   /// @}
2252
2253   bool isValid() const;
2254
2255   static bool classof(const Metadata *MD) {
2256     return MD->getMetadataID() == DIExpressionKind;
2257   }
2258
2259   /// Return whether the first element a DW_OP_deref.
2260   bool startsWithDeref() const {
2261     return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_deref;
2262   }
2263
2264   /// Holds the characteristics of one fragment of a larger variable.
2265   struct FragmentInfo {
2266     uint64_t SizeInBits;
2267     uint64_t OffsetInBits;
2268   };
2269
2270   /// Retrieve the details of this fragment expression.
2271   static Optional<FragmentInfo> getFragmentInfo(expr_op_iterator Start,
2272                                                 expr_op_iterator End);
2273
2274   /// Retrieve the details of this fragment expression.
2275   Optional<FragmentInfo> getFragmentInfo() const {
2276     return getFragmentInfo(expr_op_begin(), expr_op_end());
2277   }
2278
2279   /// Return whether this is a piece of an aggregate variable.
2280   bool isFragment() const { return getFragmentInfo().hasValue(); }
2281
2282   /// Append \p Ops with operations to apply the \p Offset.
2283   static void appendOffset(SmallVectorImpl<uint64_t> &Ops, int64_t Offset);
2284
2285   /// If this is a constant offset, extract it. If there is no expression,
2286   /// return true with an offset of zero.
2287   bool extractIfOffset(int64_t &Offset) const;
2288
2289   /// Constants for DIExpression::prepend.
2290   enum { NoDeref = false, WithDeref = true, WithStackValue = true };
2291
2292   /// Prepend \p DIExpr with a deref and offset operation and optionally turn it
2293   /// into a stack value.
2294   static DIExpression *prepend(const DIExpression *DIExpr, bool Deref,
2295                                int64_t Offset = 0, bool StackValue = false);
2296 };
2297
2298 /// Global variables.
2299 ///
2300 /// TODO: Remove DisplayName.  It's always equal to Name.
2301 class DIGlobalVariable : public DIVariable {
2302   friend class LLVMContextImpl;
2303   friend class MDNode;
2304
2305   bool IsLocalToUnit;
2306   bool IsDefinition;
2307
2308   DIGlobalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
2309                    bool IsLocalToUnit, bool IsDefinition, uint32_t AlignInBits,
2310                    ArrayRef<Metadata *> Ops)
2311       : DIVariable(C, DIGlobalVariableKind, Storage, Line, Ops, AlignInBits),
2312         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition) {}
2313   ~DIGlobalVariable() = default;
2314
2315   static DIGlobalVariable *getImpl(LLVMContext &Context, DIScope *Scope,
2316                                    StringRef Name, StringRef LinkageName,
2317                                    DIFile *File, unsigned Line, DITypeRef Type,
2318                                    bool IsLocalToUnit, bool IsDefinition,
2319                                    DIDerivedType *StaticDataMemberDeclaration,
2320                                    uint32_t AlignInBits, StorageType Storage,
2321                                    bool ShouldCreate = true) {
2322     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
2323                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
2324                    IsLocalToUnit, IsDefinition, StaticDataMemberDeclaration,
2325                    AlignInBits, Storage, ShouldCreate);
2326   }
2327   static DIGlobalVariable *
2328   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
2329           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
2330           bool IsLocalToUnit, bool IsDefinition,
2331           Metadata *StaticDataMemberDeclaration, uint32_t AlignInBits,
2332           StorageType Storage, bool ShouldCreate = true);
2333
2334   TempDIGlobalVariable cloneImpl() const {
2335     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
2336                         getFile(), getLine(), getType(), isLocalToUnit(),
2337                         isDefinition(), getStaticDataMemberDeclaration(),
2338                         getAlignInBits());
2339   }
2340
2341 public:
2342   DEFINE_MDNODE_GET(DIGlobalVariable,
2343                     (DIScope * Scope, StringRef Name, StringRef LinkageName,
2344                      DIFile *File, unsigned Line, DITypeRef Type,
2345                      bool IsLocalToUnit, bool IsDefinition,
2346                      DIDerivedType *StaticDataMemberDeclaration,
2347                      uint32_t AlignInBits),
2348                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
2349                      IsDefinition, StaticDataMemberDeclaration, AlignInBits))
2350   DEFINE_MDNODE_GET(DIGlobalVariable,
2351                     (Metadata * Scope, MDString *Name, MDString *LinkageName,
2352                      Metadata *File, unsigned Line, Metadata *Type,
2353                      bool IsLocalToUnit, bool IsDefinition,
2354                      Metadata *StaticDataMemberDeclaration,
2355                      uint32_t AlignInBits),
2356                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
2357                      IsDefinition, StaticDataMemberDeclaration, AlignInBits))
2358
2359   TempDIGlobalVariable clone() const { return cloneImpl(); }
2360
2361   bool isLocalToUnit() const { return IsLocalToUnit; }
2362   bool isDefinition() const { return IsDefinition; }
2363   StringRef getDisplayName() const { return getStringOperand(4); }
2364   StringRef getLinkageName() const { return getStringOperand(5); }
2365   DIDerivedType *getStaticDataMemberDeclaration() const {
2366     return cast_or_null<DIDerivedType>(getRawStaticDataMemberDeclaration());
2367   }
2368
2369   MDString *getRawLinkageName() const { return getOperandAs<MDString>(5); }
2370   Metadata *getRawStaticDataMemberDeclaration() const { return getOperand(6); }
2371
2372   static bool classof(const Metadata *MD) {
2373     return MD->getMetadataID() == DIGlobalVariableKind;
2374   }
2375 };
2376
2377 /// Local variable.
2378 ///
2379 /// TODO: Split up flags.
2380 class DILocalVariable : public DIVariable {
2381   friend class LLVMContextImpl;
2382   friend class MDNode;
2383
2384   unsigned Arg : 16;
2385   DIFlags Flags;
2386
2387   DILocalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
2388                   unsigned Arg, DIFlags Flags, uint32_t AlignInBits,
2389                   ArrayRef<Metadata *> Ops)
2390       : DIVariable(C, DILocalVariableKind, Storage, Line, Ops, AlignInBits),
2391         Arg(Arg), Flags(Flags) {
2392     assert(Arg < (1 << 16) && "DILocalVariable: Arg out of range");
2393   }
2394   ~DILocalVariable() = default;
2395
2396   static DILocalVariable *getImpl(LLVMContext &Context, DIScope *Scope,
2397                                   StringRef Name, DIFile *File, unsigned Line,
2398                                   DITypeRef Type, unsigned Arg, DIFlags Flags,
2399                                   uint32_t AlignInBits, StorageType Storage,
2400                                   bool ShouldCreate = true) {
2401     return getImpl(Context, Scope, getCanonicalMDString(Context, Name), File,
2402                    Line, Type, Arg, Flags, AlignInBits, Storage, ShouldCreate);
2403   }
2404   static DILocalVariable *getImpl(LLVMContext &Context, Metadata *Scope,
2405                                   MDString *Name, Metadata *File, unsigned Line,
2406                                   Metadata *Type, unsigned Arg, DIFlags Flags,
2407                                   uint32_t AlignInBits, StorageType Storage,
2408                                   bool ShouldCreate = true);
2409
2410   TempDILocalVariable cloneImpl() const {
2411     return getTemporary(getContext(), getScope(), getName(), getFile(),
2412                         getLine(), getType(), getArg(), getFlags(),
2413                         getAlignInBits());
2414   }
2415
2416 public:
2417   DEFINE_MDNODE_GET(DILocalVariable,
2418                     (DILocalScope * Scope, StringRef Name, DIFile *File,
2419                      unsigned Line, DITypeRef Type, unsigned Arg,
2420                      DIFlags Flags, uint32_t AlignInBits),
2421                     (Scope, Name, File, Line, Type, Arg, Flags, AlignInBits))
2422   DEFINE_MDNODE_GET(DILocalVariable,
2423                     (Metadata * Scope, MDString *Name, Metadata *File,
2424                      unsigned Line, Metadata *Type, unsigned Arg,
2425                      DIFlags Flags, uint32_t AlignInBits),
2426                     (Scope, Name, File, Line, Type, Arg, Flags, AlignInBits))
2427
2428   TempDILocalVariable clone() const { return cloneImpl(); }
2429
2430   /// Get the local scope for this variable.
2431   ///
2432   /// Variables must be defined in a local scope.
2433   DILocalScope *getScope() const {
2434     return cast<DILocalScope>(DIVariable::getScope());
2435   }
2436
2437   bool isParameter() const { return Arg; }
2438   unsigned getArg() const { return Arg; }
2439   DIFlags getFlags() const { return Flags; }
2440
2441   bool isArtificial() const { return getFlags() & FlagArtificial; }
2442   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
2443
2444   /// Check that a location is valid for this variable.
2445   ///
2446   /// Check that \c DL exists, is in the same subprogram, and has the same
2447   /// inlined-at location as \c this.  (Otherwise, it's not a valid attachment
2448   /// to a \a DbgInfoIntrinsic.)
2449   bool isValidLocationForIntrinsic(const DILocation *DL) const {
2450     return DL && getScope()->getSubprogram() == DL->getScope()->getSubprogram();
2451   }
2452
2453   static bool classof(const Metadata *MD) {
2454     return MD->getMetadataID() == DILocalVariableKind;
2455   }
2456 };
2457
2458 class DIObjCProperty : public DINode {
2459   friend class LLVMContextImpl;
2460   friend class MDNode;
2461
2462   unsigned Line;
2463   unsigned Attributes;
2464
2465   DIObjCProperty(LLVMContext &C, StorageType Storage, unsigned Line,
2466                  unsigned Attributes, ArrayRef<Metadata *> Ops)
2467       : DINode(C, DIObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property,
2468                Ops),
2469         Line(Line), Attributes(Attributes) {}
2470   ~DIObjCProperty() = default;
2471
2472   static DIObjCProperty *
2473   getImpl(LLVMContext &Context, StringRef Name, DIFile *File, unsigned Line,
2474           StringRef GetterName, StringRef SetterName, unsigned Attributes,
2475           DITypeRef Type, StorageType Storage, bool ShouldCreate = true) {
2476     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
2477                    getCanonicalMDString(Context, GetterName),
2478                    getCanonicalMDString(Context, SetterName), Attributes, Type,
2479                    Storage, ShouldCreate);
2480   }
2481   static DIObjCProperty *getImpl(LLVMContext &Context, MDString *Name,
2482                                  Metadata *File, unsigned Line,
2483                                  MDString *GetterName, MDString *SetterName,
2484                                  unsigned Attributes, Metadata *Type,
2485                                  StorageType Storage, bool ShouldCreate = true);
2486
2487   TempDIObjCProperty cloneImpl() const {
2488     return getTemporary(getContext(), getName(), getFile(), getLine(),
2489                         getGetterName(), getSetterName(), getAttributes(),
2490                         getType());
2491   }
2492
2493 public:
2494   DEFINE_MDNODE_GET(DIObjCProperty,
2495                     (StringRef Name, DIFile *File, unsigned Line,
2496                      StringRef GetterName, StringRef SetterName,
2497                      unsigned Attributes, DITypeRef Type),
2498                     (Name, File, Line, GetterName, SetterName, Attributes,
2499                      Type))
2500   DEFINE_MDNODE_GET(DIObjCProperty,
2501                     (MDString * Name, Metadata *File, unsigned Line,
2502                      MDString *GetterName, MDString *SetterName,
2503                      unsigned Attributes, Metadata *Type),
2504                     (Name, File, Line, GetterName, SetterName, Attributes,
2505                      Type))
2506
2507   TempDIObjCProperty clone() const { return cloneImpl(); }
2508
2509   unsigned getLine() const { return Line; }
2510   unsigned getAttributes() const { return Attributes; }
2511   StringRef getName() const { return getStringOperand(0); }
2512   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
2513   StringRef getGetterName() const { return getStringOperand(2); }
2514   StringRef getSetterName() const { return getStringOperand(3); }
2515   DITypeRef getType() const { return DITypeRef(getRawType()); }
2516
2517   StringRef getFilename() const {
2518     if (auto *F = getFile())
2519       return F->getFilename();
2520     return "";
2521   }
2522
2523   StringRef getDirectory() const {
2524     if (auto *F = getFile())
2525       return F->getDirectory();
2526     return "";
2527   }
2528
2529   MDString *getRawName() const { return getOperandAs<MDString>(0); }
2530   Metadata *getRawFile() const { return getOperand(1); }
2531   MDString *getRawGetterName() const { return getOperandAs<MDString>(2); }
2532   MDString *getRawSetterName() const { return getOperandAs<MDString>(3); }
2533   Metadata *getRawType() const { return getOperand(4); }
2534
2535   static bool classof(const Metadata *MD) {
2536     return MD->getMetadataID() == DIObjCPropertyKind;
2537   }
2538 };
2539
2540 /// An imported module (C++ using directive or similar).
2541 class DIImportedEntity : public DINode {
2542   friend class LLVMContextImpl;
2543   friend class MDNode;
2544
2545   unsigned Line;
2546
2547   DIImportedEntity(LLVMContext &C, StorageType Storage, unsigned Tag,
2548                    unsigned Line, ArrayRef<Metadata *> Ops)
2549       : DINode(C, DIImportedEntityKind, Storage, Tag, Ops), Line(Line) {}
2550   ~DIImportedEntity() = default;
2551
2552   static DIImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2553                                    DIScope *Scope, DINodeRef Entity,
2554                                    DIFile *File, unsigned Line, StringRef Name,
2555                                    StorageType Storage,
2556                                    bool ShouldCreate = true) {
2557     return getImpl(Context, Tag, Scope, Entity, File, Line,
2558                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
2559   }
2560   static DIImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2561                                    Metadata *Scope, Metadata *Entity,
2562                                    Metadata *File, unsigned Line,
2563                                    MDString *Name, StorageType Storage,
2564                                    bool ShouldCreate = true);
2565
2566   TempDIImportedEntity cloneImpl() const {
2567     return getTemporary(getContext(), getTag(), getScope(), getEntity(),
2568                         getFile(), getLine(), getName());
2569   }
2570
2571 public:
2572   DEFINE_MDNODE_GET(DIImportedEntity,
2573                     (unsigned Tag, DIScope *Scope, DINodeRef Entity,
2574                      DIFile *File, unsigned Line, StringRef Name = ""),
2575                     (Tag, Scope, Entity, File, Line, Name))
2576   DEFINE_MDNODE_GET(DIImportedEntity,
2577                     (unsigned Tag, Metadata *Scope, Metadata *Entity,
2578                      Metadata *File, unsigned Line, MDString *Name),
2579                     (Tag, Scope, Entity, File, Line, Name))
2580
2581   TempDIImportedEntity clone() const { return cloneImpl(); }
2582
2583   unsigned getLine() const { return Line; }
2584   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
2585   DINodeRef getEntity() const { return DINodeRef(getRawEntity()); }
2586   StringRef getName() const { return getStringOperand(2); }
2587   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
2588
2589   Metadata *getRawScope() const { return getOperand(0); }
2590   Metadata *getRawEntity() const { return getOperand(1); }
2591   MDString *getRawName() const { return getOperandAs<MDString>(2); }
2592   Metadata *getRawFile() const { return getOperand(3); }
2593
2594   static bool classof(const Metadata *MD) {
2595     return MD->getMetadataID() == DIImportedEntityKind;
2596   }
2597 };
2598
2599 /// A pair of DIGlobalVariable and DIExpression.
2600 class DIGlobalVariableExpression : public MDNode {
2601   friend class LLVMContextImpl;
2602   friend class MDNode;
2603
2604   DIGlobalVariableExpression(LLVMContext &C, StorageType Storage,
2605                              ArrayRef<Metadata *> Ops)
2606       : MDNode(C, DIGlobalVariableExpressionKind, Storage, Ops) {}
2607   ~DIGlobalVariableExpression() = default;
2608
2609   static DIGlobalVariableExpression *
2610   getImpl(LLVMContext &Context, Metadata *Variable, Metadata *Expression,
2611           StorageType Storage, bool ShouldCreate = true);
2612
2613   TempDIGlobalVariableExpression cloneImpl() const {
2614     return getTemporary(getContext(), getVariable(), getExpression());
2615   }
2616
2617 public:
2618   DEFINE_MDNODE_GET(DIGlobalVariableExpression,
2619                     (Metadata * Variable, Metadata *Expression),
2620                     (Variable, Expression))
2621
2622   TempDIGlobalVariableExpression clone() const { return cloneImpl(); }
2623
2624   Metadata *getRawVariable() const { return getOperand(0); }
2625
2626   DIGlobalVariable *getVariable() const {
2627     return cast_or_null<DIGlobalVariable>(getRawVariable());
2628   }
2629
2630   Metadata *getRawExpression() const { return getOperand(1); }
2631
2632   DIExpression *getExpression() const {
2633     return cast_or_null<DIExpression>(getRawExpression());
2634   }
2635
2636   static bool classof(const Metadata *MD) {
2637     return MD->getMetadataID() == DIGlobalVariableExpressionKind;
2638   }
2639 };
2640
2641 /// Macro Info DWARF-like metadata node.
2642 ///
2643 /// A metadata node with a DWARF macro info (i.e., a constant named
2644 /// \c DW_MACINFO_*, defined in llvm/BinaryFormat/Dwarf.h).  Called \a
2645 /// DIMacroNode
2646 /// because it's potentially used for non-DWARF output.
2647 class DIMacroNode : public MDNode {
2648   friend class LLVMContextImpl;
2649   friend class MDNode;
2650
2651 protected:
2652   DIMacroNode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned MIType,
2653               ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
2654       : MDNode(C, ID, Storage, Ops1, Ops2) {
2655     assert(MIType < 1u << 16);
2656     SubclassData16 = MIType;
2657   }
2658   ~DIMacroNode() = default;
2659
2660   template <class Ty> Ty *getOperandAs(unsigned I) const {
2661     return cast_or_null<Ty>(getOperand(I));
2662   }
2663
2664   StringRef getStringOperand(unsigned I) const {
2665     if (auto *S = getOperandAs<MDString>(I))
2666       return S->getString();
2667     return StringRef();
2668   }
2669
2670   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
2671     if (S.empty())
2672       return nullptr;
2673     return MDString::get(Context, S);
2674   }
2675
2676 public:
2677   unsigned getMacinfoType() const { return SubclassData16; }
2678
2679   static bool classof(const Metadata *MD) {
2680     switch (MD->getMetadataID()) {
2681     default:
2682       return false;
2683     case DIMacroKind:
2684     case DIMacroFileKind:
2685       return true;
2686     }
2687   }
2688 };
2689
2690 class DIMacro : public DIMacroNode {
2691   friend class LLVMContextImpl;
2692   friend class MDNode;
2693
2694   unsigned Line;
2695
2696   DIMacro(LLVMContext &C, StorageType Storage, unsigned MIType, unsigned Line,
2697           ArrayRef<Metadata *> Ops)
2698       : DIMacroNode(C, DIMacroKind, Storage, MIType, Ops), Line(Line) {}
2699   ~DIMacro() = default;
2700
2701   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
2702                           StringRef Name, StringRef Value, StorageType Storage,
2703                           bool ShouldCreate = true) {
2704     return getImpl(Context, MIType, Line, getCanonicalMDString(Context, Name),
2705                    getCanonicalMDString(Context, Value), Storage, ShouldCreate);
2706   }
2707   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
2708                           MDString *Name, MDString *Value, StorageType Storage,
2709                           bool ShouldCreate = true);
2710
2711   TempDIMacro cloneImpl() const {
2712     return getTemporary(getContext(), getMacinfoType(), getLine(), getName(),
2713                         getValue());
2714   }
2715
2716 public:
2717   DEFINE_MDNODE_GET(DIMacro, (unsigned MIType, unsigned Line, StringRef Name,
2718                               StringRef Value = ""),
2719                     (MIType, Line, Name, Value))
2720   DEFINE_MDNODE_GET(DIMacro, (unsigned MIType, unsigned Line, MDString *Name,
2721                               MDString *Value),
2722                     (MIType, Line, Name, Value))
2723
2724   TempDIMacro clone() const { return cloneImpl(); }
2725
2726   unsigned getLine() const { return Line; }
2727
2728   StringRef getName() const { return getStringOperand(0); }
2729   StringRef getValue() const { return getStringOperand(1); }
2730
2731   MDString *getRawName() const { return getOperandAs<MDString>(0); }
2732   MDString *getRawValue() const { return getOperandAs<MDString>(1); }
2733
2734   static bool classof(const Metadata *MD) {
2735     return MD->getMetadataID() == DIMacroKind;
2736   }
2737 };
2738
2739 class DIMacroFile : public DIMacroNode {
2740   friend class LLVMContextImpl;
2741   friend class MDNode;
2742
2743   unsigned Line;
2744
2745   DIMacroFile(LLVMContext &C, StorageType Storage, unsigned MIType,
2746               unsigned Line, ArrayRef<Metadata *> Ops)
2747       : DIMacroNode(C, DIMacroFileKind, Storage, MIType, Ops), Line(Line) {}
2748   ~DIMacroFile() = default;
2749
2750   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
2751                               unsigned Line, DIFile *File,
2752                               DIMacroNodeArray Elements, StorageType Storage,
2753                               bool ShouldCreate = true) {
2754     return getImpl(Context, MIType, Line, static_cast<Metadata *>(File),
2755                    Elements.get(), Storage, ShouldCreate);
2756   }
2757
2758   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
2759                               unsigned Line, Metadata *File, Metadata *Elements,
2760                               StorageType Storage, bool ShouldCreate = true);
2761
2762   TempDIMacroFile cloneImpl() const {
2763     return getTemporary(getContext(), getMacinfoType(), getLine(), getFile(),
2764                         getElements());
2765   }
2766
2767 public:
2768   DEFINE_MDNODE_GET(DIMacroFile, (unsigned MIType, unsigned Line, DIFile *File,
2769                                   DIMacroNodeArray Elements),
2770                     (MIType, Line, File, Elements))
2771   DEFINE_MDNODE_GET(DIMacroFile, (unsigned MIType, unsigned Line,
2772                                   Metadata *File, Metadata *Elements),
2773                     (MIType, Line, File, Elements))
2774
2775   TempDIMacroFile clone() const { return cloneImpl(); }
2776
2777   void replaceElements(DIMacroNodeArray Elements) {
2778 #ifndef NDEBUG
2779     for (DIMacroNode *Op : getElements())
2780       assert(is_contained(Elements->operands(), Op) &&
2781              "Lost a macro node during macro node list replacement");
2782 #endif
2783     replaceOperandWith(1, Elements.get());
2784   }
2785
2786   unsigned getLine() const { return Line; }
2787   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
2788
2789   DIMacroNodeArray getElements() const {
2790     return cast_or_null<MDTuple>(getRawElements());
2791   }
2792
2793   Metadata *getRawFile() const { return getOperand(0); }
2794   Metadata *getRawElements() const { return getOperand(1); }
2795
2796   static bool classof(const Metadata *MD) {
2797     return MD->getMetadataID() == DIMacroFileKind;
2798   }
2799 };
2800
2801 } // end namespace llvm
2802
2803 #undef DEFINE_MDNODE_GET_UNPACK_IMPL
2804 #undef DEFINE_MDNODE_GET_UNPACK
2805 #undef DEFINE_MDNODE_GET
2806
2807 #endif // LLVM_IR_DEBUGINFOMETADATA_H