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