DebugInfo: Add forwarding getFilename() accessor to new hierarchy
[oota-llvm.git] / include / llvm / IR / DebugInfoMetadata.h
1 //===- llvm/IR/DebugInfoMetadata.h - Debug info metadata --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Declarations for metadata specific to debug info.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_IR_DEBUGINFOMETADATA_H
15 #define LLVM_IR_DEBUGINFOMETADATA_H
16
17 #include "llvm/IR/Metadata.h"
18 #include "llvm/Support/Dwarf.h"
19
20 // Helper macros for defining get() overrides.
21 #define DEFINE_MDNODE_GET_UNPACK_IMPL(...) __VA_ARGS__
22 #define DEFINE_MDNODE_GET_UNPACK(ARGS) DEFINE_MDNODE_GET_UNPACK_IMPL ARGS
23 #define DEFINE_MDNODE_GET(CLASS, FORMAL, ARGS)                                 \
24   static CLASS *get(LLVMContext &Context, DEFINE_MDNODE_GET_UNPACK(FORMAL)) {  \
25     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued);          \
26   }                                                                            \
27   static CLASS *getIfExists(LLVMContext &Context,                              \
28                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
29     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued,           \
30                    /* ShouldCreate */ false);                                  \
31   }                                                                            \
32   static CLASS *getDistinct(LLVMContext &Context,                              \
33                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
34     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Distinct);         \
35   }                                                                            \
36   static Temp##CLASS getTemporary(LLVMContext &Context,                        \
37                                   DEFINE_MDNODE_GET_UNPACK(FORMAL)) {          \
38     return Temp##CLASS(                                                        \
39         getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Temporary));          \
40   }
41
42 namespace llvm {
43
44 /// \brief Pointer union between a subclass of DebugNode and MDString.
45 ///
46 /// \a MDCompositeType can be referenced via an \a MDString unique identifier.
47 /// This class allows some type safety in the face of that, requiring either a
48 /// node of a particular type or an \a MDString.
49 template <class T> class TypedDebugNodeRef {
50   const Metadata *MD = nullptr;
51
52 public:
53   TypedDebugNodeRef() = default;
54   TypedDebugNodeRef(std::nullptr_t) {}
55
56   /// \brief Construct from a raw pointer.
57   explicit TypedDebugNodeRef(const Metadata *MD) : MD(MD) {
58     assert((!MD || isa<MDString>(MD) || isa<T>(MD)) && "Expected valid ref");
59   }
60
61   template <class U>
62   TypedDebugNodeRef(
63       const TypedDebugNodeRef<U> &X,
64       typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
65           nullptr)
66       : MD(X) {}
67
68   operator Metadata *() const { return const_cast<Metadata *>(MD); }
69
70   bool operator==(const TypedDebugNodeRef<T> &X) const { return MD == X.MD; };
71   bool operator!=(const TypedDebugNodeRef<T> &X) const { return MD != X.MD; };
72
73   /// \brief Create a reference.
74   ///
75   /// Get a reference to \c N, using an \a MDString reference if available.
76   static TypedDebugNodeRef get(const T *N);
77
78   template <class MapTy> T *resolve(const MapTy &Map) const {
79     if (!MD)
80       return nullptr;
81
82     if (auto *Typed = dyn_cast<T>(MD))
83       return const_cast<T *>(Typed);
84
85     auto *S = cast<MDString>(MD);
86     auto I = Map.find(S);
87     assert(I != Map.end() && "Missing identifier in type map");
88     return cast<T>(I->second);
89   }
90 };
91
92 typedef TypedDebugNodeRef<DebugNode> DebugNodeRef;
93 typedef TypedDebugNodeRef<MDScope> MDScopeRef;
94 typedef TypedDebugNodeRef<MDType> MDTypeRef;
95
96 class MDTypeRefArray {
97   const MDTuple *N = nullptr;
98
99 public:
100   MDTypeRefArray(const MDTuple *N) : N(N) {}
101
102   explicit operator bool() const { return get(); }
103   explicit operator MDTuple *() const { return get(); }
104
105   MDTuple *get() const { return const_cast<MDTuple *>(N); }
106   MDTuple *operator->() const { return get(); }
107   MDTuple &operator*() const { return *get(); }
108
109   // FIXME: Fix callers and remove condition on N.
110   unsigned size() const { return N ? N->getNumOperands() : 0u; }
111   MDTypeRef operator[](unsigned I) const { return MDTypeRef(N->getOperand(I)); }
112
113   class iterator : std::iterator<std::input_iterator_tag, MDTypeRef,
114                                  std::ptrdiff_t, void, MDTypeRef> {
115     MDNode::op_iterator I = nullptr;
116
117   public:
118     iterator() = default;
119     explicit iterator(MDNode::op_iterator I) : I(I) {}
120     MDTypeRef operator*() const { return MDTypeRef(*I); }
121     iterator &operator++() {
122       ++I;
123       return *this;
124     }
125     iterator operator++(int) {
126       iterator Temp(*this);
127       ++I;
128       return Temp;
129     }
130     bool operator==(const iterator &X) const { return I == X.I; }
131     bool operator!=(const iterator &X) const { return I != X.I; }
132   };
133
134   // FIXME: Fix callers and remove condition on N.
135   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
136   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
137 };
138
139 /// \brief Tagged DWARF-like metadata node.
140 ///
141 /// A metadata node with a DWARF tag (i.e., a constant named \c DW_TAG_*,
142 /// defined in llvm/Support/Dwarf.h).  Called \a DebugNode because it's
143 /// potentially used for non-DWARF output.
144 class DebugNode : public MDNode {
145   friend class LLVMContextImpl;
146   friend class MDNode;
147
148 protected:
149   DebugNode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
150             ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
151       : MDNode(C, ID, Storage, Ops1, Ops2) {
152     assert(Tag < 1u << 16);
153     SubclassData16 = Tag;
154   }
155   ~DebugNode() {}
156
157   template <class Ty> Ty *getOperandAs(unsigned I) const {
158     return cast_or_null<Ty>(getOperand(I));
159   }
160
161   StringRef getStringOperand(unsigned I) const {
162     if (auto *S = getOperandAs<MDString>(I))
163       return S->getString();
164     return StringRef();
165   }
166
167   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
168     if (S.empty())
169       return nullptr;
170     return MDString::get(Context, S);
171   }
172
173 public:
174   unsigned getTag() const { return SubclassData16; }
175
176   /// \brief Debug info flags.
177   ///
178   /// The three accessibility flags are mutually exclusive and rolled together
179   /// in the first two bits.
180   enum DIFlags {
181 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = ID,
182 #include "llvm/IR/DebugInfoFlags.def"
183     FlagAccessibility = FlagPrivate | FlagProtected | FlagPublic
184   };
185
186   static unsigned getFlag(StringRef Flag);
187   static const char *getFlagString(unsigned Flag);
188
189   /// \brief Split up a flags bitfield.
190   ///
191   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
192   /// any remaining (unrecognized) bits.
193   static unsigned splitFlags(unsigned Flags,
194                              SmallVectorImpl<unsigned> &SplitFlags);
195
196   DebugNodeRef getRef() const { return DebugNodeRef::get(this); }
197
198   static bool classof(const Metadata *MD) {
199     switch (MD->getMetadataID()) {
200     default:
201       return false;
202     case GenericDebugNodeKind:
203     case MDSubrangeKind:
204     case MDEnumeratorKind:
205     case MDBasicTypeKind:
206     case MDDerivedTypeKind:
207     case MDCompositeTypeKind:
208     case MDSubroutineTypeKind:
209     case MDFileKind:
210     case MDCompileUnitKind:
211     case MDSubprogramKind:
212     case MDLexicalBlockKind:
213     case MDLexicalBlockFileKind:
214     case MDNamespaceKind:
215     case MDTemplateTypeParameterKind:
216     case MDTemplateValueParameterKind:
217     case MDGlobalVariableKind:
218     case MDLocalVariableKind:
219     case MDObjCPropertyKind:
220     case MDImportedEntityKind:
221       return true;
222     }
223   }
224 };
225
226 template <class T>
227 struct simplify_type<const TypedDebugNodeRef<T>> {
228   typedef Metadata *SimpleType;
229   static SimpleType getSimplifiedValue(const TypedDebugNodeRef<T> &MD) {
230     return MD;
231   }
232 };
233
234 template <class T>
235 struct simplify_type<TypedDebugNodeRef<T>>
236     : simplify_type<const TypedDebugNodeRef<T>> {};
237
238 /// \brief Generic tagged DWARF-like metadata node.
239 ///
240 /// An un-specialized DWARF-like metadata node.  The first operand is a
241 /// (possibly empty) null-separated \a MDString header that contains arbitrary
242 /// fields.  The remaining operands are \a dwarf_operands(), and are pointers
243 /// to other metadata.
244 class GenericDebugNode : public DebugNode {
245   friend class LLVMContextImpl;
246   friend class MDNode;
247
248   GenericDebugNode(LLVMContext &C, StorageType Storage, unsigned Hash,
249                    unsigned Tag, ArrayRef<Metadata *> Ops1,
250                    ArrayRef<Metadata *> Ops2)
251       : DebugNode(C, GenericDebugNodeKind, Storage, Tag, Ops1, Ops2) {
252     setHash(Hash);
253   }
254   ~GenericDebugNode() { dropAllReferences(); }
255
256   void setHash(unsigned Hash) { SubclassData32 = Hash; }
257   void recalculateHash();
258
259   static GenericDebugNode *getImpl(LLVMContext &Context, unsigned Tag,
260                                    StringRef Header,
261                                    ArrayRef<Metadata *> DwarfOps,
262                                    StorageType Storage,
263                                    bool ShouldCreate = true) {
264     return getImpl(Context, Tag, getCanonicalMDString(Context, Header),
265                    DwarfOps, Storage, ShouldCreate);
266   }
267
268   static GenericDebugNode *getImpl(LLVMContext &Context, unsigned Tag,
269                                    MDString *Header,
270                                    ArrayRef<Metadata *> DwarfOps,
271                                    StorageType Storage,
272                                    bool ShouldCreate = true);
273
274   TempGenericDebugNode cloneImpl() const {
275     return getTemporary(
276         getContext(), getTag(), getHeader(),
277         SmallVector<Metadata *, 4>(dwarf_op_begin(), dwarf_op_end()));
278   }
279
280 public:
281   unsigned getHash() const { return SubclassData32; }
282
283   DEFINE_MDNODE_GET(GenericDebugNode, (unsigned Tag, StringRef Header,
284                                        ArrayRef<Metadata *> DwarfOps),
285                     (Tag, Header, DwarfOps))
286   DEFINE_MDNODE_GET(GenericDebugNode, (unsigned Tag, MDString *Header,
287                                        ArrayRef<Metadata *> DwarfOps),
288                     (Tag, Header, DwarfOps))
289
290   /// \brief Return a (temporary) clone of this.
291   TempGenericDebugNode clone() const { return cloneImpl(); }
292
293   unsigned getTag() const { return SubclassData16; }
294   StringRef getHeader() const { return getStringOperand(0); }
295
296   op_iterator dwarf_op_begin() const { return op_begin() + 1; }
297   op_iterator dwarf_op_end() const { return op_end(); }
298   op_range dwarf_operands() const {
299     return op_range(dwarf_op_begin(), dwarf_op_end());
300   }
301
302   unsigned getNumDwarfOperands() const { return getNumOperands() - 1; }
303   const MDOperand &getDwarfOperand(unsigned I) const {
304     return getOperand(I + 1);
305   }
306   void replaceDwarfOperandWith(unsigned I, Metadata *New) {
307     replaceOperandWith(I + 1, New);
308   }
309
310   static bool classof(const Metadata *MD) {
311     return MD->getMetadataID() == GenericDebugNodeKind;
312   }
313 };
314
315 /// \brief Array subrange.
316 ///
317 /// TODO: Merge into node for DW_TAG_array_type, which should have a custom
318 /// type.
319 class MDSubrange : public DebugNode {
320   friend class LLVMContextImpl;
321   friend class MDNode;
322
323   int64_t Count;
324   int64_t LowerBound;
325
326   MDSubrange(LLVMContext &C, StorageType Storage, int64_t Count,
327              int64_t LowerBound)
328       : DebugNode(C, MDSubrangeKind, Storage, dwarf::DW_TAG_subrange_type,
329                   None),
330         Count(Count), LowerBound(LowerBound) {}
331   ~MDSubrange() {}
332
333   static MDSubrange *getImpl(LLVMContext &Context, int64_t Count,
334                              int64_t LowerBound, StorageType Storage,
335                              bool ShouldCreate = true);
336
337   TempMDSubrange cloneImpl() const {
338     return getTemporary(getContext(), getCount(), getLowerBound());
339   }
340
341 public:
342   DEFINE_MDNODE_GET(MDSubrange, (int64_t Count, int64_t LowerBound = 0),
343                     (Count, LowerBound))
344
345   TempMDSubrange clone() const { return cloneImpl(); }
346
347   int64_t getLowerBound() const { return LowerBound; }
348   int64_t getCount() const { return Count; }
349
350   static bool classof(const Metadata *MD) {
351     return MD->getMetadataID() == MDSubrangeKind;
352   }
353 };
354
355 /// \brief Enumeration value.
356 ///
357 /// TODO: Add a pointer to the context (DW_TAG_enumeration_type) once that no
358 /// longer creates a type cycle.
359 class MDEnumerator : public DebugNode {
360   friend class LLVMContextImpl;
361   friend class MDNode;
362
363   int64_t Value;
364
365   MDEnumerator(LLVMContext &C, StorageType Storage, int64_t Value,
366                ArrayRef<Metadata *> Ops)
367       : DebugNode(C, MDEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops),
368         Value(Value) {}
369   ~MDEnumerator() {}
370
371   static MDEnumerator *getImpl(LLVMContext &Context, int64_t Value,
372                                StringRef Name, StorageType Storage,
373                                bool ShouldCreate = true) {
374     return getImpl(Context, Value, getCanonicalMDString(Context, Name), Storage,
375                    ShouldCreate);
376   }
377   static MDEnumerator *getImpl(LLVMContext &Context, int64_t Value,
378                                MDString *Name, StorageType Storage,
379                                bool ShouldCreate = true);
380
381   TempMDEnumerator cloneImpl() const {
382     return getTemporary(getContext(), getValue(), getName());
383   }
384
385 public:
386   DEFINE_MDNODE_GET(MDEnumerator, (int64_t Value, StringRef Name),
387                     (Value, Name))
388   DEFINE_MDNODE_GET(MDEnumerator, (int64_t Value, MDString *Name),
389                     (Value, Name))
390
391   TempMDEnumerator clone() const { return cloneImpl(); }
392
393   int64_t getValue() const { return Value; }
394   StringRef getName() const { return getStringOperand(0); }
395
396   MDString *getRawName() const { return getOperandAs<MDString>(0); }
397
398   static bool classof(const Metadata *MD) {
399     return MD->getMetadataID() == MDEnumeratorKind;
400   }
401 };
402
403 /// \brief Base class for scope-like contexts.
404 ///
405 /// Base class for lexical scopes and types (which are also declaration
406 /// contexts).
407 ///
408 /// TODO: Separate the concepts of declaration contexts and lexical scopes.
409 class MDScope : public DebugNode {
410 protected:
411   MDScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
412           ArrayRef<Metadata *> Ops)
413       : DebugNode(C, ID, Storage, Tag, Ops) {}
414   ~MDScope() {}
415
416 public:
417   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
418
419   inline StringRef getFilename() const;
420   inline StringRef getDirectory() const;
421
422   /// \brief Return the raw underlying file.
423   ///
424   /// An \a MDFile is an \a MDScope, but it doesn't point at a separate file
425   /// (it\em is the file).  If \c this is an \a MDFile, we need to return \c
426   /// this.  Otherwise, return the first operand, which is where all other
427   /// subclasses store their file pointer.
428   Metadata *getRawFile() const {
429     return isa<MDFile>(this) ? const_cast<MDScope *>(this)
430                              : static_cast<Metadata *>(getOperand(0));
431   }
432
433   MDScopeRef getRef() const { return MDScopeRef::get(this); }
434
435   static bool classof(const Metadata *MD) {
436     switch (MD->getMetadataID()) {
437     default:
438       return false;
439     case MDBasicTypeKind:
440     case MDDerivedTypeKind:
441     case MDCompositeTypeKind:
442     case MDSubroutineTypeKind:
443     case MDFileKind:
444     case MDCompileUnitKind:
445     case MDSubprogramKind:
446     case MDLexicalBlockKind:
447     case MDLexicalBlockFileKind:
448     case MDNamespaceKind:
449       return true;
450     }
451   }
452 };
453
454 /// \brief File.
455 ///
456 /// TODO: Merge with directory/file node (including users).
457 /// TODO: Canonicalize paths on creation.
458 class MDFile : public MDScope {
459   friend class LLVMContextImpl;
460   friend class MDNode;
461
462   MDFile(LLVMContext &C, StorageType Storage, ArrayRef<Metadata *> Ops)
463       : MDScope(C, MDFileKind, Storage, dwarf::DW_TAG_file_type, Ops) {}
464   ~MDFile() {}
465
466   static MDFile *getImpl(LLVMContext &Context, StringRef Filename,
467                          StringRef Directory, StorageType Storage,
468                          bool ShouldCreate = true) {
469     return getImpl(Context, getCanonicalMDString(Context, Filename),
470                    getCanonicalMDString(Context, Directory), Storage,
471                    ShouldCreate);
472   }
473   static MDFile *getImpl(LLVMContext &Context, MDString *Filename,
474                          MDString *Directory, StorageType Storage,
475                          bool ShouldCreate = true);
476
477   TempMDFile cloneImpl() const {
478     return getTemporary(getContext(), getFilename(), getDirectory());
479   }
480
481 public:
482   DEFINE_MDNODE_GET(MDFile, (StringRef Filename, StringRef Directory),
483                     (Filename, Directory))
484   DEFINE_MDNODE_GET(MDFile, (MDString * Filename, MDString *Directory),
485                     (Filename, Directory))
486
487   TempMDFile clone() const { return cloneImpl(); }
488
489   StringRef getFilename() const { return getStringOperand(0); }
490   StringRef getDirectory() const { return getStringOperand(1); }
491
492   MDString *getRawFilename() const { return getOperandAs<MDString>(0); }
493   MDString *getRawDirectory() const { return getOperandAs<MDString>(1); }
494
495   static bool classof(const Metadata *MD) {
496     return MD->getMetadataID() == MDFileKind;
497   }
498 };
499
500 StringRef MDScope::getFilename() const {
501   if (auto *F = getFile())
502     return F->getFilename();
503   return "";
504 }
505
506 StringRef MDScope::getDirectory() const {
507   if (auto *F = getFile())
508     return F->getDirectory();
509   return "";
510 }
511
512 /// \brief Base class for types.
513 ///
514 /// TODO: Remove the hardcoded name and context, since many types don't use
515 /// them.
516 /// TODO: Split up flags.
517 class MDType : public MDScope {
518   unsigned Line;
519   unsigned Flags;
520   uint64_t SizeInBits;
521   uint64_t AlignInBits;
522   uint64_t OffsetInBits;
523
524 protected:
525   MDType(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
526          unsigned Line, uint64_t SizeInBits, uint64_t AlignInBits,
527          uint64_t OffsetInBits, unsigned Flags, ArrayRef<Metadata *> Ops)
528       : MDScope(C, ID, Storage, Tag, Ops), Line(Line), Flags(Flags),
529         SizeInBits(SizeInBits), AlignInBits(AlignInBits),
530         OffsetInBits(OffsetInBits) {}
531   ~MDType() {}
532
533 public:
534   TempMDType clone() const {
535     return TempMDType(cast<MDType>(MDNode::clone().release()));
536   }
537
538   unsigned getLine() const { return Line; }
539   uint64_t getSizeInBits() const { return SizeInBits; }
540   uint64_t getAlignInBits() const { return AlignInBits; }
541   uint64_t getOffsetInBits() const { return OffsetInBits; }
542   unsigned getFlags() const { return Flags; }
543
544   MDScopeRef getScope() const { return MDScopeRef(getRawScope()); }
545   StringRef getName() const { return getStringOperand(2); }
546
547
548   Metadata *getRawScope() const { return getOperand(1); }
549   MDString *getRawName() const { return getOperandAs<MDString>(2); }
550
551   void setFlags(unsigned NewFlags) {
552     assert(!isUniqued() && "Cannot set flags on uniqued nodes");
553     Flags = NewFlags;
554   }
555
556   bool isPrivate() const {
557     return (getFlags() & FlagAccessibility) == FlagPrivate;
558   }
559   bool isProtected() const {
560     return (getFlags() & FlagAccessibility) == FlagProtected;
561   }
562   bool isPublic() const {
563     return (getFlags() & FlagAccessibility) == FlagPublic;
564   }
565   bool isForwardDecl() const { return getFlags() & FlagFwdDecl; }
566   bool isAppleBlockExtension() const { return getFlags() & FlagAppleBlock; }
567   bool isBlockByrefStruct() const { return getFlags() & FlagBlockByrefStruct; }
568   bool isVirtual() const { return getFlags() & FlagVirtual; }
569   bool isArtificial() const { return getFlags() & FlagArtificial; }
570   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
571   bool isObjcClassComplete() const {
572     return getFlags() & FlagObjcClassComplete;
573   }
574   bool isVector() const { return getFlags() & FlagVector; }
575   bool isStaticMember() const { return getFlags() & FlagStaticMember; }
576   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
577   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
578
579   MDTypeRef getRef() const { return MDTypeRef::get(this); }
580
581   static bool classof(const Metadata *MD) {
582     switch (MD->getMetadataID()) {
583     default:
584       return false;
585     case MDBasicTypeKind:
586     case MDDerivedTypeKind:
587     case MDCompositeTypeKind:
588     case MDSubroutineTypeKind:
589       return true;
590     }
591   }
592 };
593
594 /// \brief Basic type.
595 ///
596 /// TODO: Split out DW_TAG_unspecified_type.
597 /// TODO: Drop unused accessors.
598 class MDBasicType : public MDType {
599   friend class LLVMContextImpl;
600   friend class MDNode;
601
602   unsigned Encoding;
603
604   MDBasicType(LLVMContext &C, StorageType Storage, unsigned Tag,
605               uint64_t SizeInBits, uint64_t AlignInBits, unsigned Encoding,
606               ArrayRef<Metadata *> Ops)
607       : MDType(C, MDBasicTypeKind, Storage, Tag, 0, SizeInBits, AlignInBits, 0,
608                0, Ops),
609         Encoding(Encoding) {}
610   ~MDBasicType() {}
611
612   static MDBasicType *getImpl(LLVMContext &Context, unsigned Tag,
613                               StringRef Name, uint64_t SizeInBits,
614                               uint64_t AlignInBits, unsigned Encoding,
615                               StorageType Storage, bool ShouldCreate = true) {
616     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
617                    SizeInBits, AlignInBits, Encoding, Storage, ShouldCreate);
618   }
619   static MDBasicType *getImpl(LLVMContext &Context, unsigned Tag,
620                               MDString *Name, uint64_t SizeInBits,
621                               uint64_t AlignInBits, unsigned Encoding,
622                               StorageType Storage, bool ShouldCreate = true);
623
624   TempMDBasicType cloneImpl() const {
625     return getTemporary(getContext(), getTag(), getName(), getSizeInBits(),
626                         getAlignInBits(), getEncoding());
627   }
628
629 public:
630   DEFINE_MDNODE_GET(MDBasicType, (unsigned Tag, StringRef Name),
631                     (Tag, Name, 0, 0, 0))
632   DEFINE_MDNODE_GET(MDBasicType,
633                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
634                      uint64_t AlignInBits, unsigned Encoding),
635                     (Tag, Name, SizeInBits, AlignInBits, Encoding))
636   DEFINE_MDNODE_GET(MDBasicType,
637                     (unsigned Tag, MDString *Name, uint64_t SizeInBits,
638                      uint64_t AlignInBits, unsigned Encoding),
639                     (Tag, Name, SizeInBits, AlignInBits, Encoding))
640
641   TempMDBasicType clone() const { return cloneImpl(); }
642
643   unsigned getEncoding() const { return Encoding; }
644
645   static bool classof(const Metadata *MD) {
646     return MD->getMetadataID() == MDBasicTypeKind;
647   }
648 };
649
650 /// \brief Base class for MDDerivedType and MDCompositeType.
651 ///
652 /// TODO: Delete; they're not really related.
653 class MDDerivedTypeBase : public MDType {
654 protected:
655   MDDerivedTypeBase(LLVMContext &C, unsigned ID, StorageType Storage,
656                     unsigned Tag, unsigned Line, uint64_t SizeInBits,
657                     uint64_t AlignInBits, uint64_t OffsetInBits, unsigned Flags,
658                     ArrayRef<Metadata *> Ops)
659       : MDType(C, ID, Storage, Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
660                Flags, Ops) {}
661   ~MDDerivedTypeBase() {}
662
663 public:
664   MDTypeRef getBaseType() const { return MDTypeRef(getRawBaseType()); }
665   Metadata *getRawBaseType() const { return getOperand(3); }
666
667   static bool classof(const Metadata *MD) {
668     return MD->getMetadataID() == MDDerivedTypeKind ||
669            MD->getMetadataID() == MDCompositeTypeKind ||
670            MD->getMetadataID() == MDSubroutineTypeKind;
671   }
672 };
673
674 /// \brief Derived types.
675 ///
676 /// This includes qualified types, pointers, references, friends, typedefs, and
677 /// class members.
678 ///
679 /// TODO: Split out members (inheritance, fields, methods, etc.).
680 class MDDerivedType : public MDDerivedTypeBase {
681   friend class LLVMContextImpl;
682   friend class MDNode;
683
684   MDDerivedType(LLVMContext &C, StorageType Storage, unsigned Tag,
685                 unsigned Line, uint64_t SizeInBits, uint64_t AlignInBits,
686                 uint64_t OffsetInBits, unsigned Flags, ArrayRef<Metadata *> Ops)
687       : MDDerivedTypeBase(C, MDDerivedTypeKind, Storage, Tag, Line, SizeInBits,
688                           AlignInBits, OffsetInBits, Flags, Ops) {}
689   ~MDDerivedType() {}
690
691   static MDDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
692                                 StringRef Name, MDFile *File, unsigned Line,
693                                 MDScopeRef Scope, MDTypeRef BaseType,
694                                 uint64_t SizeInBits, uint64_t AlignInBits,
695                                 uint64_t OffsetInBits, unsigned Flags,
696                                 Metadata *ExtraData, StorageType Storage,
697                                 bool ShouldCreate = true) {
698     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
699                    Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits,
700                    Flags, ExtraData, Storage, ShouldCreate);
701   }
702   static MDDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
703                                 MDString *Name, Metadata *File, unsigned Line,
704                                 Metadata *Scope, Metadata *BaseType,
705                                 uint64_t SizeInBits, uint64_t AlignInBits,
706                                 uint64_t OffsetInBits, unsigned Flags,
707                                 Metadata *ExtraData, StorageType Storage,
708                                 bool ShouldCreate = true);
709
710   TempMDDerivedType cloneImpl() const {
711     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
712                         getScope(), getBaseType(), getSizeInBits(),
713                         getAlignInBits(), getOffsetInBits(), getFlags(),
714                         getExtraData());
715   }
716
717 public:
718   DEFINE_MDNODE_GET(MDDerivedType,
719                     (unsigned Tag, MDString *Name, Metadata *File,
720                      unsigned Line, Metadata *Scope, Metadata *BaseType,
721                      uint64_t SizeInBits, uint64_t AlignInBits,
722                      uint64_t OffsetInBits, unsigned Flags,
723                      Metadata *ExtraData = nullptr),
724                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
725                      AlignInBits, OffsetInBits, Flags, ExtraData))
726   DEFINE_MDNODE_GET(MDDerivedType,
727                     (unsigned Tag, StringRef Name, MDFile *File, unsigned Line,
728                      MDScopeRef Scope, MDTypeRef BaseType, uint64_t SizeInBits,
729                      uint64_t AlignInBits, uint64_t OffsetInBits,
730                      unsigned Flags, Metadata *ExtraData = nullptr),
731                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
732                      AlignInBits, OffsetInBits, Flags, ExtraData))
733
734   TempMDDerivedType clone() const { return cloneImpl(); }
735
736   /// \brief Get extra data associated with this derived type.
737   ///
738   /// Class type for pointer-to-members, objective-c property node for ivars,
739   /// or global constant wrapper for static members.
740   ///
741   /// TODO: Separate out types that need this extra operand: pointer-to-member
742   /// types and member fields (static members and ivars).
743   Metadata *getExtraData() const { return getRawExtraData(); }
744   Metadata *getRawExtraData() const { return getOperand(4); }
745
746   static bool classof(const Metadata *MD) {
747     return MD->getMetadataID() == MDDerivedTypeKind;
748   }
749 };
750
751 /// \brief Base class for MDCompositeType and MDSubroutineType.
752 ///
753 /// TODO: Delete; they're not really related.
754 class MDCompositeTypeBase : public MDDerivedTypeBase {
755   unsigned RuntimeLang;
756
757 protected:
758   MDCompositeTypeBase(LLVMContext &C, unsigned ID, StorageType Storage,
759                       unsigned Tag, unsigned Line, unsigned RuntimeLang,
760                       uint64_t SizeInBits, uint64_t AlignInBits,
761                       uint64_t OffsetInBits, unsigned Flags,
762                       ArrayRef<Metadata *> Ops)
763       : MDDerivedTypeBase(C, ID, Storage, Tag, Line, SizeInBits, AlignInBits,
764                           OffsetInBits, Flags, Ops),
765         RuntimeLang(RuntimeLang) {}
766   ~MDCompositeTypeBase() {}
767
768 public:
769   DebugNodeArray getElements() const {
770     return cast_or_null<MDTuple>(getRawElements());
771   }
772   MDTypeRef getVTableHolder() const { return MDTypeRef(getRawVTableHolder()); }
773   MDTemplateParameterArray getTemplateParams() const {
774     return cast_or_null<MDTuple>(getRawTemplateParams());
775   }
776   StringRef getIdentifier() const { return getStringOperand(7); }
777   unsigned getRuntimeLang() const { return RuntimeLang; }
778
779   Metadata *getRawElements() const { return getOperand(4); }
780   Metadata *getRawVTableHolder() const { return getOperand(5); }
781   Metadata *getRawTemplateParams() const { return getOperand(6); }
782   MDString *getRawIdentifier() const { return getOperandAs<MDString>(7); }
783
784   /// \brief Replace operands.
785   ///
786   /// If this \a isUniqued() and not \a isResolved(), on a uniquing collision
787   /// this will be RAUW'ed and deleted.  Use a \a TrackingMDRef to keep track
788   /// of its movement if necessary.
789   /// @{
790   void replaceElements(DebugNodeArray Elements) {
791 #ifndef NDEBUG
792     for (DebugNode *Op : getElements())
793       assert(std::find(Elements->op_begin(), Elements->op_end(), Op) &&
794              "Lost a member during member list replacement");
795 #endif
796     replaceOperandWith(4, Elements.get());
797   }
798   void replaceVTableHolder(MDTypeRef VTableHolder) {
799     replaceOperandWith(5, VTableHolder);
800   }
801   void replaceTemplateParams(MDTemplateParameterArray TemplateParams) {
802     replaceOperandWith(6, TemplateParams.get());
803   }
804   /// @}
805
806   static bool classof(const Metadata *MD) {
807     return MD->getMetadataID() == MDCompositeTypeKind ||
808            MD->getMetadataID() == MDSubroutineTypeKind;
809   }
810 };
811
812 /// \brief Composite types.
813 ///
814 /// TODO: Detach from DerivedTypeBase (split out MDEnumType?).
815 /// TODO: Create a custom, unrelated node for DW_TAG_array_type.
816 class MDCompositeType : public MDCompositeTypeBase {
817   friend class LLVMContextImpl;
818   friend class MDNode;
819
820   MDCompositeType(LLVMContext &C, StorageType Storage, unsigned Tag,
821                   unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits,
822                   uint64_t AlignInBits, uint64_t OffsetInBits, unsigned Flags,
823                   ArrayRef<Metadata *> Ops)
824       : MDCompositeTypeBase(C, MDCompositeTypeKind, Storage, Tag, Line,
825                             RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
826                             Flags, Ops) {}
827   ~MDCompositeType() {}
828
829   static MDCompositeType *
830   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, Metadata *File,
831           unsigned Line, MDScopeRef Scope, MDTypeRef BaseType,
832           uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
833           uint64_t Flags, DebugNodeArray Elements, unsigned RuntimeLang,
834           MDTypeRef VTableHolder, MDTemplateParameterArray TemplateParams,
835           StringRef Identifier, StorageType Storage, bool ShouldCreate = true) {
836     return getImpl(
837         Context, Tag, getCanonicalMDString(Context, Name), File, Line, Scope,
838         BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements.get(),
839         RuntimeLang, VTableHolder, TemplateParams.get(),
840         getCanonicalMDString(Context, Identifier), Storage, ShouldCreate);
841   }
842   static MDCompositeType *
843   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
844           unsigned Line, Metadata *Scope, Metadata *BaseType,
845           uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
846           unsigned Flags, Metadata *Elements, unsigned RuntimeLang,
847           Metadata *VTableHolder, Metadata *TemplateParams,
848           MDString *Identifier, StorageType Storage, bool ShouldCreate = true);
849
850   TempMDCompositeType cloneImpl() const {
851     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
852                         getScope(), getBaseType(), getSizeInBits(),
853                         getAlignInBits(), getOffsetInBits(), getFlags(),
854                         getElements(), getRuntimeLang(), getVTableHolder(),
855                         getTemplateParams(), getIdentifier());
856   }
857
858 public:
859   DEFINE_MDNODE_GET(MDCompositeType,
860                     (unsigned Tag, StringRef Name, MDFile *File, unsigned Line,
861                      MDScopeRef Scope, MDTypeRef BaseType, uint64_t SizeInBits,
862                      uint64_t AlignInBits, uint64_t OffsetInBits,
863                      unsigned Flags, DebugNodeArray Elements,
864                      unsigned RuntimeLang, MDTypeRef VTableHolder,
865                      MDTemplateParameterArray TemplateParams = nullptr,
866                      StringRef Identifier = ""),
867                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
868                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
869                      VTableHolder, TemplateParams, Identifier))
870   DEFINE_MDNODE_GET(MDCompositeType,
871                     (unsigned Tag, MDString *Name, Metadata *File,
872                      unsigned Line, Metadata *Scope, Metadata *BaseType,
873                      uint64_t SizeInBits, uint64_t AlignInBits,
874                      uint64_t OffsetInBits, unsigned Flags, Metadata *Elements,
875                      unsigned RuntimeLang, Metadata *VTableHolder,
876                      Metadata *TemplateParams = nullptr,
877                      MDString *Identifier = nullptr),
878                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
879                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
880                      VTableHolder, TemplateParams, Identifier))
881
882   TempMDCompositeType clone() const { return cloneImpl(); }
883
884   static bool classof(const Metadata *MD) {
885     return MD->getMetadataID() == MDCompositeTypeKind;
886   }
887 };
888
889 template <class T> TypedDebugNodeRef<T> TypedDebugNodeRef<T>::get(const T *N) {
890   if (N)
891     if (auto *Composite = dyn_cast<MDCompositeType>(N))
892       if (auto *S = Composite->getRawIdentifier())
893         return TypedDebugNodeRef<T>(S);
894   return TypedDebugNodeRef<T>(N);
895 }
896
897 /// \brief Type array for a subprogram.
898 ///
899 /// TODO: Detach from CompositeType, and fold the array of types in directly
900 /// as operands.
901 class MDSubroutineType : public MDCompositeTypeBase {
902   friend class LLVMContextImpl;
903   friend class MDNode;
904
905   MDSubroutineType(LLVMContext &C, StorageType Storage, unsigned Flags,
906                    ArrayRef<Metadata *> Ops)
907       : MDCompositeTypeBase(C, MDSubroutineTypeKind, Storage,
908                             dwarf::DW_TAG_subroutine_type, 0, 0, 0, 0, 0, Flags,
909                             Ops) {}
910   ~MDSubroutineType() {}
911
912   static MDSubroutineType *getImpl(LLVMContext &Context, unsigned Flags,
913                                    MDTypeRefArray TypeArray,
914                                    StorageType Storage,
915                                    bool ShouldCreate = true) {
916     return getImpl(Context, Flags, TypeArray.get(), Storage, ShouldCreate);
917   }
918   static MDSubroutineType *getImpl(LLVMContext &Context, unsigned Flags,
919                                    Metadata *TypeArray, StorageType Storage,
920                                    bool ShouldCreate = true);
921
922   TempMDSubroutineType cloneImpl() const {
923     return getTemporary(getContext(), getFlags(), getTypeArray());
924   }
925
926 public:
927   DEFINE_MDNODE_GET(MDSubroutineType,
928                     (unsigned Flags, MDTypeRefArray TypeArray),
929                     (Flags, TypeArray))
930   DEFINE_MDNODE_GET(MDSubroutineType, (unsigned Flags, Metadata *TypeArray),
931                     (Flags, TypeArray))
932
933   TempMDSubroutineType clone() const { return cloneImpl(); }
934
935   MDTypeRefArray getTypeArray() const {
936     return cast_or_null<MDTuple>(getRawTypeArray());
937   }
938   Metadata *getRawTypeArray() const { return getRawElements(); }
939
940   static bool classof(const Metadata *MD) {
941     return MD->getMetadataID() == MDSubroutineTypeKind;
942   }
943 };
944
945 /// \brief Compile unit.
946 class MDCompileUnit : public MDScope {
947   friend class LLVMContextImpl;
948   friend class MDNode;
949
950   unsigned SourceLanguage;
951   bool IsOptimized;
952   unsigned RuntimeVersion;
953   unsigned EmissionKind;
954
955   MDCompileUnit(LLVMContext &C, StorageType Storage, unsigned SourceLanguage,
956                 bool IsOptimized, unsigned RuntimeVersion,
957                 unsigned EmissionKind, ArrayRef<Metadata *> Ops)
958       : MDScope(C, MDCompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
959         SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
960         RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind) {}
961   ~MDCompileUnit() {}
962
963   static MDCompileUnit *
964   getImpl(LLVMContext &Context, unsigned SourceLanguage, MDFile *File,
965           StringRef Producer, bool IsOptimized, StringRef Flags,
966           unsigned RuntimeVersion, StringRef SplitDebugFilename,
967           unsigned EmissionKind, MDCompositeTypeArray EnumTypes,
968           MDTypeArray RetainedTypes, MDSubprogramArray Subprograms,
969           MDGlobalVariableArray GlobalVariables,
970           MDImportedEntityArray ImportedEntities, StorageType Storage,
971           bool ShouldCreate = true) {
972     return getImpl(
973         Context, SourceLanguage, File, getCanonicalMDString(Context, Producer),
974         IsOptimized, getCanonicalMDString(Context, Flags), RuntimeVersion,
975         getCanonicalMDString(Context, SplitDebugFilename), EmissionKind,
976         EnumTypes.get(), RetainedTypes.get(), Subprograms.get(),
977         GlobalVariables.get(), ImportedEntities.get(), Storage, ShouldCreate);
978   }
979   static MDCompileUnit *
980   getImpl(LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
981           MDString *Producer, bool IsOptimized, MDString *Flags,
982           unsigned RuntimeVersion, MDString *SplitDebugFilename,
983           unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
984           Metadata *Subprograms, Metadata *GlobalVariables,
985           Metadata *ImportedEntities, StorageType Storage,
986           bool ShouldCreate = true);
987
988   TempMDCompileUnit cloneImpl() const {
989     return getTemporary(
990         getContext(), getSourceLanguage(), getFile(), getProducer(),
991         isOptimized(), getFlags(), getRuntimeVersion(), getSplitDebugFilename(),
992         getEmissionKind(), getEnumTypes(), getRetainedTypes(), getSubprograms(),
993         getGlobalVariables(), getImportedEntities());
994   }
995
996 public:
997   DEFINE_MDNODE_GET(MDCompileUnit,
998                     (unsigned SourceLanguage, MDFile *File, StringRef Producer,
999                      bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
1000                      StringRef SplitDebugFilename, unsigned EmissionKind,
1001                      MDCompositeTypeArray EnumTypes, MDTypeArray RetainedTypes,
1002                      MDSubprogramArray Subprograms,
1003                      MDGlobalVariableArray GlobalVariables,
1004                      MDImportedEntityArray ImportedEntities),
1005                     (SourceLanguage, File, Producer, IsOptimized, Flags,
1006                      RuntimeVersion, SplitDebugFilename, EmissionKind,
1007                      EnumTypes, RetainedTypes, Subprograms, GlobalVariables,
1008                      ImportedEntities))
1009   DEFINE_MDNODE_GET(MDCompileUnit,
1010                     (unsigned SourceLanguage, Metadata *File,
1011                      MDString *Producer, bool IsOptimized, MDString *Flags,
1012                      unsigned RuntimeVersion, MDString *SplitDebugFilename,
1013                      unsigned EmissionKind, Metadata *EnumTypes,
1014                      Metadata *RetainedTypes, Metadata *Subprograms,
1015                      Metadata *GlobalVariables, Metadata *ImportedEntities),
1016                     (SourceLanguage, File, Producer, IsOptimized, Flags,
1017                      RuntimeVersion, SplitDebugFilename, EmissionKind,
1018                      EnumTypes, RetainedTypes, Subprograms, GlobalVariables,
1019                      ImportedEntities))
1020
1021   TempMDCompileUnit clone() const { return cloneImpl(); }
1022
1023   unsigned getSourceLanguage() const { return SourceLanguage; }
1024   bool isOptimized() const { return IsOptimized; }
1025   unsigned getRuntimeVersion() const { return RuntimeVersion; }
1026   unsigned getEmissionKind() const { return EmissionKind; }
1027   StringRef getProducer() const { return getStringOperand(1); }
1028   StringRef getFlags() const { return getStringOperand(2); }
1029   StringRef getSplitDebugFilename() const { return getStringOperand(3); }
1030   MDCompositeTypeArray getEnumTypes() const {
1031     return cast_or_null<MDTuple>(getRawEnumTypes());
1032   }
1033   MDTypeArray getRetainedTypes() const {
1034     return cast_or_null<MDTuple>(getRawRetainedTypes());
1035   }
1036   MDSubprogramArray getSubprograms() const {
1037     return cast_or_null<MDTuple>(getRawSubprograms());
1038   }
1039   MDGlobalVariableArray getGlobalVariables() const {
1040     return cast_or_null<MDTuple>(getRawGlobalVariables());
1041   }
1042   MDImportedEntityArray getImportedEntities() const {
1043     return cast_or_null<MDTuple>(getRawImportedEntities());
1044   }
1045
1046   MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
1047   MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
1048   MDString *getRawSplitDebugFilename() const {
1049     return getOperandAs<MDString>(3);
1050   }
1051   Metadata *getRawEnumTypes() const { return getOperand(4); }
1052   Metadata *getRawRetainedTypes() const { return getOperand(5); }
1053   Metadata *getRawSubprograms() const { return getOperand(6); }
1054   Metadata *getRawGlobalVariables() const { return getOperand(7); }
1055   Metadata *getRawImportedEntities() const { return getOperand(8); }
1056
1057   /// \brief Replace arrays.
1058   ///
1059   /// If this \a isUniqued() and not \a isResolved(), it will be RAUW'ed and
1060   /// deleted on a uniquing collision.  In practice, uniquing collisions on \a
1061   /// MDCompileUnit should be fairly rare.
1062   /// @{
1063   void replaceSubprograms(MDSubprogramArray N) {
1064     replaceOperandWith(6, N.get());
1065   }
1066   void replaceGlobalVariables(MDGlobalVariableArray N) {
1067     replaceOperandWith(7, N.get());
1068   }
1069   /// @}
1070
1071   static bool classof(const Metadata *MD) {
1072     return MD->getMetadataID() == MDCompileUnitKind;
1073   }
1074 };
1075
1076 /// \brief A scope for locals.
1077 ///
1078 /// A legal scope for lexical blocks, local variables, and debug info
1079 /// locations.  Subclasses are \a MDSubprogram, \a MDLexicalBlock, and \a
1080 /// MDLexicalBlockFile.
1081 class MDLocalScope : public MDScope {
1082 protected:
1083   MDLocalScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1084                ArrayRef<Metadata *> Ops)
1085       : MDScope(C, ID, Storage, Tag, Ops) {}
1086   ~MDLocalScope() {}
1087
1088 public:
1089   /// \brief Get the subprogram for this scope.
1090   ///
1091   /// Return this if it's an \a MDSubprogram; otherwise, look up the scope
1092   /// chain.
1093   MDSubprogram *getSubprogram() const;
1094
1095   static bool classof(const Metadata *MD) {
1096     return MD->getMetadataID() == MDSubprogramKind ||
1097            MD->getMetadataID() == MDLexicalBlockKind ||
1098            MD->getMetadataID() == MDLexicalBlockFileKind;
1099   }
1100 };
1101
1102 /// \brief Debug location.
1103 ///
1104 /// A debug location in source code, used for debug info and otherwise.
1105 class MDLocation : public MDNode {
1106   friend class LLVMContextImpl;
1107   friend class MDNode;
1108
1109   MDLocation(LLVMContext &C, StorageType Storage, unsigned Line,
1110              unsigned Column, ArrayRef<Metadata *> MDs);
1111   ~MDLocation() { dropAllReferences(); }
1112
1113   static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
1114                              unsigned Column, Metadata *Scope,
1115                              Metadata *InlinedAt, StorageType Storage,
1116                              bool ShouldCreate = true);
1117   static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
1118                              unsigned Column, MDLocalScope *Scope,
1119                              MDLocation *InlinedAt, StorageType Storage,
1120                              bool ShouldCreate = true) {
1121     return getImpl(Context, Line, Column, static_cast<Metadata *>(Scope),
1122                    static_cast<Metadata *>(InlinedAt), Storage, ShouldCreate);
1123   }
1124
1125   TempMDLocation cloneImpl() const {
1126     return getTemporary(getContext(), getLine(), getColumn(), getScope(),
1127                         getInlinedAt());
1128   }
1129
1130   // Disallow replacing operands.
1131   void replaceOperandWith(unsigned I, Metadata *New) = delete;
1132
1133 public:
1134   DEFINE_MDNODE_GET(MDLocation,
1135                     (unsigned Line, unsigned Column, Metadata *Scope,
1136                      Metadata *InlinedAt = nullptr),
1137                     (Line, Column, Scope, InlinedAt))
1138   DEFINE_MDNODE_GET(MDLocation,
1139                     (unsigned Line, unsigned Column, MDLocalScope *Scope,
1140                      MDLocation *InlinedAt = nullptr),
1141                     (Line, Column, Scope, InlinedAt))
1142
1143   /// \brief Return a (temporary) clone of this.
1144   TempMDLocation clone() const { return cloneImpl(); }
1145
1146   unsigned getLine() const { return SubclassData32; }
1147   unsigned getColumn() const { return SubclassData16; }
1148   MDLocalScope *getScope() const {
1149     return cast<MDLocalScope>(getRawScope());
1150   }
1151   MDLocation *getInlinedAt() const {
1152     return cast_or_null<MDLocation>(getRawInlinedAt());
1153   }
1154
1155   MDFile *getFile() const { return getScope()->getFile(); }
1156   StringRef getFilename() const { return getScope()->getFilename(); }
1157   StringRef getDirectory() const { return getScope()->getDirectory(); }
1158
1159   /// \brief Get the scope where this is inlined.
1160   ///
1161   /// Walk through \a getInlinedAt() and return \a getScope() from the deepest
1162   /// location.
1163   MDLocalScope *getInlinedAtScope() const {
1164     if (auto *IA = getInlinedAt())
1165       return IA->getInlinedAtScope();
1166     return getScope();
1167   }
1168
1169   Metadata *getRawScope() const { return getOperand(0); }
1170   Metadata *getRawInlinedAt() const {
1171     if (getNumOperands() == 2)
1172       return getOperand(1);
1173     return nullptr;
1174   }
1175
1176   static bool classof(const Metadata *MD) {
1177     return MD->getMetadataID() == MDLocationKind;
1178   }
1179 };
1180
1181 /// \brief Subprogram description.
1182 ///
1183 /// TODO: Remove DisplayName.  It's always equal to Name.
1184 /// TODO: Split up flags.
1185 class MDSubprogram : public MDLocalScope {
1186   friend class LLVMContextImpl;
1187   friend class MDNode;
1188
1189   unsigned Line;
1190   unsigned ScopeLine;
1191   unsigned Virtuality;
1192   unsigned VirtualIndex;
1193   unsigned Flags;
1194   bool IsLocalToUnit;
1195   bool IsDefinition;
1196   bool IsOptimized;
1197
1198   MDSubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
1199                unsigned ScopeLine, unsigned Virtuality, unsigned VirtualIndex,
1200                unsigned Flags, bool IsLocalToUnit, bool IsDefinition,
1201                bool IsOptimized, ArrayRef<Metadata *> Ops)
1202       : MDLocalScope(C, MDSubprogramKind, Storage, dwarf::DW_TAG_subprogram,
1203                      Ops),
1204         Line(Line), ScopeLine(ScopeLine), Virtuality(Virtuality),
1205         VirtualIndex(VirtualIndex), Flags(Flags), IsLocalToUnit(IsLocalToUnit),
1206         IsDefinition(IsDefinition), IsOptimized(IsOptimized) {}
1207   ~MDSubprogram() {}
1208
1209   static MDSubprogram *
1210   getImpl(LLVMContext &Context, MDScopeRef Scope, StringRef Name,
1211           StringRef LinkageName, MDFile *File, unsigned Line,
1212           MDSubroutineType *Type, bool IsLocalToUnit, bool IsDefinition,
1213           unsigned ScopeLine, MDTypeRef ContainingType, unsigned Virtuality,
1214           unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1215           ConstantAsMetadata *Function, MDTemplateParameterArray TemplateParams,
1216           MDSubprogram *Declaration, MDLocalVariableArray Variables,
1217           StorageType Storage, bool ShouldCreate = true) {
1218     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1219                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1220                    IsLocalToUnit, IsDefinition, ScopeLine, ContainingType,
1221                    Virtuality, VirtualIndex, Flags, IsOptimized, Function,
1222                    TemplateParams.get(), Declaration, Variables.get(), Storage,
1223                    ShouldCreate);
1224   }
1225   static MDSubprogram *
1226   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1227           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1228           bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1229           Metadata *ContainingType, unsigned Virtuality, unsigned VirtualIndex,
1230           unsigned Flags, bool IsOptimized, Metadata *Function,
1231           Metadata *TemplateParams, Metadata *Declaration, Metadata *Variables,
1232           StorageType Storage, bool ShouldCreate = true);
1233
1234   TempMDSubprogram cloneImpl() const {
1235     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1236                         getFile(), getLine(), getType(), isLocalToUnit(),
1237                         isDefinition(), getScopeLine(), getContainingType(),
1238                         getVirtuality(), getVirtualIndex(), getFlags(),
1239                         isOptimized(), getFunction(), getTemplateParams(),
1240                         getDeclaration(), getVariables());
1241   }
1242
1243 public:
1244   DEFINE_MDNODE_GET(MDSubprogram,
1245                     (MDScopeRef Scope, StringRef Name, StringRef LinkageName,
1246                      MDFile *File, unsigned Line, MDSubroutineType *Type,
1247                      bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1248                      MDTypeRef ContainingType, unsigned Virtuality,
1249                      unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1250                      ConstantAsMetadata *Function = nullptr,
1251                      MDTemplateParameterArray TemplateParams = nullptr,
1252                      MDSubprogram *Declaration = nullptr,
1253                      MDLocalVariableArray Variables = nullptr),
1254                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1255                      IsDefinition, ScopeLine, ContainingType, Virtuality,
1256                      VirtualIndex, Flags, IsOptimized, Function, TemplateParams,
1257                      Declaration, Variables))
1258   DEFINE_MDNODE_GET(
1259       MDSubprogram,
1260       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
1261        unsigned Line, Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
1262        unsigned ScopeLine, Metadata *ContainingType, unsigned Virtuality,
1263        unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1264        Metadata *Function = nullptr, Metadata *TemplateParams = nullptr,
1265        Metadata *Declaration = nullptr, Metadata *Variables = nullptr),
1266       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
1267        ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized,
1268        Function, TemplateParams, Declaration, Variables))
1269
1270   TempMDSubprogram clone() const { return cloneImpl(); }
1271
1272 public:
1273   unsigned getLine() const { return Line; }
1274   unsigned getVirtuality() const { return Virtuality; }
1275   unsigned getVirtualIndex() const { return VirtualIndex; }
1276   unsigned getScopeLine() const { return ScopeLine; }
1277   unsigned getFlags() const { return Flags; }
1278   bool isLocalToUnit() const { return IsLocalToUnit; }
1279   bool isDefinition() const { return IsDefinition; }
1280   bool isOptimized() const { return IsOptimized; }
1281
1282   unsigned isArtificial() const { return getFlags() & FlagArtificial; }
1283   bool isPrivate() const {
1284     return (getFlags() & FlagAccessibility) == FlagPrivate;
1285   }
1286   bool isProtected() const {
1287     return (getFlags() & FlagAccessibility) == FlagProtected;
1288   }
1289   bool isPublic() const {
1290     return (getFlags() & FlagAccessibility) == FlagPublic;
1291   }
1292   bool isExplicit() const { return getFlags() & FlagExplicit; }
1293   bool isPrototyped() const { return getFlags() & FlagPrototyped; }
1294
1295   /// \brief Check if this is reference-qualified.
1296   ///
1297   /// Return true if this subprogram is a C++11 reference-qualified non-static
1298   /// member function (void foo() &).
1299   unsigned isLValueReference() const {
1300     return getFlags() & FlagLValueReference;
1301   }
1302
1303   /// \brief Check if this is rvalue-reference-qualified.
1304   ///
1305   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
1306   /// non-static member function (void foo() &&).
1307   unsigned isRValueReference() const {
1308     return getFlags() & FlagRValueReference;
1309   }
1310
1311   MDScopeRef getScope() const { return MDScopeRef(getRawScope()); }
1312
1313   StringRef getName() const { return getStringOperand(2); }
1314   StringRef getDisplayName() const { return getStringOperand(3); }
1315   StringRef getLinkageName() const { return getStringOperand(4); }
1316
1317   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1318   MDString *getRawLinkageName() const { return getOperandAs<MDString>(4); }
1319
1320   MDSubroutineType *getType() const {
1321     return cast_or_null<MDSubroutineType>(getRawType());
1322   }
1323   MDTypeRef getContainingType() const {
1324     return MDTypeRef(getRawContainingType());
1325   }
1326
1327   ConstantAsMetadata *getFunction() const {
1328     return cast_or_null<ConstantAsMetadata>(getRawFunction());
1329   }
1330   MDTemplateParameterArray getTemplateParams() const {
1331     return cast_or_null<MDTuple>(getRawTemplateParams());
1332   }
1333   MDSubprogram *getDeclaration() const {
1334     return cast_or_null<MDSubprogram>(getRawDeclaration());
1335   }
1336   MDLocalVariableArray getVariables() const {
1337     return cast_or_null<MDTuple>(getRawVariables());
1338   }
1339
1340   Metadata *getRawScope() const { return getOperand(1); }
1341   Metadata *getRawType() const { return getOperand(5); }
1342   Metadata *getRawContainingType() const { return getOperand(6); }
1343   Metadata *getRawFunction() const { return getOperand(7); }
1344   Metadata *getRawTemplateParams() const { return getOperand(8); }
1345   Metadata *getRawDeclaration() const { return getOperand(9); }
1346   Metadata *getRawVariables() const { return getOperand(10); }
1347
1348   /// \brief Replace the function.
1349   ///
1350   /// If \a isUniqued() and not \a isResolved(), this could node will be
1351   /// RAUW'ed and deleted out from under the caller.  Use a \a TrackingMDRef if
1352   /// that's a problem.
1353   /// @{
1354   void replaceFunction(Function *F);
1355   void replaceFunction(ConstantAsMetadata *MD) { replaceOperandWith(7, MD); }
1356   void replaceFunction(std::nullptr_t) { replaceOperandWith(7, nullptr); }
1357   /// @}
1358
1359   static bool classof(const Metadata *MD) {
1360     return MD->getMetadataID() == MDSubprogramKind;
1361   }
1362 };
1363
1364 class MDLexicalBlockBase : public MDLocalScope {
1365 protected:
1366   MDLexicalBlockBase(LLVMContext &C, unsigned ID, StorageType Storage,
1367                      ArrayRef<Metadata *> Ops)
1368       : MDLocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
1369   ~MDLexicalBlockBase() {}
1370
1371 public:
1372   MDLocalScope *getScope() const { return cast<MDLocalScope>(getRawScope()); }
1373
1374   Metadata *getRawScope() const { return getOperand(1); }
1375
1376   static bool classof(const Metadata *MD) {
1377     return MD->getMetadataID() == MDLexicalBlockKind ||
1378            MD->getMetadataID() == MDLexicalBlockFileKind;
1379   }
1380 };
1381
1382 class MDLexicalBlock : public MDLexicalBlockBase {
1383   friend class LLVMContextImpl;
1384   friend class MDNode;
1385
1386   unsigned Line;
1387   unsigned Column;
1388
1389   MDLexicalBlock(LLVMContext &C, StorageType Storage, unsigned Line,
1390                  unsigned Column, ArrayRef<Metadata *> Ops)
1391       : MDLexicalBlockBase(C, MDLexicalBlockKind, Storage, Ops), Line(Line),
1392         Column(Column) {}
1393   ~MDLexicalBlock() {}
1394
1395   static MDLexicalBlock *getImpl(LLVMContext &Context, MDLocalScope *Scope,
1396                                  MDFile *File, unsigned Line, unsigned Column,
1397                                  StorageType Storage,
1398                                  bool ShouldCreate = true) {
1399     return getImpl(Context, static_cast<Metadata *>(Scope),
1400                    static_cast<Metadata *>(File), Line, Column, Storage,
1401                    ShouldCreate);
1402   }
1403
1404   static MDLexicalBlock *getImpl(LLVMContext &Context, Metadata *Scope,
1405                                  Metadata *File, unsigned Line, unsigned Column,
1406                                  StorageType Storage, bool ShouldCreate = true);
1407
1408   TempMDLexicalBlock cloneImpl() const {
1409     return getTemporary(getContext(), getScope(), getFile(), getLine(),
1410                         getColumn());
1411   }
1412
1413 public:
1414   DEFINE_MDNODE_GET(MDLexicalBlock, (MDLocalScope * Scope, MDFile *File,
1415                                      unsigned Line, unsigned Column),
1416                     (Scope, File, Line, Column))
1417   DEFINE_MDNODE_GET(MDLexicalBlock, (Metadata * Scope, Metadata *File,
1418                                      unsigned Line, unsigned Column),
1419                     (Scope, File, Line, Column))
1420
1421   TempMDLexicalBlock clone() const { return cloneImpl(); }
1422
1423   unsigned getLine() const { return Line; }
1424   unsigned getColumn() const { return Column; }
1425
1426   static bool classof(const Metadata *MD) {
1427     return MD->getMetadataID() == MDLexicalBlockKind;
1428   }
1429 };
1430
1431 class MDLexicalBlockFile : public MDLexicalBlockBase {
1432   friend class LLVMContextImpl;
1433   friend class MDNode;
1434
1435   unsigned Discriminator;
1436
1437   MDLexicalBlockFile(LLVMContext &C, StorageType Storage,
1438                      unsigned Discriminator, ArrayRef<Metadata *> Ops)
1439       : MDLexicalBlockBase(C, MDLexicalBlockFileKind, Storage, Ops),
1440         Discriminator(Discriminator) {}
1441   ~MDLexicalBlockFile() {}
1442
1443   static MDLexicalBlockFile *getImpl(LLVMContext &Context, MDLocalScope *Scope,
1444                                      MDFile *File, unsigned Discriminator,
1445                                      StorageType Storage,
1446                                      bool ShouldCreate = true) {
1447     return getImpl(Context, static_cast<Metadata *>(Scope),
1448                    static_cast<Metadata *>(File), Discriminator, Storage,
1449                    ShouldCreate);
1450   }
1451
1452   static MDLexicalBlockFile *getImpl(LLVMContext &Context, Metadata *Scope,
1453                                      Metadata *File, unsigned Discriminator,
1454                                      StorageType Storage,
1455                                      bool ShouldCreate = true);
1456
1457   TempMDLexicalBlockFile cloneImpl() const {
1458     return getTemporary(getContext(), getScope(), getFile(),
1459                         getDiscriminator());
1460   }
1461
1462 public:
1463   DEFINE_MDNODE_GET(MDLexicalBlockFile, (MDLocalScope * Scope, MDFile *File,
1464                                          unsigned Discriminator),
1465                     (Scope, File, Discriminator))
1466   DEFINE_MDNODE_GET(MDLexicalBlockFile,
1467                     (Metadata * Scope, Metadata *File, unsigned Discriminator),
1468                     (Scope, File, Discriminator))
1469
1470   TempMDLexicalBlockFile clone() const { return cloneImpl(); }
1471
1472   unsigned getDiscriminator() const { return Discriminator; }
1473
1474   static bool classof(const Metadata *MD) {
1475     return MD->getMetadataID() == MDLexicalBlockFileKind;
1476   }
1477 };
1478
1479 class MDNamespace : public MDScope {
1480   friend class LLVMContextImpl;
1481   friend class MDNode;
1482
1483   unsigned Line;
1484
1485   MDNamespace(LLVMContext &Context, StorageType Storage, unsigned Line,
1486               ArrayRef<Metadata *> Ops)
1487       : MDScope(Context, MDNamespaceKind, Storage, dwarf::DW_TAG_namespace,
1488                 Ops),
1489         Line(Line) {}
1490   ~MDNamespace() {}
1491
1492   static MDNamespace *getImpl(LLVMContext &Context, MDScope *Scope,
1493                               MDFile *File, StringRef Name, unsigned Line,
1494                               StorageType Storage, bool ShouldCreate = true) {
1495     return getImpl(Context, Scope, File, getCanonicalMDString(Context, Name),
1496                    Line, Storage, ShouldCreate);
1497   }
1498   static MDNamespace *getImpl(LLVMContext &Context, Metadata *Scope,
1499                               Metadata *File, MDString *Name, unsigned Line,
1500                               StorageType Storage, bool ShouldCreate = true);
1501
1502   TempMDNamespace cloneImpl() const {
1503     return getTemporary(getContext(), getScope(), getFile(), getName(),
1504                         getLine());
1505   }
1506
1507 public:
1508   DEFINE_MDNODE_GET(MDNamespace, (MDScope * Scope, MDFile *File, StringRef Name,
1509                                   unsigned Line),
1510                     (Scope, File, Name, Line))
1511   DEFINE_MDNODE_GET(MDNamespace, (Metadata * Scope, Metadata *File,
1512                                   MDString *Name, unsigned Line),
1513                     (Scope, File, Name, Line))
1514
1515   TempMDNamespace clone() const { return cloneImpl(); }
1516
1517   unsigned getLine() const { return Line; }
1518   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
1519   StringRef getName() const { return getStringOperand(2); }
1520
1521   Metadata *getRawScope() const { return getOperand(1); }
1522   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1523
1524   static bool classof(const Metadata *MD) {
1525     return MD->getMetadataID() == MDNamespaceKind;
1526   }
1527 };
1528
1529 /// \brief Base class for template parameters.
1530 class MDTemplateParameter : public DebugNode {
1531 protected:
1532   MDTemplateParameter(LLVMContext &Context, unsigned ID, StorageType Storage,
1533                       unsigned Tag, ArrayRef<Metadata *> Ops)
1534       : DebugNode(Context, ID, Storage, Tag, Ops) {}
1535   ~MDTemplateParameter() {}
1536
1537 public:
1538   StringRef getName() const { return getStringOperand(0); }
1539   MDTypeRef getType() const { return MDTypeRef(getRawType()); }
1540
1541   MDString *getRawName() const { return getOperandAs<MDString>(0); }
1542   Metadata *getRawType() const { return getOperand(1); }
1543
1544   static bool classof(const Metadata *MD) {
1545     return MD->getMetadataID() == MDTemplateTypeParameterKind ||
1546            MD->getMetadataID() == MDTemplateValueParameterKind;
1547   }
1548 };
1549
1550 class MDTemplateTypeParameter : public MDTemplateParameter {
1551   friend class LLVMContextImpl;
1552   friend class MDNode;
1553
1554   MDTemplateTypeParameter(LLVMContext &Context, StorageType Storage,
1555                           ArrayRef<Metadata *> Ops)
1556       : MDTemplateParameter(Context, MDTemplateTypeParameterKind, Storage,
1557                             dwarf::DW_TAG_template_type_parameter, Ops) {}
1558   ~MDTemplateTypeParameter() {}
1559
1560   static MDTemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
1561                                           MDTypeRef Type, StorageType Storage,
1562                                           bool ShouldCreate = true) {
1563     return getImpl(Context, getCanonicalMDString(Context, Name), Type, Storage,
1564                    ShouldCreate);
1565   }
1566   static MDTemplateTypeParameter *getImpl(LLVMContext &Context, MDString *Name,
1567                                           Metadata *Type, StorageType Storage,
1568                                           bool ShouldCreate = true);
1569
1570   TempMDTemplateTypeParameter cloneImpl() const {
1571     return getTemporary(getContext(), getName(), getType());
1572   }
1573
1574 public:
1575   DEFINE_MDNODE_GET(MDTemplateTypeParameter, (StringRef Name, MDTypeRef Type),
1576                     (Name, Type))
1577   DEFINE_MDNODE_GET(MDTemplateTypeParameter, (MDString * Name, Metadata *Type),
1578                     (Name, Type))
1579
1580   TempMDTemplateTypeParameter clone() const { return cloneImpl(); }
1581
1582   static bool classof(const Metadata *MD) {
1583     return MD->getMetadataID() == MDTemplateTypeParameterKind;
1584   }
1585 };
1586
1587 class MDTemplateValueParameter : public MDTemplateParameter {
1588   friend class LLVMContextImpl;
1589   friend class MDNode;
1590
1591   MDTemplateValueParameter(LLVMContext &Context, StorageType Storage,
1592                            unsigned Tag, ArrayRef<Metadata *> Ops)
1593       : MDTemplateParameter(Context, MDTemplateValueParameterKind, Storage, Tag,
1594                             Ops) {}
1595   ~MDTemplateValueParameter() {}
1596
1597   static MDTemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
1598                                            StringRef Name, MDTypeRef Type,
1599                                            Metadata *Value, StorageType Storage,
1600                                            bool ShouldCreate = true) {
1601     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), Type,
1602                    Value, Storage, ShouldCreate);
1603   }
1604   static MDTemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
1605                                            MDString *Name, Metadata *Type,
1606                                            Metadata *Value, StorageType Storage,
1607                                            bool ShouldCreate = true);
1608
1609   TempMDTemplateValueParameter cloneImpl() const {
1610     return getTemporary(getContext(), getTag(), getName(), getType(),
1611                         getValue());
1612   }
1613
1614 public:
1615   DEFINE_MDNODE_GET(MDTemplateValueParameter, (unsigned Tag, StringRef Name,
1616                                                MDTypeRef Type, Metadata *Value),
1617                     (Tag, Name, Type, Value))
1618   DEFINE_MDNODE_GET(MDTemplateValueParameter, (unsigned Tag, MDString *Name,
1619                                                Metadata *Type, Metadata *Value),
1620                     (Tag, Name, Type, Value))
1621
1622   TempMDTemplateValueParameter clone() const { return cloneImpl(); }
1623
1624   Metadata *getValue() const { return getOperand(2); }
1625
1626   static bool classof(const Metadata *MD) {
1627     return MD->getMetadataID() == MDTemplateValueParameterKind;
1628   }
1629 };
1630
1631 /// \brief Base class for variables.
1632 ///
1633 /// TODO: Hardcode to DW_TAG_variable.
1634 class MDVariable : public DebugNode {
1635   unsigned Line;
1636
1637 protected:
1638   MDVariable(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1639              unsigned Line, ArrayRef<Metadata *> Ops)
1640       : DebugNode(C, ID, Storage, Tag, Ops), Line(Line) {}
1641   ~MDVariable() {}
1642
1643 public:
1644   unsigned getLine() const { return Line; }
1645   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
1646   StringRef getName() const { return getStringOperand(1); }
1647   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
1648   MDTypeRef getType() const { return MDTypeRef(getRawType()); }
1649
1650   StringRef getFilename() const {
1651     if (auto *F = getFile())
1652       return F->getFilename();
1653     return "";
1654   }
1655   StringRef getDirectory() const {
1656     if (auto *F = getFile())
1657       return F->getDirectory();
1658     return "";
1659   }
1660
1661   Metadata *getRawScope() const { return getOperand(0); }
1662   MDString *getRawName() const { return getOperandAs<MDString>(1); }
1663   Metadata *getRawFile() const { return getOperand(2); }
1664   Metadata *getRawType() const { return getOperand(3); }
1665
1666   static bool classof(const Metadata *MD) {
1667     return MD->getMetadataID() == MDLocalVariableKind ||
1668            MD->getMetadataID() == MDGlobalVariableKind;
1669   }
1670 };
1671
1672 /// \brief Global variables.
1673 ///
1674 /// TODO: Remove DisplayName.  It's always equal to Name.
1675 class MDGlobalVariable : public MDVariable {
1676   friend class LLVMContextImpl;
1677   friend class MDNode;
1678
1679   bool IsLocalToUnit;
1680   bool IsDefinition;
1681
1682   MDGlobalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
1683                    bool IsLocalToUnit, bool IsDefinition,
1684                    ArrayRef<Metadata *> Ops)
1685       : MDVariable(C, MDGlobalVariableKind, Storage, dwarf::DW_TAG_variable,
1686                    Line, Ops),
1687         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition) {}
1688   ~MDGlobalVariable() {}
1689
1690   static MDGlobalVariable *
1691   getImpl(LLVMContext &Context, MDScope *Scope, StringRef Name,
1692           StringRef LinkageName, MDFile *File, unsigned Line, MDTypeRef Type,
1693           bool IsLocalToUnit, bool IsDefinition, ConstantAsMetadata *Variable,
1694           MDDerivedType *StaticDataMemberDeclaration, StorageType Storage,
1695           bool ShouldCreate = true) {
1696     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1697                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1698                    IsLocalToUnit, IsDefinition, Variable,
1699                    StaticDataMemberDeclaration, Storage, ShouldCreate);
1700   }
1701   static MDGlobalVariable *
1702   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1703           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1704           bool IsLocalToUnit, bool IsDefinition, Metadata *Variable,
1705           Metadata *StaticDataMemberDeclaration, StorageType Storage,
1706           bool ShouldCreate = true);
1707
1708   TempMDGlobalVariable cloneImpl() const {
1709     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1710                         getFile(), getLine(), getType(), isLocalToUnit(),
1711                         isDefinition(), getVariable(),
1712                         getStaticDataMemberDeclaration());
1713   }
1714
1715 public:
1716   DEFINE_MDNODE_GET(MDGlobalVariable,
1717                     (MDScope * Scope, StringRef Name, StringRef LinkageName,
1718                      MDFile *File, unsigned Line, MDTypeRef Type,
1719                      bool IsLocalToUnit, bool IsDefinition,
1720                      ConstantAsMetadata *Variable,
1721                      MDDerivedType *StaticDataMemberDeclaration),
1722                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1723                      IsDefinition, Variable, StaticDataMemberDeclaration))
1724   DEFINE_MDNODE_GET(MDGlobalVariable,
1725                     (Metadata * Scope, MDString *Name, MDString *LinkageName,
1726                      Metadata *File, unsigned Line, Metadata *Type,
1727                      bool IsLocalToUnit, bool IsDefinition, Metadata *Variable,
1728                      Metadata *StaticDataMemberDeclaration),
1729                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1730                      IsDefinition, Variable, StaticDataMemberDeclaration))
1731
1732   TempMDGlobalVariable clone() const { return cloneImpl(); }
1733
1734   bool isLocalToUnit() const { return IsLocalToUnit; }
1735   bool isDefinition() const { return IsDefinition; }
1736   StringRef getDisplayName() const { return getStringOperand(4); }
1737   StringRef getLinkageName() const { return getStringOperand(5); }
1738   ConstantAsMetadata *getVariable() const {
1739     return cast_or_null<ConstantAsMetadata>(getRawVariable());
1740   }
1741   MDDerivedType *getStaticDataMemberDeclaration() const {
1742     return cast_or_null<MDDerivedType>(getRawStaticDataMemberDeclaration());
1743   }
1744
1745   MDString *getRawLinkageName() const { return getOperandAs<MDString>(5); }
1746   Metadata *getRawVariable() const { return getOperand(6); }
1747   Metadata *getRawStaticDataMemberDeclaration() const { return getOperand(7); }
1748
1749   static bool classof(const Metadata *MD) {
1750     return MD->getMetadataID() == MDGlobalVariableKind;
1751   }
1752 };
1753
1754 /// \brief Local variable.
1755 ///
1756 /// TODO: Split between arguments and otherwise.
1757 /// TODO: Use \c DW_TAG_variable instead of fake tags.
1758 /// TODO: Split up flags.
1759 class MDLocalVariable : public MDVariable {
1760   friend class LLVMContextImpl;
1761   friend class MDNode;
1762
1763   unsigned Arg;
1764   unsigned Flags;
1765
1766   MDLocalVariable(LLVMContext &C, StorageType Storage, unsigned Tag,
1767                   unsigned Line, unsigned Arg, unsigned Flags,
1768                   ArrayRef<Metadata *> Ops)
1769       : MDVariable(C, MDLocalVariableKind, Storage, Tag, Line, Ops), Arg(Arg),
1770         Flags(Flags) {}
1771   ~MDLocalVariable() {}
1772
1773   static MDLocalVariable *getImpl(LLVMContext &Context, unsigned Tag,
1774                                   MDScope *Scope, StringRef Name, MDFile *File,
1775                                   unsigned Line, MDTypeRef Type, unsigned Arg,
1776                                   unsigned Flags, MDLocation *InlinedAt,
1777                                   StorageType Storage,
1778                                   bool ShouldCreate = true) {
1779     return getImpl(Context, Tag, Scope, getCanonicalMDString(Context, Name),
1780                    File, Line, Type, Arg, Flags, InlinedAt, Storage,
1781                    ShouldCreate);
1782   }
1783   static MDLocalVariable *getImpl(LLVMContext &Context, unsigned Tag,
1784                                   Metadata *Scope, MDString *Name,
1785                                   Metadata *File, unsigned Line, Metadata *Type,
1786                                   unsigned Arg, unsigned Flags,
1787                                   Metadata *InlinedAt, StorageType Storage,
1788                                   bool ShouldCreate = true);
1789
1790   TempMDLocalVariable cloneImpl() const {
1791     return getTemporary(getContext(), getTag(), getScope(), getName(),
1792                         getFile(), getLine(), getType(), getArg(), getFlags(),
1793                         getInlinedAt());
1794   }
1795
1796 public:
1797   DEFINE_MDNODE_GET(MDLocalVariable,
1798                     (unsigned Tag, MDLocalScope *Scope, StringRef Name,
1799                      MDFile *File, unsigned Line, MDTypeRef Type, unsigned Arg,
1800                      unsigned Flags, MDLocation *InlinedAt = nullptr),
1801                     (Tag, Scope, Name, File, Line, Type, Arg, Flags, InlinedAt))
1802   DEFINE_MDNODE_GET(MDLocalVariable,
1803                     (unsigned Tag, Metadata *Scope, MDString *Name,
1804                      Metadata *File, unsigned Line, Metadata *Type,
1805                      unsigned Arg, unsigned Flags,
1806                      Metadata *InlinedAt = nullptr),
1807                     (Tag, Scope, Name, File, Line, Type, Arg, Flags, InlinedAt))
1808
1809   TempMDLocalVariable clone() const { return cloneImpl(); }
1810
1811   /// \brief Get the local scope for this variable.
1812   ///
1813   /// Variables must be defined in a local scope.
1814   MDLocalScope *getScope() const {
1815     return cast<MDLocalScope>(MDVariable::getScope());
1816   }
1817
1818   unsigned getArg() const { return Arg; }
1819   unsigned getFlags() const { return Flags; }
1820   MDLocation *getInlinedAt() const {
1821     return cast_or_null<MDLocation>(getRawInlinedAt());
1822   }
1823
1824   Metadata *getRawInlinedAt() const { return getOperand(4); }
1825
1826   bool isArtificial() const { return getFlags() & FlagArtificial; }
1827   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
1828
1829   /// \brief Check that a location is valid for this variable.
1830   ///
1831   /// Check that \c DL has the same inlined-at location as this variable,
1832   /// making them valid for the same \a DbgInfoIntrinsic.
1833   bool isValidLocationForIntrinsic(const MDLocation *DL) const {
1834     return getInlinedAt() == (DL ? DL->getInlinedAt() : nullptr);
1835   }
1836
1837   /// \brief Get an inlined version of this variable.
1838   ///
1839   /// Returns a version of this with \a getAlinedAt() set to \c InlinedAt.
1840   MDLocalVariable *withInline(MDLocation *InlinedAt) const {
1841     if (InlinedAt == getInlinedAt())
1842       return const_cast<MDLocalVariable *>(this);
1843     auto Temp = clone();
1844     Temp->replaceOperandWith(4, InlinedAt);
1845     return replaceWithUniqued(std::move(Temp));
1846   }
1847   MDLocalVariable *withoutInline() const { return withInline(nullptr); }
1848
1849   static bool classof(const Metadata *MD) {
1850     return MD->getMetadataID() == MDLocalVariableKind;
1851   }
1852 };
1853
1854 /// \brief DWARF expression.
1855 ///
1856 /// TODO: Co-allocate the expression elements.
1857 /// TODO: Separate from MDNode, or otherwise drop Distinct and Temporary
1858 /// storage types.
1859 class MDExpression : public MDNode {
1860   friend class LLVMContextImpl;
1861   friend class MDNode;
1862
1863   std::vector<uint64_t> Elements;
1864
1865   MDExpression(LLVMContext &C, StorageType Storage, ArrayRef<uint64_t> Elements)
1866       : MDNode(C, MDExpressionKind, Storage, None),
1867         Elements(Elements.begin(), Elements.end()) {}
1868   ~MDExpression() {}
1869
1870   static MDExpression *getImpl(LLVMContext &Context,
1871                                ArrayRef<uint64_t> Elements, StorageType Storage,
1872                                bool ShouldCreate = true);
1873
1874   TempMDExpression cloneImpl() const {
1875     return getTemporary(getContext(), getElements());
1876   }
1877
1878 public:
1879   DEFINE_MDNODE_GET(MDExpression, (ArrayRef<uint64_t> Elements), (Elements))
1880
1881   TempMDExpression clone() const { return cloneImpl(); }
1882
1883   ArrayRef<uint64_t> getElements() const { return Elements; }
1884
1885   unsigned getNumElements() const { return Elements.size(); }
1886   uint64_t getElement(unsigned I) const {
1887     assert(I < Elements.size() && "Index out of range");
1888     return Elements[I];
1889   }
1890
1891   /// \brief Return whether this is a piece of an aggregate variable.
1892   bool isBitPiece() const;
1893
1894   /// \brief Return the offset of this piece in bits.
1895   uint64_t getBitPieceOffset() const;
1896
1897   /// \brief Return the size of this piece in bits.
1898   uint64_t getBitPieceSize() const;
1899
1900   typedef ArrayRef<uint64_t>::iterator element_iterator;
1901   element_iterator elements_begin() const { return getElements().begin(); }
1902   element_iterator elements_end() const { return getElements().end(); }
1903
1904   /// \brief A lightweight wrapper around an expression operand.
1905   ///
1906   /// TODO: Store arguments directly and change \a MDExpression to store a
1907   /// range of these.
1908   class ExprOperand {
1909     const uint64_t *Op;
1910
1911   public:
1912     explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
1913
1914     const uint64_t *get() const { return Op; }
1915
1916     /// \brief Get the operand code.
1917     uint64_t getOp() const { return *Op; }
1918
1919     /// \brief Get an argument to the operand.
1920     ///
1921     /// Never returns the operand itself.
1922     uint64_t getArg(unsigned I) const { return Op[I + 1]; }
1923
1924     unsigned getNumArgs() const { return getSize() - 1; }
1925
1926     /// \brief Return the size of the operand.
1927     ///
1928     /// Return the number of elements in the operand (1 + args).
1929     unsigned getSize() const;
1930   };
1931
1932   /// \brief An iterator for expression operands.
1933   class expr_op_iterator
1934       : public std::iterator<std::input_iterator_tag, ExprOperand> {
1935     ExprOperand Op;
1936
1937   public:
1938     explicit expr_op_iterator(element_iterator I) : Op(I) {}
1939
1940     element_iterator getBase() const { return Op.get(); }
1941     const ExprOperand &operator*() const { return Op; }
1942     const ExprOperand *operator->() const { return &Op; }
1943
1944     expr_op_iterator &operator++() {
1945       increment();
1946       return *this;
1947     }
1948     expr_op_iterator operator++(int) {
1949       expr_op_iterator T(*this);
1950       increment();
1951       return T;
1952     }
1953
1954     /// \brief Get the next iterator.
1955     ///
1956     /// \a std::next() doesn't work because this is technically an
1957     /// input_iterator, but it's a perfectly valid operation.  This is an
1958     /// accessor to provide the same functionality.
1959     expr_op_iterator getNext() const { return ++expr_op_iterator(*this); }
1960
1961     bool operator==(const expr_op_iterator &X) const {
1962       return getBase() == X.getBase();
1963     }
1964     bool operator!=(const expr_op_iterator &X) const {
1965       return getBase() != X.getBase();
1966     }
1967
1968   private:
1969     void increment() { Op = ExprOperand(getBase() + Op.getSize()); }
1970   };
1971
1972   /// \brief Visit the elements via ExprOperand wrappers.
1973   ///
1974   /// These range iterators visit elements through \a ExprOperand wrappers.
1975   /// This is not guaranteed to be a valid range unless \a isValid() gives \c
1976   /// true.
1977   ///
1978   /// \pre \a isValid() gives \c true.
1979   /// @{
1980   expr_op_iterator expr_op_begin() const {
1981     return expr_op_iterator(elements_begin());
1982   }
1983   expr_op_iterator expr_op_end() const {
1984     return expr_op_iterator(elements_end());
1985   }
1986   /// @}
1987
1988   bool isValid() const;
1989
1990   static bool classof(const Metadata *MD) {
1991     return MD->getMetadataID() == MDExpressionKind;
1992   }
1993 };
1994
1995 class MDObjCProperty : public DebugNode {
1996   friend class LLVMContextImpl;
1997   friend class MDNode;
1998
1999   unsigned Line;
2000   unsigned Attributes;
2001
2002   MDObjCProperty(LLVMContext &C, StorageType Storage, unsigned Line,
2003                  unsigned Attributes, ArrayRef<Metadata *> Ops)
2004       : DebugNode(C, MDObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property,
2005                   Ops),
2006         Line(Line), Attributes(Attributes) {}
2007   ~MDObjCProperty() {}
2008
2009   static MDObjCProperty *
2010   getImpl(LLVMContext &Context, StringRef Name, MDFile *File, unsigned Line,
2011           StringRef GetterName, StringRef SetterName, unsigned Attributes,
2012           MDType *Type, StorageType Storage, bool ShouldCreate = true) {
2013     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
2014                    getCanonicalMDString(Context, GetterName),
2015                    getCanonicalMDString(Context, SetterName), Attributes, Type,
2016                    Storage, ShouldCreate);
2017   }
2018   static MDObjCProperty *getImpl(LLVMContext &Context, MDString *Name,
2019                                  Metadata *File, unsigned Line,
2020                                  MDString *GetterName, MDString *SetterName,
2021                                  unsigned Attributes, Metadata *Type,
2022                                  StorageType Storage, bool ShouldCreate = true);
2023
2024   TempMDObjCProperty cloneImpl() const {
2025     return getTemporary(getContext(), getName(), getFile(), getLine(),
2026                         getGetterName(), getSetterName(), getAttributes(),
2027                         getType());
2028   }
2029
2030 public:
2031   DEFINE_MDNODE_GET(MDObjCProperty,
2032                     (StringRef Name, MDFile *File, unsigned Line,
2033                      StringRef GetterName, StringRef SetterName,
2034                      unsigned Attributes, MDType *Type),
2035                     (Name, File, Line, GetterName, SetterName, Attributes,
2036                      Type))
2037   DEFINE_MDNODE_GET(MDObjCProperty,
2038                     (MDString * Name, Metadata *File, unsigned Line,
2039                      MDString *GetterName, MDString *SetterName,
2040                      unsigned Attributes, Metadata *Type),
2041                     (Name, File, Line, GetterName, SetterName, Attributes,
2042                      Type))
2043
2044   TempMDObjCProperty clone() const { return cloneImpl(); }
2045
2046   unsigned getLine() const { return Line; }
2047   unsigned getAttributes() const { return Attributes; }
2048   StringRef getName() const { return getStringOperand(0); }
2049   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
2050   StringRef getGetterName() const { return getStringOperand(2); }
2051   StringRef getSetterName() const { return getStringOperand(3); }
2052   MDType *getType() const { return cast_or_null<MDType>(getRawType()); }
2053
2054   StringRef getFilename() const {
2055     if (auto *F = getFile())
2056       return F->getFilename();
2057     return "";
2058   }
2059   StringRef getDirectory() const {
2060     if (auto *F = getFile())
2061       return F->getDirectory();
2062     return "";
2063   }
2064
2065   MDString *getRawName() const { return getOperandAs<MDString>(0); }
2066   Metadata *getRawFile() const { return getOperand(1); }
2067   MDString *getRawGetterName() const { return getOperandAs<MDString>(2); }
2068   MDString *getRawSetterName() const { return getOperandAs<MDString>(3); }
2069   Metadata *getRawType() const { return getOperand(4); }
2070
2071   static bool classof(const Metadata *MD) {
2072     return MD->getMetadataID() == MDObjCPropertyKind;
2073   }
2074 };
2075
2076 class MDImportedEntity : public DebugNode {
2077   friend class LLVMContextImpl;
2078   friend class MDNode;
2079
2080   unsigned Line;
2081
2082   MDImportedEntity(LLVMContext &C, StorageType Storage, unsigned Tag,
2083                    unsigned Line, ArrayRef<Metadata *> Ops)
2084       : DebugNode(C, MDImportedEntityKind, Storage, Tag, Ops), Line(Line) {}
2085   ~MDImportedEntity() {}
2086
2087   static MDImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2088                                    MDScope *Scope, DebugNodeRef Entity,
2089                                    unsigned Line, StringRef Name,
2090                                    StorageType Storage,
2091                                    bool ShouldCreate = true) {
2092     return getImpl(Context, Tag, Scope, Entity, Line,
2093                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
2094   }
2095   static MDImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2096                                    Metadata *Scope, Metadata *Entity,
2097                                    unsigned Line, MDString *Name,
2098                                    StorageType Storage,
2099                                    bool ShouldCreate = true);
2100
2101   TempMDImportedEntity cloneImpl() const {
2102     return getTemporary(getContext(), getTag(), getScope(), getEntity(),
2103                         getLine(), getName());
2104   }
2105
2106 public:
2107   DEFINE_MDNODE_GET(MDImportedEntity,
2108                     (unsigned Tag, MDScope *Scope, DebugNodeRef Entity,
2109                      unsigned Line, StringRef Name = ""),
2110                     (Tag, Scope, Entity, Line, Name))
2111   DEFINE_MDNODE_GET(MDImportedEntity,
2112                     (unsigned Tag, Metadata *Scope, Metadata *Entity,
2113                      unsigned Line, MDString *Name),
2114                     (Tag, Scope, Entity, Line, Name))
2115
2116   TempMDImportedEntity clone() const { return cloneImpl(); }
2117
2118   unsigned getLine() const { return Line; }
2119   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
2120   DebugNodeRef getEntity() const { return DebugNodeRef(getRawEntity()); }
2121   StringRef getName() const { return getStringOperand(2); }
2122
2123   Metadata *getRawScope() const { return getOperand(0); }
2124   Metadata *getRawEntity() const { return getOperand(1); }
2125   MDString *getRawName() const { return getOperandAs<MDString>(2); }
2126
2127   static bool classof(const Metadata *MD) {
2128     return MD->getMetadataID() == MDImportedEntityKind;
2129   }
2130 };
2131
2132 } // end namespace llvm
2133
2134 #undef DEFINE_MDNODE_GET_UNPACK_IMPL
2135 #undef DEFINE_MDNODE_GET_UNPACK
2136 #undef DEFINE_MDNODE_GET
2137
2138 #endif