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