1 //===- llvm/IR/DebugInfoMetadata.h - Debug info metadata --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Declarations for metadata specific to debug info.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_IR_DEBUGINFOMETADATA_H
14 #define LLVM_IR_DEBUGINFOMETADATA_H
15 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/BitmaskEnum.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/PointerUnion.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/iterator_range.h"
25 #include "llvm/BinaryFormat/Dwarf.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/Metadata.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Discriminator.h"
31 #include <cassert>
32 #include <climits>
33 #include <cstddef>
34 #include <cstdint>
35 #include <iterator>
36 #include <type_traits>
37 #include <vector>
38 
39 // Helper macros for defining get() overrides.
40 #define DEFINE_MDNODE_GET_UNPACK_IMPL(...) __VA_ARGS__
41 #define DEFINE_MDNODE_GET_UNPACK(ARGS) DEFINE_MDNODE_GET_UNPACK_IMPL ARGS
42 #define DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(CLASS, FORMAL, ARGS)              \
43   static CLASS *getDistinct(LLVMContext &Context,                              \
44                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
45     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Distinct);         \
46   }                                                                            \
47   static Temp##CLASS getTemporary(LLVMContext &Context,                        \
48                                   DEFINE_MDNODE_GET_UNPACK(FORMAL)) {          \
49     return Temp##CLASS(                                                        \
50         getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Temporary));          \
51   }
52 #define DEFINE_MDNODE_GET(CLASS, FORMAL, ARGS)                                 \
53   static CLASS *get(LLVMContext &Context, DEFINE_MDNODE_GET_UNPACK(FORMAL)) {  \
54     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued);          \
55   }                                                                            \
56   static CLASS *getIfExists(LLVMContext &Context,                              \
57                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
58     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued,           \
59                    /* ShouldCreate */ false);                                  \
60   }                                                                            \
61   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(CLASS, FORMAL, ARGS)
62 
63 namespace llvm {
64 
65 extern cl::opt<bool> EnableFSDiscriminator;
66 
67 class DITypeRefArray {
68   const MDTuple *N = nullptr;
69 
70 public:
71   DITypeRefArray() = default;
DITypeRefArray(const MDTuple * N)72   DITypeRefArray(const MDTuple *N) : N(N) {}
73 
74   explicit operator bool() const { return get(); }
75   explicit operator MDTuple *() const { return get(); }
76 
get()77   MDTuple *get() const { return const_cast<MDTuple *>(N); }
78   MDTuple *operator->() const { return get(); }
79   MDTuple &operator*() const { return *get(); }
80 
81   // FIXME: Fix callers and remove condition on N.
size()82   unsigned size() const { return N ? N->getNumOperands() : 0u; }
83   DIType *operator[](unsigned I) const {
84     return cast_or_null<DIType>(N->getOperand(I));
85   }
86 
87   class iterator {
88     MDNode::op_iterator I = nullptr;
89 
90   public:
91     using iterator_category = std::input_iterator_tag;
92     using value_type = DIType *;
93     using difference_type = std::ptrdiff_t;
94     using pointer = void;
95     using reference = DIType *;
96 
97     iterator() = default;
iterator(MDNode::op_iterator I)98     explicit iterator(MDNode::op_iterator I) : I(I) {}
99 
100     DIType *operator*() const { return cast_or_null<DIType>(*I); }
101 
102     iterator &operator++() {
103       ++I;
104       return *this;
105     }
106 
107     iterator operator++(int) {
108       iterator Temp(*this);
109       ++I;
110       return Temp;
111     }
112 
113     bool operator==(const iterator &X) const { return I == X.I; }
114     bool operator!=(const iterator &X) const { return I != X.I; }
115   };
116 
117   // FIXME: Fix callers and remove condition on N.
begin()118   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
end()119   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
120 };
121 
122 /// Tagged DWARF-like metadata node.
123 ///
124 /// A metadata node with a DWARF tag (i.e., a constant named \c DW_TAG_*,
125 /// defined in llvm/BinaryFormat/Dwarf.h).  Called \a DINode because it's
126 /// potentially used for non-DWARF output.
127 class DINode : public MDNode {
128   friend class LLVMContextImpl;
129   friend class MDNode;
130 
131 protected:
132   DINode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
133          ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
MDNode(C,ID,Storage,Ops1,Ops2)134       : MDNode(C, ID, Storage, Ops1, Ops2) {
135     assert(Tag < 1u << 16);
136     SubclassData16 = Tag;
137   }
138   ~DINode() = default;
139 
getOperandAs(unsigned I)140   template <class Ty> Ty *getOperandAs(unsigned I) const {
141     return cast_or_null<Ty>(getOperand(I));
142   }
143 
getStringOperand(unsigned I)144   StringRef getStringOperand(unsigned I) const {
145     if (auto *S = getOperandAs<MDString>(I))
146       return S->getString();
147     return StringRef();
148   }
149 
getCanonicalMDString(LLVMContext & Context,StringRef S)150   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
151     if (S.empty())
152       return nullptr;
153     return MDString::get(Context, S);
154   }
155 
156   /// Allow subclasses to mutate the tag.
setTag(unsigned Tag)157   void setTag(unsigned Tag) { SubclassData16 = Tag; }
158 
159 public:
getTag()160   dwarf::Tag getTag() const { return (dwarf::Tag)SubclassData16; }
161 
162   /// Debug info flags.
163   ///
164   /// The three accessibility flags are mutually exclusive and rolled together
165   /// in the first two bits.
166   enum DIFlags : uint32_t {
167 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = ID,
168 #define DI_FLAG_LARGEST_NEEDED
169 #include "llvm/IR/DebugInfoFlags.def"
170     FlagAccessibility = FlagPrivate | FlagProtected | FlagPublic,
171     FlagPtrToMemberRep = FlagSingleInheritance | FlagMultipleInheritance |
172                          FlagVirtualInheritance,
173     LLVM_MARK_AS_BITMASK_ENUM(FlagLargest)
174   };
175 
176   static DIFlags getFlag(StringRef Flag);
177   static StringRef getFlagString(DIFlags Flag);
178 
179   /// Split up a flags bitfield.
180   ///
181   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
182   /// any remaining (unrecognized) bits.
183   static DIFlags splitFlags(DIFlags Flags,
184                             SmallVectorImpl<DIFlags> &SplitFlags);
185 
classof(const Metadata * MD)186   static bool classof(const Metadata *MD) {
187     switch (MD->getMetadataID()) {
188     default:
189       return false;
190     case GenericDINodeKind:
191     case DISubrangeKind:
192     case DIEnumeratorKind:
193     case DIBasicTypeKind:
194     case DIStringTypeKind:
195     case DIDerivedTypeKind:
196     case DICompositeTypeKind:
197     case DISubroutineTypeKind:
198     case DIFileKind:
199     case DICompileUnitKind:
200     case DISubprogramKind:
201     case DILexicalBlockKind:
202     case DILexicalBlockFileKind:
203     case DINamespaceKind:
204     case DICommonBlockKind:
205     case DITemplateTypeParameterKind:
206     case DITemplateValueParameterKind:
207     case DIGlobalVariableKind:
208     case DILocalVariableKind:
209     case DILabelKind:
210     case DIObjCPropertyKind:
211     case DIImportedEntityKind:
212     case DIModuleKind:
213     case DIGenericSubrangeKind:
214       return true;
215     }
216   }
217 };
218 
219 /// Generic tagged DWARF-like metadata node.
220 ///
221 /// An un-specialized DWARF-like metadata node.  The first operand is a
222 /// (possibly empty) null-separated \a MDString header that contains arbitrary
223 /// fields.  The remaining operands are \a dwarf_operands(), and are pointers
224 /// to other metadata.
225 class GenericDINode : public DINode {
226   friend class LLVMContextImpl;
227   friend class MDNode;
228 
GenericDINode(LLVMContext & C,StorageType Storage,unsigned Hash,unsigned Tag,ArrayRef<Metadata * > Ops1,ArrayRef<Metadata * > Ops2)229   GenericDINode(LLVMContext &C, StorageType Storage, unsigned Hash,
230                 unsigned Tag, ArrayRef<Metadata *> Ops1,
231                 ArrayRef<Metadata *> Ops2)
232       : DINode(C, GenericDINodeKind, Storage, Tag, Ops1, Ops2) {
233     setHash(Hash);
234   }
~GenericDINode()235   ~GenericDINode() { dropAllReferences(); }
236 
setHash(unsigned Hash)237   void setHash(unsigned Hash) { SubclassData32 = Hash; }
238   void recalculateHash();
239 
240   static GenericDINode *getImpl(LLVMContext &Context, unsigned Tag,
241                                 StringRef Header, ArrayRef<Metadata *> DwarfOps,
242                                 StorageType Storage, bool ShouldCreate = true) {
243     return getImpl(Context, Tag, getCanonicalMDString(Context, Header),
244                    DwarfOps, Storage, ShouldCreate);
245   }
246 
247   static GenericDINode *getImpl(LLVMContext &Context, unsigned Tag,
248                                 MDString *Header, ArrayRef<Metadata *> DwarfOps,
249                                 StorageType Storage, bool ShouldCreate = true);
250 
cloneImpl()251   TempGenericDINode cloneImpl() const {
252     return getTemporary(getContext(), getTag(), getHeader(),
253                         SmallVector<Metadata *, 4>(dwarf_operands()));
254   }
255 
256 public:
getHash()257   unsigned getHash() const { return SubclassData32; }
258 
259   DEFINE_MDNODE_GET(GenericDINode, (unsigned Tag, StringRef Header,
260                                     ArrayRef<Metadata *> DwarfOps),
261                     (Tag, Header, DwarfOps))
262   DEFINE_MDNODE_GET(GenericDINode, (unsigned Tag, MDString *Header,
263                                     ArrayRef<Metadata *> DwarfOps),
264                     (Tag, Header, DwarfOps))
265 
266   /// Return a (temporary) clone of this.
clone()267   TempGenericDINode clone() const { return cloneImpl(); }
268 
getTag()269   dwarf::Tag getTag() const { return (dwarf::Tag)SubclassData16; }
getHeader()270   StringRef getHeader() const { return getStringOperand(0); }
getRawHeader()271   MDString *getRawHeader() const { return getOperandAs<MDString>(0); }
272 
dwarf_op_begin()273   op_iterator dwarf_op_begin() const { return op_begin() + 1; }
dwarf_op_end()274   op_iterator dwarf_op_end() const { return op_end(); }
dwarf_operands()275   op_range dwarf_operands() const {
276     return op_range(dwarf_op_begin(), dwarf_op_end());
277   }
278 
getNumDwarfOperands()279   unsigned getNumDwarfOperands() const { return getNumOperands() - 1; }
getDwarfOperand(unsigned I)280   const MDOperand &getDwarfOperand(unsigned I) const {
281     return getOperand(I + 1);
282   }
replaceDwarfOperandWith(unsigned I,Metadata * New)283   void replaceDwarfOperandWith(unsigned I, Metadata *New) {
284     replaceOperandWith(I + 1, New);
285   }
286 
classof(const Metadata * MD)287   static bool classof(const Metadata *MD) {
288     return MD->getMetadataID() == GenericDINodeKind;
289   }
290 };
291 
292 /// Array subrange.
293 ///
294 /// TODO: Merge into node for DW_TAG_array_type, which should have a custom
295 /// type.
296 class DISubrange : public DINode {
297   friend class LLVMContextImpl;
298   friend class MDNode;
299 
DISubrange(LLVMContext & C,StorageType Storage,ArrayRef<Metadata * > Ops)300   DISubrange(LLVMContext &C, StorageType Storage, ArrayRef<Metadata *> Ops)
301       : DINode(C, DISubrangeKind, Storage, dwarf::DW_TAG_subrange_type, Ops) {}
302 
303   ~DISubrange() = default;
304 
305   static DISubrange *getImpl(LLVMContext &Context, int64_t Count,
306                              int64_t LowerBound, StorageType Storage,
307                              bool ShouldCreate = true);
308 
309   static DISubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
310                              int64_t LowerBound, StorageType Storage,
311                              bool ShouldCreate = true);
312 
313   static DISubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
314                              Metadata *LowerBound, Metadata *UpperBound,
315                              Metadata *Stride, StorageType Storage,
316                              bool ShouldCreate = true);
317 
cloneImpl()318   TempDISubrange cloneImpl() const {
319     return getTemporary(getContext(), getRawCountNode(), getRawLowerBound(),
320                         getRawUpperBound(), getRawStride());
321   }
322 
323 public:
324   DEFINE_MDNODE_GET(DISubrange, (int64_t Count, int64_t LowerBound = 0),
325                     (Count, LowerBound))
326 
327   DEFINE_MDNODE_GET(DISubrange, (Metadata *CountNode, int64_t LowerBound = 0),
328                     (CountNode, LowerBound))
329 
330   DEFINE_MDNODE_GET(DISubrange,
331                     (Metadata * CountNode, Metadata *LowerBound,
332                      Metadata *UpperBound, Metadata *Stride),
333                     (CountNode, LowerBound, UpperBound, Stride))
334 
clone()335   TempDISubrange clone() const { return cloneImpl(); }
336 
getRawCountNode()337   Metadata *getRawCountNode() const {
338     return getOperand(0).get();
339   }
340 
getRawLowerBound()341   Metadata *getRawLowerBound() const { return getOperand(1).get(); }
342 
getRawUpperBound()343   Metadata *getRawUpperBound() const { return getOperand(2).get(); }
344 
getRawStride()345   Metadata *getRawStride() const { return getOperand(3).get(); }
346 
347   typedef PointerUnion<ConstantInt *, DIVariable *, DIExpression *> BoundType;
348 
349   BoundType getCount() const;
350 
351   BoundType getLowerBound() const;
352 
353   BoundType getUpperBound() const;
354 
355   BoundType getStride() const;
356 
classof(const Metadata * MD)357   static bool classof(const Metadata *MD) {
358     return MD->getMetadataID() == DISubrangeKind;
359   }
360 };
361 
362 class DIGenericSubrange : public DINode {
363   friend class LLVMContextImpl;
364   friend class MDNode;
365 
DIGenericSubrange(LLVMContext & C,StorageType Storage,ArrayRef<Metadata * > Ops)366   DIGenericSubrange(LLVMContext &C, StorageType Storage,
367                     ArrayRef<Metadata *> Ops)
368       : DINode(C, DIGenericSubrangeKind, Storage,
369                dwarf::DW_TAG_generic_subrange, Ops) {}
370 
371   ~DIGenericSubrange() = default;
372 
373   static DIGenericSubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
374                                     Metadata *LowerBound, Metadata *UpperBound,
375                                     Metadata *Stride, StorageType Storage,
376                                     bool ShouldCreate = true);
377 
cloneImpl()378   TempDIGenericSubrange cloneImpl() const {
379     return getTemporary(getContext(), getRawCountNode(), getRawLowerBound(),
380                         getRawUpperBound(), getRawStride());
381   }
382 
383 public:
384   DEFINE_MDNODE_GET(DIGenericSubrange,
385                     (Metadata * CountNode, Metadata *LowerBound,
386                      Metadata *UpperBound, Metadata *Stride),
387                     (CountNode, LowerBound, UpperBound, Stride))
388 
clone()389   TempDIGenericSubrange clone() const { return cloneImpl(); }
390 
getRawCountNode()391   Metadata *getRawCountNode() const { return getOperand(0).get(); }
getRawLowerBound()392   Metadata *getRawLowerBound() const { return getOperand(1).get(); }
getRawUpperBound()393   Metadata *getRawUpperBound() const { return getOperand(2).get(); }
getRawStride()394   Metadata *getRawStride() const { return getOperand(3).get(); }
395 
396   using BoundType = PointerUnion<DIVariable *, DIExpression *>;
397 
398   BoundType getCount() const;
399   BoundType getLowerBound() const;
400   BoundType getUpperBound() const;
401   BoundType getStride() const;
402 
classof(const Metadata * MD)403   static bool classof(const Metadata *MD) {
404     return MD->getMetadataID() == DIGenericSubrangeKind;
405   }
406 };
407 
408 /// Enumeration value.
409 ///
410 /// TODO: Add a pointer to the context (DW_TAG_enumeration_type) once that no
411 /// longer creates a type cycle.
412 class DIEnumerator : public DINode {
413   friend class LLVMContextImpl;
414   friend class MDNode;
415 
416   APInt Value;
DIEnumerator(LLVMContext & C,StorageType Storage,const APInt & Value,bool IsUnsigned,ArrayRef<Metadata * > Ops)417   DIEnumerator(LLVMContext &C, StorageType Storage, const APInt &Value,
418                bool IsUnsigned, ArrayRef<Metadata *> Ops)
419       : DINode(C, DIEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops),
420         Value(Value) {
421     SubclassData32 = IsUnsigned;
422   }
DIEnumerator(LLVMContext & C,StorageType Storage,int64_t Value,bool IsUnsigned,ArrayRef<Metadata * > Ops)423   DIEnumerator(LLVMContext &C, StorageType Storage, int64_t Value,
424                bool IsUnsigned, ArrayRef<Metadata *> Ops)
425       : DIEnumerator(C, Storage, APInt(64, Value, !IsUnsigned), IsUnsigned,
426                      Ops) {}
427   ~DIEnumerator() = default;
428 
429   static DIEnumerator *getImpl(LLVMContext &Context, const APInt &Value,
430                                bool IsUnsigned, StringRef Name,
431                                StorageType Storage, bool ShouldCreate = true) {
432     return getImpl(Context, Value, IsUnsigned,
433                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
434   }
435   static DIEnumerator *getImpl(LLVMContext &Context, const APInt &Value,
436                                bool IsUnsigned, MDString *Name,
437                                StorageType Storage, bool ShouldCreate = true);
438 
cloneImpl()439   TempDIEnumerator cloneImpl() const {
440     return getTemporary(getContext(), getValue(), isUnsigned(), getName());
441   }
442 
443 public:
444   DEFINE_MDNODE_GET(DIEnumerator,
445                     (int64_t Value, bool IsUnsigned, StringRef Name),
446                     (APInt(64, Value, !IsUnsigned), IsUnsigned, Name))
447   DEFINE_MDNODE_GET(DIEnumerator,
448                     (int64_t Value, bool IsUnsigned, MDString *Name),
449                     (APInt(64, Value, !IsUnsigned), IsUnsigned, Name))
450   DEFINE_MDNODE_GET(DIEnumerator,
451                     (APInt Value, bool IsUnsigned, StringRef Name),
452                     (Value, IsUnsigned, Name))
453   DEFINE_MDNODE_GET(DIEnumerator,
454                     (APInt Value, bool IsUnsigned, MDString *Name),
455                     (Value, IsUnsigned, Name))
456 
clone()457   TempDIEnumerator clone() const { return cloneImpl(); }
458 
getValue()459   const APInt &getValue() const { return Value; }
isUnsigned()460   bool isUnsigned() const { return SubclassData32; }
getName()461   StringRef getName() const { return getStringOperand(0); }
462 
getRawName()463   MDString *getRawName() const { return getOperandAs<MDString>(0); }
464 
classof(const Metadata * MD)465   static bool classof(const Metadata *MD) {
466     return MD->getMetadataID() == DIEnumeratorKind;
467   }
468 };
469 
470 /// Base class for scope-like contexts.
471 ///
472 /// Base class for lexical scopes and types (which are also declaration
473 /// contexts).
474 ///
475 /// TODO: Separate the concepts of declaration contexts and lexical scopes.
476 class DIScope : public DINode {
477 protected:
DIScope(LLVMContext & C,unsigned ID,StorageType Storage,unsigned Tag,ArrayRef<Metadata * > Ops)478   DIScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
479           ArrayRef<Metadata *> Ops)
480       : DINode(C, ID, Storage, Tag, Ops) {}
481   ~DIScope() = default;
482 
483 public:
getFile()484   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
485 
486   inline StringRef getFilename() const;
487   inline StringRef getDirectory() const;
488   inline Optional<StringRef> getSource() const;
489 
490   StringRef getName() const;
491   DIScope *getScope() const;
492 
493   /// Return the raw underlying file.
494   ///
495   /// A \a DIFile is a \a DIScope, but it doesn't point at a separate file (it
496   /// \em is the file).  If \c this is an \a DIFile, we need to return \c this.
497   /// Otherwise, return the first operand, which is where all other subclasses
498   /// store their file pointer.
getRawFile()499   Metadata *getRawFile() const {
500     return isa<DIFile>(this) ? const_cast<DIScope *>(this)
501                              : static_cast<Metadata *>(getOperand(0));
502   }
503 
classof(const Metadata * MD)504   static bool classof(const Metadata *MD) {
505     switch (MD->getMetadataID()) {
506     default:
507       return false;
508     case DIBasicTypeKind:
509     case DIStringTypeKind:
510     case DIDerivedTypeKind:
511     case DICompositeTypeKind:
512     case DISubroutineTypeKind:
513     case DIFileKind:
514     case DICompileUnitKind:
515     case DISubprogramKind:
516     case DILexicalBlockKind:
517     case DILexicalBlockFileKind:
518     case DINamespaceKind:
519     case DICommonBlockKind:
520     case DIModuleKind:
521       return true;
522     }
523   }
524 };
525 
526 /// File.
527 ///
528 /// TODO: Merge with directory/file node (including users).
529 /// TODO: Canonicalize paths on creation.
530 class DIFile : public DIScope {
531   friend class LLVMContextImpl;
532   friend class MDNode;
533 
534 public:
535   /// Which algorithm (e.g. MD5) a checksum was generated with.
536   ///
537   /// The encoding is explicit because it is used directly in Bitcode. The
538   /// value 0 is reserved to indicate the absence of a checksum in Bitcode.
539   enum ChecksumKind {
540     // The first variant was originally CSK_None, encoded as 0. The new
541     // internal representation removes the need for this by wrapping the
542     // ChecksumInfo in an Optional, but to preserve Bitcode compatibility the 0
543     // encoding is reserved.
544     CSK_MD5 = 1,
545     CSK_SHA1 = 2,
546     CSK_SHA256 = 3,
547     CSK_Last = CSK_SHA256 // Should be last enumeration.
548   };
549 
550   /// A single checksum, represented by a \a Kind and a \a Value (a string).
551   template <typename T>
552   struct ChecksumInfo {
553     /// The kind of checksum which \a Value encodes.
554     ChecksumKind Kind;
555     /// The string value of the checksum.
556     T Value;
557 
ChecksumInfoChecksumInfo558     ChecksumInfo(ChecksumKind Kind, T Value) : Kind(Kind), Value(Value) { }
559     ~ChecksumInfo() = default;
560     bool operator==(const ChecksumInfo<T> &X) const {
561       return Kind == X.Kind && Value == X.Value;
562     }
563     bool operator!=(const ChecksumInfo<T> &X) const { return !(*this == X); }
getKindAsStringChecksumInfo564     StringRef getKindAsString() const { return getChecksumKindAsString(Kind); }
565   };
566 
567 private:
568   Optional<ChecksumInfo<MDString *>> Checksum;
569   Optional<MDString *> Source;
570 
DIFile(LLVMContext & C,StorageType Storage,Optional<ChecksumInfo<MDString * >> CS,Optional<MDString * > Src,ArrayRef<Metadata * > Ops)571   DIFile(LLVMContext &C, StorageType Storage,
572          Optional<ChecksumInfo<MDString *>> CS, Optional<MDString *> Src,
573          ArrayRef<Metadata *> Ops)
574       : DIScope(C, DIFileKind, Storage, dwarf::DW_TAG_file_type, Ops),
575         Checksum(CS), Source(Src) {}
576   ~DIFile() = default;
577 
578   static DIFile *getImpl(LLVMContext &Context, StringRef Filename,
579                          StringRef Directory,
580                          Optional<ChecksumInfo<StringRef>> CS,
581                          Optional<StringRef> Source,
582                          StorageType Storage, bool ShouldCreate = true) {
583     Optional<ChecksumInfo<MDString *>> MDChecksum;
584     if (CS)
585       MDChecksum.emplace(CS->Kind, getCanonicalMDString(Context, CS->Value));
586     return getImpl(Context, getCanonicalMDString(Context, Filename),
587                    getCanonicalMDString(Context, Directory), MDChecksum,
588                    Source ? Optional<MDString *>(getCanonicalMDString(Context, *Source)) : None,
589                    Storage, ShouldCreate);
590   }
591   static DIFile *getImpl(LLVMContext &Context, MDString *Filename,
592                          MDString *Directory,
593                          Optional<ChecksumInfo<MDString *>> CS,
594                          Optional<MDString *> Source, StorageType Storage,
595                          bool ShouldCreate = true);
596 
cloneImpl()597   TempDIFile cloneImpl() const {
598     return getTemporary(getContext(), getFilename(), getDirectory(),
599                         getChecksum(), getSource());
600   }
601 
602 public:
603   DEFINE_MDNODE_GET(DIFile, (StringRef Filename, StringRef Directory,
604                              Optional<ChecksumInfo<StringRef>> CS = None,
605                              Optional<StringRef> Source = None),
606                     (Filename, Directory, CS, Source))
607   DEFINE_MDNODE_GET(DIFile, (MDString * Filename, MDString *Directory,
608                              Optional<ChecksumInfo<MDString *>> CS = None,
609                              Optional<MDString *> Source = None),
610                     (Filename, Directory, CS, Source))
611 
clone()612   TempDIFile clone() const { return cloneImpl(); }
613 
getFilename()614   StringRef getFilename() const { return getStringOperand(0); }
getDirectory()615   StringRef getDirectory() const { return getStringOperand(1); }
getChecksum()616   Optional<ChecksumInfo<StringRef>> getChecksum() const {
617     Optional<ChecksumInfo<StringRef>> StringRefChecksum;
618     if (Checksum)
619       StringRefChecksum.emplace(Checksum->Kind, Checksum->Value->getString());
620     return StringRefChecksum;
621   }
getSource()622   Optional<StringRef> getSource() const {
623     return Source ? Optional<StringRef>((*Source)->getString()) : None;
624   }
625 
getRawFilename()626   MDString *getRawFilename() const { return getOperandAs<MDString>(0); }
getRawDirectory()627   MDString *getRawDirectory() const { return getOperandAs<MDString>(1); }
getRawChecksum()628   Optional<ChecksumInfo<MDString *>> getRawChecksum() const { return Checksum; }
getRawSource()629   Optional<MDString *> getRawSource() const { return Source; }
630 
631   static StringRef getChecksumKindAsString(ChecksumKind CSKind);
632   static Optional<ChecksumKind> getChecksumKind(StringRef CSKindStr);
633 
classof(const Metadata * MD)634   static bool classof(const Metadata *MD) {
635     return MD->getMetadataID() == DIFileKind;
636   }
637 };
638 
getFilename()639 StringRef DIScope::getFilename() const {
640   if (auto *F = getFile())
641     return F->getFilename();
642   return "";
643 }
644 
getDirectory()645 StringRef DIScope::getDirectory() const {
646   if (auto *F = getFile())
647     return F->getDirectory();
648   return "";
649 }
650 
getSource()651 Optional<StringRef> DIScope::getSource() const {
652   if (auto *F = getFile())
653     return F->getSource();
654   return None;
655 }
656 
657 /// Base class for types.
658 ///
659 /// TODO: Remove the hardcoded name and context, since many types don't use
660 /// them.
661 /// TODO: Split up flags.
662 class DIType : public DIScope {
663   unsigned Line;
664   DIFlags Flags;
665   uint64_t SizeInBits;
666   uint64_t OffsetInBits;
667   uint32_t AlignInBits;
668 
669 protected:
DIType(LLVMContext & C,unsigned ID,StorageType Storage,unsigned Tag,unsigned Line,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,DIFlags Flags,ArrayRef<Metadata * > Ops)670   DIType(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
671          unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
672          uint64_t OffsetInBits, DIFlags Flags, ArrayRef<Metadata *> Ops)
673       : DIScope(C, ID, Storage, Tag, Ops) {
674     init(Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
675   }
676   ~DIType() = default;
677 
init(unsigned Line,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,DIFlags Flags)678   void init(unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
679             uint64_t OffsetInBits, DIFlags Flags) {
680     this->Line = Line;
681     this->Flags = Flags;
682     this->SizeInBits = SizeInBits;
683     this->AlignInBits = AlignInBits;
684     this->OffsetInBits = OffsetInBits;
685   }
686 
687   /// Change fields in place.
mutate(unsigned Tag,unsigned Line,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,DIFlags Flags)688   void mutate(unsigned Tag, unsigned Line, uint64_t SizeInBits,
689               uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags) {
690     assert(isDistinct() && "Only distinct nodes can mutate");
691     setTag(Tag);
692     init(Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
693   }
694 
695 public:
clone()696   TempDIType clone() const {
697     return TempDIType(cast<DIType>(MDNode::clone().release()));
698   }
699 
getLine()700   unsigned getLine() const { return Line; }
getSizeInBits()701   uint64_t getSizeInBits() const { return SizeInBits; }
getAlignInBits()702   uint32_t getAlignInBits() const { return AlignInBits; }
getAlignInBytes()703   uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
getOffsetInBits()704   uint64_t getOffsetInBits() const { return OffsetInBits; }
getFlags()705   DIFlags getFlags() const { return Flags; }
706 
getScope()707   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
getName()708   StringRef getName() const { return getStringOperand(2); }
709 
710 
getRawScope()711   Metadata *getRawScope() const { return getOperand(1); }
getRawName()712   MDString *getRawName() const { return getOperandAs<MDString>(2); }
713 
714   /// Returns a new temporary DIType with updated Flags
cloneWithFlags(DIFlags NewFlags)715   TempDIType cloneWithFlags(DIFlags NewFlags) const {
716     auto NewTy = clone();
717     NewTy->Flags = NewFlags;
718     return NewTy;
719   }
720 
isPrivate()721   bool isPrivate() const {
722     return (getFlags() & FlagAccessibility) == FlagPrivate;
723   }
isProtected()724   bool isProtected() const {
725     return (getFlags() & FlagAccessibility) == FlagProtected;
726   }
isPublic()727   bool isPublic() const {
728     return (getFlags() & FlagAccessibility) == FlagPublic;
729   }
isForwardDecl()730   bool isForwardDecl() const { return getFlags() & FlagFwdDecl; }
isAppleBlockExtension()731   bool isAppleBlockExtension() const { return getFlags() & FlagAppleBlock; }
isVirtual()732   bool isVirtual() const { return getFlags() & FlagVirtual; }
isArtificial()733   bool isArtificial() const { return getFlags() & FlagArtificial; }
isObjectPointer()734   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
isObjcClassComplete()735   bool isObjcClassComplete() const {
736     return getFlags() & FlagObjcClassComplete;
737   }
isVector()738   bool isVector() const { return getFlags() & FlagVector; }
isBitField()739   bool isBitField() const { return getFlags() & FlagBitField; }
isStaticMember()740   bool isStaticMember() const { return getFlags() & FlagStaticMember; }
isLValueReference()741   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
isRValueReference()742   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
isTypePassByValue()743   bool isTypePassByValue() const { return getFlags() & FlagTypePassByValue; }
isTypePassByReference()744   bool isTypePassByReference() const {
745     return getFlags() & FlagTypePassByReference;
746   }
isBigEndian()747   bool isBigEndian() const { return getFlags() & FlagBigEndian; }
isLittleEndian()748   bool isLittleEndian() const { return getFlags() & FlagLittleEndian; }
getExportSymbols()749   bool getExportSymbols() const { return getFlags() & FlagExportSymbols; }
750 
classof(const Metadata * MD)751   static bool classof(const Metadata *MD) {
752     switch (MD->getMetadataID()) {
753     default:
754       return false;
755     case DIBasicTypeKind:
756     case DIStringTypeKind:
757     case DIDerivedTypeKind:
758     case DICompositeTypeKind:
759     case DISubroutineTypeKind:
760       return true;
761     }
762   }
763 };
764 
765 /// Basic type, like 'int' or 'float'.
766 ///
767 /// TODO: Split out DW_TAG_unspecified_type.
768 /// TODO: Drop unused accessors.
769 class DIBasicType : public DIType {
770   friend class LLVMContextImpl;
771   friend class MDNode;
772 
773   unsigned Encoding;
774 
DIBasicType(LLVMContext & C,StorageType Storage,unsigned Tag,uint64_t SizeInBits,uint32_t AlignInBits,unsigned Encoding,DIFlags Flags,ArrayRef<Metadata * > Ops)775   DIBasicType(LLVMContext &C, StorageType Storage, unsigned Tag,
776               uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding,
777               DIFlags Flags, ArrayRef<Metadata *> Ops)
778       : DIType(C, DIBasicTypeKind, Storage, Tag, 0, SizeInBits, AlignInBits, 0,
779                Flags, Ops),
780         Encoding(Encoding) {}
781   ~DIBasicType() = default;
782 
783   static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
784                               StringRef Name, uint64_t SizeInBits,
785                               uint32_t AlignInBits, unsigned Encoding,
786                               DIFlags Flags, StorageType Storage,
787                               bool ShouldCreate = true) {
788     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
789                    SizeInBits, AlignInBits, Encoding, Flags, Storage,
790                    ShouldCreate);
791   }
792   static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
793                               MDString *Name, uint64_t SizeInBits,
794                               uint32_t AlignInBits, unsigned Encoding,
795                               DIFlags Flags, StorageType Storage,
796                               bool ShouldCreate = true);
797 
cloneImpl()798   TempDIBasicType cloneImpl() const {
799     return getTemporary(getContext(), getTag(), getName(), getSizeInBits(),
800                         getAlignInBits(), getEncoding(), getFlags());
801   }
802 
803 public:
804   DEFINE_MDNODE_GET(DIBasicType, (unsigned Tag, StringRef Name),
805                     (Tag, Name, 0, 0, 0, FlagZero))
806   DEFINE_MDNODE_GET(DIBasicType,
807                     (unsigned Tag, StringRef Name, uint64_t SizeInBits),
808                     (Tag, Name, SizeInBits, 0, 0, FlagZero))
809   DEFINE_MDNODE_GET(DIBasicType,
810                     (unsigned Tag, MDString *Name, uint64_t SizeInBits),
811                     (Tag, Name, SizeInBits, 0, 0, FlagZero))
812   DEFINE_MDNODE_GET(DIBasicType,
813                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
814                      uint32_t AlignInBits, unsigned Encoding, DIFlags Flags),
815                     (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags))
816   DEFINE_MDNODE_GET(DIBasicType,
817                     (unsigned Tag, MDString *Name, uint64_t SizeInBits,
818                      uint32_t AlignInBits, unsigned Encoding, DIFlags Flags),
819                     (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags))
820 
clone()821   TempDIBasicType clone() const { return cloneImpl(); }
822 
getEncoding()823   unsigned getEncoding() const { return Encoding; }
824 
825   enum class Signedness { Signed, Unsigned };
826 
827   /// Return the signedness of this type, or None if this type is neither
828   /// signed nor unsigned.
829   Optional<Signedness> getSignedness() const;
830 
classof(const Metadata * MD)831   static bool classof(const Metadata *MD) {
832     return MD->getMetadataID() == DIBasicTypeKind;
833   }
834 };
835 
836 /// String type, Fortran CHARACTER(n)
837 class DIStringType : public DIType {
838   friend class LLVMContextImpl;
839   friend class MDNode;
840 
841   unsigned Encoding;
842 
DIStringType(LLVMContext & C,StorageType Storage,unsigned Tag,uint64_t SizeInBits,uint32_t AlignInBits,unsigned Encoding,ArrayRef<Metadata * > Ops)843   DIStringType(LLVMContext &C, StorageType Storage, unsigned Tag,
844                uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding,
845                ArrayRef<Metadata *> Ops)
846       : DIType(C, DIStringTypeKind, Storage, Tag, 0, SizeInBits, AlignInBits, 0,
847                FlagZero, Ops),
848         Encoding(Encoding) {}
849   ~DIStringType() = default;
850 
851   static DIStringType *getImpl(LLVMContext &Context, unsigned Tag,
852                                StringRef Name, Metadata *StringLength,
853                                Metadata *StrLenExp, uint64_t SizeInBits,
854                                uint32_t AlignInBits, unsigned Encoding,
855                                StorageType Storage, bool ShouldCreate = true) {
856     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
857                    StringLength, StrLenExp, SizeInBits, AlignInBits, Encoding,
858                    Storage, ShouldCreate);
859   }
860   static DIStringType *getImpl(LLVMContext &Context, unsigned Tag,
861                                MDString *Name, Metadata *StringLength,
862                                Metadata *StrLenExp, uint64_t SizeInBits,
863                                uint32_t AlignInBits, unsigned Encoding,
864                                StorageType Storage, bool ShouldCreate = true);
865 
cloneImpl()866   TempDIStringType cloneImpl() const {
867     return getTemporary(getContext(), getTag(), getRawName(),
868                         getRawStringLength(), getRawStringLengthExp(),
869                         getSizeInBits(), getAlignInBits(), getEncoding());
870   }
871 
872 public:
873   DEFINE_MDNODE_GET(DIStringType,
874                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
875                      uint32_t AlignInBits),
876                     (Tag, Name, nullptr, nullptr, SizeInBits, AlignInBits, 0))
877   DEFINE_MDNODE_GET(DIStringType,
878                     (unsigned Tag, MDString *Name, Metadata *StringLength,
879                      Metadata *StringLengthExp, uint64_t SizeInBits,
880                      uint32_t AlignInBits, unsigned Encoding),
881                     (Tag, Name, StringLength, StringLengthExp, SizeInBits,
882                      AlignInBits, Encoding))
883   DEFINE_MDNODE_GET(DIStringType,
884                     (unsigned Tag, StringRef Name, Metadata *StringLength,
885                      Metadata *StringLengthExp, uint64_t SizeInBits,
886                      uint32_t AlignInBits, unsigned Encoding),
887                     (Tag, Name, StringLength, StringLengthExp, SizeInBits,
888                      AlignInBits, Encoding))
889 
clone()890   TempDIStringType clone() const { return cloneImpl(); }
891 
classof(const Metadata * MD)892   static bool classof(const Metadata *MD) {
893     return MD->getMetadataID() == DIStringTypeKind;
894   }
895 
getStringLength()896   DIVariable *getStringLength() const {
897     return cast_or_null<DIVariable>(getRawStringLength());
898   }
899 
getStringLengthExp()900   DIExpression *getStringLengthExp() const {
901     return cast_or_null<DIExpression>(getRawStringLengthExp());
902   }
903 
getEncoding()904   unsigned getEncoding() const { return Encoding; }
905 
getRawStringLength()906   Metadata *getRawStringLength() const { return getOperand(3); }
907 
getRawStringLengthExp()908   Metadata *getRawStringLengthExp() const { return getOperand(4); }
909 };
910 
911 /// Derived types.
912 ///
913 /// This includes qualified types, pointers, references, friends, typedefs, and
914 /// class members.
915 ///
916 /// TODO: Split out members (inheritance, fields, methods, etc.).
917 class DIDerivedType : public DIType {
918   friend class LLVMContextImpl;
919   friend class MDNode;
920 
921   /// The DWARF address space of the memory pointed to or referenced by a
922   /// pointer or reference type respectively.
923   Optional<unsigned> DWARFAddressSpace;
924 
DIDerivedType(LLVMContext & C,StorageType Storage,unsigned Tag,unsigned Line,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,Optional<unsigned> DWARFAddressSpace,DIFlags Flags,ArrayRef<Metadata * > Ops)925   DIDerivedType(LLVMContext &C, StorageType Storage, unsigned Tag,
926                 unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
927                 uint64_t OffsetInBits, Optional<unsigned> DWARFAddressSpace,
928                 DIFlags Flags, ArrayRef<Metadata *> Ops)
929       : DIType(C, DIDerivedTypeKind, Storage, Tag, Line, SizeInBits,
930                AlignInBits, OffsetInBits, Flags, Ops),
931         DWARFAddressSpace(DWARFAddressSpace) {}
932   ~DIDerivedType() = default;
933 
934   static DIDerivedType *
935   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, DIFile *File,
936           unsigned Line, DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
937           uint32_t AlignInBits, uint64_t OffsetInBits,
938           Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
939           Metadata *ExtraData, StorageType Storage, bool ShouldCreate = true) {
940     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
941                    Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits,
942                    DWARFAddressSpace, Flags, ExtraData, Storage, ShouldCreate);
943   }
944   static DIDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
945                                 MDString *Name, Metadata *File, unsigned Line,
946                                 Metadata *Scope, Metadata *BaseType,
947                                 uint64_t SizeInBits, uint32_t AlignInBits,
948                                 uint64_t OffsetInBits,
949                                 Optional<unsigned> DWARFAddressSpace,
950                                 DIFlags Flags, Metadata *ExtraData,
951                                 StorageType Storage, bool ShouldCreate = true);
952 
cloneImpl()953   TempDIDerivedType cloneImpl() const {
954     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
955                         getScope(), getBaseType(), getSizeInBits(),
956                         getAlignInBits(), getOffsetInBits(),
957                         getDWARFAddressSpace(), getFlags(), getExtraData());
958   }
959 
960 public:
961   DEFINE_MDNODE_GET(DIDerivedType,
962                     (unsigned Tag, MDString *Name, Metadata *File,
963                      unsigned Line, Metadata *Scope, Metadata *BaseType,
964                      uint64_t SizeInBits, uint32_t AlignInBits,
965                      uint64_t OffsetInBits,
966                      Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
967                      Metadata *ExtraData = nullptr),
968                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
969                      AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
970                      ExtraData))
971   DEFINE_MDNODE_GET(DIDerivedType,
972                     (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
973                      DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
974                      uint32_t AlignInBits, uint64_t OffsetInBits,
975                      Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
976                      Metadata *ExtraData = nullptr),
977                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
978                      AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
979                      ExtraData))
980 
clone()981   TempDIDerivedType clone() const { return cloneImpl(); }
982 
983   /// Get the base type this is derived from.
getBaseType()984   DIType *getBaseType() const { return cast_or_null<DIType>(getRawBaseType()); }
getRawBaseType()985   Metadata *getRawBaseType() const { return getOperand(3); }
986 
987   /// \returns The DWARF address space of the memory pointed to or referenced by
988   /// a pointer or reference type respectively.
getDWARFAddressSpace()989   Optional<unsigned> getDWARFAddressSpace() const { return DWARFAddressSpace; }
990 
991   /// Get extra data associated with this derived type.
992   ///
993   /// Class type for pointer-to-members, objective-c property node for ivars,
994   /// global constant wrapper for static members, or virtual base pointer offset
995   /// for inheritance.
996   ///
997   /// TODO: Separate out types that need this extra operand: pointer-to-member
998   /// types and member fields (static members and ivars).
getExtraData()999   Metadata *getExtraData() const { return getRawExtraData(); }
getRawExtraData()1000   Metadata *getRawExtraData() const { return getOperand(4); }
1001 
1002   /// Get casted version of extra data.
1003   /// @{
getClassType()1004   DIType *getClassType() const {
1005     assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
1006     return cast_or_null<DIType>(getExtraData());
1007   }
1008 
getObjCProperty()1009   DIObjCProperty *getObjCProperty() const {
1010     return dyn_cast_or_null<DIObjCProperty>(getExtraData());
1011   }
1012 
getVBPtrOffset()1013   uint32_t getVBPtrOffset() const {
1014     assert(getTag() == dwarf::DW_TAG_inheritance);
1015     if (auto *CM = cast_or_null<ConstantAsMetadata>(getExtraData()))
1016       if (auto *CI = dyn_cast_or_null<ConstantInt>(CM->getValue()))
1017         return static_cast<uint32_t>(CI->getZExtValue());
1018     return 0;
1019   }
1020 
getStorageOffsetInBits()1021   Constant *getStorageOffsetInBits() const {
1022     assert(getTag() == dwarf::DW_TAG_member && isBitField());
1023     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
1024       return C->getValue();
1025     return nullptr;
1026   }
1027 
getConstant()1028   Constant *getConstant() const {
1029     assert(getTag() == dwarf::DW_TAG_member && isStaticMember());
1030     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
1031       return C->getValue();
1032     return nullptr;
1033   }
getDiscriminantValue()1034   Constant *getDiscriminantValue() const {
1035     assert(getTag() == dwarf::DW_TAG_member && !isStaticMember());
1036     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
1037       return C->getValue();
1038     return nullptr;
1039   }
1040   /// @}
1041 
classof(const Metadata * MD)1042   static bool classof(const Metadata *MD) {
1043     return MD->getMetadataID() == DIDerivedTypeKind;
1044   }
1045 };
1046 
1047 /// Composite types.
1048 ///
1049 /// TODO: Detach from DerivedTypeBase (split out MDEnumType?).
1050 /// TODO: Create a custom, unrelated node for DW_TAG_array_type.
1051 class DICompositeType : public DIType {
1052   friend class LLVMContextImpl;
1053   friend class MDNode;
1054 
1055   unsigned RuntimeLang;
1056 
DICompositeType(LLVMContext & C,StorageType Storage,unsigned Tag,unsigned Line,unsigned RuntimeLang,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,DIFlags Flags,ArrayRef<Metadata * > Ops)1057   DICompositeType(LLVMContext &C, StorageType Storage, unsigned Tag,
1058                   unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits,
1059                   uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
1060                   ArrayRef<Metadata *> Ops)
1061       : DIType(C, DICompositeTypeKind, Storage, Tag, Line, SizeInBits,
1062                AlignInBits, OffsetInBits, Flags, Ops),
1063         RuntimeLang(RuntimeLang) {}
1064   ~DICompositeType() = default;
1065 
1066   /// Change fields in place.
mutate(unsigned Tag,unsigned Line,unsigned RuntimeLang,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,DIFlags Flags)1067   void mutate(unsigned Tag, unsigned Line, unsigned RuntimeLang,
1068               uint64_t SizeInBits, uint32_t AlignInBits,
1069               uint64_t OffsetInBits, DIFlags Flags) {
1070     assert(isDistinct() && "Only distinct nodes can mutate");
1071     assert(getRawIdentifier() && "Only ODR-uniqued nodes should mutate");
1072     this->RuntimeLang = RuntimeLang;
1073     DIType::mutate(Tag, Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
1074   }
1075 
1076   static DICompositeType *
1077   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, Metadata *File,
1078           unsigned Line, DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
1079           uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
1080           DINodeArray Elements, unsigned RuntimeLang, DIType *VTableHolder,
1081           DITemplateParameterArray TemplateParams, StringRef Identifier,
1082           DIDerivedType *Discriminator, Metadata *DataLocation,
1083           Metadata *Associated, Metadata *Allocated, Metadata *Rank,
1084           StorageType Storage, bool ShouldCreate = true) {
1085     return getImpl(
1086         Context, Tag, getCanonicalMDString(Context, Name), File, Line, Scope,
1087         BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements.get(),
1088         RuntimeLang, VTableHolder, TemplateParams.get(),
1089         getCanonicalMDString(Context, Identifier), Discriminator, DataLocation,
1090         Associated, Allocated, Rank, Storage, ShouldCreate);
1091   }
1092   static DICompositeType *
1093   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
1094           unsigned Line, Metadata *Scope, Metadata *BaseType,
1095           uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
1096           DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
1097           Metadata *VTableHolder, Metadata *TemplateParams,
1098           MDString *Identifier, Metadata *Discriminator, Metadata *DataLocation,
1099           Metadata *Associated, Metadata *Allocated, Metadata *Rank,
1100           StorageType Storage, bool ShouldCreate = true);
1101 
cloneImpl()1102   TempDICompositeType cloneImpl() const {
1103     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
1104                         getScope(), getBaseType(), getSizeInBits(),
1105                         getAlignInBits(), getOffsetInBits(), getFlags(),
1106                         getElements(), getRuntimeLang(), getVTableHolder(),
1107                         getTemplateParams(), getIdentifier(),
1108                         getDiscriminator(), getRawDataLocation(),
1109                         getRawAssociated(), getRawAllocated(), getRawRank());
1110   }
1111 
1112 public:
1113   DEFINE_MDNODE_GET(
1114       DICompositeType,
1115       (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
1116        DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
1117        uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
1118        DINodeArray Elements, unsigned RuntimeLang, DIType *VTableHolder,
1119        DITemplateParameterArray TemplateParams = nullptr,
1120        StringRef Identifier = "", DIDerivedType *Discriminator = nullptr,
1121        Metadata *DataLocation = nullptr, Metadata *Associated = nullptr,
1122        Metadata *Allocated = nullptr, Metadata *Rank = nullptr),
1123       (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits,
1124        OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams,
1125        Identifier, Discriminator, DataLocation, Associated, Allocated, Rank))
1126   DEFINE_MDNODE_GET(
1127       DICompositeType,
1128       (unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
1129        Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
1130        uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
1131        Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
1132        Metadata *TemplateParams = nullptr, MDString *Identifier = nullptr,
1133        Metadata *Discriminator = nullptr, Metadata *DataLocation = nullptr,
1134        Metadata *Associated = nullptr, Metadata *Allocated = nullptr,
1135        Metadata *Rank = nullptr),
1136       (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits,
1137        OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams,
1138        Identifier, Discriminator, DataLocation, Associated, Allocated, Rank))
1139 
clone()1140   TempDICompositeType clone() const { return cloneImpl(); }
1141 
1142   /// Get a DICompositeType with the given ODR identifier.
1143   ///
1144   /// If \a LLVMContext::isODRUniquingDebugTypes(), gets the mapped
1145   /// DICompositeType for the given ODR \c Identifier.  If none exists, creates
1146   /// a new node.
1147   ///
1148   /// Else, returns \c nullptr.
1149   static DICompositeType *
1150   getODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag,
1151              MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
1152              Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits,
1153              uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements,
1154              unsigned RuntimeLang, Metadata *VTableHolder,
1155              Metadata *TemplateParams, Metadata *Discriminator,
1156              Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
1157              Metadata *Rank);
1158   static DICompositeType *getODRTypeIfExists(LLVMContext &Context,
1159                                              MDString &Identifier);
1160 
1161   /// Build a DICompositeType with the given ODR identifier.
1162   ///
1163   /// Looks up the mapped DICompositeType for the given ODR \c Identifier.  If
1164   /// it doesn't exist, creates a new one.  If it does exist and \a
1165   /// isForwardDecl(), and the new arguments would be a definition, mutates the
1166   /// the type in place.  In either case, returns the type.
1167   ///
1168   /// If not \a LLVMContext::isODRUniquingDebugTypes(), this function returns
1169   /// nullptr.
1170   static DICompositeType *
1171   buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag,
1172                MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
1173                Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits,
1174                uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements,
1175                unsigned RuntimeLang, Metadata *VTableHolder,
1176                Metadata *TemplateParams, Metadata *Discriminator,
1177                Metadata *DataLocation, Metadata *Associated,
1178                Metadata *Allocated, Metadata *Rank);
1179 
getBaseType()1180   DIType *getBaseType() const { return cast_or_null<DIType>(getRawBaseType()); }
getElements()1181   DINodeArray getElements() const {
1182     return cast_or_null<MDTuple>(getRawElements());
1183   }
getVTableHolder()1184   DIType *getVTableHolder() const {
1185     return cast_or_null<DIType>(getRawVTableHolder());
1186   }
getTemplateParams()1187   DITemplateParameterArray getTemplateParams() const {
1188     return cast_or_null<MDTuple>(getRawTemplateParams());
1189   }
getIdentifier()1190   StringRef getIdentifier() const { return getStringOperand(7); }
getRuntimeLang()1191   unsigned getRuntimeLang() const { return RuntimeLang; }
1192 
getRawBaseType()1193   Metadata *getRawBaseType() const { return getOperand(3); }
getRawElements()1194   Metadata *getRawElements() const { return getOperand(4); }
getRawVTableHolder()1195   Metadata *getRawVTableHolder() const { return getOperand(5); }
getRawTemplateParams()1196   Metadata *getRawTemplateParams() const { return getOperand(6); }
getRawIdentifier()1197   MDString *getRawIdentifier() const { return getOperandAs<MDString>(7); }
getRawDiscriminator()1198   Metadata *getRawDiscriminator() const { return getOperand(8); }
getDiscriminator()1199   DIDerivedType *getDiscriminator() const { return getOperandAs<DIDerivedType>(8); }
getRawDataLocation()1200   Metadata *getRawDataLocation() const { return getOperand(9); }
getDataLocation()1201   DIVariable *getDataLocation() const {
1202     return dyn_cast_or_null<DIVariable>(getRawDataLocation());
1203   }
getDataLocationExp()1204   DIExpression *getDataLocationExp() const {
1205     return dyn_cast_or_null<DIExpression>(getRawDataLocation());
1206   }
getRawAssociated()1207   Metadata *getRawAssociated() const { return getOperand(10); }
getAssociated()1208   DIVariable *getAssociated() const {
1209     return dyn_cast_or_null<DIVariable>(getRawAssociated());
1210   }
getAssociatedExp()1211   DIExpression *getAssociatedExp() const {
1212     return dyn_cast_or_null<DIExpression>(getRawAssociated());
1213   }
getRawAllocated()1214   Metadata *getRawAllocated() const { return getOperand(11); }
getAllocated()1215   DIVariable *getAllocated() const {
1216     return dyn_cast_or_null<DIVariable>(getRawAllocated());
1217   }
getAllocatedExp()1218   DIExpression *getAllocatedExp() const {
1219     return dyn_cast_or_null<DIExpression>(getRawAllocated());
1220   }
getRawRank()1221   Metadata *getRawRank() const { return getOperand(12); }
getRankConst()1222   ConstantInt *getRankConst() const {
1223     if (auto *MD = dyn_cast_or_null<ConstantAsMetadata>(getRawRank()))
1224       return dyn_cast_or_null<ConstantInt>(MD->getValue());
1225     return nullptr;
1226   }
getRankExp()1227   DIExpression *getRankExp() const {
1228     return dyn_cast_or_null<DIExpression>(getRawRank());
1229   }
1230 
1231   /// Replace operands.
1232   ///
1233   /// If this \a isUniqued() and not \a isResolved(), on a uniquing collision
1234   /// this will be RAUW'ed and deleted.  Use a \a TrackingMDRef to keep track
1235   /// of its movement if necessary.
1236   /// @{
replaceElements(DINodeArray Elements)1237   void replaceElements(DINodeArray Elements) {
1238 #ifndef NDEBUG
1239     for (DINode *Op : getElements())
1240       assert(is_contained(Elements->operands(), Op) &&
1241              "Lost a member during member list replacement");
1242 #endif
1243     replaceOperandWith(4, Elements.get());
1244   }
1245 
replaceVTableHolder(DIType * VTableHolder)1246   void replaceVTableHolder(DIType *VTableHolder) {
1247     replaceOperandWith(5, VTableHolder);
1248   }
1249 
replaceTemplateParams(DITemplateParameterArray TemplateParams)1250   void replaceTemplateParams(DITemplateParameterArray TemplateParams) {
1251     replaceOperandWith(6, TemplateParams.get());
1252   }
1253   /// @}
1254 
classof(const Metadata * MD)1255   static bool classof(const Metadata *MD) {
1256     return MD->getMetadataID() == DICompositeTypeKind;
1257   }
1258 };
1259 
1260 /// Type array for a subprogram.
1261 ///
1262 /// TODO: Fold the array of types in directly as operands.
1263 class DISubroutineType : public DIType {
1264   friend class LLVMContextImpl;
1265   friend class MDNode;
1266 
1267   /// The calling convention used with DW_AT_calling_convention. Actually of
1268   /// type dwarf::CallingConvention.
1269   uint8_t CC;
1270 
DISubroutineType(LLVMContext & C,StorageType Storage,DIFlags Flags,uint8_t CC,ArrayRef<Metadata * > Ops)1271   DISubroutineType(LLVMContext &C, StorageType Storage, DIFlags Flags,
1272                    uint8_t CC, ArrayRef<Metadata *> Ops)
1273       : DIType(C, DISubroutineTypeKind, Storage, dwarf::DW_TAG_subroutine_type,
1274                0, 0, 0, 0, Flags, Ops),
1275         CC(CC) {}
1276   ~DISubroutineType() = default;
1277 
1278   static DISubroutineType *getImpl(LLVMContext &Context, DIFlags Flags,
1279                                    uint8_t CC, DITypeRefArray TypeArray,
1280                                    StorageType Storage,
1281                                    bool ShouldCreate = true) {
1282     return getImpl(Context, Flags, CC, TypeArray.get(), Storage, ShouldCreate);
1283   }
1284   static DISubroutineType *getImpl(LLVMContext &Context, DIFlags Flags,
1285                                    uint8_t CC, Metadata *TypeArray,
1286                                    StorageType Storage,
1287                                    bool ShouldCreate = true);
1288 
cloneImpl()1289   TempDISubroutineType cloneImpl() const {
1290     return getTemporary(getContext(), getFlags(), getCC(), getTypeArray());
1291   }
1292 
1293 public:
1294   DEFINE_MDNODE_GET(DISubroutineType,
1295                     (DIFlags Flags, uint8_t CC, DITypeRefArray TypeArray),
1296                     (Flags, CC, TypeArray))
1297   DEFINE_MDNODE_GET(DISubroutineType,
1298                     (DIFlags Flags, uint8_t CC, Metadata *TypeArray),
1299                     (Flags, CC, TypeArray))
1300 
clone()1301   TempDISubroutineType clone() const { return cloneImpl(); }
1302 
getCC()1303   uint8_t getCC() const { return CC; }
1304 
getTypeArray()1305   DITypeRefArray getTypeArray() const {
1306     return cast_or_null<MDTuple>(getRawTypeArray());
1307   }
1308 
getRawTypeArray()1309   Metadata *getRawTypeArray() const { return getOperand(3); }
1310 
classof(const Metadata * MD)1311   static bool classof(const Metadata *MD) {
1312     return MD->getMetadataID() == DISubroutineTypeKind;
1313   }
1314 };
1315 
1316 /// Compile unit.
1317 class DICompileUnit : public DIScope {
1318   friend class LLVMContextImpl;
1319   friend class MDNode;
1320 
1321 public:
1322   enum DebugEmissionKind : unsigned {
1323     NoDebug = 0,
1324     FullDebug,
1325     LineTablesOnly,
1326     DebugDirectivesOnly,
1327     LastEmissionKind = DebugDirectivesOnly
1328   };
1329 
1330   enum class DebugNameTableKind : unsigned {
1331     Default = 0,
1332     GNU = 1,
1333     None = 2,
1334     LastDebugNameTableKind = None
1335   };
1336 
1337   static Optional<DebugEmissionKind> getEmissionKind(StringRef Str);
1338   static const char *emissionKindString(DebugEmissionKind EK);
1339   static Optional<DebugNameTableKind> getNameTableKind(StringRef Str);
1340   static const char *nameTableKindString(DebugNameTableKind PK);
1341 
1342 private:
1343   unsigned SourceLanguage;
1344   bool IsOptimized;
1345   unsigned RuntimeVersion;
1346   unsigned EmissionKind;
1347   uint64_t DWOId;
1348   bool SplitDebugInlining;
1349   bool DebugInfoForProfiling;
1350   unsigned NameTableKind;
1351   bool RangesBaseAddress;
1352 
DICompileUnit(LLVMContext & C,StorageType Storage,unsigned SourceLanguage,bool IsOptimized,unsigned RuntimeVersion,unsigned EmissionKind,uint64_t DWOId,bool SplitDebugInlining,bool DebugInfoForProfiling,unsigned NameTableKind,bool RangesBaseAddress,ArrayRef<Metadata * > Ops)1353   DICompileUnit(LLVMContext &C, StorageType Storage, unsigned SourceLanguage,
1354                 bool IsOptimized, unsigned RuntimeVersion,
1355                 unsigned EmissionKind, uint64_t DWOId, bool SplitDebugInlining,
1356                 bool DebugInfoForProfiling, unsigned NameTableKind,
1357                 bool RangesBaseAddress, ArrayRef<Metadata *> Ops)
1358       : DIScope(C, DICompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
1359         SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
1360         RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind),
1361         DWOId(DWOId), SplitDebugInlining(SplitDebugInlining),
1362         DebugInfoForProfiling(DebugInfoForProfiling),
1363         NameTableKind(NameTableKind), RangesBaseAddress(RangesBaseAddress) {
1364     assert(Storage != Uniqued);
1365   }
1366   ~DICompileUnit() = default;
1367 
1368   static DICompileUnit *
1369   getImpl(LLVMContext &Context, unsigned SourceLanguage, DIFile *File,
1370           StringRef Producer, bool IsOptimized, StringRef Flags,
1371           unsigned RuntimeVersion, StringRef SplitDebugFilename,
1372           unsigned EmissionKind, DICompositeTypeArray EnumTypes,
1373           DIScopeArray RetainedTypes,
1374           DIGlobalVariableExpressionArray GlobalVariables,
1375           DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
1376           uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
1377           unsigned NameTableKind, bool RangesBaseAddress, StringRef SysRoot,
1378           StringRef SDK, StorageType Storage, bool ShouldCreate = true) {
1379     return getImpl(
1380         Context, SourceLanguage, File, getCanonicalMDString(Context, Producer),
1381         IsOptimized, getCanonicalMDString(Context, Flags), RuntimeVersion,
1382         getCanonicalMDString(Context, SplitDebugFilename), EmissionKind,
1383         EnumTypes.get(), RetainedTypes.get(), GlobalVariables.get(),
1384         ImportedEntities.get(), Macros.get(), DWOId, SplitDebugInlining,
1385         DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
1386         getCanonicalMDString(Context, SysRoot),
1387         getCanonicalMDString(Context, SDK), Storage, ShouldCreate);
1388   }
1389   static DICompileUnit *
1390   getImpl(LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
1391           MDString *Producer, bool IsOptimized, MDString *Flags,
1392           unsigned RuntimeVersion, MDString *SplitDebugFilename,
1393           unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
1394           Metadata *GlobalVariables, Metadata *ImportedEntities,
1395           Metadata *Macros, uint64_t DWOId, bool SplitDebugInlining,
1396           bool DebugInfoForProfiling, unsigned NameTableKind,
1397           bool RangesBaseAddress, MDString *SysRoot, MDString *SDK,
1398           StorageType Storage, bool ShouldCreate = true);
1399 
cloneImpl()1400   TempDICompileUnit cloneImpl() const {
1401     return getTemporary(
1402         getContext(), getSourceLanguage(), getFile(), getProducer(),
1403         isOptimized(), getFlags(), getRuntimeVersion(), getSplitDebugFilename(),
1404         getEmissionKind(), getEnumTypes(), getRetainedTypes(),
1405         getGlobalVariables(), getImportedEntities(), getMacros(), DWOId,
1406         getSplitDebugInlining(), getDebugInfoForProfiling(), getNameTableKind(),
1407         getRangesBaseAddress(), getSysRoot(), getSDK());
1408   }
1409 
1410 public:
1411   static void get() = delete;
1412   static void getIfExists() = delete;
1413 
1414   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
1415       DICompileUnit,
1416       (unsigned SourceLanguage, DIFile *File, StringRef Producer,
1417        bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
1418        StringRef SplitDebugFilename, DebugEmissionKind EmissionKind,
1419        DICompositeTypeArray EnumTypes, DIScopeArray RetainedTypes,
1420        DIGlobalVariableExpressionArray GlobalVariables,
1421        DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
1422        uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
1423        DebugNameTableKind NameTableKind, bool RangesBaseAddress,
1424        StringRef SysRoot, StringRef SDK),
1425       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
1426        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
1427        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
1428        DebugInfoForProfiling, (unsigned)NameTableKind, RangesBaseAddress,
1429        SysRoot, SDK))
1430   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
1431       DICompileUnit,
1432       (unsigned SourceLanguage, Metadata *File, MDString *Producer,
1433        bool IsOptimized, MDString *Flags, unsigned RuntimeVersion,
1434        MDString *SplitDebugFilename, unsigned EmissionKind, Metadata *EnumTypes,
1435        Metadata *RetainedTypes, Metadata *GlobalVariables,
1436        Metadata *ImportedEntities, Metadata *Macros, uint64_t DWOId,
1437        bool SplitDebugInlining, bool DebugInfoForProfiling,
1438        unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
1439        MDString *SDK),
1440       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
1441        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
1442        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
1443        DebugInfoForProfiling, NameTableKind, RangesBaseAddress, SysRoot, SDK))
1444 
clone()1445   TempDICompileUnit clone() const { return cloneImpl(); }
1446 
getSourceLanguage()1447   unsigned getSourceLanguage() const { return SourceLanguage; }
isOptimized()1448   bool isOptimized() const { return IsOptimized; }
getRuntimeVersion()1449   unsigned getRuntimeVersion() const { return RuntimeVersion; }
getEmissionKind()1450   DebugEmissionKind getEmissionKind() const {
1451     return (DebugEmissionKind)EmissionKind;
1452   }
isDebugDirectivesOnly()1453   bool isDebugDirectivesOnly() const {
1454     return EmissionKind == DebugDirectivesOnly;
1455   }
getDebugInfoForProfiling()1456   bool getDebugInfoForProfiling() const { return DebugInfoForProfiling; }
getNameTableKind()1457   DebugNameTableKind getNameTableKind() const {
1458     return (DebugNameTableKind)NameTableKind;
1459   }
getRangesBaseAddress()1460   bool getRangesBaseAddress() const { return RangesBaseAddress; }
getProducer()1461   StringRef getProducer() const { return getStringOperand(1); }
getFlags()1462   StringRef getFlags() const { return getStringOperand(2); }
getSplitDebugFilename()1463   StringRef getSplitDebugFilename() const { return getStringOperand(3); }
getEnumTypes()1464   DICompositeTypeArray getEnumTypes() const {
1465     return cast_or_null<MDTuple>(getRawEnumTypes());
1466   }
getRetainedTypes()1467   DIScopeArray getRetainedTypes() const {
1468     return cast_or_null<MDTuple>(getRawRetainedTypes());
1469   }
getGlobalVariables()1470   DIGlobalVariableExpressionArray getGlobalVariables() const {
1471     return cast_or_null<MDTuple>(getRawGlobalVariables());
1472   }
getImportedEntities()1473   DIImportedEntityArray getImportedEntities() const {
1474     return cast_or_null<MDTuple>(getRawImportedEntities());
1475   }
getMacros()1476   DIMacroNodeArray getMacros() const {
1477     return cast_or_null<MDTuple>(getRawMacros());
1478   }
getDWOId()1479   uint64_t getDWOId() const { return DWOId; }
setDWOId(uint64_t DwoId)1480   void setDWOId(uint64_t DwoId) { DWOId = DwoId; }
getSplitDebugInlining()1481   bool getSplitDebugInlining() const { return SplitDebugInlining; }
setSplitDebugInlining(bool SplitDebugInlining)1482   void setSplitDebugInlining(bool SplitDebugInlining) {
1483     this->SplitDebugInlining = SplitDebugInlining;
1484   }
getSysRoot()1485   StringRef getSysRoot() const { return getStringOperand(9); }
getSDK()1486   StringRef getSDK() const { return getStringOperand(10); }
1487 
getRawProducer()1488   MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
getRawFlags()1489   MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
getRawSplitDebugFilename()1490   MDString *getRawSplitDebugFilename() const {
1491     return getOperandAs<MDString>(3);
1492   }
getRawEnumTypes()1493   Metadata *getRawEnumTypes() const { return getOperand(4); }
getRawRetainedTypes()1494   Metadata *getRawRetainedTypes() const { return getOperand(5); }
getRawGlobalVariables()1495   Metadata *getRawGlobalVariables() const { return getOperand(6); }
getRawImportedEntities()1496   Metadata *getRawImportedEntities() const { return getOperand(7); }
getRawMacros()1497   Metadata *getRawMacros() const { return getOperand(8); }
getRawSysRoot()1498   MDString *getRawSysRoot() const { return getOperandAs<MDString>(9); }
getRawSDK()1499   MDString *getRawSDK() const { return getOperandAs<MDString>(10); }
1500 
1501   /// Replace arrays.
1502   ///
1503   /// If this \a isUniqued() and not \a isResolved(), it will be RAUW'ed and
1504   /// deleted on a uniquing collision.  In practice, uniquing collisions on \a
1505   /// DICompileUnit should be fairly rare.
1506   /// @{
replaceEnumTypes(DICompositeTypeArray N)1507   void replaceEnumTypes(DICompositeTypeArray N) {
1508     replaceOperandWith(4, N.get());
1509   }
replaceRetainedTypes(DITypeArray N)1510   void replaceRetainedTypes(DITypeArray N) {
1511     replaceOperandWith(5, N.get());
1512   }
replaceGlobalVariables(DIGlobalVariableExpressionArray N)1513   void replaceGlobalVariables(DIGlobalVariableExpressionArray N) {
1514     replaceOperandWith(6, N.get());
1515   }
replaceImportedEntities(DIImportedEntityArray N)1516   void replaceImportedEntities(DIImportedEntityArray N) {
1517     replaceOperandWith(7, N.get());
1518   }
replaceMacros(DIMacroNodeArray N)1519   void replaceMacros(DIMacroNodeArray N) { replaceOperandWith(8, N.get()); }
1520   /// @}
1521 
classof(const Metadata * MD)1522   static bool classof(const Metadata *MD) {
1523     return MD->getMetadataID() == DICompileUnitKind;
1524   }
1525 };
1526 
1527 /// A scope for locals.
1528 ///
1529 /// A legal scope for lexical blocks, local variables, and debug info
1530 /// locations.  Subclasses are \a DISubprogram, \a DILexicalBlock, and \a
1531 /// DILexicalBlockFile.
1532 class DILocalScope : public DIScope {
1533 protected:
DILocalScope(LLVMContext & C,unsigned ID,StorageType Storage,unsigned Tag,ArrayRef<Metadata * > Ops)1534   DILocalScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1535                ArrayRef<Metadata *> Ops)
1536       : DIScope(C, ID, Storage, Tag, Ops) {}
1537   ~DILocalScope() = default;
1538 
1539 public:
1540   /// Get the subprogram for this scope.
1541   ///
1542   /// Return this if it's an \a DISubprogram; otherwise, look up the scope
1543   /// chain.
1544   DISubprogram *getSubprogram() const;
1545 
1546   /// Get the first non DILexicalBlockFile scope of this scope.
1547   ///
1548   /// Return this if it's not a \a DILexicalBlockFIle; otherwise, look up the
1549   /// scope chain.
1550   DILocalScope *getNonLexicalBlockFileScope() const;
1551 
classof(const Metadata * MD)1552   static bool classof(const Metadata *MD) {
1553     return MD->getMetadataID() == DISubprogramKind ||
1554            MD->getMetadataID() == DILexicalBlockKind ||
1555            MD->getMetadataID() == DILexicalBlockFileKind;
1556   }
1557 };
1558 
1559 /// Debug location.
1560 ///
1561 /// A debug location in source code, used for debug info and otherwise.
1562 class DILocation : public MDNode {
1563   friend class LLVMContextImpl;
1564   friend class MDNode;
1565 
1566   DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
1567              unsigned Column, ArrayRef<Metadata *> MDs, bool ImplicitCode);
~DILocation()1568   ~DILocation() { dropAllReferences(); }
1569 
1570   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
1571                              unsigned Column, Metadata *Scope,
1572                              Metadata *InlinedAt, bool ImplicitCode,
1573                              StorageType Storage, bool ShouldCreate = true);
1574   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
1575                              unsigned Column, DILocalScope *Scope,
1576                              DILocation *InlinedAt, bool ImplicitCode,
1577                              StorageType Storage, bool ShouldCreate = true) {
1578     return getImpl(Context, Line, Column, static_cast<Metadata *>(Scope),
1579                    static_cast<Metadata *>(InlinedAt), ImplicitCode, Storage,
1580                    ShouldCreate);
1581   }
1582 
cloneImpl()1583   TempDILocation cloneImpl() const {
1584     // Get the raw scope/inlinedAt since it is possible to invoke this on
1585     // a DILocation containing temporary metadata.
1586     return getTemporary(getContext(), getLine(), getColumn(), getRawScope(),
1587                         getRawInlinedAt(), isImplicitCode());
1588   }
1589 
1590 public:
1591   // Disallow replacing operands.
1592   void replaceOperandWith(unsigned I, Metadata *New) = delete;
1593 
1594   DEFINE_MDNODE_GET(DILocation,
1595                     (unsigned Line, unsigned Column, Metadata *Scope,
1596                      Metadata *InlinedAt = nullptr, bool ImplicitCode = false),
1597                     (Line, Column, Scope, InlinedAt, ImplicitCode))
1598   DEFINE_MDNODE_GET(DILocation,
1599                     (unsigned Line, unsigned Column, DILocalScope *Scope,
1600                      DILocation *InlinedAt = nullptr,
1601                      bool ImplicitCode = false),
1602                     (Line, Column, Scope, InlinedAt, ImplicitCode))
1603 
1604   /// Return a (temporary) clone of this.
clone()1605   TempDILocation clone() const { return cloneImpl(); }
1606 
getLine()1607   unsigned getLine() const { return SubclassData32; }
getColumn()1608   unsigned getColumn() const { return SubclassData16; }
getScope()1609   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
1610 
getInlinedAt()1611   DILocation *getInlinedAt() const {
1612     return cast_or_null<DILocation>(getRawInlinedAt());
1613   }
1614 
1615   /// Check if the location corresponds to an implicit code.
1616   /// When the ImplicitCode flag is true, it means that the Instruction
1617   /// with this DILocation has been added by the front-end but it hasn't been
1618   /// written explicitly by the user (e.g. cleanup stuff in C++ put on a closing
1619   /// bracket). It's useful for code coverage to not show a counter on "empty"
1620   /// lines.
isImplicitCode()1621   bool isImplicitCode() const { return SubclassData1; }
setImplicitCode(bool ImplicitCode)1622   void setImplicitCode(bool ImplicitCode) { SubclassData1 = ImplicitCode; }
1623 
getFile()1624   DIFile *getFile() const { return getScope()->getFile(); }
getFilename()1625   StringRef getFilename() const { return getScope()->getFilename(); }
getDirectory()1626   StringRef getDirectory() const { return getScope()->getDirectory(); }
getSource()1627   Optional<StringRef> getSource() const { return getScope()->getSource(); }
1628 
1629   /// Get the scope where this is inlined.
1630   ///
1631   /// Walk through \a getInlinedAt() and return \a getScope() from the deepest
1632   /// location.
getInlinedAtScope()1633   DILocalScope *getInlinedAtScope() const {
1634     if (auto *IA = getInlinedAt())
1635       return IA->getInlinedAtScope();
1636     return getScope();
1637   }
1638 
1639   /// Get the DWARF discriminator.
1640   ///
1641   /// DWARF discriminators distinguish identical file locations between
1642   /// instructions that are on different basic blocks.
1643   ///
1644   /// There are 3 components stored in discriminator, from lower bits:
1645   ///
1646   /// Base discriminator: assigned by AddDiscriminators pass to identify IRs
1647   ///                     that are defined by the same source line, but
1648   ///                     different basic blocks.
1649   /// Duplication factor: assigned by optimizations that will scale down
1650   ///                     the execution frequency of the original IR.
1651   /// Copy Identifier: assigned by optimizations that clones the IR.
1652   ///                  Each copy of the IR will be assigned an identifier.
1653   ///
1654   /// Encoding:
1655   ///
1656   /// The above 3 components are encoded into a 32bit unsigned integer in
1657   /// order. If the lowest bit is 1, the current component is empty, and the
1658   /// next component will start in the next bit. Otherwise, the current
1659   /// component is non-empty, and its content starts in the next bit. The
1660   /// value of each components is either 5 bit or 12 bit: if the 7th bit
1661   /// is 0, the bit 2~6 (5 bits) are used to represent the component; if the
1662   /// 7th bit is 1, the bit 2~6 (5 bits) and 8~14 (7 bits) are combined to
1663   /// represent the component. Thus, the number of bits used for a component
1664   /// is either 0 (if it and all the next components are empty); 1 - if it is
1665   /// empty; 7 - if its value is up to and including 0x1f (lsb and msb are both
1666   /// 0); or 14, if its value is up to and including 0x1ff. Note that the last
1667   /// component is also capped at 0x1ff, even in the case when both first
1668   /// components are 0, and we'd technically have 29 bits available.
1669   ///
1670   /// For precise control over the data being encoded in the discriminator,
1671   /// use encodeDiscriminator/decodeDiscriminator.
1672 
1673   inline unsigned getDiscriminator() const;
1674 
1675   // For the regular discriminator, it stands for all empty components if all
1676   // the lowest 3 bits are non-zero and all higher 29 bits are unused(zero by
1677   // default). Here we fully leverage the higher 29 bits for pseudo probe use.
1678   // This is the format:
1679   // [2:0] - 0x7
1680   // [31:3] - pseudo probe fields guaranteed to be non-zero as a whole
1681   // So if the lower 3 bits is non-zero and the others has at least one
1682   // non-zero bit, it guarantees to be a pseudo probe discriminator
isPseudoProbeDiscriminator(unsigned Discriminator)1683   inline static bool isPseudoProbeDiscriminator(unsigned Discriminator) {
1684     return ((Discriminator & 0x7) == 0x7) && (Discriminator & 0xFFFFFFF8);
1685   }
1686 
1687   /// Returns a new DILocation with updated \p Discriminator.
1688   inline const DILocation *cloneWithDiscriminator(unsigned Discriminator) const;
1689 
1690   /// Returns a new DILocation with updated base discriminator \p BD. Only the
1691   /// base discriminator is set in the new DILocation, the other encoded values
1692   /// are elided.
1693   /// If the discriminator cannot be encoded, the function returns None.
1694   inline Optional<const DILocation *> cloneWithBaseDiscriminator(unsigned BD) const;
1695 
1696   /// Returns the duplication factor stored in the discriminator, or 1 if no
1697   /// duplication factor (or 0) is encoded.
1698   inline unsigned getDuplicationFactor() const;
1699 
1700   /// Returns the copy identifier stored in the discriminator.
1701   inline unsigned getCopyIdentifier() const;
1702 
1703   /// Returns the base discriminator stored in the discriminator.
1704   inline unsigned getBaseDiscriminator() const;
1705 
1706   /// Returns a new DILocation with duplication factor \p DF * current
1707   /// duplication factor encoded in the discriminator. The current duplication
1708   /// factor is as defined by getDuplicationFactor().
1709   /// Returns None if encoding failed.
1710   inline Optional<const DILocation *> cloneByMultiplyingDuplicationFactor(unsigned DF) const;
1711 
1712   /// When two instructions are combined into a single instruction we also
1713   /// need to combine the original locations into a single location.
1714   ///
1715   /// When the locations are the same we can use either location. When they
1716   /// differ, we need a third location which is distinct from either. If they
1717   /// have the same file/line but have a different discriminator we could
1718   /// create a location with a new discriminator. If they are from different
1719   /// files/lines the location is ambiguous and can't be represented in a line
1720   /// entry. In this case, if \p GenerateLocation is true, we will set the
1721   /// merged debug location as line 0 of the nearest common scope where the two
1722   /// locations are inlined from.
1723   ///
1724   /// \p GenerateLocation: Whether the merged location can be generated when
1725   /// \p LocA and \p LocB differ.
1726   static const DILocation *getMergedLocation(const DILocation *LocA,
1727                                              const DILocation *LocB);
1728 
1729   /// Try to combine the vector of locations passed as input in a single one.
1730   /// This function applies getMergedLocation() repeatedly left-to-right.
1731   ///
1732   /// \p Locs: The locations to be merged.
1733   static
1734   const DILocation *getMergedLocations(ArrayRef<const DILocation *> Locs);
1735 
1736   /// Return the masked discriminator value for an input discrimnator value D
1737   /// (i.e. zero out the (B+1)-th and above bits for D (B is 0-base).
1738   // Example: an input of (0x1FF, 7) returns 0xFF.
getMaskedDiscriminator(unsigned D,unsigned B)1739   static unsigned getMaskedDiscriminator(unsigned D, unsigned B) {
1740     return (D & getN1Bits(B));
1741   }
1742 
1743   /// Return the bits used for base discriminators.
getBaseDiscriminatorBits()1744   static unsigned getBaseDiscriminatorBits() { return getBaseFSBitEnd(); }
1745 
1746   /// Returns the base discriminator for a given encoded discriminator \p D.
1747   static unsigned
1748   getBaseDiscriminatorFromDiscriminator(unsigned D,
1749                                         bool IsFSDiscriminator = false) {
1750     if (IsFSDiscriminator)
1751       return getMaskedDiscriminator(D, getBaseDiscriminatorBits());
1752     return getUnsignedFromPrefixEncoding(D);
1753   }
1754 
1755   /// Raw encoding of the discriminator. APIs such as cloneWithDuplicationFactor
1756   /// have certain special case behavior (e.g. treating empty duplication factor
1757   /// as the value '1').
1758   /// This API, in conjunction with cloneWithDiscriminator, may be used to encode
1759   /// the raw values provided. \p BD: base discriminator \p DF: duplication factor
1760   /// \p CI: copy index
1761   /// The return is None if the values cannot be encoded in 32 bits - for
1762   /// example, values for BD or DF larger than 12 bits. Otherwise, the return
1763   /// is the encoded value.
1764   static Optional<unsigned> encodeDiscriminator(unsigned BD, unsigned DF, unsigned CI);
1765 
1766   /// Raw decoder for values in an encoded discriminator D.
1767   static void decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
1768                                   unsigned &CI);
1769 
1770   /// Returns the duplication factor for a given encoded discriminator \p D, or
1771   /// 1 if no value or 0 is encoded.
getDuplicationFactorFromDiscriminator(unsigned D)1772   static unsigned getDuplicationFactorFromDiscriminator(unsigned D) {
1773     if (EnableFSDiscriminator)
1774       return 1;
1775     D = getNextComponentInDiscriminator(D);
1776     unsigned Ret = getUnsignedFromPrefixEncoding(D);
1777     if (Ret == 0)
1778       return 1;
1779     return Ret;
1780   }
1781 
1782   /// Returns the copy identifier for a given encoded discriminator \p D.
getCopyIdentifierFromDiscriminator(unsigned D)1783   static unsigned getCopyIdentifierFromDiscriminator(unsigned D) {
1784     return getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(
1785         getNextComponentInDiscriminator(D)));
1786   }
1787 
1788 
getRawScope()1789   Metadata *getRawScope() const { return getOperand(0); }
getRawInlinedAt()1790   Metadata *getRawInlinedAt() const {
1791     if (getNumOperands() == 2)
1792       return getOperand(1);
1793     return nullptr;
1794   }
1795 
classof(const Metadata * MD)1796   static bool classof(const Metadata *MD) {
1797     return MD->getMetadataID() == DILocationKind;
1798   }
1799 };
1800 
1801 /// Subprogram description.
1802 class DISubprogram : public DILocalScope {
1803   friend class LLVMContextImpl;
1804   friend class MDNode;
1805 
1806   unsigned Line;
1807   unsigned ScopeLine;
1808   unsigned VirtualIndex;
1809 
1810   /// In the MS ABI, the implicit 'this' parameter is adjusted in the prologue
1811   /// of method overrides from secondary bases by this amount. It may be
1812   /// negative.
1813   int ThisAdjustment;
1814 
1815 public:
1816   /// Debug info subprogram flags.
1817   enum DISPFlags : uint32_t {
1818 #define HANDLE_DISP_FLAG(ID, NAME) SPFlag##NAME = ID,
1819 #define DISP_FLAG_LARGEST_NEEDED
1820 #include "llvm/IR/DebugInfoFlags.def"
1821     SPFlagNonvirtual = SPFlagZero,
1822     SPFlagVirtuality = SPFlagVirtual | SPFlagPureVirtual,
1823     LLVM_MARK_AS_BITMASK_ENUM(SPFlagLargest)
1824   };
1825 
1826   static DISPFlags getFlag(StringRef Flag);
1827   static StringRef getFlagString(DISPFlags Flag);
1828 
1829   /// Split up a flags bitfield for easier printing.
1830   ///
1831   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
1832   /// any remaining (unrecognized) bits.
1833   static DISPFlags splitFlags(DISPFlags Flags,
1834                               SmallVectorImpl<DISPFlags> &SplitFlags);
1835 
1836   // Helper for converting old bitfields to new flags word.
1837   static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition,
1838                              bool IsOptimized,
1839                              unsigned Virtuality = SPFlagNonvirtual,
1840                              bool IsMainSubprogram = false) {
1841     // We're assuming virtuality is the low-order field.
1842     static_assert(
1843         int(SPFlagVirtual) == int(dwarf::DW_VIRTUALITY_virtual) &&
1844             int(SPFlagPureVirtual) == int(dwarf::DW_VIRTUALITY_pure_virtual),
1845         "Virtuality constant mismatch");
1846     return static_cast<DISPFlags>(
1847         (Virtuality & SPFlagVirtuality) |
1848         (IsLocalToUnit ? SPFlagLocalToUnit : SPFlagZero) |
1849         (IsDefinition ? SPFlagDefinition : SPFlagZero) |
1850         (IsOptimized ? SPFlagOptimized : SPFlagZero) |
1851         (IsMainSubprogram ? SPFlagMainSubprogram : SPFlagZero));
1852   }
1853 
1854 private:
1855   DIFlags Flags;
1856   DISPFlags SPFlags;
1857 
DISubprogram(LLVMContext & C,StorageType Storage,unsigned Line,unsigned ScopeLine,unsigned VirtualIndex,int ThisAdjustment,DIFlags Flags,DISPFlags SPFlags,ArrayRef<Metadata * > Ops)1858   DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
1859                unsigned ScopeLine, unsigned VirtualIndex, int ThisAdjustment,
1860                DIFlags Flags, DISPFlags SPFlags, ArrayRef<Metadata *> Ops)
1861       : DILocalScope(C, DISubprogramKind, Storage, dwarf::DW_TAG_subprogram,
1862                      Ops),
1863         Line(Line), ScopeLine(ScopeLine), VirtualIndex(VirtualIndex),
1864         ThisAdjustment(ThisAdjustment), Flags(Flags), SPFlags(SPFlags) {
1865     static_assert(dwarf::DW_VIRTUALITY_max < 4, "Virtuality out of range");
1866   }
1867   ~DISubprogram() = default;
1868 
1869   static DISubprogram *
1870   getImpl(LLVMContext &Context, DIScope *Scope, StringRef Name,
1871           StringRef LinkageName, DIFile *File, unsigned Line,
1872           DISubroutineType *Type, unsigned ScopeLine, DIType *ContainingType,
1873           unsigned VirtualIndex, int ThisAdjustment, DIFlags Flags,
1874           DISPFlags SPFlags, DICompileUnit *Unit,
1875           DITemplateParameterArray TemplateParams, DISubprogram *Declaration,
1876           DINodeArray RetainedNodes, DITypeArray ThrownTypes,
1877           StorageType Storage, bool ShouldCreate = true) {
1878     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1879                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1880                    ScopeLine, ContainingType, VirtualIndex, ThisAdjustment,
1881                    Flags, SPFlags, Unit, TemplateParams.get(), Declaration,
1882                    RetainedNodes.get(), ThrownTypes.get(), Storage,
1883                    ShouldCreate);
1884   }
1885   static DISubprogram *getImpl(LLVMContext &Context, Metadata *Scope,
1886                                MDString *Name, MDString *LinkageName,
1887                                Metadata *File, unsigned Line, Metadata *Type,
1888                                unsigned ScopeLine, Metadata *ContainingType,
1889                                unsigned VirtualIndex, int ThisAdjustment,
1890                                DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
1891                                Metadata *TemplateParams, Metadata *Declaration,
1892                                Metadata *RetainedNodes, Metadata *ThrownTypes,
1893                                StorageType Storage, bool ShouldCreate = true);
1894 
cloneImpl()1895   TempDISubprogram cloneImpl() const {
1896     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1897                         getFile(), getLine(), getType(), getScopeLine(),
1898                         getContainingType(), getVirtualIndex(),
1899                         getThisAdjustment(), getFlags(), getSPFlags(),
1900                         getUnit(), getTemplateParams(), getDeclaration(),
1901                         getRetainedNodes(), getThrownTypes());
1902   }
1903 
1904 public:
1905   DEFINE_MDNODE_GET(
1906       DISubprogram,
1907       (DIScope * Scope, StringRef Name, StringRef LinkageName, DIFile *File,
1908        unsigned Line, DISubroutineType *Type, unsigned ScopeLine,
1909        DIType *ContainingType, unsigned VirtualIndex, int ThisAdjustment,
1910        DIFlags Flags, DISPFlags SPFlags, DICompileUnit *Unit,
1911        DITemplateParameterArray TemplateParams = nullptr,
1912        DISubprogram *Declaration = nullptr, DINodeArray RetainedNodes = nullptr,
1913        DITypeArray ThrownTypes = nullptr),
1914       (Scope, Name, LinkageName, File, Line, Type, ScopeLine, ContainingType,
1915        VirtualIndex, ThisAdjustment, Flags, SPFlags, Unit, TemplateParams,
1916        Declaration, RetainedNodes, ThrownTypes))
1917 
1918   DEFINE_MDNODE_GET(
1919       DISubprogram,
1920       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
1921        unsigned Line, Metadata *Type, unsigned ScopeLine,
1922        Metadata *ContainingType, unsigned VirtualIndex, int ThisAdjustment,
1923        DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
1924        Metadata *TemplateParams = nullptr, Metadata *Declaration = nullptr,
1925        Metadata *RetainedNodes = nullptr, Metadata *ThrownTypes = nullptr),
1926       (Scope, Name, LinkageName, File, Line, Type, ScopeLine, ContainingType,
1927        VirtualIndex, ThisAdjustment, Flags, SPFlags, Unit, TemplateParams,
1928        Declaration, RetainedNodes, ThrownTypes))
1929 
clone()1930   TempDISubprogram clone() const { return cloneImpl(); }
1931 
1932   /// Returns a new temporary DISubprogram with updated Flags
cloneWithFlags(DIFlags NewFlags)1933   TempDISubprogram cloneWithFlags(DIFlags NewFlags) const {
1934     auto NewSP = clone();
1935     NewSP->Flags = NewFlags;
1936     return NewSP;
1937   }
1938 
1939 public:
getLine()1940   unsigned getLine() const { return Line; }
getVirtuality()1941   unsigned getVirtuality() const { return getSPFlags() & SPFlagVirtuality; }
getVirtualIndex()1942   unsigned getVirtualIndex() const { return VirtualIndex; }
getThisAdjustment()1943   int getThisAdjustment() const { return ThisAdjustment; }
getScopeLine()1944   unsigned getScopeLine() const { return ScopeLine; }
setScopeLine(unsigned L)1945   void setScopeLine(unsigned L) { assert(isDistinct()); ScopeLine = L; }
getFlags()1946   DIFlags getFlags() const { return Flags; }
getSPFlags()1947   DISPFlags getSPFlags() const { return SPFlags; }
isLocalToUnit()1948   bool isLocalToUnit() const { return getSPFlags() & SPFlagLocalToUnit; }
isDefinition()1949   bool isDefinition() const { return getSPFlags() & SPFlagDefinition; }
isOptimized()1950   bool isOptimized() const { return getSPFlags() & SPFlagOptimized; }
isMainSubprogram()1951   bool isMainSubprogram() const { return getSPFlags() & SPFlagMainSubprogram; }
1952 
isArtificial()1953   bool isArtificial() const { return getFlags() & FlagArtificial; }
isPrivate()1954   bool isPrivate() const {
1955     return (getFlags() & FlagAccessibility) == FlagPrivate;
1956   }
isProtected()1957   bool isProtected() const {
1958     return (getFlags() & FlagAccessibility) == FlagProtected;
1959   }
isPublic()1960   bool isPublic() const {
1961     return (getFlags() & FlagAccessibility) == FlagPublic;
1962   }
isExplicit()1963   bool isExplicit() const { return getFlags() & FlagExplicit; }
isPrototyped()1964   bool isPrototyped() const { return getFlags() & FlagPrototyped; }
areAllCallsDescribed()1965   bool areAllCallsDescribed() const {
1966     return getFlags() & FlagAllCallsDescribed;
1967   }
isPure()1968   bool isPure() const { return getSPFlags() & SPFlagPure; }
isElemental()1969   bool isElemental() const { return getSPFlags() & SPFlagElemental; }
isRecursive()1970   bool isRecursive() const { return getSPFlags() & SPFlagRecursive; }
isObjCDirect()1971   bool isObjCDirect() const { return getSPFlags() & SPFlagObjCDirect; }
1972 
1973   /// Check if this is deleted member function.
1974   ///
1975   /// Return true if this subprogram is a C++11 special
1976   /// member function declared deleted.
isDeleted()1977   bool isDeleted() const { return getSPFlags() & SPFlagDeleted; }
1978 
1979   /// Check if this is reference-qualified.
1980   ///
1981   /// Return true if this subprogram is a C++11 reference-qualified non-static
1982   /// member function (void foo() &).
isLValueReference()1983   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
1984 
1985   /// Check if this is rvalue-reference-qualified.
1986   ///
1987   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
1988   /// non-static member function (void foo() &&).
isRValueReference()1989   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
1990 
1991   /// Check if this is marked as noreturn.
1992   ///
1993   /// Return true if this subprogram is C++11 noreturn or C11 _Noreturn
isNoReturn()1994   bool isNoReturn() const { return getFlags() & FlagNoReturn; }
1995 
1996   // Check if this routine is a compiler-generated thunk.
1997   //
1998   // Returns true if this subprogram is a thunk generated by the compiler.
isThunk()1999   bool isThunk() const { return getFlags() & FlagThunk; }
2000 
getScope()2001   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
2002 
getName()2003   StringRef getName() const { return getStringOperand(2); }
getLinkageName()2004   StringRef getLinkageName() const { return getStringOperand(3); }
2005   /// Only used by clients of CloneFunction, and only right after the cloning.
replaceLinkageName(MDString * LN)2006   void replaceLinkageName(MDString *LN) { replaceOperandWith(3, LN); }
2007 
getType()2008   DISubroutineType *getType() const {
2009     return cast_or_null<DISubroutineType>(getRawType());
2010   }
getContainingType()2011   DIType *getContainingType() const {
2012     return cast_or_null<DIType>(getRawContainingType());
2013   }
2014 
getUnit()2015   DICompileUnit *getUnit() const {
2016     return cast_or_null<DICompileUnit>(getRawUnit());
2017   }
replaceUnit(DICompileUnit * CU)2018   void replaceUnit(DICompileUnit *CU) { replaceOperandWith(5, CU); }
getTemplateParams()2019   DITemplateParameterArray getTemplateParams() const {
2020     return cast_or_null<MDTuple>(getRawTemplateParams());
2021   }
getDeclaration()2022   DISubprogram *getDeclaration() const {
2023     return cast_or_null<DISubprogram>(getRawDeclaration());
2024   }
getRetainedNodes()2025   DINodeArray getRetainedNodes() const {
2026     return cast_or_null<MDTuple>(getRawRetainedNodes());
2027   }
getThrownTypes()2028   DITypeArray getThrownTypes() const {
2029     return cast_or_null<MDTuple>(getRawThrownTypes());
2030   }
2031 
getRawScope()2032   Metadata *getRawScope() const { return getOperand(1); }
getRawName()2033   MDString *getRawName() const { return getOperandAs<MDString>(2); }
getRawLinkageName()2034   MDString *getRawLinkageName() const { return getOperandAs<MDString>(3); }
getRawType()2035   Metadata *getRawType() const { return getOperand(4); }
getRawUnit()2036   Metadata *getRawUnit() const { return getOperand(5); }
getRawDeclaration()2037   Metadata *getRawDeclaration() const { return getOperand(6); }
getRawRetainedNodes()2038   Metadata *getRawRetainedNodes() const { return getOperand(7); }
getRawContainingType()2039   Metadata *getRawContainingType() const {
2040     return getNumOperands() > 8 ? getOperandAs<Metadata>(8) : nullptr;
2041   }
getRawTemplateParams()2042   Metadata *getRawTemplateParams() const {
2043     return getNumOperands() > 9 ? getOperandAs<Metadata>(9) : nullptr;
2044   }
getRawThrownTypes()2045   Metadata *getRawThrownTypes() const {
2046     return getNumOperands() > 10 ? getOperandAs<Metadata>(10) : nullptr;
2047   }
2048 
replaceRawLinkageName(MDString * LinkageName)2049   void replaceRawLinkageName(MDString *LinkageName) {
2050     replaceOperandWith(3, LinkageName);
2051   }
2052 
2053   /// Check if this subprogram describes the given function.
2054   ///
2055   /// FIXME: Should this be looking through bitcasts?
2056   bool describes(const Function *F) const;
2057 
classof(const Metadata * MD)2058   static bool classof(const Metadata *MD) {
2059     return MD->getMetadataID() == DISubprogramKind;
2060   }
2061 };
2062 
2063 class DILexicalBlockBase : public DILocalScope {
2064 protected:
DILexicalBlockBase(LLVMContext & C,unsigned ID,StorageType Storage,ArrayRef<Metadata * > Ops)2065   DILexicalBlockBase(LLVMContext &C, unsigned ID, StorageType Storage,
2066                      ArrayRef<Metadata *> Ops)
2067       : DILocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
2068   ~DILexicalBlockBase() = default;
2069 
2070 public:
getScope()2071   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
2072 
getRawScope()2073   Metadata *getRawScope() const { return getOperand(1); }
2074 
classof(const Metadata * MD)2075   static bool classof(const Metadata *MD) {
2076     return MD->getMetadataID() == DILexicalBlockKind ||
2077            MD->getMetadataID() == DILexicalBlockFileKind;
2078   }
2079 };
2080 
2081 class DILexicalBlock : public DILexicalBlockBase {
2082   friend class LLVMContextImpl;
2083   friend class MDNode;
2084 
2085   unsigned Line;
2086   uint16_t Column;
2087 
DILexicalBlock(LLVMContext & C,StorageType Storage,unsigned Line,unsigned Column,ArrayRef<Metadata * > Ops)2088   DILexicalBlock(LLVMContext &C, StorageType Storage, unsigned Line,
2089                  unsigned Column, ArrayRef<Metadata *> Ops)
2090       : DILexicalBlockBase(C, DILexicalBlockKind, Storage, Ops), Line(Line),
2091         Column(Column) {
2092     assert(Column < (1u << 16) && "Expected 16-bit column");
2093   }
2094   ~DILexicalBlock() = default;
2095 
2096   static DILexicalBlock *getImpl(LLVMContext &Context, DILocalScope *Scope,
2097                                  DIFile *File, unsigned Line, unsigned Column,
2098                                  StorageType Storage,
2099                                  bool ShouldCreate = true) {
2100     return getImpl(Context, static_cast<Metadata *>(Scope),
2101                    static_cast<Metadata *>(File), Line, Column, Storage,
2102                    ShouldCreate);
2103   }
2104 
2105   static DILexicalBlock *getImpl(LLVMContext &Context, Metadata *Scope,
2106                                  Metadata *File, unsigned Line, unsigned Column,
2107                                  StorageType Storage, bool ShouldCreate = true);
2108 
cloneImpl()2109   TempDILexicalBlock cloneImpl() const {
2110     return getTemporary(getContext(), getScope(), getFile(), getLine(),
2111                         getColumn());
2112   }
2113 
2114 public:
2115   DEFINE_MDNODE_GET(DILexicalBlock, (DILocalScope * Scope, DIFile *File,
2116                                      unsigned Line, unsigned Column),
2117                     (Scope, File, Line, Column))
2118   DEFINE_MDNODE_GET(DILexicalBlock, (Metadata * Scope, Metadata *File,
2119                                      unsigned Line, unsigned Column),
2120                     (Scope, File, Line, Column))
2121 
clone()2122   TempDILexicalBlock clone() const { return cloneImpl(); }
2123 
getLine()2124   unsigned getLine() const { return Line; }
getColumn()2125   unsigned getColumn() const { return Column; }
2126 
classof(const Metadata * MD)2127   static bool classof(const Metadata *MD) {
2128     return MD->getMetadataID() == DILexicalBlockKind;
2129   }
2130 };
2131 
2132 class DILexicalBlockFile : public DILexicalBlockBase {
2133   friend class LLVMContextImpl;
2134   friend class MDNode;
2135 
2136   unsigned Discriminator;
2137 
DILexicalBlockFile(LLVMContext & C,StorageType Storage,unsigned Discriminator,ArrayRef<Metadata * > Ops)2138   DILexicalBlockFile(LLVMContext &C, StorageType Storage,
2139                      unsigned Discriminator, ArrayRef<Metadata *> Ops)
2140       : DILexicalBlockBase(C, DILexicalBlockFileKind, Storage, Ops),
2141         Discriminator(Discriminator) {}
2142   ~DILexicalBlockFile() = default;
2143 
2144   static DILexicalBlockFile *getImpl(LLVMContext &Context, DILocalScope *Scope,
2145                                      DIFile *File, unsigned Discriminator,
2146                                      StorageType Storage,
2147                                      bool ShouldCreate = true) {
2148     return getImpl(Context, static_cast<Metadata *>(Scope),
2149                    static_cast<Metadata *>(File), Discriminator, Storage,
2150                    ShouldCreate);
2151   }
2152 
2153   static DILexicalBlockFile *getImpl(LLVMContext &Context, Metadata *Scope,
2154                                      Metadata *File, unsigned Discriminator,
2155                                      StorageType Storage,
2156                                      bool ShouldCreate = true);
2157 
cloneImpl()2158   TempDILexicalBlockFile cloneImpl() const {
2159     return getTemporary(getContext(), getScope(), getFile(),
2160                         getDiscriminator());
2161   }
2162 
2163 public:
2164   DEFINE_MDNODE_GET(DILexicalBlockFile, (DILocalScope * Scope, DIFile *File,
2165                                          unsigned Discriminator),
2166                     (Scope, File, Discriminator))
2167   DEFINE_MDNODE_GET(DILexicalBlockFile,
2168                     (Metadata * Scope, Metadata *File, unsigned Discriminator),
2169                     (Scope, File, Discriminator))
2170 
clone()2171   TempDILexicalBlockFile clone() const { return cloneImpl(); }
getDiscriminator()2172   unsigned getDiscriminator() const { return Discriminator; }
2173 
classof(const Metadata * MD)2174   static bool classof(const Metadata *MD) {
2175     return MD->getMetadataID() == DILexicalBlockFileKind;
2176   }
2177 };
2178 
getDiscriminator()2179 unsigned DILocation::getDiscriminator() const {
2180   if (auto *F = dyn_cast<DILexicalBlockFile>(getScope()))
2181     return F->getDiscriminator();
2182   return 0;
2183 }
2184 
2185 const DILocation *
cloneWithDiscriminator(unsigned Discriminator)2186 DILocation::cloneWithDiscriminator(unsigned Discriminator) const {
2187   DIScope *Scope = getScope();
2188   // Skip all parent DILexicalBlockFile that already have a discriminator
2189   // assigned. We do not want to have nested DILexicalBlockFiles that have
2190   // mutliple discriminators because only the leaf DILexicalBlockFile's
2191   // dominator will be used.
2192   for (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope);
2193        LBF && LBF->getDiscriminator() != 0;
2194        LBF = dyn_cast<DILexicalBlockFile>(Scope))
2195     Scope = LBF->getScope();
2196   DILexicalBlockFile *NewScope =
2197       DILexicalBlockFile::get(getContext(), Scope, getFile(), Discriminator);
2198   return DILocation::get(getContext(), getLine(), getColumn(), NewScope,
2199                          getInlinedAt());
2200 }
2201 
getBaseDiscriminator()2202 unsigned DILocation::getBaseDiscriminator() const {
2203   return getBaseDiscriminatorFromDiscriminator(getDiscriminator(),
2204                                                EnableFSDiscriminator);
2205 }
2206 
getDuplicationFactor()2207 unsigned DILocation::getDuplicationFactor() const {
2208   return getDuplicationFactorFromDiscriminator(getDiscriminator());
2209 }
2210 
getCopyIdentifier()2211 unsigned DILocation::getCopyIdentifier() const {
2212   return getCopyIdentifierFromDiscriminator(getDiscriminator());
2213 }
2214 
cloneWithBaseDiscriminator(unsigned D)2215 Optional<const DILocation *> DILocation::cloneWithBaseDiscriminator(unsigned D) const {
2216   unsigned BD, DF, CI;
2217 
2218   if (EnableFSDiscriminator) {
2219     BD = getBaseDiscriminator();
2220     if (D == BD)
2221       return this;
2222     return cloneWithDiscriminator(D);
2223   }
2224 
2225   decodeDiscriminator(getDiscriminator(), BD, DF, CI);
2226   if (D == BD)
2227     return this;
2228   if (Optional<unsigned> Encoded = encodeDiscriminator(D, DF, CI))
2229     return cloneWithDiscriminator(*Encoded);
2230   return None;
2231 }
2232 
cloneByMultiplyingDuplicationFactor(unsigned DF)2233 Optional<const DILocation *> DILocation::cloneByMultiplyingDuplicationFactor(unsigned DF) const {
2234   assert(!EnableFSDiscriminator && "FSDiscriminator should not call this.");
2235 
2236   DF *= getDuplicationFactor();
2237   if (DF <= 1)
2238     return this;
2239 
2240   unsigned BD = getBaseDiscriminator();
2241   unsigned CI = getCopyIdentifier();
2242   if (Optional<unsigned> D = encodeDiscriminator(BD, DF, CI))
2243     return cloneWithDiscriminator(*D);
2244   return None;
2245 }
2246 
2247 class DINamespace : public DIScope {
2248   friend class LLVMContextImpl;
2249   friend class MDNode;
2250 
2251   unsigned ExportSymbols : 1;
2252 
DINamespace(LLVMContext & Context,StorageType Storage,bool ExportSymbols,ArrayRef<Metadata * > Ops)2253   DINamespace(LLVMContext &Context, StorageType Storage, bool ExportSymbols,
2254               ArrayRef<Metadata *> Ops)
2255       : DIScope(Context, DINamespaceKind, Storage, dwarf::DW_TAG_namespace,
2256                 Ops),
2257         ExportSymbols(ExportSymbols) {}
2258   ~DINamespace() = default;
2259 
2260   static DINamespace *getImpl(LLVMContext &Context, DIScope *Scope,
2261                               StringRef Name, bool ExportSymbols,
2262                               StorageType Storage, bool ShouldCreate = true) {
2263     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
2264                    ExportSymbols, Storage, ShouldCreate);
2265   }
2266   static DINamespace *getImpl(LLVMContext &Context, Metadata *Scope,
2267                               MDString *Name, bool ExportSymbols,
2268                               StorageType Storage, bool ShouldCreate = true);
2269 
cloneImpl()2270   TempDINamespace cloneImpl() const {
2271     return getTemporary(getContext(), getScope(), getName(),
2272                         getExportSymbols());
2273   }
2274 
2275 public:
2276   DEFINE_MDNODE_GET(DINamespace,
2277                     (DIScope *Scope, StringRef Name, bool ExportSymbols),
2278                     (Scope, Name, ExportSymbols))
2279   DEFINE_MDNODE_GET(DINamespace,
2280                     (Metadata *Scope, MDString *Name, bool ExportSymbols),
2281                     (Scope, Name, ExportSymbols))
2282 
clone()2283   TempDINamespace clone() const { return cloneImpl(); }
2284 
getExportSymbols()2285   bool getExportSymbols() const { return ExportSymbols; }
getScope()2286   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
getName()2287   StringRef getName() const { return getStringOperand(2); }
2288 
getRawScope()2289   Metadata *getRawScope() const { return getOperand(1); }
getRawName()2290   MDString *getRawName() const { return getOperandAs<MDString>(2); }
2291 
classof(const Metadata * MD)2292   static bool classof(const Metadata *MD) {
2293     return MD->getMetadataID() == DINamespaceKind;
2294   }
2295 };
2296 
2297 /// Represents a module in the programming language, for example, a Clang
2298 /// module, or a Fortran module.
2299 class DIModule : public DIScope {
2300   friend class LLVMContextImpl;
2301   friend class MDNode;
2302   unsigned LineNo;
2303   bool IsDecl;
2304 
DIModule(LLVMContext & Context,StorageType Storage,unsigned LineNo,bool IsDecl,ArrayRef<Metadata * > Ops)2305   DIModule(LLVMContext &Context, StorageType Storage, unsigned LineNo,
2306            bool IsDecl, ArrayRef<Metadata *> Ops)
2307       : DIScope(Context, DIModuleKind, Storage, dwarf::DW_TAG_module, Ops),
2308         LineNo(LineNo), IsDecl(IsDecl) {}
2309   ~DIModule() = default;
2310 
2311   static DIModule *getImpl(LLVMContext &Context, DIFile *File, DIScope *Scope,
2312                            StringRef Name, StringRef ConfigurationMacros,
2313                            StringRef IncludePath, StringRef APINotesFile,
2314                            unsigned LineNo, bool IsDecl, StorageType Storage,
2315                            bool ShouldCreate = true) {
2316     return getImpl(Context, File, Scope, getCanonicalMDString(Context, Name),
2317                    getCanonicalMDString(Context, ConfigurationMacros),
2318                    getCanonicalMDString(Context, IncludePath),
2319                    getCanonicalMDString(Context, APINotesFile), LineNo, IsDecl,
2320                    Storage, ShouldCreate);
2321   }
2322   static DIModule *getImpl(LLVMContext &Context, Metadata *File,
2323                            Metadata *Scope, MDString *Name,
2324                            MDString *ConfigurationMacros, MDString *IncludePath,
2325                            MDString *APINotesFile, unsigned LineNo, bool IsDecl,
2326                            StorageType Storage, bool ShouldCreate = true);
2327 
cloneImpl()2328   TempDIModule cloneImpl() const {
2329     return getTemporary(getContext(), getFile(), getScope(), getName(),
2330                         getConfigurationMacros(), getIncludePath(),
2331                         getAPINotesFile(), getLineNo(), getIsDecl());
2332   }
2333 
2334 public:
2335   DEFINE_MDNODE_GET(DIModule,
2336                     (DIFile * File, DIScope *Scope, StringRef Name,
2337                      StringRef ConfigurationMacros, StringRef IncludePath,
2338                      StringRef APINotesFile, unsigned LineNo,
2339                      bool IsDecl = false),
2340                     (File, Scope, Name, ConfigurationMacros, IncludePath,
2341                      APINotesFile, LineNo, IsDecl))
2342   DEFINE_MDNODE_GET(DIModule,
2343                     (Metadata * File, Metadata *Scope, MDString *Name,
2344                      MDString *ConfigurationMacros, MDString *IncludePath,
2345                      MDString *APINotesFile, unsigned LineNo,
2346                      bool IsDecl = false),
2347                     (File, Scope, Name, ConfigurationMacros, IncludePath,
2348                      APINotesFile, LineNo, IsDecl))
2349 
clone()2350   TempDIModule clone() const { return cloneImpl(); }
2351 
getScope()2352   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
getName()2353   StringRef getName() const { return getStringOperand(2); }
getConfigurationMacros()2354   StringRef getConfigurationMacros() const { return getStringOperand(3); }
getIncludePath()2355   StringRef getIncludePath() const { return getStringOperand(4); }
getAPINotesFile()2356   StringRef getAPINotesFile() const { return getStringOperand(5); }
getLineNo()2357   unsigned getLineNo() const { return LineNo; }
getIsDecl()2358   bool getIsDecl() const { return IsDecl; }
2359 
getRawScope()2360   Metadata *getRawScope() const { return getOperand(1); }
getRawName()2361   MDString *getRawName() const { return getOperandAs<MDString>(2); }
getRawConfigurationMacros()2362   MDString *getRawConfigurationMacros() const {
2363     return getOperandAs<MDString>(3);
2364   }
getRawIncludePath()2365   MDString *getRawIncludePath() const { return getOperandAs<MDString>(4); }
getRawAPINotesFile()2366   MDString *getRawAPINotesFile() const { return getOperandAs<MDString>(5); }
2367 
classof(const Metadata * MD)2368   static bool classof(const Metadata *MD) {
2369     return MD->getMetadataID() == DIModuleKind;
2370   }
2371 };
2372 
2373 /// Base class for template parameters.
2374 class DITemplateParameter : public DINode {
2375 protected:
2376   bool IsDefault;
2377 
DITemplateParameter(LLVMContext & Context,unsigned ID,StorageType Storage,unsigned Tag,bool IsDefault,ArrayRef<Metadata * > Ops)2378   DITemplateParameter(LLVMContext &Context, unsigned ID, StorageType Storage,
2379                       unsigned Tag, bool IsDefault, ArrayRef<Metadata *> Ops)
2380       : DINode(Context, ID, Storage, Tag, Ops), IsDefault(IsDefault) {}
2381   ~DITemplateParameter() = default;
2382 
2383 public:
getName()2384   StringRef getName() const { return getStringOperand(0); }
getType()2385   DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
2386 
getRawName()2387   MDString *getRawName() const { return getOperandAs<MDString>(0); }
getRawType()2388   Metadata *getRawType() const { return getOperand(1); }
isDefault()2389   bool isDefault() const { return IsDefault; }
2390 
classof(const Metadata * MD)2391   static bool classof(const Metadata *MD) {
2392     return MD->getMetadataID() == DITemplateTypeParameterKind ||
2393            MD->getMetadataID() == DITemplateValueParameterKind;
2394   }
2395 };
2396 
2397 class DITemplateTypeParameter : public DITemplateParameter {
2398   friend class LLVMContextImpl;
2399   friend class MDNode;
2400 
DITemplateTypeParameter(LLVMContext & Context,StorageType Storage,bool IsDefault,ArrayRef<Metadata * > Ops)2401   DITemplateTypeParameter(LLVMContext &Context, StorageType Storage,
2402                           bool IsDefault, ArrayRef<Metadata *> Ops)
2403       : DITemplateParameter(Context, DITemplateTypeParameterKind, Storage,
2404                             dwarf::DW_TAG_template_type_parameter, IsDefault,
2405                             Ops) {}
2406   ~DITemplateTypeParameter() = default;
2407 
2408   static DITemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
2409                                           DIType *Type, bool IsDefault,
2410                                           StorageType Storage,
2411                                           bool ShouldCreate = true) {
2412     return getImpl(Context, getCanonicalMDString(Context, Name), Type,
2413                    IsDefault, Storage, ShouldCreate);
2414   }
2415   static DITemplateTypeParameter *getImpl(LLVMContext &Context, MDString *Name,
2416                                           Metadata *Type, bool IsDefault,
2417                                           StorageType Storage,
2418                                           bool ShouldCreate = true);
2419 
cloneImpl()2420   TempDITemplateTypeParameter cloneImpl() const {
2421     return getTemporary(getContext(), getName(), getType(), isDefault());
2422   }
2423 
2424 public:
2425   DEFINE_MDNODE_GET(DITemplateTypeParameter,
2426                     (StringRef Name, DIType *Type, bool IsDefault),
2427                     (Name, Type, IsDefault))
2428   DEFINE_MDNODE_GET(DITemplateTypeParameter,
2429                     (MDString *Name, Metadata *Type, bool IsDefault),
2430                     (Name, Type, IsDefault))
2431 
clone()2432   TempDITemplateTypeParameter clone() const { return cloneImpl(); }
2433 
classof(const Metadata * MD)2434   static bool classof(const Metadata *MD) {
2435     return MD->getMetadataID() == DITemplateTypeParameterKind;
2436   }
2437 };
2438 
2439 class DITemplateValueParameter : public DITemplateParameter {
2440   friend class LLVMContextImpl;
2441   friend class MDNode;
2442 
DITemplateValueParameter(LLVMContext & Context,StorageType Storage,unsigned Tag,bool IsDefault,ArrayRef<Metadata * > Ops)2443   DITemplateValueParameter(LLVMContext &Context, StorageType Storage,
2444                            unsigned Tag, bool IsDefault,
2445                            ArrayRef<Metadata *> Ops)
2446       : DITemplateParameter(Context, DITemplateValueParameterKind, Storage, Tag,
2447                             IsDefault, Ops) {}
2448   ~DITemplateValueParameter() = default;
2449 
2450   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
2451                                            StringRef Name, DIType *Type,
2452                                            bool IsDefault, Metadata *Value,
2453                                            StorageType Storage,
2454                                            bool ShouldCreate = true) {
2455     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), Type,
2456                    IsDefault, Value, Storage, ShouldCreate);
2457   }
2458   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
2459                                            MDString *Name, Metadata *Type,
2460                                            bool IsDefault, Metadata *Value,
2461                                            StorageType Storage,
2462                                            bool ShouldCreate = true);
2463 
cloneImpl()2464   TempDITemplateValueParameter cloneImpl() const {
2465     return getTemporary(getContext(), getTag(), getName(), getType(),
2466                         isDefault(), getValue());
2467   }
2468 
2469 public:
2470   DEFINE_MDNODE_GET(DITemplateValueParameter,
2471                     (unsigned Tag, StringRef Name, DIType *Type, bool IsDefault,
2472                      Metadata *Value),
2473                     (Tag, Name, Type, IsDefault, Value))
2474   DEFINE_MDNODE_GET(DITemplateValueParameter,
2475                     (unsigned Tag, MDString *Name, Metadata *Type,
2476                      bool IsDefault, Metadata *Value),
2477                     (Tag, Name, Type, IsDefault, Value))
2478 
clone()2479   TempDITemplateValueParameter clone() const { return cloneImpl(); }
2480 
getValue()2481   Metadata *getValue() const { return getOperand(2); }
2482 
classof(const Metadata * MD)2483   static bool classof(const Metadata *MD) {
2484     return MD->getMetadataID() == DITemplateValueParameterKind;
2485   }
2486 };
2487 
2488 /// Base class for variables.
2489 class DIVariable : public DINode {
2490   unsigned Line;
2491   uint32_t AlignInBits;
2492 
2493 protected:
2494   DIVariable(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Line,
2495              ArrayRef<Metadata *> Ops, uint32_t AlignInBits = 0)
DINode(C,ID,Storage,dwarf::DW_TAG_variable,Ops)2496       : DINode(C, ID, Storage, dwarf::DW_TAG_variable, Ops), Line(Line),
2497         AlignInBits(AlignInBits) {}
2498   ~DIVariable() = default;
2499 
2500 public:
getLine()2501   unsigned getLine() const { return Line; }
getScope()2502   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
getName()2503   StringRef getName() const { return getStringOperand(1); }
getFile()2504   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
getType()2505   DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
getAlignInBits()2506   uint32_t getAlignInBits() const { return AlignInBits; }
getAlignInBytes()2507   uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
2508   /// Determines the size of the variable's type.
2509   Optional<uint64_t> getSizeInBits() const;
2510 
2511   /// Return the signedness of this variable's type, or None if this type is
2512   /// neither signed nor unsigned.
getSignedness()2513   Optional<DIBasicType::Signedness> getSignedness() const {
2514     if (auto *BT = dyn_cast<DIBasicType>(getType()))
2515       return BT->getSignedness();
2516     return None;
2517   }
2518 
getFilename()2519   StringRef getFilename() const {
2520     if (auto *F = getFile())
2521       return F->getFilename();
2522     return "";
2523   }
2524 
getDirectory()2525   StringRef getDirectory() const {
2526     if (auto *F = getFile())
2527       return F->getDirectory();
2528     return "";
2529   }
2530 
getSource()2531   Optional<StringRef> getSource() const {
2532     if (auto *F = getFile())
2533       return F->getSource();
2534     return None;
2535   }
2536 
getRawScope()2537   Metadata *getRawScope() const { return getOperand(0); }
getRawName()2538   MDString *getRawName() const { return getOperandAs<MDString>(1); }
getRawFile()2539   Metadata *getRawFile() const { return getOperand(2); }
getRawType()2540   Metadata *getRawType() const { return getOperand(3); }
2541 
classof(const Metadata * MD)2542   static bool classof(const Metadata *MD) {
2543     return MD->getMetadataID() == DILocalVariableKind ||
2544            MD->getMetadataID() == DIGlobalVariableKind;
2545   }
2546 };
2547 
2548 /// DWARF expression.
2549 ///
2550 /// This is (almost) a DWARF expression that modifies the location of a
2551 /// variable, or the location of a single piece of a variable, or (when using
2552 /// DW_OP_stack_value) is the constant variable value.
2553 ///
2554 /// TODO: Co-allocate the expression elements.
2555 /// TODO: Separate from MDNode, or otherwise drop Distinct and Temporary
2556 /// storage types.
2557 class DIExpression : public MDNode {
2558   friend class LLVMContextImpl;
2559   friend class MDNode;
2560 
2561   std::vector<uint64_t> Elements;
2562 
DIExpression(LLVMContext & C,StorageType Storage,ArrayRef<uint64_t> Elements)2563   DIExpression(LLVMContext &C, StorageType Storage, ArrayRef<uint64_t> Elements)
2564       : MDNode(C, DIExpressionKind, Storage, None),
2565         Elements(Elements.begin(), Elements.end()) {}
2566   ~DIExpression() = default;
2567 
2568   static DIExpression *getImpl(LLVMContext &Context,
2569                                ArrayRef<uint64_t> Elements, StorageType Storage,
2570                                bool ShouldCreate = true);
2571 
cloneImpl()2572   TempDIExpression cloneImpl() const {
2573     return getTemporary(getContext(), getElements());
2574   }
2575 
2576 public:
2577   DEFINE_MDNODE_GET(DIExpression, (ArrayRef<uint64_t> Elements), (Elements))
2578 
clone()2579   TempDIExpression clone() const { return cloneImpl(); }
2580 
getElements()2581   ArrayRef<uint64_t> getElements() const { return Elements; }
2582 
getNumElements()2583   unsigned getNumElements() const { return Elements.size(); }
2584 
getElement(unsigned I)2585   uint64_t getElement(unsigned I) const {
2586     assert(I < Elements.size() && "Index out of range");
2587     return Elements[I];
2588   }
2589 
2590   enum SignedOrUnsignedConstant { SignedConstant, UnsignedConstant };
2591   /// Determine whether this represents a constant value, if so
2592   // return it's sign information.
2593   llvm::Optional<SignedOrUnsignedConstant> isConstant() const;
2594 
2595   /// Return the number of unique location operands referred to (via
2596   /// DW_OP_LLVM_arg) in this expression; this is not necessarily the number of
2597   /// instances of DW_OP_LLVM_arg within the expression.
2598   /// For example, for the expression:
2599   ///   (DW_OP_LLVM_arg 0, DW_OP_LLVM_arg 1, DW_OP_plus,
2600   ///    DW_OP_LLVM_arg 0, DW_OP_mul)
2601   /// This function would return 2, as there are two unique location operands
2602   /// (0 and 1).
2603   uint64_t getNumLocationOperands() const;
2604 
2605   using element_iterator = ArrayRef<uint64_t>::iterator;
2606 
elements_begin()2607   element_iterator elements_begin() const { return getElements().begin(); }
elements_end()2608   element_iterator elements_end() const { return getElements().end(); }
2609 
2610   /// A lightweight wrapper around an expression operand.
2611   ///
2612   /// TODO: Store arguments directly and change \a DIExpression to store a
2613   /// range of these.
2614   class ExprOperand {
2615     const uint64_t *Op = nullptr;
2616 
2617   public:
2618     ExprOperand() = default;
ExprOperand(const uint64_t * Op)2619     explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
2620 
get()2621     const uint64_t *get() const { return Op; }
2622 
2623     /// Get the operand code.
getOp()2624     uint64_t getOp() const { return *Op; }
2625 
2626     /// Get an argument to the operand.
2627     ///
2628     /// Never returns the operand itself.
getArg(unsigned I)2629     uint64_t getArg(unsigned I) const { return Op[I + 1]; }
2630 
getNumArgs()2631     unsigned getNumArgs() const { return getSize() - 1; }
2632 
2633     /// Return the size of the operand.
2634     ///
2635     /// Return the number of elements in the operand (1 + args).
2636     unsigned getSize() const;
2637 
2638     /// Append the elements of this operand to \p V.
appendToVector(SmallVectorImpl<uint64_t> & V)2639     void appendToVector(SmallVectorImpl<uint64_t> &V) const {
2640       V.append(get(), get() + getSize());
2641     }
2642   };
2643 
2644   /// An iterator for expression operands.
2645   class expr_op_iterator {
2646     ExprOperand Op;
2647 
2648   public:
2649     using iterator_category = std::input_iterator_tag;
2650     using value_type = ExprOperand;
2651     using difference_type = std::ptrdiff_t;
2652     using pointer = value_type *;
2653     using reference = value_type &;
2654 
2655     expr_op_iterator() = default;
expr_op_iterator(element_iterator I)2656     explicit expr_op_iterator(element_iterator I) : Op(I) {}
2657 
getBase()2658     element_iterator getBase() const { return Op.get(); }
2659     const ExprOperand &operator*() const { return Op; }
2660     const ExprOperand *operator->() const { return &Op; }
2661 
2662     expr_op_iterator &operator++() {
2663       increment();
2664       return *this;
2665     }
2666     expr_op_iterator operator++(int) {
2667       expr_op_iterator T(*this);
2668       increment();
2669       return T;
2670     }
2671 
2672     /// Get the next iterator.
2673     ///
2674     /// \a std::next() doesn't work because this is technically an
2675     /// input_iterator, but it's a perfectly valid operation.  This is an
2676     /// accessor to provide the same functionality.
getNext()2677     expr_op_iterator getNext() const { return ++expr_op_iterator(*this); }
2678 
2679     bool operator==(const expr_op_iterator &X) const {
2680       return getBase() == X.getBase();
2681     }
2682     bool operator!=(const expr_op_iterator &X) const {
2683       return getBase() != X.getBase();
2684     }
2685 
2686   private:
increment()2687     void increment() { Op = ExprOperand(getBase() + Op.getSize()); }
2688   };
2689 
2690   /// Visit the elements via ExprOperand wrappers.
2691   ///
2692   /// These range iterators visit elements through \a ExprOperand wrappers.
2693   /// This is not guaranteed to be a valid range unless \a isValid() gives \c
2694   /// true.
2695   ///
2696   /// \pre \a isValid() gives \c true.
2697   /// @{
expr_op_begin()2698   expr_op_iterator expr_op_begin() const {
2699     return expr_op_iterator(elements_begin());
2700   }
expr_op_end()2701   expr_op_iterator expr_op_end() const {
2702     return expr_op_iterator(elements_end());
2703   }
expr_ops()2704   iterator_range<expr_op_iterator> expr_ops() const {
2705     return {expr_op_begin(), expr_op_end()};
2706   }
2707   /// @}
2708 
2709   bool isValid() const;
2710 
classof(const Metadata * MD)2711   static bool classof(const Metadata *MD) {
2712     return MD->getMetadataID() == DIExpressionKind;
2713   }
2714 
2715   /// Return whether the first element a DW_OP_deref.
startsWithDeref()2716   bool startsWithDeref() const {
2717     return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_deref;
2718   }
2719 
2720   /// Holds the characteristics of one fragment of a larger variable.
2721   struct FragmentInfo {
2722     uint64_t SizeInBits;
2723     uint64_t OffsetInBits;
2724   };
2725 
2726   /// Retrieve the details of this fragment expression.
2727   static Optional<FragmentInfo> getFragmentInfo(expr_op_iterator Start,
2728                                                 expr_op_iterator End);
2729 
2730   /// Retrieve the details of this fragment expression.
getFragmentInfo()2731   Optional<FragmentInfo> getFragmentInfo() const {
2732     return getFragmentInfo(expr_op_begin(), expr_op_end());
2733   }
2734 
2735   /// Return whether this is a piece of an aggregate variable.
isFragment()2736   bool isFragment() const { return getFragmentInfo().hasValue(); }
2737 
2738   /// Return whether this is an implicit location description.
2739   bool isImplicit() const;
2740 
2741   /// Return whether the location is computed on the expression stack, meaning
2742   /// it cannot be a simple register location.
2743   bool isComplex() const;
2744 
2745   /// Append \p Ops with operations to apply the \p Offset.
2746   static void appendOffset(SmallVectorImpl<uint64_t> &Ops, int64_t Offset);
2747 
2748   /// If this is a constant offset, extract it. If there is no expression,
2749   /// return true with an offset of zero.
2750   bool extractIfOffset(int64_t &Offset) const;
2751 
2752   /// Returns true iff this DIExpression contains at least one instance of
2753   /// `DW_OP_LLVM_arg, n` for all n in [0, N).
2754   bool hasAllLocationOps(unsigned N) const;
2755 
2756   /// Checks if the last 4 elements of the expression are DW_OP_constu <DWARF
2757   /// Address Space> DW_OP_swap DW_OP_xderef and extracts the <DWARF Address
2758   /// Space>.
2759   static const DIExpression *extractAddressClass(const DIExpression *Expr,
2760                                                  unsigned &AddrClass);
2761 
2762   /// Used for DIExpression::prepend.
2763   enum PrependOps : uint8_t {
2764     ApplyOffset = 0,
2765     DerefBefore = 1 << 0,
2766     DerefAfter = 1 << 1,
2767     StackValue = 1 << 2,
2768     EntryValue = 1 << 3
2769   };
2770 
2771   /// Prepend \p DIExpr with a deref and offset operation and optionally turn it
2772   /// into a stack value or/and an entry value.
2773   static DIExpression *prepend(const DIExpression *Expr, uint8_t Flags,
2774                                int64_t Offset = 0);
2775 
2776   /// Prepend \p DIExpr with the given opcodes and optionally turn it into a
2777   /// stack value.
2778   static DIExpression *prependOpcodes(const DIExpression *Expr,
2779                                       SmallVectorImpl<uint64_t> &Ops,
2780                                       bool StackValue = false,
2781                                       bool EntryValue = false);
2782 
2783   /// Append the opcodes \p Ops to \p DIExpr. Unlike \ref appendToStack, the
2784   /// returned expression is a stack value only if \p DIExpr is a stack value.
2785   /// If \p DIExpr describes a fragment, the returned expression will describe
2786   /// the same fragment.
2787   static DIExpression *append(const DIExpression *Expr, ArrayRef<uint64_t> Ops);
2788 
2789   /// Convert \p DIExpr into a stack value if it isn't one already by appending
2790   /// DW_OP_deref if needed, and appending \p Ops to the resulting expression.
2791   /// If \p DIExpr describes a fragment, the returned expression will describe
2792   /// the same fragment.
2793   static DIExpression *appendToStack(const DIExpression *Expr,
2794                                      ArrayRef<uint64_t> Ops);
2795 
2796   /// Create a copy of \p Expr by appending the given list of \p Ops to each
2797   /// instance of the operand `DW_OP_LLVM_arg, \p ArgNo`. This is used to
2798   /// modify a specific location used by \p Expr, such as when salvaging that
2799   /// location.
2800   static DIExpression *appendOpsToArg(const DIExpression *Expr,
2801                                       ArrayRef<uint64_t> Ops, unsigned ArgNo,
2802                                       bool StackValue = false);
2803 
2804   /// Create a copy of \p Expr with each instance of
2805   /// `DW_OP_LLVM_arg, \p OldArg` replaced with `DW_OP_LLVM_arg, \p NewArg`,
2806   /// and each instance of `DW_OP_LLVM_arg, Arg` with `DW_OP_LLVM_arg, Arg - 1`
2807   /// for all Arg > \p OldArg.
2808   /// This is used when replacing one of the operands of a debug value list
2809   /// with another operand in the same list and deleting the old operand.
2810   static DIExpression *replaceArg(const DIExpression *Expr, uint64_t OldArg,
2811                                   uint64_t NewArg);
2812 
2813   /// Create a DIExpression to describe one part of an aggregate variable that
2814   /// is fragmented across multiple Values. The DW_OP_LLVM_fragment operation
2815   /// will be appended to the elements of \c Expr. If \c Expr already contains
2816   /// a \c DW_OP_LLVM_fragment \c OffsetInBits is interpreted as an offset
2817   /// into the existing fragment.
2818   ///
2819   /// \param OffsetInBits Offset of the piece in bits.
2820   /// \param SizeInBits   Size of the piece in bits.
2821   /// \return             Creating a fragment expression may fail if \c Expr
2822   ///                     contains arithmetic operations that would be truncated.
2823   static Optional<DIExpression *>
2824   createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits,
2825                            unsigned SizeInBits);
2826 
2827   /// Determine the relative position of the fragments passed in.
2828   /// Returns -1 if this is entirely before Other, 0 if this and Other overlap,
2829   /// 1 if this is entirely after Other.
fragmentCmp(const FragmentInfo & A,const FragmentInfo & B)2830   static int fragmentCmp(const FragmentInfo &A, const FragmentInfo &B) {
2831     uint64_t l1 = A.OffsetInBits;
2832     uint64_t l2 = B.OffsetInBits;
2833     uint64_t r1 = l1 + A.SizeInBits;
2834     uint64_t r2 = l2 + B.SizeInBits;
2835     if (r1 <= l2)
2836       return -1;
2837     else if (r2 <= l1)
2838       return 1;
2839     else
2840       return 0;
2841   }
2842 
2843   using ExtOps = std::array<uint64_t, 6>;
2844 
2845   /// Returns the ops for a zero- or sign-extension in a DIExpression.
2846   static ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed);
2847 
2848   /// Append a zero- or sign-extension to \p Expr. Converts the expression to a
2849   /// stack value if it isn't one already.
2850   static DIExpression *appendExt(const DIExpression *Expr, unsigned FromSize,
2851                                  unsigned ToSize, bool Signed);
2852 
2853   /// Check if fragments overlap between a pair of FragmentInfos.
fragmentsOverlap(const FragmentInfo & A,const FragmentInfo & B)2854   static bool fragmentsOverlap(const FragmentInfo &A, const FragmentInfo &B) {
2855     return fragmentCmp(A, B) == 0;
2856   }
2857 
2858   /// Determine the relative position of the fragments described by this
2859   /// DIExpression and \p Other. Calls static fragmentCmp implementation.
fragmentCmp(const DIExpression * Other)2860   int fragmentCmp(const DIExpression *Other) const {
2861     auto Fragment1 = *getFragmentInfo();
2862     auto Fragment2 = *Other->getFragmentInfo();
2863     return fragmentCmp(Fragment1, Fragment2);
2864   }
2865 
2866   /// Check if fragments overlap between this DIExpression and \p Other.
fragmentsOverlap(const DIExpression * Other)2867   bool fragmentsOverlap(const DIExpression *Other) const {
2868     if (!isFragment() || !Other->isFragment())
2869       return true;
2870     return fragmentCmp(Other) == 0;
2871   }
2872 
2873   /// Check if the expression consists of exactly one entry value operand.
2874   /// (This is the only configuration of entry values that is supported.)
isEntryValue()2875   bool isEntryValue() const {
2876     return getNumElements() > 0 &&
2877            getElement(0) == dwarf::DW_OP_LLVM_entry_value;
2878   }
2879 };
2880 
2881 inline bool operator==(const DIExpression::FragmentInfo &A,
2882                        const DIExpression::FragmentInfo &B) {
2883   return std::tie(A.SizeInBits, A.OffsetInBits) ==
2884          std::tie(B.SizeInBits, B.OffsetInBits);
2885 }
2886 
2887 inline bool operator<(const DIExpression::FragmentInfo &A,
2888                       const DIExpression::FragmentInfo &B) {
2889   return std::tie(A.SizeInBits, A.OffsetInBits) <
2890          std::tie(B.SizeInBits, B.OffsetInBits);
2891 }
2892 
2893 template <> struct DenseMapInfo<DIExpression::FragmentInfo> {
2894   using FragInfo = DIExpression::FragmentInfo;
2895   static const uint64_t MaxVal = std::numeric_limits<uint64_t>::max();
2896 
2897   static inline FragInfo getEmptyKey() { return {MaxVal, MaxVal}; }
2898 
2899   static inline FragInfo getTombstoneKey() { return {MaxVal - 1, MaxVal - 1}; }
2900 
2901   static unsigned getHashValue(const FragInfo &Frag) {
2902     return (Frag.SizeInBits & 0xffff) << 16 | (Frag.OffsetInBits & 0xffff);
2903   }
2904 
2905   static bool isEqual(const FragInfo &A, const FragInfo &B) { return A == B; }
2906 };
2907 
2908 /// Global variables.
2909 ///
2910 /// TODO: Remove DisplayName.  It's always equal to Name.
2911 class DIGlobalVariable : public DIVariable {
2912   friend class LLVMContextImpl;
2913   friend class MDNode;
2914 
2915   bool IsLocalToUnit;
2916   bool IsDefinition;
2917 
2918   DIGlobalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
2919                    bool IsLocalToUnit, bool IsDefinition, uint32_t AlignInBits,
2920                    ArrayRef<Metadata *> Ops)
2921       : DIVariable(C, DIGlobalVariableKind, Storage, Line, Ops, AlignInBits),
2922         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition) {}
2923   ~DIGlobalVariable() = default;
2924 
2925   static DIGlobalVariable *
2926   getImpl(LLVMContext &Context, DIScope *Scope, StringRef Name,
2927           StringRef LinkageName, DIFile *File, unsigned Line, DIType *Type,
2928           bool IsLocalToUnit, bool IsDefinition,
2929           DIDerivedType *StaticDataMemberDeclaration, MDTuple *TemplateParams,
2930           uint32_t AlignInBits, StorageType Storage, bool ShouldCreate = true) {
2931     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
2932                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
2933                    IsLocalToUnit, IsDefinition, StaticDataMemberDeclaration,
2934                    cast_or_null<Metadata>(TemplateParams), AlignInBits, Storage,
2935                    ShouldCreate);
2936   }
2937   static DIGlobalVariable *
2938   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
2939           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
2940           bool IsLocalToUnit, bool IsDefinition,
2941           Metadata *StaticDataMemberDeclaration, Metadata *TemplateParams,
2942           uint32_t AlignInBits, StorageType Storage, bool ShouldCreate = true);
2943 
2944   TempDIGlobalVariable cloneImpl() const {
2945     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
2946                         getFile(), getLine(), getType(), isLocalToUnit(),
2947                         isDefinition(), getStaticDataMemberDeclaration(),
2948                         getTemplateParams(), getAlignInBits());
2949   }
2950 
2951 public:
2952   DEFINE_MDNODE_GET(DIGlobalVariable,
2953                     (DIScope * Scope, StringRef Name, StringRef LinkageName,
2954                      DIFile *File, unsigned Line, DIType *Type,
2955                      bool IsLocalToUnit, bool IsDefinition,
2956                      DIDerivedType *StaticDataMemberDeclaration,
2957                      MDTuple *TemplateParams, uint32_t AlignInBits),
2958                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
2959                      IsDefinition, StaticDataMemberDeclaration, TemplateParams,
2960                      AlignInBits))
2961   DEFINE_MDNODE_GET(DIGlobalVariable,
2962                     (Metadata * Scope, MDString *Name, MDString *LinkageName,
2963                      Metadata *File, unsigned Line, Metadata *Type,
2964                      bool IsLocalToUnit, bool IsDefinition,
2965                      Metadata *StaticDataMemberDeclaration,
2966                      Metadata *TemplateParams, uint32_t AlignInBits),
2967                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
2968                      IsDefinition, StaticDataMemberDeclaration, TemplateParams,
2969                      AlignInBits))
2970 
2971   TempDIGlobalVariable clone() const { return cloneImpl(); }
2972 
2973   bool isLocalToUnit() const { return IsLocalToUnit; }
2974   bool isDefinition() const { return IsDefinition; }
2975   StringRef getDisplayName() const { return getStringOperand(4); }
2976   StringRef getLinkageName() const { return getStringOperand(5); }
2977   DIDerivedType *getStaticDataMemberDeclaration() const {
2978     return cast_or_null<DIDerivedType>(getRawStaticDataMemberDeclaration());
2979   }
2980 
2981   MDString *getRawLinkageName() const { return getOperandAs<MDString>(5); }
2982   Metadata *getRawStaticDataMemberDeclaration() const { return getOperand(6); }
2983   Metadata *getRawTemplateParams() const { return getOperand(7); }
2984   MDTuple *getTemplateParams() const { return getOperandAs<MDTuple>(7); }
2985 
2986   static bool classof(const Metadata *MD) {
2987     return MD->getMetadataID() == DIGlobalVariableKind;
2988   }
2989 };
2990 
2991 class DICommonBlock : public DIScope {
2992   unsigned LineNo;
2993 
2994   friend class LLVMContextImpl;
2995   friend class MDNode;
2996 
2997   DICommonBlock(LLVMContext &Context, StorageType Storage, unsigned LineNo,
2998                 ArrayRef<Metadata *> Ops)
2999       : DIScope(Context, DICommonBlockKind, Storage, dwarf::DW_TAG_common_block,
3000                 Ops), LineNo(LineNo) {}
3001 
3002   static DICommonBlock *getImpl(LLVMContext &Context, DIScope *Scope,
3003                                 DIGlobalVariable *Decl, StringRef Name,
3004                                 DIFile *File, unsigned LineNo,
3005                                 StorageType Storage,
3006                                 bool ShouldCreate = true) {
3007     return getImpl(Context, Scope, Decl, getCanonicalMDString(Context, Name),
3008                    File, LineNo, Storage, ShouldCreate);
3009   }
3010   static DICommonBlock *getImpl(LLVMContext &Context, Metadata *Scope,
3011                                 Metadata *Decl, MDString *Name, Metadata *File,
3012                                 unsigned LineNo,
3013                                 StorageType Storage, bool ShouldCreate = true);
3014 
3015   TempDICommonBlock cloneImpl() const {
3016     return getTemporary(getContext(), getScope(), getDecl(), getName(),
3017                         getFile(), getLineNo());
3018   }
3019 
3020 public:
3021   DEFINE_MDNODE_GET(DICommonBlock,
3022                     (DIScope *Scope, DIGlobalVariable *Decl, StringRef Name,
3023                      DIFile *File, unsigned LineNo),
3024                     (Scope, Decl, Name, File, LineNo))
3025   DEFINE_MDNODE_GET(DICommonBlock,
3026                     (Metadata *Scope, Metadata *Decl, MDString *Name,
3027                      Metadata *File, unsigned LineNo),
3028                     (Scope, Decl, Name, File, LineNo))
3029 
3030   TempDICommonBlock clone() const { return cloneImpl(); }
3031 
3032   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
3033   DIGlobalVariable *getDecl() const {
3034     return cast_or_null<DIGlobalVariable>(getRawDecl());
3035   }
3036   StringRef getName() const { return getStringOperand(2); }
3037   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
3038   unsigned getLineNo() const { return LineNo; }
3039 
3040   Metadata *getRawScope() const { return getOperand(0); }
3041   Metadata *getRawDecl() const { return getOperand(1); }
3042   MDString *getRawName() const { return getOperandAs<MDString>(2); }
3043   Metadata *getRawFile() const { return getOperand(3); }
3044 
3045   static bool classof(const Metadata *MD) {
3046     return MD->getMetadataID() == DICommonBlockKind;
3047   }
3048 };
3049 
3050 /// Local variable.
3051 ///
3052 /// TODO: Split up flags.
3053 class DILocalVariable : public DIVariable {
3054   friend class LLVMContextImpl;
3055   friend class MDNode;
3056 
3057   unsigned Arg : 16;
3058   DIFlags Flags;
3059 
3060   DILocalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
3061                   unsigned Arg, DIFlags Flags, uint32_t AlignInBits,
3062                   ArrayRef<Metadata *> Ops)
3063       : DIVariable(C, DILocalVariableKind, Storage, Line, Ops, AlignInBits),
3064         Arg(Arg), Flags(Flags) {
3065     assert(Arg < (1 << 16) && "DILocalVariable: Arg out of range");
3066   }
3067   ~DILocalVariable() = default;
3068 
3069   static DILocalVariable *getImpl(LLVMContext &Context, DIScope *Scope,
3070                                   StringRef Name, DIFile *File, unsigned Line,
3071                                   DIType *Type, unsigned Arg, DIFlags Flags,
3072                                   uint32_t AlignInBits, StorageType Storage,
3073                                   bool ShouldCreate = true) {
3074     return getImpl(Context, Scope, getCanonicalMDString(Context, Name), File,
3075                    Line, Type, Arg, Flags, AlignInBits, Storage, ShouldCreate);
3076   }
3077   static DILocalVariable *getImpl(LLVMContext &Context, Metadata *Scope,
3078                                   MDString *Name, Metadata *File, unsigned Line,
3079                                   Metadata *Type, unsigned Arg, DIFlags Flags,
3080                                   uint32_t AlignInBits, StorageType Storage,
3081                                   bool ShouldCreate = true);
3082 
3083   TempDILocalVariable cloneImpl() const {
3084     return getTemporary(getContext(), getScope(), getName(), getFile(),
3085                         getLine(), getType(), getArg(), getFlags(),
3086                         getAlignInBits());
3087   }
3088 
3089 public:
3090   DEFINE_MDNODE_GET(DILocalVariable,
3091                     (DILocalScope * Scope, StringRef Name, DIFile *File,
3092                      unsigned Line, DIType *Type, unsigned Arg, DIFlags Flags,
3093                      uint32_t AlignInBits),
3094                     (Scope, Name, File, Line, Type, Arg, Flags, AlignInBits))
3095   DEFINE_MDNODE_GET(DILocalVariable,
3096                     (Metadata * Scope, MDString *Name, Metadata *File,
3097                      unsigned Line, Metadata *Type, unsigned Arg,
3098                      DIFlags Flags, uint32_t AlignInBits),
3099                     (Scope, Name, File, Line, Type, Arg, Flags, AlignInBits))
3100 
3101   TempDILocalVariable clone() const { return cloneImpl(); }
3102 
3103   /// Get the local scope for this variable.
3104   ///
3105   /// Variables must be defined in a local scope.
3106   DILocalScope *getScope() const {
3107     return cast<DILocalScope>(DIVariable::getScope());
3108   }
3109 
3110   bool isParameter() const { return Arg; }
3111   unsigned getArg() const { return Arg; }
3112   DIFlags getFlags() const { return Flags; }
3113 
3114   bool isArtificial() const { return getFlags() & FlagArtificial; }
3115   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
3116 
3117   /// Check that a location is valid for this variable.
3118   ///
3119   /// Check that \c DL exists, is in the same subprogram, and has the same
3120   /// inlined-at location as \c this.  (Otherwise, it's not a valid attachment
3121   /// to a \a DbgInfoIntrinsic.)
3122   bool isValidLocationForIntrinsic(const DILocation *DL) const {
3123     return DL && getScope()->getSubprogram() == DL->getScope()->getSubprogram();
3124   }
3125 
3126   static bool classof(const Metadata *MD) {
3127     return MD->getMetadataID() == DILocalVariableKind;
3128   }
3129 };
3130 
3131 /// Label.
3132 ///
3133 class DILabel : public DINode {
3134   friend class LLVMContextImpl;
3135   friend class MDNode;
3136 
3137   unsigned Line;
3138 
3139   DILabel(LLVMContext &C, StorageType Storage, unsigned Line,
3140           ArrayRef<Metadata *> Ops)
3141       : DINode(C, DILabelKind, Storage, dwarf::DW_TAG_label, Ops), Line(Line) {}
3142   ~DILabel() = default;
3143 
3144   static DILabel *getImpl(LLVMContext &Context, DIScope *Scope,
3145                           StringRef Name, DIFile *File, unsigned Line,
3146                           StorageType Storage,
3147                           bool ShouldCreate = true) {
3148     return getImpl(Context, Scope, getCanonicalMDString(Context, Name), File,
3149                    Line, Storage, ShouldCreate);
3150   }
3151   static DILabel *getImpl(LLVMContext &Context, Metadata *Scope,
3152                           MDString *Name, Metadata *File, unsigned Line,
3153                           StorageType Storage,
3154                           bool ShouldCreate = true);
3155 
3156   TempDILabel cloneImpl() const {
3157     return getTemporary(getContext(), getScope(), getName(), getFile(),
3158                         getLine());
3159   }
3160 
3161 public:
3162   DEFINE_MDNODE_GET(DILabel,
3163                     (DILocalScope * Scope, StringRef Name, DIFile *File,
3164                      unsigned Line),
3165                     (Scope, Name, File, Line))
3166   DEFINE_MDNODE_GET(DILabel,
3167                     (Metadata * Scope, MDString *Name, Metadata *File,
3168                      unsigned Line),
3169                     (Scope, Name, File, Line))
3170 
3171   TempDILabel clone() const { return cloneImpl(); }
3172 
3173   /// Get the local scope for this label.
3174   ///
3175   /// Labels must be defined in a local scope.
3176   DILocalScope *getScope() const {
3177     return cast_or_null<DILocalScope>(getRawScope());
3178   }
3179   unsigned getLine() const { return Line; }
3180   StringRef getName() const { return getStringOperand(1); }
3181   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
3182 
3183   Metadata *getRawScope() const { return getOperand(0); }
3184   MDString *getRawName() const { return getOperandAs<MDString>(1); }
3185   Metadata *getRawFile() const { return getOperand(2); }
3186 
3187   /// Check that a location is valid for this label.
3188   ///
3189   /// Check that \c DL exists, is in the same subprogram, and has the same
3190   /// inlined-at location as \c this.  (Otherwise, it's not a valid attachment
3191   /// to a \a DbgInfoIntrinsic.)
3192   bool isValidLocationForIntrinsic(const DILocation *DL) const {
3193     return DL && getScope()->getSubprogram() == DL->getScope()->getSubprogram();
3194   }
3195 
3196   static bool classof(const Metadata *MD) {
3197     return MD->getMetadataID() == DILabelKind;
3198   }
3199 };
3200 
3201 class DIObjCProperty : public DINode {
3202   friend class LLVMContextImpl;
3203   friend class MDNode;
3204 
3205   unsigned Line;
3206   unsigned Attributes;
3207 
3208   DIObjCProperty(LLVMContext &C, StorageType Storage, unsigned Line,
3209                  unsigned Attributes, ArrayRef<Metadata *> Ops)
3210       : DINode(C, DIObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property,
3211                Ops),
3212         Line(Line), Attributes(Attributes) {}
3213   ~DIObjCProperty() = default;
3214 
3215   static DIObjCProperty *
3216   getImpl(LLVMContext &Context, StringRef Name, DIFile *File, unsigned Line,
3217           StringRef GetterName, StringRef SetterName, unsigned Attributes,
3218           DIType *Type, StorageType Storage, bool ShouldCreate = true) {
3219     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
3220                    getCanonicalMDString(Context, GetterName),
3221                    getCanonicalMDString(Context, SetterName), Attributes, Type,
3222                    Storage, ShouldCreate);
3223   }
3224   static DIObjCProperty *getImpl(LLVMContext &Context, MDString *Name,
3225                                  Metadata *File, unsigned Line,
3226                                  MDString *GetterName, MDString *SetterName,
3227                                  unsigned Attributes, Metadata *Type,
3228                                  StorageType Storage, bool ShouldCreate = true);
3229 
3230   TempDIObjCProperty cloneImpl() const {
3231     return getTemporary(getContext(), getName(), getFile(), getLine(),
3232                         getGetterName(), getSetterName(), getAttributes(),
3233                         getType());
3234   }
3235 
3236 public:
3237   DEFINE_MDNODE_GET(DIObjCProperty,
3238                     (StringRef Name, DIFile *File, unsigned Line,
3239                      StringRef GetterName, StringRef SetterName,
3240                      unsigned Attributes, DIType *Type),
3241                     (Name, File, Line, GetterName, SetterName, Attributes,
3242                      Type))
3243   DEFINE_MDNODE_GET(DIObjCProperty,
3244                     (MDString * Name, Metadata *File, unsigned Line,
3245                      MDString *GetterName, MDString *SetterName,
3246                      unsigned Attributes, Metadata *Type),
3247                     (Name, File, Line, GetterName, SetterName, Attributes,
3248                      Type))
3249 
3250   TempDIObjCProperty clone() const { return cloneImpl(); }
3251 
3252   unsigned getLine() const { return Line; }
3253   unsigned getAttributes() const { return Attributes; }
3254   StringRef getName() const { return getStringOperand(0); }
3255   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
3256   StringRef getGetterName() const { return getStringOperand(2); }
3257   StringRef getSetterName() const { return getStringOperand(3); }
3258   DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
3259 
3260   StringRef getFilename() const {
3261     if (auto *F = getFile())
3262       return F->getFilename();
3263     return "";
3264   }
3265 
3266   StringRef getDirectory() const {
3267     if (auto *F = getFile())
3268       return F->getDirectory();
3269     return "";
3270   }
3271 
3272   MDString *getRawName() const { return getOperandAs<MDString>(0); }
3273   Metadata *getRawFile() const { return getOperand(1); }
3274   MDString *getRawGetterName() const { return getOperandAs<MDString>(2); }
3275   MDString *getRawSetterName() const { return getOperandAs<MDString>(3); }
3276   Metadata *getRawType() const { return getOperand(4); }
3277 
3278   static bool classof(const Metadata *MD) {
3279     return MD->getMetadataID() == DIObjCPropertyKind;
3280   }
3281 };
3282 
3283 /// An imported module (C++ using directive or similar).
3284 class DIImportedEntity : public DINode {
3285   friend class LLVMContextImpl;
3286   friend class MDNode;
3287 
3288   unsigned Line;
3289 
3290   DIImportedEntity(LLVMContext &C, StorageType Storage, unsigned Tag,
3291                    unsigned Line, ArrayRef<Metadata *> Ops)
3292       : DINode(C, DIImportedEntityKind, Storage, Tag, Ops), Line(Line) {}
3293   ~DIImportedEntity() = default;
3294 
3295   static DIImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
3296                                    DIScope *Scope, DINode *Entity, DIFile *File,
3297                                    unsigned Line, StringRef Name,
3298                                    StorageType Storage,
3299                                    bool ShouldCreate = true) {
3300     return getImpl(Context, Tag, Scope, Entity, File, Line,
3301                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
3302   }
3303   static DIImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
3304                                    Metadata *Scope, Metadata *Entity,
3305                                    Metadata *File, unsigned Line,
3306                                    MDString *Name, StorageType Storage,
3307                                    bool ShouldCreate = true);
3308 
3309   TempDIImportedEntity cloneImpl() const {
3310     return getTemporary(getContext(), getTag(), getScope(), getEntity(),
3311                         getFile(), getLine(), getName());
3312   }
3313 
3314 public:
3315   DEFINE_MDNODE_GET(DIImportedEntity,
3316                     (unsigned Tag, DIScope *Scope, DINode *Entity, DIFile *File,
3317                      unsigned Line, StringRef Name = ""),
3318                     (Tag, Scope, Entity, File, Line, Name))
3319   DEFINE_MDNODE_GET(DIImportedEntity,
3320                     (unsigned Tag, Metadata *Scope, Metadata *Entity,
3321                      Metadata *File, unsigned Line, MDString *Name),
3322                     (Tag, Scope, Entity, File, Line, Name))
3323 
3324   TempDIImportedEntity clone() const { return cloneImpl(); }
3325 
3326   unsigned getLine() const { return Line; }
3327   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
3328   DINode *getEntity() const { return cast_or_null<DINode>(getRawEntity()); }
3329   StringRef getName() const { return getStringOperand(2); }
3330   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
3331 
3332   Metadata *getRawScope() const { return getOperand(0); }
3333   Metadata *getRawEntity() const { return getOperand(1); }
3334   MDString *getRawName() const { return getOperandAs<MDString>(2); }
3335   Metadata *getRawFile() const { return getOperand(3); }
3336 
3337   static bool classof(const Metadata *MD) {
3338     return MD->getMetadataID() == DIImportedEntityKind;
3339   }
3340 };
3341 
3342 /// A pair of DIGlobalVariable and DIExpression.
3343 class DIGlobalVariableExpression : public MDNode {
3344   friend class LLVMContextImpl;
3345   friend class MDNode;
3346 
3347   DIGlobalVariableExpression(LLVMContext &C, StorageType Storage,
3348                              ArrayRef<Metadata *> Ops)
3349       : MDNode(C, DIGlobalVariableExpressionKind, Storage, Ops) {}
3350   ~DIGlobalVariableExpression() = default;
3351 
3352   static DIGlobalVariableExpression *
3353   getImpl(LLVMContext &Context, Metadata *Variable, Metadata *Expression,
3354           StorageType Storage, bool ShouldCreate = true);
3355 
3356   TempDIGlobalVariableExpression cloneImpl() const {
3357     return getTemporary(getContext(), getVariable(), getExpression());
3358   }
3359 
3360 public:
3361   DEFINE_MDNODE_GET(DIGlobalVariableExpression,
3362                     (Metadata * Variable, Metadata *Expression),
3363                     (Variable, Expression))
3364 
3365   TempDIGlobalVariableExpression clone() const { return cloneImpl(); }
3366 
3367   Metadata *getRawVariable() const { return getOperand(0); }
3368 
3369   DIGlobalVariable *getVariable() const {
3370     return cast_or_null<DIGlobalVariable>(getRawVariable());
3371   }
3372 
3373   Metadata *getRawExpression() const { return getOperand(1); }
3374 
3375   DIExpression *getExpression() const {
3376     return cast<DIExpression>(getRawExpression());
3377   }
3378 
3379   static bool classof(const Metadata *MD) {
3380     return MD->getMetadataID() == DIGlobalVariableExpressionKind;
3381   }
3382 };
3383 
3384 /// Macro Info DWARF-like metadata node.
3385 ///
3386 /// A metadata node with a DWARF macro info (i.e., a constant named
3387 /// \c DW_MACINFO_*, defined in llvm/BinaryFormat/Dwarf.h).  Called \a
3388 /// DIMacroNode
3389 /// because it's potentially used for non-DWARF output.
3390 class DIMacroNode : public MDNode {
3391   friend class LLVMContextImpl;
3392   friend class MDNode;
3393 
3394 protected:
3395   DIMacroNode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned MIType,
3396               ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
3397       : MDNode(C, ID, Storage, Ops1, Ops2) {
3398     assert(MIType < 1u << 16);
3399     SubclassData16 = MIType;
3400   }
3401   ~DIMacroNode() = default;
3402 
3403   template <class Ty> Ty *getOperandAs(unsigned I) const {
3404     return cast_or_null<Ty>(getOperand(I));
3405   }
3406 
3407   StringRef getStringOperand(unsigned I) const {
3408     if (auto *S = getOperandAs<MDString>(I))
3409       return S->getString();
3410     return StringRef();
3411   }
3412 
3413   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
3414     if (S.empty())
3415       return nullptr;
3416     return MDString::get(Context, S);
3417   }
3418 
3419 public:
3420   unsigned getMacinfoType() const { return SubclassData16; }
3421 
3422   static bool classof(const Metadata *MD) {
3423     switch (MD->getMetadataID()) {
3424     default:
3425       return false;
3426     case DIMacroKind:
3427     case DIMacroFileKind:
3428       return true;
3429     }
3430   }
3431 };
3432 
3433 class DIMacro : public DIMacroNode {
3434   friend class LLVMContextImpl;
3435   friend class MDNode;
3436 
3437   unsigned Line;
3438 
3439   DIMacro(LLVMContext &C, StorageType Storage, unsigned MIType, unsigned Line,
3440           ArrayRef<Metadata *> Ops)
3441       : DIMacroNode(C, DIMacroKind, Storage, MIType, Ops), Line(Line) {}
3442   ~DIMacro() = default;
3443 
3444   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
3445                           StringRef Name, StringRef Value, StorageType Storage,
3446                           bool ShouldCreate = true) {
3447     return getImpl(Context, MIType, Line, getCanonicalMDString(Context, Name),
3448                    getCanonicalMDString(Context, Value), Storage, ShouldCreate);
3449   }
3450   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
3451                           MDString *Name, MDString *Value, StorageType Storage,
3452                           bool ShouldCreate = true);
3453 
3454   TempDIMacro cloneImpl() const {
3455     return getTemporary(getContext(), getMacinfoType(), getLine(), getName(),
3456                         getValue());
3457   }
3458 
3459 public:
3460   DEFINE_MDNODE_GET(DIMacro, (unsigned MIType, unsigned Line, StringRef Name,
3461                               StringRef Value = ""),
3462                     (MIType, Line, Name, Value))
3463   DEFINE_MDNODE_GET(DIMacro, (unsigned MIType, unsigned Line, MDString *Name,
3464                               MDString *Value),
3465                     (MIType, Line, Name, Value))
3466 
3467   TempDIMacro clone() const { return cloneImpl(); }
3468 
3469   unsigned getLine() const { return Line; }
3470 
3471   StringRef getName() const { return getStringOperand(0); }
3472   StringRef getValue() const { return getStringOperand(1); }
3473 
3474   MDString *getRawName() const { return getOperandAs<MDString>(0); }
3475   MDString *getRawValue() const { return getOperandAs<MDString>(1); }
3476 
3477   static bool classof(const Metadata *MD) {
3478     return MD->getMetadataID() == DIMacroKind;
3479   }
3480 };
3481 
3482 class DIMacroFile : public DIMacroNode {
3483   friend class LLVMContextImpl;
3484   friend class MDNode;
3485 
3486   unsigned Line;
3487 
3488   DIMacroFile(LLVMContext &C, StorageType Storage, unsigned MIType,
3489               unsigned Line, ArrayRef<Metadata *> Ops)
3490       : DIMacroNode(C, DIMacroFileKind, Storage, MIType, Ops), Line(Line) {}
3491   ~DIMacroFile() = default;
3492 
3493   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
3494                               unsigned Line, DIFile *File,
3495                               DIMacroNodeArray Elements, StorageType Storage,
3496                               bool ShouldCreate = true) {
3497     return getImpl(Context, MIType, Line, static_cast<Metadata *>(File),
3498                    Elements.get(), Storage, ShouldCreate);
3499   }
3500 
3501   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
3502                               unsigned Line, Metadata *File, Metadata *Elements,
3503                               StorageType Storage, bool ShouldCreate = true);
3504 
3505   TempDIMacroFile cloneImpl() const {
3506     return getTemporary(getContext(), getMacinfoType(), getLine(), getFile(),
3507                         getElements());
3508   }
3509 
3510 public:
3511   DEFINE_MDNODE_GET(DIMacroFile, (unsigned MIType, unsigned Line, DIFile *File,
3512                                   DIMacroNodeArray Elements),
3513                     (MIType, Line, File, Elements))
3514   DEFINE_MDNODE_GET(DIMacroFile, (unsigned MIType, unsigned Line,
3515                                   Metadata *File, Metadata *Elements),
3516                     (MIType, Line, File, Elements))
3517 
3518   TempDIMacroFile clone() const { return cloneImpl(); }
3519 
3520   void replaceElements(DIMacroNodeArray Elements) {
3521 #ifndef NDEBUG
3522     for (DIMacroNode *Op : getElements())
3523       assert(is_contained(Elements->operands(), Op) &&
3524              "Lost a macro node during macro node list replacement");
3525 #endif
3526     replaceOperandWith(1, Elements.get());
3527   }
3528 
3529   unsigned getLine() const { return Line; }
3530   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
3531 
3532   DIMacroNodeArray getElements() const {
3533     return cast_or_null<MDTuple>(getRawElements());
3534   }
3535 
3536   Metadata *getRawFile() const { return getOperand(0); }
3537   Metadata *getRawElements() const { return getOperand(1); }
3538 
3539   static bool classof(const Metadata *MD) {
3540     return MD->getMetadataID() == DIMacroFileKind;
3541   }
3542 };
3543 
3544 /// List of ValueAsMetadata, to be used as an argument to a dbg.value
3545 /// intrinsic.
3546 class DIArgList : public MDNode {
3547   friend class LLVMContextImpl;
3548   friend class MDNode;
3549   using iterator = SmallVectorImpl<ValueAsMetadata *>::iterator;
3550 
3551   SmallVector<ValueAsMetadata *, 4> Args;
3552 
3553   DIArgList(LLVMContext &C, StorageType Storage,
3554             ArrayRef<ValueAsMetadata *> Args)
3555       : MDNode(C, DIArgListKind, Storage, None),
3556         Args(Args.begin(), Args.end()) {
3557     track();
3558   }
3559   ~DIArgList() { untrack(); }
3560 
3561   static DIArgList *getImpl(LLVMContext &Context,
3562                             ArrayRef<ValueAsMetadata *> Args,
3563                             StorageType Storage, bool ShouldCreate = true);
3564 
3565   TempDIArgList cloneImpl() const {
3566     return getTemporary(getContext(), getArgs());
3567   }
3568 
3569   void track();
3570   void untrack();
3571   void dropAllReferences();
3572 
3573 public:
3574   DEFINE_MDNODE_GET(DIArgList, (ArrayRef<ValueAsMetadata *> Args), (Args))
3575 
3576   TempDIArgList clone() const { return cloneImpl(); }
3577 
3578   ArrayRef<ValueAsMetadata *> getArgs() const { return Args; }
3579 
3580   iterator args_begin() { return Args.begin(); }
3581   iterator args_end() { return Args.end(); }
3582 
3583   static bool classof(const Metadata *MD) {
3584     return MD->getMetadataID() == DIArgListKind;
3585   }
3586 
3587   void handleChangedOperand(void *Ref, Metadata *New);
3588 };
3589 
3590 /// Identifies a unique instance of a variable.
3591 ///
3592 /// Storage for identifying a potentially inlined instance of a variable,
3593 /// or a fragment thereof. This guarantees that exactly one variable instance
3594 /// may be identified by this class, even when that variable is a fragment of
3595 /// an aggregate variable and/or there is another inlined instance of the same
3596 /// source code variable nearby.
3597 /// This class does not necessarily uniquely identify that variable: it is
3598 /// possible that a DebugVariable with different parameters may point to the
3599 /// same variable instance, but not that one DebugVariable points to multiple
3600 /// variable instances.
3601 class DebugVariable {
3602   using FragmentInfo = DIExpression::FragmentInfo;
3603 
3604   const DILocalVariable *Variable;
3605   Optional<FragmentInfo> Fragment;
3606   const DILocation *InlinedAt;
3607 
3608   /// Fragment that will overlap all other fragments. Used as default when
3609   /// caller demands a fragment.
3610   static const FragmentInfo DefaultFragment;
3611 
3612 public:
3613   DebugVariable(const DILocalVariable *Var, Optional<FragmentInfo> FragmentInfo,
3614                 const DILocation *InlinedAt)
3615       : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
3616 
3617   DebugVariable(const DILocalVariable *Var, const DIExpression *DIExpr,
3618                 const DILocation *InlinedAt)
3619       : Variable(Var),
3620         Fragment(DIExpr ? DIExpr->getFragmentInfo() : NoneType()),
3621         InlinedAt(InlinedAt) {}
3622 
3623   const DILocalVariable *getVariable() const { return Variable; }
3624   Optional<FragmentInfo> getFragment() const { return Fragment; }
3625   const DILocation *getInlinedAt() const { return InlinedAt; }
3626 
3627   FragmentInfo getFragmentOrDefault() const {
3628     return Fragment.getValueOr(DefaultFragment);
3629   }
3630 
3631   static bool isDefaultFragment(const FragmentInfo F) {
3632     return F == DefaultFragment;
3633   }
3634 
3635   bool operator==(const DebugVariable &Other) const {
3636     return std::tie(Variable, Fragment, InlinedAt) ==
3637            std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
3638   }
3639 
3640   bool operator<(const DebugVariable &Other) const {
3641     return std::tie(Variable, Fragment, InlinedAt) <
3642            std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
3643   }
3644 };
3645 
3646 template <> struct DenseMapInfo<DebugVariable> {
3647   using FragmentInfo = DIExpression::FragmentInfo;
3648 
3649   /// Empty key: no key should be generated that has no DILocalVariable.
3650   static inline DebugVariable getEmptyKey() {
3651     return DebugVariable(nullptr, NoneType(), nullptr);
3652   }
3653 
3654   /// Difference in tombstone is that the Optional is meaningful.
3655   static inline DebugVariable getTombstoneKey() {
3656     return DebugVariable(nullptr, {{0, 0}}, nullptr);
3657   }
3658 
3659   static unsigned getHashValue(const DebugVariable &D) {
3660     unsigned HV = 0;
3661     const Optional<FragmentInfo> Fragment = D.getFragment();
3662     if (Fragment)
3663       HV = DenseMapInfo<FragmentInfo>::getHashValue(*Fragment);
3664 
3665     return hash_combine(D.getVariable(), HV, D.getInlinedAt());
3666   }
3667 
3668   static bool isEqual(const DebugVariable &A, const DebugVariable &B) {
3669     return A == B;
3670   }
3671 };
3672 
3673 } // end namespace llvm
3674 
3675 #undef DEFINE_MDNODE_GET_UNPACK_IMPL
3676 #undef DEFINE_MDNODE_GET_UNPACK
3677 #undef DEFINE_MDNODE_GET
3678 
3679 #endif // LLVM_IR_DEBUGINFOMETADATA_H
3680