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