xref: /freebsd/contrib/llvm-project/llvm/include/llvm/IR/DebugInfoMetadata.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
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/PointerUnion.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DbgVariableFragmentInfo.h"
25 #include "llvm/IR/Metadata.h"
26 #include "llvm/IR/PseudoProbe.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Discriminator.h"
31 #include <cassert>
32 #include <climits>
33 #include <cstddef>
34 #include <cstdint>
35 #include <iterator>
36 #include <optional>
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 namespace dwarf {
66 enum Tag : uint16_t;
67 }
68 
69 class DbgVariableIntrinsic;
70 class DbgVariableRecord;
71 
72 LLVM_ABI extern cl::opt<bool> EnableFSDiscriminator;
73 
74 class DITypeRefArray {
75   const MDTuple *N = nullptr;
76 
77 public:
78   DITypeRefArray() = default;
DITypeRefArray(const MDTuple * N)79   DITypeRefArray(const MDTuple *N) : N(N) {}
80 
81   explicit operator bool() const { return get(); }
82   explicit operator MDTuple *() const { return get(); }
83 
get()84   MDTuple *get() const { return const_cast<MDTuple *>(N); }
85   MDTuple *operator->() const { return get(); }
86   MDTuple &operator*() const { return *get(); }
87 
88   // FIXME: Fix callers and remove condition on N.
size()89   unsigned size() const { return N ? N->getNumOperands() : 0u; }
90   DIType *operator[](unsigned I) const {
91     return cast_or_null<DIType>(N->getOperand(I));
92   }
93 
94   class iterator {
95     MDNode::op_iterator I = nullptr;
96 
97   public:
98     using iterator_category = std::input_iterator_tag;
99     using value_type = DIType *;
100     using difference_type = std::ptrdiff_t;
101     using pointer = void;
102     using reference = DIType *;
103 
104     iterator() = default;
iterator(MDNode::op_iterator I)105     explicit iterator(MDNode::op_iterator I) : I(I) {}
106 
107     DIType *operator*() const { return cast_or_null<DIType>(*I); }
108 
109     iterator &operator++() {
110       ++I;
111       return *this;
112     }
113 
114     iterator operator++(int) {
115       iterator Temp(*this);
116       ++I;
117       return Temp;
118     }
119 
120     bool operator==(const iterator &X) const { return I == X.I; }
121     bool operator!=(const iterator &X) const { return I != X.I; }
122   };
123 
124   // FIXME: Fix callers and remove condition on N.
begin()125   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
end()126   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
127 };
128 
129 /// Tagged DWARF-like metadata node.
130 ///
131 /// A metadata node with a DWARF tag (i.e., a constant named \c DW_TAG_*,
132 /// defined in llvm/BinaryFormat/Dwarf.h).  Called \a DINode because it's
133 /// potentially used for non-DWARF output.
134 ///
135 /// Uses the SubclassData16 Metadata slot.
136 class DINode : public MDNode {
137   friend class LLVMContextImpl;
138   friend class MDNode;
139 
140 protected:
141   DINode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
142          ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = {})
MDNode(C,ID,Storage,Ops1,Ops2)143       : MDNode(C, ID, Storage, Ops1, Ops2) {
144     assert(Tag < 1u << 16);
145     SubclassData16 = Tag;
146   }
147   ~DINode() = default;
148 
getOperandAs(unsigned I)149   template <class Ty> Ty *getOperandAs(unsigned I) const {
150     return cast_or_null<Ty>(getOperand(I));
151   }
152 
getStringOperand(unsigned I)153   StringRef getStringOperand(unsigned I) const {
154     if (auto *S = getOperandAs<MDString>(I))
155       return S->getString();
156     return StringRef();
157   }
158 
getCanonicalMDString(LLVMContext & Context,StringRef S)159   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
160     if (S.empty())
161       return nullptr;
162     return MDString::get(Context, S);
163   }
164 
165   /// Allow subclasses to mutate the tag.
setTag(unsigned Tag)166   void setTag(unsigned Tag) { SubclassData16 = Tag; }
167 
168 public:
169   LLVM_ABI dwarf::Tag getTag() const;
170 
171   /// Debug info flags.
172   ///
173   /// The three accessibility flags are mutually exclusive and rolled together
174   /// in the first two bits.
175   enum DIFlags : uint32_t {
176 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = ID,
177 #define DI_FLAG_LARGEST_NEEDED
178 #include "llvm/IR/DebugInfoFlags.def"
179     FlagAccessibility = FlagPrivate | FlagProtected | FlagPublic,
180     FlagPtrToMemberRep = FlagSingleInheritance | FlagMultipleInheritance |
181                          FlagVirtualInheritance,
182     LLVM_MARK_AS_BITMASK_ENUM(FlagLargest)
183   };
184 
185   LLVM_ABI static DIFlags getFlag(StringRef Flag);
186   LLVM_ABI static StringRef getFlagString(DIFlags Flag);
187 
188   /// Split up a flags bitfield.
189   ///
190   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
191   /// any remaining (unrecognized) bits.
192   LLVM_ABI static DIFlags splitFlags(DIFlags Flags,
193                                      SmallVectorImpl<DIFlags> &SplitFlags);
194 
classof(const Metadata * MD)195   static bool classof(const Metadata *MD) {
196     switch (MD->getMetadataID()) {
197     default:
198       return false;
199     case GenericDINodeKind:
200     case DISubrangeKind:
201     case DIEnumeratorKind:
202     case DIBasicTypeKind:
203     case DIFixedPointTypeKind:
204     case DIStringTypeKind:
205     case DISubrangeTypeKind:
206     case DIDerivedTypeKind:
207     case DICompositeTypeKind:
208     case DISubroutineTypeKind:
209     case DIFileKind:
210     case DICompileUnitKind:
211     case DISubprogramKind:
212     case DILexicalBlockKind:
213     case DILexicalBlockFileKind:
214     case DINamespaceKind:
215     case DICommonBlockKind:
216     case DITemplateTypeParameterKind:
217     case DITemplateValueParameterKind:
218     case DIGlobalVariableKind:
219     case DILocalVariableKind:
220     case DILabelKind:
221     case DIObjCPropertyKind:
222     case DIImportedEntityKind:
223     case DIModuleKind:
224     case DIGenericSubrangeKind:
225     case DIAssignIDKind:
226       return true;
227     }
228   }
229 };
230 
231 /// Generic tagged DWARF-like metadata node.
232 ///
233 /// An un-specialized DWARF-like metadata node.  The first operand is a
234 /// (possibly empty) null-separated \a MDString header that contains arbitrary
235 /// fields.  The remaining operands are \a dwarf_operands(), and are pointers
236 /// to other metadata.
237 ///
238 /// Uses the SubclassData32 Metadata slot.
239 class GenericDINode : public DINode {
240   friend class LLVMContextImpl;
241   friend class MDNode;
242 
GenericDINode(LLVMContext & C,StorageType Storage,unsigned Hash,unsigned Tag,ArrayRef<Metadata * > Ops1,ArrayRef<Metadata * > Ops2)243   GenericDINode(LLVMContext &C, StorageType Storage, unsigned Hash,
244                 unsigned Tag, ArrayRef<Metadata *> Ops1,
245                 ArrayRef<Metadata *> Ops2)
246       : DINode(C, GenericDINodeKind, Storage, Tag, Ops1, Ops2) {
247     setHash(Hash);
248   }
~GenericDINode()249   ~GenericDINode() { dropAllReferences(); }
250 
setHash(unsigned Hash)251   void setHash(unsigned Hash) { SubclassData32 = Hash; }
252   void recalculateHash();
253 
254   static GenericDINode *getImpl(LLVMContext &Context, unsigned Tag,
255                                 StringRef Header, ArrayRef<Metadata *> DwarfOps,
256                                 StorageType Storage, bool ShouldCreate = true) {
257     return getImpl(Context, Tag, getCanonicalMDString(Context, Header),
258                    DwarfOps, Storage, ShouldCreate);
259   }
260 
261   LLVM_ABI static GenericDINode *getImpl(LLVMContext &Context, unsigned Tag,
262                                          MDString *Header,
263                                          ArrayRef<Metadata *> DwarfOps,
264                                          StorageType Storage,
265                                          bool ShouldCreate = true);
266 
cloneImpl()267   TempGenericDINode cloneImpl() const {
268     return getTemporary(getContext(), getTag(), getHeader(),
269                         SmallVector<Metadata *, 4>(dwarf_operands()));
270   }
271 
272 public:
getHash()273   unsigned getHash() const { return SubclassData32; }
274 
275   DEFINE_MDNODE_GET(GenericDINode,
276                     (unsigned Tag, StringRef Header,
277                      ArrayRef<Metadata *> DwarfOps),
278                     (Tag, Header, DwarfOps))
279   DEFINE_MDNODE_GET(GenericDINode,
280                     (unsigned Tag, MDString *Header,
281                      ArrayRef<Metadata *> DwarfOps),
282                     (Tag, Header, DwarfOps))
283 
284   /// Return a (temporary) clone of this.
clone()285   TempGenericDINode clone() const { return cloneImpl(); }
286 
287   LLVM_ABI dwarf::Tag getTag() const;
getHeader()288   StringRef getHeader() const { return getStringOperand(0); }
getRawHeader()289   MDString *getRawHeader() const { return getOperandAs<MDString>(0); }
290 
dwarf_op_begin()291   op_iterator dwarf_op_begin() const { return op_begin() + 1; }
dwarf_op_end()292   op_iterator dwarf_op_end() const { return op_end(); }
dwarf_operands()293   op_range dwarf_operands() const {
294     return op_range(dwarf_op_begin(), dwarf_op_end());
295   }
296 
getNumDwarfOperands()297   unsigned getNumDwarfOperands() const { return getNumOperands() - 1; }
getDwarfOperand(unsigned I)298   const MDOperand &getDwarfOperand(unsigned I) const {
299     return getOperand(I + 1);
300   }
replaceDwarfOperandWith(unsigned I,Metadata * New)301   void replaceDwarfOperandWith(unsigned I, Metadata *New) {
302     replaceOperandWith(I + 1, New);
303   }
304 
classof(const Metadata * MD)305   static bool classof(const Metadata *MD) {
306     return MD->getMetadataID() == GenericDINodeKind;
307   }
308 };
309 
310 /// Assignment ID.
311 /// Used to link stores (as an attachment) and dbg.assigns (as an operand).
312 /// DIAssignID metadata is never uniqued as we compare instances using
313 /// referential equality (the instance/address is the ID).
314 class DIAssignID : public MDNode {
315   friend class LLVMContextImpl;
316   friend class MDNode;
317 
DIAssignID(LLVMContext & C,StorageType Storage)318   DIAssignID(LLVMContext &C, StorageType Storage)
319       : MDNode(C, DIAssignIDKind, Storage, {}) {}
320 
~DIAssignID()321   ~DIAssignID() { dropAllReferences(); }
322 
323   LLVM_ABI static DIAssignID *getImpl(LLVMContext &Context, StorageType Storage,
324                                       bool ShouldCreate = true);
325 
cloneImpl()326   TempDIAssignID cloneImpl() const { return getTemporary(getContext()); }
327 
328 public:
329   // This node has no operands to replace.
330   void replaceOperandWith(unsigned I, Metadata *New) = delete;
331 
getAllDbgVariableRecordUsers()332   SmallVector<DbgVariableRecord *> getAllDbgVariableRecordUsers() {
333     return Context.getReplaceableUses()->getAllDbgVariableRecordUsers();
334   }
335 
getDistinct(LLVMContext & Context)336   static DIAssignID *getDistinct(LLVMContext &Context) {
337     return getImpl(Context, Distinct);
338   }
getTemporary(LLVMContext & Context)339   static TempDIAssignID getTemporary(LLVMContext &Context) {
340     return TempDIAssignID(getImpl(Context, Temporary));
341   }
342   // NOTE: Do not define get(LLVMContext&) - see class comment.
343 
classof(const Metadata * MD)344   static bool classof(const Metadata *MD) {
345     return MD->getMetadataID() == DIAssignIDKind;
346   }
347 };
348 
349 /// Array subrange.
350 class DISubrange : public DINode {
351   friend class LLVMContextImpl;
352   friend class MDNode;
353 
354   DISubrange(LLVMContext &C, StorageType Storage, ArrayRef<Metadata *> Ops);
355 
356   ~DISubrange() = default;
357 
358   LLVM_ABI static DISubrange *getImpl(LLVMContext &Context, int64_t Count,
359                                       int64_t LowerBound, StorageType Storage,
360                                       bool ShouldCreate = true);
361 
362   LLVM_ABI static DISubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
363                                       int64_t LowerBound, StorageType Storage,
364                                       bool ShouldCreate = true);
365 
366   LLVM_ABI static DISubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
367                                       Metadata *LowerBound,
368                                       Metadata *UpperBound, Metadata *Stride,
369                                       StorageType Storage,
370                                       bool ShouldCreate = true);
371 
cloneImpl()372   TempDISubrange cloneImpl() const {
373     return getTemporary(getContext(), getRawCountNode(), getRawLowerBound(),
374                         getRawUpperBound(), getRawStride());
375   }
376 
377 public:
378   DEFINE_MDNODE_GET(DISubrange, (int64_t Count, int64_t LowerBound = 0),
379                     (Count, LowerBound))
380 
381   DEFINE_MDNODE_GET(DISubrange, (Metadata * CountNode, int64_t LowerBound = 0),
382                     (CountNode, LowerBound))
383 
384   DEFINE_MDNODE_GET(DISubrange,
385                     (Metadata * CountNode, Metadata *LowerBound,
386                      Metadata *UpperBound, Metadata *Stride),
387                     (CountNode, LowerBound, UpperBound, Stride))
388 
clone()389   TempDISubrange clone() const { return cloneImpl(); }
390 
getRawCountNode()391   Metadata *getRawCountNode() const { return getOperand(0).get(); }
392 
getRawLowerBound()393   Metadata *getRawLowerBound() const { return getOperand(1).get(); }
394 
getRawUpperBound()395   Metadata *getRawUpperBound() const { return getOperand(2).get(); }
396 
getRawStride()397   Metadata *getRawStride() const { return getOperand(3).get(); }
398 
399   typedef PointerUnion<ConstantInt *, DIVariable *, DIExpression *> BoundType;
400 
401   LLVM_ABI BoundType getCount() const;
402 
403   LLVM_ABI BoundType getLowerBound() const;
404 
405   LLVM_ABI BoundType getUpperBound() const;
406 
407   LLVM_ABI BoundType getStride() const;
408 
classof(const Metadata * MD)409   static bool classof(const Metadata *MD) {
410     return MD->getMetadataID() == DISubrangeKind;
411   }
412 };
413 
414 class DIGenericSubrange : public DINode {
415   friend class LLVMContextImpl;
416   friend class MDNode;
417 
418   DIGenericSubrange(LLVMContext &C, StorageType Storage,
419                     ArrayRef<Metadata *> Ops);
420 
421   ~DIGenericSubrange() = default;
422 
423   LLVM_ABI static DIGenericSubrange *
424   getImpl(LLVMContext &Context, Metadata *CountNode, Metadata *LowerBound,
425           Metadata *UpperBound, Metadata *Stride, StorageType Storage,
426           bool ShouldCreate = true);
427 
cloneImpl()428   TempDIGenericSubrange cloneImpl() const {
429     return getTemporary(getContext(), getRawCountNode(), getRawLowerBound(),
430                         getRawUpperBound(), getRawStride());
431   }
432 
433 public:
434   DEFINE_MDNODE_GET(DIGenericSubrange,
435                     (Metadata * CountNode, Metadata *LowerBound,
436                      Metadata *UpperBound, Metadata *Stride),
437                     (CountNode, LowerBound, UpperBound, Stride))
438 
clone()439   TempDIGenericSubrange clone() const { return cloneImpl(); }
440 
getRawCountNode()441   Metadata *getRawCountNode() const { return getOperand(0).get(); }
getRawLowerBound()442   Metadata *getRawLowerBound() const { return getOperand(1).get(); }
getRawUpperBound()443   Metadata *getRawUpperBound() const { return getOperand(2).get(); }
getRawStride()444   Metadata *getRawStride() const { return getOperand(3).get(); }
445 
446   using BoundType = PointerUnion<DIVariable *, DIExpression *>;
447 
448   LLVM_ABI BoundType getCount() const;
449   LLVM_ABI BoundType getLowerBound() const;
450   LLVM_ABI BoundType getUpperBound() const;
451   LLVM_ABI BoundType getStride() const;
452 
classof(const Metadata * MD)453   static bool classof(const Metadata *MD) {
454     return MD->getMetadataID() == DIGenericSubrangeKind;
455   }
456 };
457 
458 /// Enumeration value.
459 ///
460 /// TODO: Add a pointer to the context (DW_TAG_enumeration_type) once that no
461 /// longer creates a type cycle.
462 class DIEnumerator : public DINode {
463   friend class LLVMContextImpl;
464   friend class MDNode;
465 
466   APInt Value;
467   LLVM_ABI DIEnumerator(LLVMContext &C, StorageType Storage, const APInt &Value,
468                         bool IsUnsigned, ArrayRef<Metadata *> Ops);
DIEnumerator(LLVMContext & C,StorageType Storage,int64_t Value,bool IsUnsigned,ArrayRef<Metadata * > Ops)469   DIEnumerator(LLVMContext &C, StorageType Storage, int64_t Value,
470                bool IsUnsigned, ArrayRef<Metadata *> Ops)
471       : DIEnumerator(C, Storage, APInt(64, Value, !IsUnsigned), IsUnsigned,
472                      Ops) {}
473   ~DIEnumerator() = default;
474 
475   static DIEnumerator *getImpl(LLVMContext &Context, const APInt &Value,
476                                bool IsUnsigned, StringRef Name,
477                                StorageType Storage, bool ShouldCreate = true) {
478     return getImpl(Context, Value, IsUnsigned,
479                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
480   }
481   LLVM_ABI static DIEnumerator *getImpl(LLVMContext &Context,
482                                         const APInt &Value, bool IsUnsigned,
483                                         MDString *Name, StorageType Storage,
484                                         bool ShouldCreate = true);
485 
cloneImpl()486   TempDIEnumerator cloneImpl() const {
487     return getTemporary(getContext(), getValue(), isUnsigned(), getName());
488   }
489 
490 public:
491   DEFINE_MDNODE_GET(DIEnumerator,
492                     (int64_t Value, bool IsUnsigned, StringRef Name),
493                     (APInt(64, Value, !IsUnsigned), IsUnsigned, Name))
494   DEFINE_MDNODE_GET(DIEnumerator,
495                     (int64_t Value, bool IsUnsigned, MDString *Name),
496                     (APInt(64, Value, !IsUnsigned), IsUnsigned, Name))
497   DEFINE_MDNODE_GET(DIEnumerator,
498                     (APInt Value, bool IsUnsigned, StringRef Name),
499                     (Value, IsUnsigned, Name))
500   DEFINE_MDNODE_GET(DIEnumerator,
501                     (APInt Value, bool IsUnsigned, MDString *Name),
502                     (Value, IsUnsigned, Name))
503 
clone()504   TempDIEnumerator clone() const { return cloneImpl(); }
505 
getValue()506   const APInt &getValue() const { return Value; }
isUnsigned()507   bool isUnsigned() const { return SubclassData32; }
getName()508   StringRef getName() const { return getStringOperand(0); }
509 
getRawName()510   MDString *getRawName() const { return getOperandAs<MDString>(0); }
511 
classof(const Metadata * MD)512   static bool classof(const Metadata *MD) {
513     return MD->getMetadataID() == DIEnumeratorKind;
514   }
515 };
516 
517 /// Base class for scope-like contexts.
518 ///
519 /// Base class for lexical scopes and types (which are also declaration
520 /// contexts).
521 ///
522 /// TODO: Separate the concepts of declaration contexts and lexical scopes.
523 class DIScope : public DINode {
524 protected:
DIScope(LLVMContext & C,unsigned ID,StorageType Storage,unsigned Tag,ArrayRef<Metadata * > Ops)525   DIScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
526           ArrayRef<Metadata *> Ops)
527       : DINode(C, ID, Storage, Tag, Ops) {}
528   ~DIScope() = default;
529 
530 public:
getFile()531   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
532 
533   inline StringRef getFilename() const;
534   inline StringRef getDirectory() const;
535   inline std::optional<StringRef> getSource() const;
536 
537   LLVM_ABI StringRef getName() const;
538   LLVM_ABI DIScope *getScope() const;
539 
540   /// Return the raw underlying file.
541   ///
542   /// A \a DIFile is a \a DIScope, but it doesn't point at a separate file (it
543   /// \em is the file).  If \c this is an \a DIFile, we need to return \c this.
544   /// Otherwise, return the first operand, which is where all other subclasses
545   /// store their file pointer.
getRawFile()546   Metadata *getRawFile() const {
547     return isa<DIFile>(this) ? const_cast<DIScope *>(this)
548                              : static_cast<Metadata *>(getOperand(0));
549   }
550 
classof(const Metadata * MD)551   static bool classof(const Metadata *MD) {
552     switch (MD->getMetadataID()) {
553     default:
554       return false;
555     case DIBasicTypeKind:
556     case DIFixedPointTypeKind:
557     case DIStringTypeKind:
558     case DISubrangeTypeKind:
559     case DIDerivedTypeKind:
560     case DICompositeTypeKind:
561     case DISubroutineTypeKind:
562     case DIFileKind:
563     case DICompileUnitKind:
564     case DISubprogramKind:
565     case DILexicalBlockKind:
566     case DILexicalBlockFileKind:
567     case DINamespaceKind:
568     case DICommonBlockKind:
569     case DIModuleKind:
570       return true;
571     }
572   }
573 };
574 
575 /// File.
576 ///
577 /// TODO: Merge with directory/file node (including users).
578 /// TODO: Canonicalize paths on creation.
579 class DIFile : public DIScope {
580   friend class LLVMContextImpl;
581   friend class MDNode;
582 
583 public:
584   /// Which algorithm (e.g. MD5) a checksum was generated with.
585   ///
586   /// The encoding is explicit because it is used directly in Bitcode. The
587   /// value 0 is reserved to indicate the absence of a checksum in Bitcode.
588   enum ChecksumKind {
589     // The first variant was originally CSK_None, encoded as 0. The new
590     // internal representation removes the need for this by wrapping the
591     // ChecksumInfo in an Optional, but to preserve Bitcode compatibility the 0
592     // encoding is reserved.
593     CSK_MD5 = 1,
594     CSK_SHA1 = 2,
595     CSK_SHA256 = 3,
596     CSK_Last = CSK_SHA256 // Should be last enumeration.
597   };
598 
599   /// A single checksum, represented by a \a Kind and a \a Value (a string).
600   template <typename T> struct ChecksumInfo {
601     /// The kind of checksum which \a Value encodes.
602     ChecksumKind Kind;
603     /// The string value of the checksum.
604     T Value;
605 
ChecksumInfoChecksumInfo606     ChecksumInfo(ChecksumKind Kind, T Value) : Kind(Kind), Value(Value) {}
607     ~ChecksumInfo() = default;
608     bool operator==(const ChecksumInfo<T> &X) const {
609       return Kind == X.Kind && Value == X.Value;
610     }
611     bool operator!=(const ChecksumInfo<T> &X) const { return !(*this == X); }
getKindAsStringChecksumInfo612     StringRef getKindAsString() const { return getChecksumKindAsString(Kind); }
613   };
614 
615 private:
616   std::optional<ChecksumInfo<MDString *>> Checksum;
617   /// An optional source. A nullptr means none.
618   MDString *Source;
619 
620   DIFile(LLVMContext &C, StorageType Storage,
621          std::optional<ChecksumInfo<MDString *>> CS, MDString *Src,
622          ArrayRef<Metadata *> Ops);
623   ~DIFile() = default;
624 
625   static DIFile *getImpl(LLVMContext &Context, StringRef Filename,
626                          StringRef Directory,
627                          std::optional<ChecksumInfo<StringRef>> CS,
628                          std::optional<StringRef> Source, StorageType Storage,
629                          bool ShouldCreate = true) {
630     std::optional<ChecksumInfo<MDString *>> MDChecksum;
631     if (CS)
632       MDChecksum.emplace(CS->Kind, getCanonicalMDString(Context, CS->Value));
633     return getImpl(Context, getCanonicalMDString(Context, Filename),
634                    getCanonicalMDString(Context, Directory), MDChecksum,
635                    Source ? MDString::get(Context, *Source) : nullptr, Storage,
636                    ShouldCreate);
637   }
638   LLVM_ABI static DIFile *getImpl(LLVMContext &Context, MDString *Filename,
639                                   MDString *Directory,
640                                   std::optional<ChecksumInfo<MDString *>> CS,
641                                   MDString *Source, StorageType Storage,
642                                   bool ShouldCreate = true);
643 
cloneImpl()644   TempDIFile cloneImpl() const {
645     return getTemporary(getContext(), getFilename(), getDirectory(),
646                         getChecksum(), getSource());
647   }
648 
649 public:
650   DEFINE_MDNODE_GET(DIFile,
651                     (StringRef Filename, StringRef Directory,
652                      std::optional<ChecksumInfo<StringRef>> CS = std::nullopt,
653                      std::optional<StringRef> Source = std::nullopt),
654                     (Filename, Directory, CS, Source))
655   DEFINE_MDNODE_GET(DIFile,
656                     (MDString * Filename, MDString *Directory,
657                      std::optional<ChecksumInfo<MDString *>> CS = std::nullopt,
658                      MDString *Source = nullptr),
659                     (Filename, Directory, CS, Source))
660 
clone()661   TempDIFile clone() const { return cloneImpl(); }
662 
getFilename()663   StringRef getFilename() const { return getStringOperand(0); }
getDirectory()664   StringRef getDirectory() const { return getStringOperand(1); }
getChecksum()665   std::optional<ChecksumInfo<StringRef>> getChecksum() const {
666     std::optional<ChecksumInfo<StringRef>> StringRefChecksum;
667     if (Checksum)
668       StringRefChecksum.emplace(Checksum->Kind, Checksum->Value->getString());
669     return StringRefChecksum;
670   }
getSource()671   std::optional<StringRef> getSource() const {
672     return Source ? std::optional<StringRef>(Source->getString())
673                   : std::nullopt;
674   }
675 
getRawFilename()676   MDString *getRawFilename() const { return getOperandAs<MDString>(0); }
getRawDirectory()677   MDString *getRawDirectory() const { return getOperandAs<MDString>(1); }
getRawChecksum()678   std::optional<ChecksumInfo<MDString *>> getRawChecksum() const {
679     return Checksum;
680   }
getRawSource()681   MDString *getRawSource() const { return Source; }
682 
683   LLVM_ABI static StringRef getChecksumKindAsString(ChecksumKind CSKind);
684   LLVM_ABI static std::optional<ChecksumKind>
685   getChecksumKind(StringRef CSKindStr);
686 
classof(const Metadata * MD)687   static bool classof(const Metadata *MD) {
688     return MD->getMetadataID() == DIFileKind;
689   }
690 };
691 
getFilename()692 StringRef DIScope::getFilename() const {
693   if (auto *F = getFile())
694     return F->getFilename();
695   return "";
696 }
697 
getDirectory()698 StringRef DIScope::getDirectory() const {
699   if (auto *F = getFile())
700     return F->getDirectory();
701   return "";
702 }
703 
getSource()704 std::optional<StringRef> DIScope::getSource() const {
705   if (auto *F = getFile())
706     return F->getSource();
707   return std::nullopt;
708 }
709 
710 /// Base class for types.
711 ///
712 /// TODO: Remove the hardcoded name and context, since many types don't use
713 /// them.
714 /// TODO: Split up flags.
715 ///
716 /// Uses the SubclassData32 Metadata slot.
717 class DIType : public DIScope {
718   unsigned Line;
719   DIFlags Flags;
720   uint32_t NumExtraInhabitants;
721 
722 protected:
723   static constexpr unsigned N_OPERANDS = 5;
724 
DIType(LLVMContext & C,unsigned ID,StorageType Storage,unsigned Tag,unsigned Line,uint32_t AlignInBits,uint32_t NumExtraInhabitants,DIFlags Flags,ArrayRef<Metadata * > Ops)725   DIType(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
726          unsigned Line, uint32_t AlignInBits, uint32_t NumExtraInhabitants,
727          DIFlags Flags, ArrayRef<Metadata *> Ops)
728       : DIScope(C, ID, Storage, Tag, Ops) {
729     init(Line, AlignInBits, NumExtraInhabitants, Flags);
730   }
731   ~DIType() = default;
732 
init(unsigned Line,uint32_t AlignInBits,uint32_t NumExtraInhabitants,DIFlags Flags)733   void init(unsigned Line, uint32_t AlignInBits, uint32_t NumExtraInhabitants,
734             DIFlags Flags) {
735     this->Line = Line;
736     this->Flags = Flags;
737     this->SubclassData32 = AlignInBits;
738     this->NumExtraInhabitants = NumExtraInhabitants;
739   }
740 
741   /// Change fields in place.
mutate(unsigned Tag,unsigned Line,uint32_t AlignInBits,uint32_t NumExtraInhabitants,DIFlags Flags)742   void mutate(unsigned Tag, unsigned Line, uint32_t AlignInBits,
743               uint32_t NumExtraInhabitants, DIFlags Flags) {
744     assert(isDistinct() && "Only distinct nodes can mutate");
745     setTag(Tag);
746     init(Line, AlignInBits, NumExtraInhabitants, Flags);
747   }
748 
749 public:
clone()750   TempDIType clone() const {
751     return TempDIType(cast<DIType>(MDNode::clone().release()));
752   }
753 
getLine()754   unsigned getLine() const { return Line; }
755   LLVM_ABI uint32_t getAlignInBits() const;
getAlignInBytes()756   uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
getNumExtraInhabitants()757   uint32_t getNumExtraInhabitants() const { return NumExtraInhabitants; }
getFlags()758   DIFlags getFlags() const { return Flags; }
759 
getScope()760   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
getName()761   StringRef getName() const { return getStringOperand(2); }
762 
getRawScope()763   Metadata *getRawScope() const { return getOperand(1); }
getRawName()764   MDString *getRawName() const { return getOperandAs<MDString>(2); }
765 
getRawSizeInBits()766   Metadata *getRawSizeInBits() const { return getOperand(3); }
getSizeInBits()767   uint64_t getSizeInBits() const {
768     if (auto *MD = dyn_cast_or_null<ConstantAsMetadata>(getRawSizeInBits())) {
769       if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(MD->getValue()))
770         return CI->getZExtValue();
771     }
772     return 0;
773   }
774 
getRawOffsetInBits()775   Metadata *getRawOffsetInBits() const { return getOperand(4); }
getOffsetInBits()776   uint64_t getOffsetInBits() const {
777     if (auto *MD = dyn_cast_or_null<ConstantAsMetadata>(getRawOffsetInBits())) {
778       if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(MD->getValue()))
779         return CI->getZExtValue();
780     }
781     return 0;
782   }
783 
784   /// Returns a new temporary DIType with updated Flags
cloneWithFlags(DIFlags NewFlags)785   TempDIType cloneWithFlags(DIFlags NewFlags) const {
786     auto NewTy = clone();
787     NewTy->Flags = NewFlags;
788     return NewTy;
789   }
790 
isPrivate()791   bool isPrivate() const {
792     return (getFlags() & FlagAccessibility) == FlagPrivate;
793   }
isProtected()794   bool isProtected() const {
795     return (getFlags() & FlagAccessibility) == FlagProtected;
796   }
isPublic()797   bool isPublic() const {
798     return (getFlags() & FlagAccessibility) == FlagPublic;
799   }
isForwardDecl()800   bool isForwardDecl() const { return getFlags() & FlagFwdDecl; }
isAppleBlockExtension()801   bool isAppleBlockExtension() const { return getFlags() & FlagAppleBlock; }
isVirtual()802   bool isVirtual() const { return getFlags() & FlagVirtual; }
isArtificial()803   bool isArtificial() const { return getFlags() & FlagArtificial; }
isObjectPointer()804   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
isObjcClassComplete()805   bool isObjcClassComplete() const {
806     return getFlags() & FlagObjcClassComplete;
807   }
isVector()808   bool isVector() const { return getFlags() & FlagVector; }
isBitField()809   bool isBitField() const { return getFlags() & FlagBitField; }
isStaticMember()810   bool isStaticMember() const { return getFlags() & FlagStaticMember; }
isLValueReference()811   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
isRValueReference()812   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
isTypePassByValue()813   bool isTypePassByValue() const { return getFlags() & FlagTypePassByValue; }
isTypePassByReference()814   bool isTypePassByReference() const {
815     return getFlags() & FlagTypePassByReference;
816   }
isBigEndian()817   bool isBigEndian() const { return getFlags() & FlagBigEndian; }
isLittleEndian()818   bool isLittleEndian() const { return getFlags() & FlagLittleEndian; }
getExportSymbols()819   bool getExportSymbols() const { return getFlags() & FlagExportSymbols; }
820 
classof(const Metadata * MD)821   static bool classof(const Metadata *MD) {
822     switch (MD->getMetadataID()) {
823     default:
824       return false;
825     case DIBasicTypeKind:
826     case DIFixedPointTypeKind:
827     case DIStringTypeKind:
828     case DISubrangeTypeKind:
829     case DIDerivedTypeKind:
830     case DICompositeTypeKind:
831     case DISubroutineTypeKind:
832       return true;
833     }
834   }
835 };
836 
837 /// Basic type, like 'int' or 'float'.
838 ///
839 /// TODO: Split out DW_TAG_unspecified_type.
840 /// TODO: Drop unused accessors.
841 class DIBasicType : public DIType {
842   friend class LLVMContextImpl;
843   friend class MDNode;
844 
845   unsigned Encoding;
846 
847 protected:
DIBasicType(LLVMContext & C,StorageType Storage,unsigned Tag,uint32_t AlignInBits,unsigned Encoding,uint32_t NumExtraInhabitants,DIFlags Flags,ArrayRef<Metadata * > Ops)848   DIBasicType(LLVMContext &C, StorageType Storage, unsigned Tag,
849               uint32_t AlignInBits, unsigned Encoding,
850               uint32_t NumExtraInhabitants, DIFlags Flags,
851               ArrayRef<Metadata *> Ops)
852       : DIType(C, DIBasicTypeKind, Storage, Tag, 0, AlignInBits,
853                NumExtraInhabitants, Flags, Ops),
854         Encoding(Encoding) {}
DIBasicType(LLVMContext & C,unsigned ID,StorageType Storage,unsigned Tag,uint32_t AlignInBits,unsigned Encoding,uint32_t NumExtraInhabitants,DIFlags Flags,ArrayRef<Metadata * > Ops)855   DIBasicType(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
856               uint32_t AlignInBits, unsigned Encoding,
857               uint32_t NumExtraInhabitants, DIFlags Flags,
858               ArrayRef<Metadata *> Ops)
859       : DIType(C, ID, Storage, Tag, 0, AlignInBits, NumExtraInhabitants, Flags,
860                Ops),
861         Encoding(Encoding) {}
862   ~DIBasicType() = default;
863 
864   static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
865                               StringRef Name, uint64_t SizeInBits,
866                               uint32_t AlignInBits, unsigned Encoding,
867                               uint32_t NumExtraInhabitants, DIFlags Flags,
868                               StorageType Storage, bool ShouldCreate = true) {
869     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
870                    SizeInBits, AlignInBits, Encoding, NumExtraInhabitants,
871                    Flags, Storage, ShouldCreate);
872   }
873   static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
874                               MDString *Name, uint64_t SizeInBits,
875                               uint32_t AlignInBits, unsigned Encoding,
876                               uint32_t NumExtraInhabitants, DIFlags Flags,
877                               StorageType Storage, bool ShouldCreate = true) {
878     auto *SizeInBitsNode = ConstantAsMetadata::get(
879         ConstantInt::get(Type::getInt64Ty(Context), SizeInBits));
880     return getImpl(Context, Tag, Name, SizeInBitsNode, AlignInBits, Encoding,
881                    NumExtraInhabitants, Flags, Storage, ShouldCreate);
882   }
883   LLVM_ABI static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
884                                        MDString *Name, Metadata *SizeInBits,
885                                        uint32_t AlignInBits, unsigned Encoding,
886                                        uint32_t NumExtraInhabitants,
887                                        DIFlags Flags, StorageType Storage,
888                                        bool ShouldCreate = true);
889 
cloneImpl()890   TempDIBasicType cloneImpl() const {
891     return getTemporary(getContext(), getTag(), getRawName(),
892                         getRawSizeInBits(), getAlignInBits(), getEncoding(),
893                         getNumExtraInhabitants(), getFlags());
894   }
895 
896 public:
897   DEFINE_MDNODE_GET(DIBasicType, (unsigned Tag, StringRef Name),
898                     (Tag, Name, 0, 0, 0, 0, FlagZero))
899   DEFINE_MDNODE_GET(DIBasicType,
900                     (unsigned Tag, StringRef Name, uint64_t SizeInBits),
901                     (Tag, Name, SizeInBits, 0, 0, 0, FlagZero))
902   DEFINE_MDNODE_GET(DIBasicType,
903                     (unsigned Tag, MDString *Name, uint64_t SizeInBits),
904                     (Tag, Name, SizeInBits, 0, 0, 0, FlagZero))
905   DEFINE_MDNODE_GET(DIBasicType,
906                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
907                      uint32_t AlignInBits, unsigned Encoding, DIFlags Flags),
908                     (Tag, Name, SizeInBits, AlignInBits, Encoding, 0, Flags))
909   DEFINE_MDNODE_GET(DIBasicType,
910                     (unsigned Tag, MDString *Name, uint64_t SizeInBits,
911                      uint32_t AlignInBits, unsigned Encoding, DIFlags Flags),
912                     (Tag, Name, SizeInBits, AlignInBits, Encoding, 0, Flags))
913   DEFINE_MDNODE_GET(DIBasicType,
914                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
915                      uint32_t AlignInBits, unsigned Encoding,
916                      uint32_t NumExtraInhabitants, DIFlags Flags),
917                     (Tag, Name, SizeInBits, AlignInBits, Encoding,
918                      NumExtraInhabitants, Flags))
919   DEFINE_MDNODE_GET(DIBasicType,
920                     (unsigned Tag, MDString *Name, uint64_t SizeInBits,
921                      uint32_t AlignInBits, unsigned Encoding,
922                      uint32_t NumExtraInhabitants, DIFlags Flags),
923                     (Tag, Name, SizeInBits, AlignInBits, Encoding,
924                      NumExtraInhabitants, Flags))
925   DEFINE_MDNODE_GET(DIBasicType,
926                     (unsigned Tag, MDString *Name, Metadata *SizeInBits,
927                      uint32_t AlignInBits, unsigned Encoding,
928                      uint32_t NumExtraInhabitants, DIFlags Flags),
929                     (Tag, Name, SizeInBits, AlignInBits, Encoding,
930                      NumExtraInhabitants, Flags))
931 
clone()932   TempDIBasicType clone() const { return cloneImpl(); }
933 
getEncoding()934   unsigned getEncoding() const { return Encoding; }
935 
936   enum class Signedness { Signed, Unsigned };
937 
938   /// Return the signedness of this type, or std::nullopt if this type is
939   /// neither signed nor unsigned.
940   LLVM_ABI std::optional<Signedness> getSignedness() const;
941 
classof(const Metadata * MD)942   static bool classof(const Metadata *MD) {
943     return MD->getMetadataID() == DIBasicTypeKind ||
944            MD->getMetadataID() == DIFixedPointTypeKind;
945   }
946 };
947 
948 /// Fixed-point type.
949 class DIFixedPointType : public DIBasicType {
950   friend class LLVMContextImpl;
951   friend class MDNode;
952 
953   // Actually FixedPointKind.
954   unsigned Kind;
955   // Used for binary and decimal.
956   int Factor;
957   // Used for rational.
958   APInt Numerator;
959   APInt Denominator;
960 
DIFixedPointType(LLVMContext & C,StorageType Storage,unsigned Tag,uint32_t AlignInBits,unsigned Encoding,DIFlags Flags,unsigned Kind,int Factor,ArrayRef<Metadata * > Ops)961   DIFixedPointType(LLVMContext &C, StorageType Storage, unsigned Tag,
962                    uint32_t AlignInBits, unsigned Encoding, DIFlags Flags,
963                    unsigned Kind, int Factor, ArrayRef<Metadata *> Ops)
964       : DIBasicType(C, DIFixedPointTypeKind, Storage, Tag, AlignInBits,
965                     Encoding, 0, Flags, Ops),
966         Kind(Kind), Factor(Factor) {
967     assert(Kind == FixedPointBinary || Kind == FixedPointDecimal);
968   }
DIFixedPointType(LLVMContext & C,StorageType Storage,unsigned Tag,uint32_t AlignInBits,unsigned Encoding,DIFlags Flags,unsigned Kind,APInt Numerator,APInt Denominator,ArrayRef<Metadata * > Ops)969   DIFixedPointType(LLVMContext &C, StorageType Storage, unsigned Tag,
970                    uint32_t AlignInBits, unsigned Encoding, DIFlags Flags,
971                    unsigned Kind, APInt Numerator, APInt Denominator,
972                    ArrayRef<Metadata *> Ops)
973       : DIBasicType(C, DIFixedPointTypeKind, Storage, Tag, AlignInBits,
974                     Encoding, 0, Flags, Ops),
975         Kind(Kind), Factor(0), Numerator(Numerator), Denominator(Denominator) {
976     assert(Kind == FixedPointRational);
977   }
DIFixedPointType(LLVMContext & C,StorageType Storage,unsigned Tag,uint32_t AlignInBits,unsigned Encoding,DIFlags Flags,unsigned Kind,int Factor,APInt Numerator,APInt Denominator,ArrayRef<Metadata * > Ops)978   DIFixedPointType(LLVMContext &C, StorageType Storage, unsigned Tag,
979                    uint32_t AlignInBits, unsigned Encoding, DIFlags Flags,
980                    unsigned Kind, int Factor, APInt Numerator,
981                    APInt Denominator, ArrayRef<Metadata *> Ops)
982       : DIBasicType(C, DIFixedPointTypeKind, Storage, Tag, AlignInBits,
983                     Encoding, 0, Flags, Ops),
984         Kind(Kind), Factor(Factor), Numerator(Numerator),
985         Denominator(Denominator) {}
986   ~DIFixedPointType() = default;
987 
988   static DIFixedPointType *
989   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name,
990           uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding,
991           DIFlags Flags, unsigned Kind, int Factor, APInt Numerator,
992           APInt Denominator, StorageType Storage, bool ShouldCreate = true) {
993     auto *SizeInBitsNode = ConstantAsMetadata::get(
994         ConstantInt::get(Type::getInt64Ty(Context), SizeInBits));
995     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
996                    SizeInBitsNode, AlignInBits, Encoding, Flags, Kind, Factor,
997                    Numerator, Denominator, Storage, ShouldCreate);
998   }
999   static DIFixedPointType *
1000   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name,
1001           Metadata *SizeInBits, uint32_t AlignInBits, unsigned Encoding,
1002           DIFlags Flags, unsigned Kind, int Factor, APInt Numerator,
1003           APInt Denominator, StorageType Storage, bool ShouldCreate = true) {
1004     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
1005                    SizeInBits, AlignInBits, Encoding, Flags, Kind, Factor,
1006                    Numerator, Denominator, Storage, ShouldCreate);
1007   }
1008   static DIFixedPointType *
1009   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name,
1010           uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding,
1011           DIFlags Flags, unsigned Kind, int Factor, APInt Numerator,
1012           APInt Denominator, StorageType Storage, bool ShouldCreate = true) {
1013     auto *SizeInBitsNode = ConstantAsMetadata::get(
1014         ConstantInt::get(Type::getInt64Ty(Context), SizeInBits));
1015     return getImpl(Context, Tag, Name, SizeInBitsNode, AlignInBits, Encoding,
1016                    Flags, Kind, Factor, Numerator, Denominator, Storage,
1017                    ShouldCreate);
1018   }
1019   LLVM_ABI static DIFixedPointType *
1020   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name,
1021           Metadata *SizeInBits, uint32_t AlignInBits, unsigned Encoding,
1022           DIFlags Flags, unsigned Kind, int Factor, APInt Numerator,
1023           APInt Denominator, StorageType Storage, bool ShouldCreate = true);
1024 
cloneImpl()1025   TempDIFixedPointType cloneImpl() const {
1026     return getTemporary(getContext(), getTag(), getRawName(),
1027                         getRawSizeInBits(), getAlignInBits(), getEncoding(),
1028                         getFlags(), Kind, Factor, Numerator, Denominator);
1029   }
1030 
1031 public:
1032   enum FixedPointKind : unsigned {
1033     /// Scale factor 2^Factor.
1034     FixedPointBinary,
1035     /// Scale factor 10^Factor.
1036     FixedPointDecimal,
1037     /// Arbitrary rational scale factor.
1038     FixedPointRational,
1039     LastFixedPointKind = FixedPointRational,
1040   };
1041 
1042   LLVM_ABI static std::optional<FixedPointKind>
1043   getFixedPointKind(StringRef Str);
1044   LLVM_ABI static const char *fixedPointKindString(FixedPointKind);
1045 
1046   DEFINE_MDNODE_GET(DIFixedPointType,
1047                     (unsigned Tag, MDString *Name, uint64_t SizeInBits,
1048                      uint32_t AlignInBits, unsigned Encoding, DIFlags Flags,
1049                      unsigned Kind, int Factor, APInt Numerator,
1050                      APInt Denominator),
1051                     (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags, Kind,
1052                      Factor, Numerator, Denominator))
1053   DEFINE_MDNODE_GET(DIFixedPointType,
1054                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
1055                      uint32_t AlignInBits, unsigned Encoding, DIFlags Flags,
1056                      unsigned Kind, int Factor, APInt Numerator,
1057                      APInt Denominator),
1058                     (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags, Kind,
1059                      Factor, Numerator, Denominator))
1060   DEFINE_MDNODE_GET(DIFixedPointType,
1061                     (unsigned Tag, MDString *Name, Metadata *SizeInBits,
1062                      uint32_t AlignInBits, unsigned Encoding, DIFlags Flags,
1063                      unsigned Kind, int Factor, APInt Numerator,
1064                      APInt Denominator),
1065                     (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags, Kind,
1066                      Factor, Numerator, Denominator))
1067 
clone()1068   TempDIFixedPointType clone() const { return cloneImpl(); }
1069 
isBinary()1070   bool isBinary() const { return Kind == FixedPointBinary; }
isDecimal()1071   bool isDecimal() const { return Kind == FixedPointDecimal; }
isRational()1072   bool isRational() const { return Kind == FixedPointRational; }
1073 
1074   LLVM_ABI bool isSigned() const;
1075 
getKind()1076   FixedPointKind getKind() const { return static_cast<FixedPointKind>(Kind); }
1077 
getFactorRaw()1078   int getFactorRaw() const { return Factor; }
getFactor()1079   int getFactor() const {
1080     assert(Kind == FixedPointBinary || Kind == FixedPointDecimal);
1081     return Factor;
1082   }
1083 
getNumeratorRaw()1084   const APInt &getNumeratorRaw() const { return Numerator; }
getNumerator()1085   const APInt &getNumerator() const {
1086     assert(Kind == FixedPointRational);
1087     return Numerator;
1088   }
1089 
getDenominatorRaw()1090   const APInt &getDenominatorRaw() const { return Denominator; }
getDenominator()1091   const APInt &getDenominator() const {
1092     assert(Kind == FixedPointRational);
1093     return Denominator;
1094   }
1095 
classof(const Metadata * MD)1096   static bool classof(const Metadata *MD) {
1097     return MD->getMetadataID() == DIFixedPointTypeKind;
1098   }
1099 };
1100 
1101 /// String type, Fortran CHARACTER(n)
1102 class DIStringType : public DIType {
1103   friend class LLVMContextImpl;
1104   friend class MDNode;
1105 
1106   static constexpr unsigned MY_FIRST_OPERAND = DIType::N_OPERANDS;
1107 
1108   unsigned Encoding;
1109 
DIStringType(LLVMContext & C,StorageType Storage,unsigned Tag,uint32_t AlignInBits,unsigned Encoding,ArrayRef<Metadata * > Ops)1110   DIStringType(LLVMContext &C, StorageType Storage, unsigned Tag,
1111                uint32_t AlignInBits, unsigned Encoding,
1112                ArrayRef<Metadata *> Ops)
1113       : DIType(C, DIStringTypeKind, Storage, Tag, 0, AlignInBits, 0, FlagZero,
1114                Ops),
1115         Encoding(Encoding) {}
1116   ~DIStringType() = default;
1117 
1118   static DIStringType *getImpl(LLVMContext &Context, unsigned Tag,
1119                                StringRef Name, Metadata *StringLength,
1120                                Metadata *StrLenExp, Metadata *StrLocationExp,
1121                                uint64_t SizeInBits, uint32_t AlignInBits,
1122                                unsigned Encoding, StorageType Storage,
1123                                bool ShouldCreate = true) {
1124     auto *SizeInBitsNode = ConstantAsMetadata::get(
1125         ConstantInt::get(Type::getInt64Ty(Context), SizeInBits));
1126     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
1127                    StringLength, StrLenExp, StrLocationExp, SizeInBitsNode,
1128                    AlignInBits, Encoding, Storage, ShouldCreate);
1129   }
1130   static DIStringType *getImpl(LLVMContext &Context, unsigned Tag,
1131                                MDString *Name, Metadata *StringLength,
1132                                Metadata *StrLenExp, Metadata *StrLocationExp,
1133                                uint64_t SizeInBits, uint32_t AlignInBits,
1134                                unsigned Encoding, StorageType Storage,
1135                                bool ShouldCreate = true) {
1136     auto *SizeInBitsNode = ConstantAsMetadata::get(
1137         ConstantInt::get(Type::getInt64Ty(Context), SizeInBits));
1138     return getImpl(Context, Tag, Name, StringLength, StrLenExp, StrLocationExp,
1139                    SizeInBitsNode, AlignInBits, Encoding, Storage,
1140                    ShouldCreate);
1141   }
1142   LLVM_ABI static DIStringType *
1143   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name,
1144           Metadata *StringLength, Metadata *StrLenExp, Metadata *StrLocationExp,
1145           Metadata *SizeInBits, uint32_t AlignInBits, unsigned Encoding,
1146           StorageType Storage, bool ShouldCreate = true);
1147 
cloneImpl()1148   TempDIStringType cloneImpl() const {
1149     return getTemporary(getContext(), getTag(), getRawName(),
1150                         getRawStringLength(), getRawStringLengthExp(),
1151                         getRawStringLocationExp(), getRawSizeInBits(),
1152                         getAlignInBits(), getEncoding());
1153   }
1154 
1155 public:
1156   DEFINE_MDNODE_GET(DIStringType,
1157                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
1158                      uint32_t AlignInBits),
1159                     (Tag, Name, nullptr, nullptr, nullptr, SizeInBits,
1160                      AlignInBits, 0))
1161   DEFINE_MDNODE_GET(DIStringType,
1162                     (unsigned Tag, MDString *Name, Metadata *StringLength,
1163                      Metadata *StringLengthExp, Metadata *StringLocationExp,
1164                      uint64_t SizeInBits, uint32_t AlignInBits,
1165                      unsigned Encoding),
1166                     (Tag, Name, StringLength, StringLengthExp,
1167                      StringLocationExp, SizeInBits, AlignInBits, Encoding))
1168   DEFINE_MDNODE_GET(DIStringType,
1169                     (unsigned Tag, StringRef Name, Metadata *StringLength,
1170                      Metadata *StringLengthExp, Metadata *StringLocationExp,
1171                      uint64_t SizeInBits, uint32_t AlignInBits,
1172                      unsigned Encoding),
1173                     (Tag, Name, StringLength, StringLengthExp,
1174                      StringLocationExp, SizeInBits, AlignInBits, Encoding))
1175   DEFINE_MDNODE_GET(DIStringType,
1176                     (unsigned Tag, MDString *Name, Metadata *StringLength,
1177                      Metadata *StringLengthExp, Metadata *StringLocationExp,
1178                      Metadata *SizeInBits, uint32_t AlignInBits,
1179                      unsigned Encoding),
1180                     (Tag, Name, StringLength, StringLengthExp,
1181                      StringLocationExp, SizeInBits, AlignInBits, Encoding))
1182 
clone()1183   TempDIStringType clone() const { return cloneImpl(); }
1184 
classof(const Metadata * MD)1185   static bool classof(const Metadata *MD) {
1186     return MD->getMetadataID() == DIStringTypeKind;
1187   }
1188 
getStringLength()1189   DIVariable *getStringLength() const {
1190     return cast_or_null<DIVariable>(getRawStringLength());
1191   }
1192 
getStringLengthExp()1193   DIExpression *getStringLengthExp() const {
1194     return cast_or_null<DIExpression>(getRawStringLengthExp());
1195   }
1196 
getStringLocationExp()1197   DIExpression *getStringLocationExp() const {
1198     return cast_or_null<DIExpression>(getRawStringLocationExp());
1199   }
1200 
getEncoding()1201   unsigned getEncoding() const { return Encoding; }
1202 
getRawStringLength()1203   Metadata *getRawStringLength() const { return getOperand(MY_FIRST_OPERAND); }
1204 
getRawStringLengthExp()1205   Metadata *getRawStringLengthExp() const {
1206     return getOperand(MY_FIRST_OPERAND + 1);
1207   }
1208 
getRawStringLocationExp()1209   Metadata *getRawStringLocationExp() const {
1210     return getOperand(MY_FIRST_OPERAND + 2);
1211   }
1212 };
1213 
1214 /// Derived types.
1215 ///
1216 /// This includes qualified types, pointers, references, friends, typedefs, and
1217 /// class members.
1218 ///
1219 /// TODO: Split out members (inheritance, fields, methods, etc.).
1220 class DIDerivedType : public DIType {
1221 public:
1222   /// Pointer authentication (__ptrauth) metadata.
1223   struct PtrAuthData {
1224     // RawData layout:
1225     // - Bits 0..3:  Key
1226     // - Bit  4:     IsAddressDiscriminated
1227     // - Bits 5..20: ExtraDiscriminator
1228     // - Bit  21:    IsaPointer
1229     // - Bit  22:    AuthenticatesNullValues
1230     unsigned RawData;
1231 
PtrAuthDataPtrAuthData1232     PtrAuthData(unsigned FromRawData) : RawData(FromRawData) {}
PtrAuthDataPtrAuthData1233     PtrAuthData(unsigned Key, bool IsDiscr, unsigned Discriminator,
1234                 bool IsaPointer, bool AuthenticatesNullValues) {
1235       assert(Key < 16);
1236       assert(Discriminator <= 0xffff);
1237       RawData = (Key << 0) | (IsDiscr ? (1 << 4) : 0) | (Discriminator << 5) |
1238                 (IsaPointer ? (1 << 21) : 0) |
1239                 (AuthenticatesNullValues ? (1 << 22) : 0);
1240     }
1241 
keyPtrAuthData1242     unsigned key() { return (RawData >> 0) & 0b1111; }
isAddressDiscriminatedPtrAuthData1243     bool isAddressDiscriminated() { return (RawData >> 4) & 1; }
extraDiscriminatorPtrAuthData1244     unsigned extraDiscriminator() { return (RawData >> 5) & 0xffff; }
isaPointerPtrAuthData1245     bool isaPointer() { return (RawData >> 21) & 1; }
authenticatesNullValuesPtrAuthData1246     bool authenticatesNullValues() { return (RawData >> 22) & 1; }
1247   };
1248 
1249 private:
1250   friend class LLVMContextImpl;
1251   friend class MDNode;
1252 
1253   static constexpr unsigned MY_FIRST_OPERAND = DIType::N_OPERANDS;
1254 
1255   /// The DWARF address space of the memory pointed to or referenced by a
1256   /// pointer or reference type respectively.
1257   std::optional<unsigned> DWARFAddressSpace;
1258 
DIDerivedType(LLVMContext & C,StorageType Storage,unsigned Tag,unsigned Line,uint32_t AlignInBits,std::optional<unsigned> DWARFAddressSpace,std::optional<PtrAuthData> PtrAuthData,DIFlags Flags,ArrayRef<Metadata * > Ops)1259   DIDerivedType(LLVMContext &C, StorageType Storage, unsigned Tag,
1260                 unsigned Line, uint32_t AlignInBits,
1261                 std::optional<unsigned> DWARFAddressSpace,
1262                 std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1263                 ArrayRef<Metadata *> Ops)
1264       : DIType(C, DIDerivedTypeKind, Storage, Tag, Line, AlignInBits, 0, Flags,
1265                Ops),
1266         DWARFAddressSpace(DWARFAddressSpace) {
1267     if (PtrAuthData)
1268       SubclassData32 = PtrAuthData->RawData;
1269   }
1270   ~DIDerivedType() = default;
1271   static DIDerivedType *
1272   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, DIFile *File,
1273           unsigned Line, DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
1274           uint32_t AlignInBits, uint64_t OffsetInBits,
1275           std::optional<unsigned> DWARFAddressSpace,
1276           std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1277           Metadata *ExtraData, DINodeArray Annotations, StorageType Storage,
1278           bool ShouldCreate = true) {
1279     auto *SizeInBitsNode = ConstantAsMetadata::get(
1280         ConstantInt::get(Type::getInt64Ty(Context), SizeInBits));
1281     auto *OffsetInBitsNode = ConstantAsMetadata::get(
1282         ConstantInt::get(Type::getInt64Ty(Context), OffsetInBits));
1283     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
1284                    Line, Scope, BaseType, SizeInBitsNode, AlignInBits,
1285                    OffsetInBitsNode, DWARFAddressSpace, PtrAuthData, Flags,
1286                    ExtraData, Annotations.get(), Storage, ShouldCreate);
1287   }
1288   static DIDerivedType *
1289   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, DIFile *File,
1290           unsigned Line, DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
1291           uint32_t AlignInBits, uint64_t OffsetInBits,
1292           std::optional<unsigned> DWARFAddressSpace,
1293           std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1294           Metadata *ExtraData, DINodeArray Annotations, StorageType Storage,
1295           bool ShouldCreate = true) {
1296     auto *SizeInBitsNode = ConstantAsMetadata::get(
1297         ConstantInt::get(Type::getInt64Ty(Context), SizeInBits));
1298     auto *OffsetInBitsNode = ConstantAsMetadata::get(
1299         ConstantInt::get(Type::getInt64Ty(Context), OffsetInBits));
1300     return getImpl(Context, Tag, Name, File, Line, Scope, BaseType,
1301                    SizeInBitsNode, AlignInBits, OffsetInBitsNode,
1302                    DWARFAddressSpace, PtrAuthData, Flags, ExtraData,
1303                    Annotations.get(), Storage, ShouldCreate);
1304   }
1305   static DIDerivedType *
1306   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, DIFile *File,
1307           unsigned Line, DIScope *Scope, DIType *BaseType, Metadata *SizeInBits,
1308           uint32_t AlignInBits, Metadata *OffsetInBits,
1309           std::optional<unsigned> DWARFAddressSpace,
1310           std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1311           Metadata *ExtraData, DINodeArray Annotations, StorageType Storage,
1312           bool ShouldCreate = true) {
1313     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
1314                    Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits,
1315                    DWARFAddressSpace, PtrAuthData, Flags, ExtraData,
1316                    Annotations.get(), Storage, ShouldCreate);
1317   }
1318   LLVM_ABI static DIDerivedType *
1319   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
1320           unsigned Line, Metadata *Scope, Metadata *BaseType,
1321           Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits,
1322           std::optional<unsigned> DWARFAddressSpace,
1323           std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1324           Metadata *ExtraData, Metadata *Annotations, StorageType Storage,
1325           bool ShouldCreate = true);
1326 
cloneImpl()1327   TempDIDerivedType cloneImpl() const {
1328     return getTemporary(
1329         getContext(), getTag(), getRawName(), getFile(), getLine(), getScope(),
1330         getBaseType(), getRawSizeInBits(), getAlignInBits(),
1331         getRawOffsetInBits(), getDWARFAddressSpace(), getPtrAuthData(),
1332         getFlags(), getExtraData(), getRawAnnotations());
1333   }
1334 
1335 public:
1336   DEFINE_MDNODE_GET(DIDerivedType,
1337                     (unsigned Tag, MDString *Name, Metadata *File,
1338                      unsigned Line, Metadata *Scope, Metadata *BaseType,
1339                      Metadata *SizeInBits, uint32_t AlignInBits,
1340                      Metadata *OffsetInBits,
1341                      std::optional<unsigned> DWARFAddressSpace,
1342                      std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1343                      Metadata *ExtraData = nullptr,
1344                      Metadata *Annotations = nullptr),
1345                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1346                      AlignInBits, OffsetInBits, DWARFAddressSpace, PtrAuthData,
1347                      Flags, ExtraData, Annotations))
1348   DEFINE_MDNODE_GET(DIDerivedType,
1349                     (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
1350                      DIScope *Scope, DIType *BaseType, Metadata *SizeInBits,
1351                      uint32_t AlignInBits, Metadata *OffsetInBits,
1352                      std::optional<unsigned> DWARFAddressSpace,
1353                      std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1354                      Metadata *ExtraData = nullptr,
1355                      DINodeArray Annotations = nullptr),
1356                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1357                      AlignInBits, OffsetInBits, DWARFAddressSpace, PtrAuthData,
1358                      Flags, ExtraData, Annotations))
1359   DEFINE_MDNODE_GET(DIDerivedType,
1360                     (unsigned Tag, MDString *Name, DIFile *File, unsigned Line,
1361                      DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
1362                      uint32_t AlignInBits, uint64_t OffsetInBits,
1363                      std::optional<unsigned> DWARFAddressSpace,
1364                      std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1365                      Metadata *ExtraData = nullptr,
1366                      DINodeArray Annotations = nullptr),
1367                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1368                      AlignInBits, OffsetInBits, DWARFAddressSpace, PtrAuthData,
1369                      Flags, ExtraData, Annotations))
1370   DEFINE_MDNODE_GET(DIDerivedType,
1371                     (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
1372                      DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
1373                      uint32_t AlignInBits, uint64_t OffsetInBits,
1374                      std::optional<unsigned> DWARFAddressSpace,
1375                      std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1376                      Metadata *ExtraData = nullptr,
1377                      DINodeArray Annotations = nullptr),
1378                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1379                      AlignInBits, OffsetInBits, DWARFAddressSpace, PtrAuthData,
1380                      Flags, ExtraData, Annotations))
1381 
clone()1382   TempDIDerivedType clone() const { return cloneImpl(); }
1383 
1384   /// Get the base type this is derived from.
getBaseType()1385   DIType *getBaseType() const { return cast_or_null<DIType>(getRawBaseType()); }
getRawBaseType()1386   Metadata *getRawBaseType() const { return getOperand(MY_FIRST_OPERAND); }
1387 
1388   /// \returns The DWARF address space of the memory pointed to or referenced by
1389   /// a pointer or reference type respectively.
getDWARFAddressSpace()1390   std::optional<unsigned> getDWARFAddressSpace() const {
1391     return DWARFAddressSpace;
1392   }
1393 
1394   LLVM_ABI std::optional<PtrAuthData> getPtrAuthData() const;
1395 
1396   /// Get extra data associated with this derived type.
1397   ///
1398   /// Class type for pointer-to-members, objective-c property node for ivars,
1399   /// global constant wrapper for static members, virtual base pointer offset
1400   /// for inheritance, a tuple of template parameters for template aliases,
1401   /// discriminant for a variant, or storage offset for a bit field.
1402   ///
1403   /// TODO: Separate out types that need this extra operand: pointer-to-member
1404   /// types and member fields (static members and ivars).
getExtraData()1405   Metadata *getExtraData() const { return getRawExtraData(); }
getRawExtraData()1406   Metadata *getRawExtraData() const { return getOperand(MY_FIRST_OPERAND + 1); }
1407 
1408   /// Get the template parameters from a template alias.
getTemplateParams()1409   DITemplateParameterArray getTemplateParams() const {
1410     return cast_or_null<MDTuple>(getExtraData());
1411   }
1412 
1413   /// Get annotations associated with this derived type.
getAnnotations()1414   DINodeArray getAnnotations() const {
1415     return cast_or_null<MDTuple>(getRawAnnotations());
1416   }
getRawAnnotations()1417   Metadata *getRawAnnotations() const {
1418     return getOperand(MY_FIRST_OPERAND + 2);
1419   }
1420 
1421   /// Get casted version of extra data.
1422   /// @{
1423   LLVM_ABI DIType *getClassType() const;
1424 
getObjCProperty()1425   DIObjCProperty *getObjCProperty() const {
1426     return dyn_cast_or_null<DIObjCProperty>(getExtraData());
1427   }
1428 
1429   LLVM_ABI uint32_t getVBPtrOffset() const;
1430 
1431   LLVM_ABI Constant *getStorageOffsetInBits() const;
1432 
1433   LLVM_ABI Constant *getConstant() const;
1434 
1435   LLVM_ABI Constant *getDiscriminantValue() const;
1436   /// @}
1437 
classof(const Metadata * MD)1438   static bool classof(const Metadata *MD) {
1439     return MD->getMetadataID() == DIDerivedTypeKind;
1440   }
1441 };
1442 
1443 inline bool operator==(DIDerivedType::PtrAuthData Lhs,
1444                        DIDerivedType::PtrAuthData Rhs) {
1445   return Lhs.RawData == Rhs.RawData;
1446 }
1447 
1448 inline bool operator!=(DIDerivedType::PtrAuthData Lhs,
1449                        DIDerivedType::PtrAuthData Rhs) {
1450   return !(Lhs == Rhs);
1451 }
1452 
1453 /// Subrange type.  This is somewhat similar to DISubrange, but it
1454 /// is also a DIType.
1455 class DISubrangeType : public DIType {
1456 public:
1457   typedef PointerUnion<ConstantInt *, DIVariable *, DIExpression *> BoundType;
1458 
1459 private:
1460   friend class LLVMContextImpl;
1461   friend class MDNode;
1462 
1463   static constexpr unsigned MY_FIRST_OPERAND = DIType::N_OPERANDS;
1464 
1465   DISubrangeType(LLVMContext &C, StorageType Storage, unsigned Line,
1466                  uint32_t AlignInBits, DIFlags Flags, ArrayRef<Metadata *> Ops);
1467 
1468   ~DISubrangeType() = default;
1469 
1470   static DISubrangeType *
1471   getImpl(LLVMContext &Context, StringRef Name, DIFile *File, unsigned Line,
1472           DIScope *Scope, uint64_t SizeInBits, uint32_t AlignInBits,
1473           DIFlags Flags, DIType *BaseType, Metadata *LowerBound,
1474           Metadata *UpperBound, Metadata *Stride, Metadata *Bias,
1475           StorageType Storage, bool ShouldCreate = true) {
1476     auto *SizeInBitsNode = ConstantAsMetadata::get(
1477         ConstantInt::get(Type::getInt64Ty(Context), SizeInBits));
1478     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
1479                    Scope, SizeInBitsNode, AlignInBits, Flags, BaseType,
1480                    LowerBound, UpperBound, Stride, Bias, Storage, ShouldCreate);
1481   }
1482 
1483   LLVM_ABI static DISubrangeType *
1484   getImpl(LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
1485           Metadata *Scope, Metadata *SizeInBits, uint32_t AlignInBits,
1486           DIFlags Flags, Metadata *BaseType, Metadata *LowerBound,
1487           Metadata *UpperBound, Metadata *Stride, Metadata *Bias,
1488           StorageType Storage, bool ShouldCreate = true);
1489 
cloneImpl()1490   TempDISubrangeType cloneImpl() const {
1491     return getTemporary(getContext(), getRawName(), getFile(), getLine(),
1492                         getScope(), getRawSizeInBits(), getAlignInBits(),
1493                         getFlags(), getBaseType(), getRawLowerBound(),
1494                         getRawUpperBound(), getRawStride(), getRawBias());
1495   }
1496 
1497   LLVM_ABI BoundType convertRawToBound(Metadata *IN) const;
1498 
1499 public:
1500   DEFINE_MDNODE_GET(DISubrangeType,
1501                     (MDString * Name, Metadata *File, unsigned Line,
1502                      Metadata *Scope, Metadata *SizeInBits,
1503                      uint32_t AlignInBits, DIFlags Flags, Metadata *BaseType,
1504                      Metadata *LowerBound, Metadata *UpperBound,
1505                      Metadata *Stride, Metadata *Bias),
1506                     (Name, File, Line, Scope, SizeInBits, AlignInBits, Flags,
1507                      BaseType, LowerBound, UpperBound, Stride, Bias))
1508   DEFINE_MDNODE_GET(DISubrangeType,
1509                     (StringRef Name, DIFile *File, unsigned Line,
1510                      DIScope *Scope, uint64_t SizeInBits, uint32_t AlignInBits,
1511                      DIFlags Flags, DIType *BaseType, Metadata *LowerBound,
1512                      Metadata *UpperBound, Metadata *Stride, Metadata *Bias),
1513                     (Name, File, Line, Scope, SizeInBits, AlignInBits, Flags,
1514                      BaseType, LowerBound, UpperBound, Stride, Bias))
1515 
clone()1516   TempDISubrangeType clone() const { return cloneImpl(); }
1517 
1518   /// Get the base type this is derived from.
getBaseType()1519   DIType *getBaseType() const { return cast_or_null<DIType>(getRawBaseType()); }
getRawBaseType()1520   Metadata *getRawBaseType() const { return getOperand(MY_FIRST_OPERAND); }
1521 
getRawLowerBound()1522   Metadata *getRawLowerBound() const {
1523     return getOperand(MY_FIRST_OPERAND + 1).get();
1524   }
1525 
getRawUpperBound()1526   Metadata *getRawUpperBound() const {
1527     return getOperand(MY_FIRST_OPERAND + 2).get();
1528   }
1529 
getRawStride()1530   Metadata *getRawStride() const {
1531     return getOperand(MY_FIRST_OPERAND + 3).get();
1532   }
1533 
getRawBias()1534   Metadata *getRawBias() const {
1535     return getOperand(MY_FIRST_OPERAND + 4).get();
1536   }
1537 
getLowerBound()1538   BoundType getLowerBound() const {
1539     return convertRawToBound(getRawLowerBound());
1540   }
1541 
getUpperBound()1542   BoundType getUpperBound() const {
1543     return convertRawToBound(getRawUpperBound());
1544   }
1545 
getStride()1546   BoundType getStride() const { return convertRawToBound(getRawStride()); }
1547 
getBias()1548   BoundType getBias() const { return convertRawToBound(getRawBias()); }
1549 
classof(const Metadata * MD)1550   static bool classof(const Metadata *MD) {
1551     return MD->getMetadataID() == DISubrangeTypeKind;
1552   }
1553 };
1554 
1555 /// Composite types.
1556 ///
1557 /// TODO: Detach from DerivedTypeBase (split out MDEnumType?).
1558 /// TODO: Create a custom, unrelated node for DW_TAG_array_type.
1559 class DICompositeType : public DIType {
1560   friend class LLVMContextImpl;
1561   friend class MDNode;
1562 
1563   static constexpr unsigned MY_FIRST_OPERAND = DIType::N_OPERANDS;
1564 
1565   unsigned RuntimeLang;
1566   std::optional<uint32_t> EnumKind;
1567 
DICompositeType(LLVMContext & C,StorageType Storage,unsigned Tag,unsigned Line,unsigned RuntimeLang,uint32_t AlignInBits,uint32_t NumExtraInhabitants,std::optional<uint32_t> EnumKind,DIFlags Flags,ArrayRef<Metadata * > Ops)1568   DICompositeType(LLVMContext &C, StorageType Storage, unsigned Tag,
1569                   unsigned Line, unsigned RuntimeLang, uint32_t AlignInBits,
1570                   uint32_t NumExtraInhabitants,
1571                   std::optional<uint32_t> EnumKind, DIFlags Flags,
1572                   ArrayRef<Metadata *> Ops)
1573       : DIType(C, DICompositeTypeKind, Storage, Tag, Line, AlignInBits,
1574                NumExtraInhabitants, Flags, Ops),
1575         RuntimeLang(RuntimeLang), EnumKind(EnumKind) {}
1576   ~DICompositeType() = default;
1577 
1578   /// Change fields in place.
mutate(unsigned Tag,unsigned Line,unsigned RuntimeLang,uint32_t AlignInBits,uint32_t NumExtraInhabitants,std::optional<uint32_t> EnumKind,DIFlags Flags)1579   void mutate(unsigned Tag, unsigned Line, unsigned RuntimeLang,
1580               uint32_t AlignInBits, uint32_t NumExtraInhabitants,
1581               std::optional<uint32_t> EnumKind, DIFlags Flags) {
1582     assert(isDistinct() && "Only distinct nodes can mutate");
1583     assert(getRawIdentifier() && "Only ODR-uniqued nodes should mutate");
1584     this->RuntimeLang = RuntimeLang;
1585     this->EnumKind = EnumKind;
1586     DIType::mutate(Tag, Line, AlignInBits, NumExtraInhabitants, Flags);
1587   }
1588 
1589   static DICompositeType *
1590   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, Metadata *File,
1591           unsigned Line, DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
1592           uint32_t AlignInBits, uint64_t OffsetInBits, DIType *Specification,
1593           uint32_t NumExtraInhabitants, DIFlags Flags, DINodeArray Elements,
1594           unsigned RuntimeLang, std::optional<uint32_t> EnumKind,
1595           DIType *VTableHolder, DITemplateParameterArray TemplateParams,
1596           StringRef Identifier, DIDerivedType *Discriminator,
1597           Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
1598           Metadata *Rank, DINodeArray Annotations, Metadata *BitStride,
1599           StorageType Storage, bool ShouldCreate = true) {
1600     auto *SizeInBitsNode = ConstantAsMetadata::get(
1601         ConstantInt::get(Type::getInt64Ty(Context), SizeInBits));
1602     auto *OffsetInBitsNode = ConstantAsMetadata::get(
1603         ConstantInt::get(Type::getInt64Ty(Context), OffsetInBits));
1604     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
1605                    Line, Scope, BaseType, SizeInBitsNode, AlignInBits,
1606                    OffsetInBitsNode, Flags, Elements.get(), RuntimeLang,
1607                    EnumKind, VTableHolder, TemplateParams.get(),
1608                    getCanonicalMDString(Context, Identifier), Discriminator,
1609                    DataLocation, Associated, Allocated, Rank, Annotations.get(),
1610                    Specification, NumExtraInhabitants, BitStride, Storage,
1611                    ShouldCreate);
1612   }
1613   static DICompositeType *
1614   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
1615           unsigned Line, Metadata *Scope, Metadata *BaseType,
1616           uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
1617           DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
1618           std::optional<uint32_t> EnumKind, Metadata *VTableHolder,
1619           Metadata *TemplateParams, MDString *Identifier,
1620           Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated,
1621           Metadata *Allocated, Metadata *Rank, Metadata *Annotations,
1622           Metadata *Specification, uint32_t NumExtraInhabitants,
1623           Metadata *BitStride, StorageType Storage, bool ShouldCreate = true) {
1624     auto *SizeInBitsNode = ConstantAsMetadata::get(
1625         ConstantInt::get(Type::getInt64Ty(Context), SizeInBits));
1626     auto *OffsetInBitsNode = ConstantAsMetadata::get(
1627         ConstantInt::get(Type::getInt64Ty(Context), OffsetInBits));
1628     return getImpl(Context, Tag, Name, File, Line, Scope, BaseType,
1629                    SizeInBitsNode, AlignInBits, OffsetInBitsNode, Flags,
1630                    Elements, RuntimeLang, EnumKind, VTableHolder,
1631                    TemplateParams, Identifier, Discriminator, DataLocation,
1632                    Associated, Allocated, Rank, Annotations, Specification,
1633                    NumExtraInhabitants, BitStride, Storage, ShouldCreate);
1634   }
1635   static DICompositeType *
1636   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, Metadata *File,
1637           unsigned Line, DIScope *Scope, DIType *BaseType, Metadata *SizeInBits,
1638           uint32_t AlignInBits, Metadata *OffsetInBits, DIType *Specification,
1639           uint32_t NumExtraInhabitants, DIFlags Flags, DINodeArray Elements,
1640           unsigned RuntimeLang, std::optional<uint32_t> EnumKind,
1641           DIType *VTableHolder, DITemplateParameterArray TemplateParams,
1642           StringRef Identifier, DIDerivedType *Discriminator,
1643           Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
1644           Metadata *Rank, DINodeArray Annotations, Metadata *BitStride,
1645           StorageType Storage, bool ShouldCreate = true) {
1646     return getImpl(
1647         Context, Tag, getCanonicalMDString(Context, Name), File, Line, Scope,
1648         BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements.get(),
1649         RuntimeLang, EnumKind, VTableHolder, TemplateParams.get(),
1650         getCanonicalMDString(Context, Identifier), Discriminator, DataLocation,
1651         Associated, Allocated, Rank, Annotations.get(), Specification,
1652         NumExtraInhabitants, BitStride, Storage, ShouldCreate);
1653   }
1654   LLVM_ABI static DICompositeType *
1655   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
1656           unsigned Line, Metadata *Scope, Metadata *BaseType,
1657           Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits,
1658           DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
1659           std::optional<uint32_t> EnumKind, Metadata *VTableHolder,
1660           Metadata *TemplateParams, MDString *Identifier,
1661           Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated,
1662           Metadata *Allocated, Metadata *Rank, Metadata *Annotations,
1663           Metadata *Specification, uint32_t NumExtraInhabitants,
1664           Metadata *BitStride, StorageType Storage, bool ShouldCreate = true);
1665 
cloneImpl()1666   TempDICompositeType cloneImpl() const {
1667     return getTemporary(
1668         getContext(), getTag(), getRawName(), getFile(), getLine(), getScope(),
1669         getBaseType(), getRawSizeInBits(), getAlignInBits(),
1670         getRawOffsetInBits(), getFlags(), getRawElements(), getRuntimeLang(),
1671         getEnumKind(), getVTableHolder(), getRawTemplateParams(),
1672         getRawIdentifier(), getDiscriminator(), getRawDataLocation(),
1673         getRawAssociated(), getRawAllocated(), getRawRank(),
1674         getRawAnnotations(), getSpecification(), getNumExtraInhabitants(),
1675         getRawBitStride());
1676   }
1677 
1678 public:
1679   DEFINE_MDNODE_GET(
1680       DICompositeType,
1681       (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
1682        DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
1683        uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
1684        DINodeArray Elements, unsigned RuntimeLang,
1685        std::optional<uint32_t> EnumKind, DIType *VTableHolder,
1686        DITemplateParameterArray TemplateParams = nullptr,
1687        StringRef Identifier = "", DIDerivedType *Discriminator = nullptr,
1688        Metadata *DataLocation = nullptr, Metadata *Associated = nullptr,
1689        Metadata *Allocated = nullptr, Metadata *Rank = nullptr,
1690        DINodeArray Annotations = nullptr, DIType *Specification = nullptr,
1691        uint32_t NumExtraInhabitants = 0, Metadata *BitStride = nullptr),
1692       (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits,
1693        OffsetInBits, Specification, NumExtraInhabitants, Flags, Elements,
1694        RuntimeLang, EnumKind, VTableHolder, TemplateParams, Identifier,
1695        Discriminator, DataLocation, Associated, Allocated, Rank, Annotations,
1696        BitStride))
1697   DEFINE_MDNODE_GET(
1698       DICompositeType,
1699       (unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
1700        Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
1701        uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
1702        Metadata *Elements, unsigned RuntimeLang,
1703        std::optional<uint32_t> EnumKind, Metadata *VTableHolder,
1704        Metadata *TemplateParams = nullptr, MDString *Identifier = nullptr,
1705        Metadata *Discriminator = nullptr, Metadata *DataLocation = nullptr,
1706        Metadata *Associated = nullptr, Metadata *Allocated = nullptr,
1707        Metadata *Rank = nullptr, Metadata *Annotations = nullptr,
1708        Metadata *Specification = nullptr, uint32_t NumExtraInhabitants = 0,
1709        Metadata *BitStride = nullptr),
1710       (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits,
1711        OffsetInBits, Flags, Elements, RuntimeLang, EnumKind, VTableHolder,
1712        TemplateParams, Identifier, Discriminator, DataLocation, Associated,
1713        Allocated, Rank, Annotations, Specification, NumExtraInhabitants,
1714        BitStride))
1715   DEFINE_MDNODE_GET(
1716       DICompositeType,
1717       (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
1718        DIScope *Scope, DIType *BaseType, Metadata *SizeInBits,
1719        uint32_t AlignInBits, Metadata *OffsetInBits, DIFlags Flags,
1720        DINodeArray Elements, unsigned RuntimeLang,
1721        std::optional<uint32_t> EnumKind, DIType *VTableHolder,
1722        DITemplateParameterArray TemplateParams = nullptr,
1723        StringRef Identifier = "", DIDerivedType *Discriminator = nullptr,
1724        Metadata *DataLocation = nullptr, Metadata *Associated = nullptr,
1725        Metadata *Allocated = nullptr, Metadata *Rank = nullptr,
1726        DINodeArray Annotations = nullptr, DIType *Specification = nullptr,
1727        uint32_t NumExtraInhabitants = 0, Metadata *BitStride = nullptr),
1728       (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits,
1729        OffsetInBits, Specification, NumExtraInhabitants, Flags, Elements,
1730        RuntimeLang, EnumKind, VTableHolder, TemplateParams, Identifier,
1731        Discriminator, DataLocation, Associated, Allocated, Rank, Annotations,
1732        BitStride))
1733   DEFINE_MDNODE_GET(
1734       DICompositeType,
1735       (unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
1736        Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits,
1737        uint32_t AlignInBits, Metadata *OffsetInBits, DIFlags Flags,
1738        Metadata *Elements, unsigned RuntimeLang,
1739        std::optional<uint32_t> EnumKind, Metadata *VTableHolder,
1740        Metadata *TemplateParams = nullptr, MDString *Identifier = nullptr,
1741        Metadata *Discriminator = nullptr, Metadata *DataLocation = nullptr,
1742        Metadata *Associated = nullptr, Metadata *Allocated = nullptr,
1743        Metadata *Rank = nullptr, Metadata *Annotations = nullptr,
1744        Metadata *Specification = nullptr, uint32_t NumExtraInhabitants = 0,
1745        Metadata *BitStride = nullptr),
1746       (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits,
1747        OffsetInBits, Flags, Elements, RuntimeLang, EnumKind, VTableHolder,
1748        TemplateParams, Identifier, Discriminator, DataLocation, Associated,
1749        Allocated, Rank, Annotations, Specification, NumExtraInhabitants,
1750        BitStride))
1751 
clone()1752   TempDICompositeType clone() const { return cloneImpl(); }
1753 
1754   /// Get a DICompositeType with the given ODR identifier.
1755   ///
1756   /// If \a LLVMContext::isODRUniquingDebugTypes(), gets the mapped
1757   /// DICompositeType for the given ODR \c Identifier.  If none exists, creates
1758   /// a new node.
1759   ///
1760   /// Else, returns \c nullptr.
1761   LLVM_ABI static DICompositeType *
1762   getODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag,
1763              MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
1764              Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits,
1765              Metadata *OffsetInBits, Metadata *Specification,
1766              uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements,
1767              unsigned RuntimeLang, std::optional<uint32_t> EnumKind,
1768              Metadata *VTableHolder, Metadata *TemplateParams,
1769              Metadata *Discriminator, Metadata *DataLocation,
1770              Metadata *Associated, Metadata *Allocated, Metadata *Rank,
1771              Metadata *Annotations, Metadata *BitStride);
1772   LLVM_ABI static DICompositeType *getODRTypeIfExists(LLVMContext &Context,
1773                                                       MDString &Identifier);
1774 
1775   /// Build a DICompositeType with the given ODR identifier.
1776   ///
1777   /// Looks up the mapped DICompositeType for the given ODR \c Identifier.  If
1778   /// it doesn't exist, creates a new one.  If it does exist and \a
1779   /// isForwardDecl(), and the new arguments would be a definition, mutates the
1780   /// the type in place.  In either case, returns the type.
1781   ///
1782   /// If not \a LLVMContext::isODRUniquingDebugTypes(), this function returns
1783   /// nullptr.
1784   LLVM_ABI static DICompositeType *
1785   buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag,
1786                MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
1787                Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits,
1788                Metadata *OffsetInBits, Metadata *Specification,
1789                uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements,
1790                unsigned RuntimeLang, std::optional<uint32_t> EnumKind,
1791                Metadata *VTableHolder, Metadata *TemplateParams,
1792                Metadata *Discriminator, Metadata *DataLocation,
1793                Metadata *Associated, Metadata *Allocated, Metadata *Rank,
1794                Metadata *Annotations, Metadata *BitStride);
1795 
getBaseType()1796   DIType *getBaseType() const { return cast_or_null<DIType>(getRawBaseType()); }
getElements()1797   DINodeArray getElements() const {
1798     return cast_or_null<MDTuple>(getRawElements());
1799   }
getVTableHolder()1800   DIType *getVTableHolder() const {
1801     return cast_or_null<DIType>(getRawVTableHolder());
1802   }
getTemplateParams()1803   DITemplateParameterArray getTemplateParams() const {
1804     return cast_or_null<MDTuple>(getRawTemplateParams());
1805   }
getIdentifier()1806   StringRef getIdentifier() const {
1807     return getStringOperand(MY_FIRST_OPERAND + 4);
1808   }
getRuntimeLang()1809   unsigned getRuntimeLang() const { return RuntimeLang; }
getEnumKind()1810   std::optional<uint32_t> getEnumKind() const { return EnumKind; }
1811 
getRawBaseType()1812   Metadata *getRawBaseType() const { return getOperand(MY_FIRST_OPERAND); }
getRawElements()1813   Metadata *getRawElements() const { return getOperand(MY_FIRST_OPERAND + 1); }
getRawVTableHolder()1814   Metadata *getRawVTableHolder() const {
1815     return getOperand(MY_FIRST_OPERAND + 2);
1816   }
getRawTemplateParams()1817   Metadata *getRawTemplateParams() const {
1818     return getOperand(MY_FIRST_OPERAND + 3);
1819   }
getRawIdentifier()1820   MDString *getRawIdentifier() const {
1821     return getOperandAs<MDString>(MY_FIRST_OPERAND + 4);
1822   }
getRawDiscriminator()1823   Metadata *getRawDiscriminator() const {
1824     return getOperand(MY_FIRST_OPERAND + 5);
1825   }
getDiscriminator()1826   DIDerivedType *getDiscriminator() const {
1827     return getOperandAs<DIDerivedType>(MY_FIRST_OPERAND + 5);
1828   }
getRawDataLocation()1829   Metadata *getRawDataLocation() const {
1830     return getOperand(MY_FIRST_OPERAND + 6);
1831   }
getDataLocation()1832   DIVariable *getDataLocation() const {
1833     return dyn_cast_or_null<DIVariable>(getRawDataLocation());
1834   }
getDataLocationExp()1835   DIExpression *getDataLocationExp() const {
1836     return dyn_cast_or_null<DIExpression>(getRawDataLocation());
1837   }
getRawAssociated()1838   Metadata *getRawAssociated() const {
1839     return getOperand(MY_FIRST_OPERAND + 7);
1840   }
getAssociated()1841   DIVariable *getAssociated() const {
1842     return dyn_cast_or_null<DIVariable>(getRawAssociated());
1843   }
getAssociatedExp()1844   DIExpression *getAssociatedExp() const {
1845     return dyn_cast_or_null<DIExpression>(getRawAssociated());
1846   }
getRawAllocated()1847   Metadata *getRawAllocated() const { return getOperand(MY_FIRST_OPERAND + 8); }
getAllocated()1848   DIVariable *getAllocated() const {
1849     return dyn_cast_or_null<DIVariable>(getRawAllocated());
1850   }
getAllocatedExp()1851   DIExpression *getAllocatedExp() const {
1852     return dyn_cast_or_null<DIExpression>(getRawAllocated());
1853   }
getRawRank()1854   Metadata *getRawRank() const { return getOperand(MY_FIRST_OPERAND + 9); }
getRankConst()1855   ConstantInt *getRankConst() const {
1856     if (auto *MD = dyn_cast_or_null<ConstantAsMetadata>(getRawRank()))
1857       return dyn_cast_or_null<ConstantInt>(MD->getValue());
1858     return nullptr;
1859   }
getRankExp()1860   DIExpression *getRankExp() const {
1861     return dyn_cast_or_null<DIExpression>(getRawRank());
1862   }
1863 
getRawAnnotations()1864   Metadata *getRawAnnotations() const {
1865     return getOperand(MY_FIRST_OPERAND + 10);
1866   }
getAnnotations()1867   DINodeArray getAnnotations() const {
1868     return cast_or_null<MDTuple>(getRawAnnotations());
1869   }
1870 
getRawSpecification()1871   Metadata *getRawSpecification() const {
1872     return getOperand(MY_FIRST_OPERAND + 11);
1873   }
getSpecification()1874   DIType *getSpecification() const {
1875     return cast_or_null<DIType>(getRawSpecification());
1876   }
1877 
getRawBitStride()1878   Metadata *getRawBitStride() const {
1879     return getOperand(MY_FIRST_OPERAND + 12);
1880   }
getBitStrideConst()1881   ConstantInt *getBitStrideConst() const {
1882     if (auto *MD = dyn_cast_or_null<ConstantAsMetadata>(getRawBitStride()))
1883       return dyn_cast_or_null<ConstantInt>(MD->getValue());
1884     return nullptr;
1885   }
1886 
1887   /// Replace operands.
1888   ///
1889   /// If this \a isUniqued() and not \a isResolved(), on a uniquing collision
1890   /// this will be RAUW'ed and deleted.  Use a \a TrackingMDRef to keep track
1891   /// of its movement if necessary.
1892   /// @{
replaceElements(DINodeArray Elements)1893   void replaceElements(DINodeArray Elements) {
1894 #ifndef NDEBUG
1895     for (DINode *Op : getElements())
1896       assert(is_contained(Elements->operands(), Op) &&
1897              "Lost a member during member list replacement");
1898 #endif
1899     replaceOperandWith(MY_FIRST_OPERAND + 1, Elements.get());
1900   }
1901 
replaceVTableHolder(DIType * VTableHolder)1902   void replaceVTableHolder(DIType *VTableHolder) {
1903     replaceOperandWith(MY_FIRST_OPERAND + 2, VTableHolder);
1904   }
1905 
replaceTemplateParams(DITemplateParameterArray TemplateParams)1906   void replaceTemplateParams(DITemplateParameterArray TemplateParams) {
1907     replaceOperandWith(MY_FIRST_OPERAND + 3, TemplateParams.get());
1908   }
1909   /// @}
1910 
classof(const Metadata * MD)1911   static bool classof(const Metadata *MD) {
1912     return MD->getMetadataID() == DICompositeTypeKind;
1913   }
1914 };
1915 
1916 /// Type array for a subprogram.
1917 ///
1918 /// TODO: Fold the array of types in directly as operands.
1919 class DISubroutineType : public DIType {
1920   friend class LLVMContextImpl;
1921   friend class MDNode;
1922 
1923   static constexpr unsigned MY_FIRST_OPERAND = DIType::N_OPERANDS;
1924 
1925   /// The calling convention used with DW_AT_calling_convention. Actually of
1926   /// type dwarf::CallingConvention.
1927   uint8_t CC;
1928 
1929   DISubroutineType(LLVMContext &C, StorageType Storage, DIFlags Flags,
1930                    uint8_t CC, ArrayRef<Metadata *> Ops);
1931   ~DISubroutineType() = default;
1932 
1933   static DISubroutineType *getImpl(LLVMContext &Context, DIFlags Flags,
1934                                    uint8_t CC, DITypeRefArray TypeArray,
1935                                    StorageType Storage,
1936                                    bool ShouldCreate = true) {
1937     return getImpl(Context, Flags, CC, TypeArray.get(), Storage, ShouldCreate);
1938   }
1939   LLVM_ABI static DISubroutineType *getImpl(LLVMContext &Context, DIFlags Flags,
1940                                             uint8_t CC, Metadata *TypeArray,
1941                                             StorageType Storage,
1942                                             bool ShouldCreate = true);
1943 
cloneImpl()1944   TempDISubroutineType cloneImpl() const {
1945     return getTemporary(getContext(), getFlags(), getCC(), getTypeArray());
1946   }
1947 
1948 public:
1949   DEFINE_MDNODE_GET(DISubroutineType,
1950                     (DIFlags Flags, uint8_t CC, DITypeRefArray TypeArray),
1951                     (Flags, CC, TypeArray))
1952   DEFINE_MDNODE_GET(DISubroutineType,
1953                     (DIFlags Flags, uint8_t CC, Metadata *TypeArray),
1954                     (Flags, CC, TypeArray))
1955 
clone()1956   TempDISubroutineType clone() const { return cloneImpl(); }
1957   // Returns a new temporary DISubroutineType with updated CC
cloneWithCC(uint8_t CC)1958   TempDISubroutineType cloneWithCC(uint8_t CC) const {
1959     auto NewTy = clone();
1960     NewTy->CC = CC;
1961     return NewTy;
1962   }
1963 
getCC()1964   uint8_t getCC() const { return CC; }
1965 
getTypeArray()1966   DITypeRefArray getTypeArray() const {
1967     return cast_or_null<MDTuple>(getRawTypeArray());
1968   }
1969 
getRawTypeArray()1970   Metadata *getRawTypeArray() const { return getOperand(MY_FIRST_OPERAND); }
1971 
classof(const Metadata * MD)1972   static bool classof(const Metadata *MD) {
1973     return MD->getMetadataID() == DISubroutineTypeKind;
1974   }
1975 };
1976 
1977 /// Compile unit.
1978 class DICompileUnit : public DIScope {
1979   friend class LLVMContextImpl;
1980   friend class MDNode;
1981 
1982 public:
1983   enum DebugEmissionKind : unsigned {
1984     NoDebug = 0,
1985     FullDebug,
1986     LineTablesOnly,
1987     DebugDirectivesOnly,
1988     LastEmissionKind = DebugDirectivesOnly
1989   };
1990 
1991   enum class DebugNameTableKind : unsigned {
1992     Default = 0,
1993     GNU = 1,
1994     None = 2,
1995     Apple = 3,
1996     LastDebugNameTableKind = Apple
1997   };
1998 
1999   LLVM_ABI static std::optional<DebugEmissionKind>
2000   getEmissionKind(StringRef Str);
2001   LLVM_ABI static const char *emissionKindString(DebugEmissionKind EK);
2002   LLVM_ABI static std::optional<DebugNameTableKind>
2003   getNameTableKind(StringRef Str);
2004   LLVM_ABI static const char *nameTableKindString(DebugNameTableKind PK);
2005 
2006 private:
2007   unsigned SourceLanguage;
2008   unsigned RuntimeVersion;
2009   uint64_t DWOId;
2010   unsigned EmissionKind;
2011   unsigned NameTableKind;
2012   bool IsOptimized;
2013   bool SplitDebugInlining;
2014   bool DebugInfoForProfiling;
2015   bool RangesBaseAddress;
2016 
2017   DICompileUnit(LLVMContext &C, StorageType Storage, unsigned SourceLanguage,
2018                 bool IsOptimized, unsigned RuntimeVersion,
2019                 unsigned EmissionKind, uint64_t DWOId, bool SplitDebugInlining,
2020                 bool DebugInfoForProfiling, unsigned NameTableKind,
2021                 bool RangesBaseAddress, ArrayRef<Metadata *> Ops);
2022   ~DICompileUnit() = default;
2023 
2024   static DICompileUnit *
2025   getImpl(LLVMContext &Context, unsigned SourceLanguage, DIFile *File,
2026           StringRef Producer, bool IsOptimized, StringRef Flags,
2027           unsigned RuntimeVersion, StringRef SplitDebugFilename,
2028           unsigned EmissionKind, DICompositeTypeArray EnumTypes,
2029           DIScopeArray RetainedTypes,
2030           DIGlobalVariableExpressionArray GlobalVariables,
2031           DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
2032           uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
2033           unsigned NameTableKind, bool RangesBaseAddress, StringRef SysRoot,
2034           StringRef SDK, StorageType Storage, bool ShouldCreate = true) {
2035     return getImpl(
2036         Context, SourceLanguage, File, getCanonicalMDString(Context, Producer),
2037         IsOptimized, getCanonicalMDString(Context, Flags), RuntimeVersion,
2038         getCanonicalMDString(Context, SplitDebugFilename), EmissionKind,
2039         EnumTypes.get(), RetainedTypes.get(), GlobalVariables.get(),
2040         ImportedEntities.get(), Macros.get(), DWOId, SplitDebugInlining,
2041         DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
2042         getCanonicalMDString(Context, SysRoot),
2043         getCanonicalMDString(Context, SDK), Storage, ShouldCreate);
2044   }
2045   LLVM_ABI static DICompileUnit *
2046   getImpl(LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
2047           MDString *Producer, bool IsOptimized, MDString *Flags,
2048           unsigned RuntimeVersion, MDString *SplitDebugFilename,
2049           unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
2050           Metadata *GlobalVariables, Metadata *ImportedEntities,
2051           Metadata *Macros, uint64_t DWOId, bool SplitDebugInlining,
2052           bool DebugInfoForProfiling, unsigned NameTableKind,
2053           bool RangesBaseAddress, MDString *SysRoot, MDString *SDK,
2054           StorageType Storage, bool ShouldCreate = true);
2055 
cloneImpl()2056   TempDICompileUnit cloneImpl() const {
2057     return getTemporary(
2058         getContext(), getSourceLanguage(), getFile(), getProducer(),
2059         isOptimized(), getFlags(), getRuntimeVersion(), getSplitDebugFilename(),
2060         getEmissionKind(), getEnumTypes(), getRetainedTypes(),
2061         getGlobalVariables(), getImportedEntities(), getMacros(), DWOId,
2062         getSplitDebugInlining(), getDebugInfoForProfiling(), getNameTableKind(),
2063         getRangesBaseAddress(), getSysRoot(), getSDK());
2064   }
2065 
2066 public:
2067   static void get() = delete;
2068   static void getIfExists() = delete;
2069 
2070   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
2071       DICompileUnit,
2072       (unsigned SourceLanguage, DIFile *File, StringRef Producer,
2073        bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
2074        StringRef SplitDebugFilename, DebugEmissionKind EmissionKind,
2075        DICompositeTypeArray EnumTypes, DIScopeArray RetainedTypes,
2076        DIGlobalVariableExpressionArray GlobalVariables,
2077        DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
2078        uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
2079        DebugNameTableKind NameTableKind, bool RangesBaseAddress,
2080        StringRef SysRoot, StringRef SDK),
2081       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
2082        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
2083        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
2084        DebugInfoForProfiling, (unsigned)NameTableKind, RangesBaseAddress,
2085        SysRoot, SDK))
2086   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
2087       DICompileUnit,
2088       (unsigned SourceLanguage, Metadata *File, MDString *Producer,
2089        bool IsOptimized, MDString *Flags, unsigned RuntimeVersion,
2090        MDString *SplitDebugFilename, unsigned EmissionKind, Metadata *EnumTypes,
2091        Metadata *RetainedTypes, Metadata *GlobalVariables,
2092        Metadata *ImportedEntities, Metadata *Macros, uint64_t DWOId,
2093        bool SplitDebugInlining, bool DebugInfoForProfiling,
2094        unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
2095        MDString *SDK),
2096       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
2097        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
2098        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
2099        DebugInfoForProfiling, NameTableKind, RangesBaseAddress, SysRoot, SDK))
2100 
clone()2101   TempDICompileUnit clone() const { return cloneImpl(); }
2102 
getSourceLanguage()2103   unsigned getSourceLanguage() const { return SourceLanguage; }
isOptimized()2104   bool isOptimized() const { return IsOptimized; }
getRuntimeVersion()2105   unsigned getRuntimeVersion() const { return RuntimeVersion; }
getEmissionKind()2106   DebugEmissionKind getEmissionKind() const {
2107     return (DebugEmissionKind)EmissionKind;
2108   }
isDebugDirectivesOnly()2109   bool isDebugDirectivesOnly() const {
2110     return EmissionKind == DebugDirectivesOnly;
2111   }
getDebugInfoForProfiling()2112   bool getDebugInfoForProfiling() const { return DebugInfoForProfiling; }
getNameTableKind()2113   DebugNameTableKind getNameTableKind() const {
2114     return (DebugNameTableKind)NameTableKind;
2115   }
getRangesBaseAddress()2116   bool getRangesBaseAddress() const { return RangesBaseAddress; }
getProducer()2117   StringRef getProducer() const { return getStringOperand(1); }
getFlags()2118   StringRef getFlags() const { return getStringOperand(2); }
getSplitDebugFilename()2119   StringRef getSplitDebugFilename() const { return getStringOperand(3); }
getEnumTypes()2120   DICompositeTypeArray getEnumTypes() const {
2121     return cast_or_null<MDTuple>(getRawEnumTypes());
2122   }
getRetainedTypes()2123   DIScopeArray getRetainedTypes() const {
2124     return cast_or_null<MDTuple>(getRawRetainedTypes());
2125   }
getGlobalVariables()2126   DIGlobalVariableExpressionArray getGlobalVariables() const {
2127     return cast_or_null<MDTuple>(getRawGlobalVariables());
2128   }
getImportedEntities()2129   DIImportedEntityArray getImportedEntities() const {
2130     return cast_or_null<MDTuple>(getRawImportedEntities());
2131   }
getMacros()2132   DIMacroNodeArray getMacros() const {
2133     return cast_or_null<MDTuple>(getRawMacros());
2134   }
getDWOId()2135   uint64_t getDWOId() const { return DWOId; }
setDWOId(uint64_t DwoId)2136   void setDWOId(uint64_t DwoId) { DWOId = DwoId; }
getSplitDebugInlining()2137   bool getSplitDebugInlining() const { return SplitDebugInlining; }
setSplitDebugInlining(bool SplitDebugInlining)2138   void setSplitDebugInlining(bool SplitDebugInlining) {
2139     this->SplitDebugInlining = SplitDebugInlining;
2140   }
getSysRoot()2141   StringRef getSysRoot() const { return getStringOperand(9); }
getSDK()2142   StringRef getSDK() const { return getStringOperand(10); }
2143 
getRawProducer()2144   MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
getRawFlags()2145   MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
getRawSplitDebugFilename()2146   MDString *getRawSplitDebugFilename() const {
2147     return getOperandAs<MDString>(3);
2148   }
getRawEnumTypes()2149   Metadata *getRawEnumTypes() const { return getOperand(4); }
getRawRetainedTypes()2150   Metadata *getRawRetainedTypes() const { return getOperand(5); }
getRawGlobalVariables()2151   Metadata *getRawGlobalVariables() const { return getOperand(6); }
getRawImportedEntities()2152   Metadata *getRawImportedEntities() const { return getOperand(7); }
getRawMacros()2153   Metadata *getRawMacros() const { return getOperand(8); }
getRawSysRoot()2154   MDString *getRawSysRoot() const { return getOperandAs<MDString>(9); }
getRawSDK()2155   MDString *getRawSDK() const { return getOperandAs<MDString>(10); }
2156 
2157   /// Replace arrays.
2158   ///
2159   /// If this \a isUniqued() and not \a isResolved(), it will be RAUW'ed and
2160   /// deleted on a uniquing collision.  In practice, uniquing collisions on \a
2161   /// DICompileUnit should be fairly rare.
2162   /// @{
replaceEnumTypes(DICompositeTypeArray N)2163   void replaceEnumTypes(DICompositeTypeArray N) {
2164     replaceOperandWith(4, N.get());
2165   }
replaceRetainedTypes(DITypeArray N)2166   void replaceRetainedTypes(DITypeArray N) { replaceOperandWith(5, N.get()); }
replaceGlobalVariables(DIGlobalVariableExpressionArray N)2167   void replaceGlobalVariables(DIGlobalVariableExpressionArray N) {
2168     replaceOperandWith(6, N.get());
2169   }
replaceImportedEntities(DIImportedEntityArray N)2170   void replaceImportedEntities(DIImportedEntityArray N) {
2171     replaceOperandWith(7, N.get());
2172   }
replaceMacros(DIMacroNodeArray N)2173   void replaceMacros(DIMacroNodeArray N) { replaceOperandWith(8, N.get()); }
2174   /// @}
2175 
classof(const Metadata * MD)2176   static bool classof(const Metadata *MD) {
2177     return MD->getMetadataID() == DICompileUnitKind;
2178   }
2179 };
2180 
2181 /// A scope for locals.
2182 ///
2183 /// A legal scope for lexical blocks, local variables, and debug info
2184 /// locations.  Subclasses are \a DISubprogram, \a DILexicalBlock, and \a
2185 /// DILexicalBlockFile.
2186 class DILocalScope : public DIScope {
2187 protected:
DILocalScope(LLVMContext & C,unsigned ID,StorageType Storage,unsigned Tag,ArrayRef<Metadata * > Ops)2188   DILocalScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
2189                ArrayRef<Metadata *> Ops)
2190       : DIScope(C, ID, Storage, Tag, Ops) {}
2191   ~DILocalScope() = default;
2192 
2193 public:
2194   /// Get the subprogram for this scope.
2195   ///
2196   /// Return this if it's an \a DISubprogram; otherwise, look up the scope
2197   /// chain.
2198   LLVM_ABI DISubprogram *getSubprogram() const;
2199 
2200   /// Traverses the scope chain rooted at RootScope until it hits a Subprogram,
2201   /// recreating the chain with "NewSP" instead.
2202   LLVM_ABI static DILocalScope *
2203   cloneScopeForSubprogram(DILocalScope &RootScope, DISubprogram &NewSP,
2204                           LLVMContext &Ctx,
2205                           DenseMap<const MDNode *, MDNode *> &Cache);
2206 
2207   /// Get the first non DILexicalBlockFile scope of this scope.
2208   ///
2209   /// Return this if it's not a \a DILexicalBlockFIle; otherwise, look up the
2210   /// scope chain.
2211   LLVM_ABI DILocalScope *getNonLexicalBlockFileScope() const;
2212 
classof(const Metadata * MD)2213   static bool classof(const Metadata *MD) {
2214     return MD->getMetadataID() == DISubprogramKind ||
2215            MD->getMetadataID() == DILexicalBlockKind ||
2216            MD->getMetadataID() == DILexicalBlockFileKind;
2217   }
2218 };
2219 
2220 /// Subprogram description. Uses SubclassData1.
2221 class DISubprogram : public DILocalScope {
2222   friend class LLVMContextImpl;
2223   friend class MDNode;
2224 
2225   unsigned Line;
2226   unsigned ScopeLine;
2227   unsigned VirtualIndex;
2228 
2229   /// In the MS ABI, the implicit 'this' parameter is adjusted in the prologue
2230   /// of method overrides from secondary bases by this amount. It may be
2231   /// negative.
2232   int ThisAdjustment;
2233 
2234 public:
2235   /// Debug info subprogram flags.
2236   enum DISPFlags : uint32_t {
2237 #define HANDLE_DISP_FLAG(ID, NAME) SPFlag##NAME = ID,
2238 #define DISP_FLAG_LARGEST_NEEDED
2239 #include "llvm/IR/DebugInfoFlags.def"
2240     SPFlagNonvirtual = SPFlagZero,
2241     SPFlagVirtuality = SPFlagVirtual | SPFlagPureVirtual,
2242     LLVM_MARK_AS_BITMASK_ENUM(SPFlagLargest)
2243   };
2244 
2245   LLVM_ABI static DISPFlags getFlag(StringRef Flag);
2246   LLVM_ABI static StringRef getFlagString(DISPFlags Flag);
2247 
2248   /// Split up a flags bitfield for easier printing.
2249   ///
2250   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
2251   /// any remaining (unrecognized) bits.
2252   LLVM_ABI static DISPFlags splitFlags(DISPFlags Flags,
2253                                        SmallVectorImpl<DISPFlags> &SplitFlags);
2254 
2255   // Helper for converting old bitfields to new flags word.
2256   LLVM_ABI static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition,
2257                                       bool IsOptimized,
2258                                       unsigned Virtuality = SPFlagNonvirtual,
2259                                       bool IsMainSubprogram = false);
2260 
2261 private:
2262   DIFlags Flags;
2263   DISPFlags SPFlags;
2264 
2265   DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
2266                unsigned ScopeLine, unsigned VirtualIndex, int ThisAdjustment,
2267                DIFlags Flags, DISPFlags SPFlags, bool UsesKeyInstructions,
2268                ArrayRef<Metadata *> Ops);
2269   ~DISubprogram() = default;
2270 
2271   static DISubprogram *
2272   getImpl(LLVMContext &Context, DIScope *Scope, StringRef Name,
2273           StringRef LinkageName, DIFile *File, unsigned Line,
2274           DISubroutineType *Type, unsigned ScopeLine, DIType *ContainingType,
2275           unsigned VirtualIndex, int ThisAdjustment, DIFlags Flags,
2276           DISPFlags SPFlags, DICompileUnit *Unit,
2277           DITemplateParameterArray TemplateParams, DISubprogram *Declaration,
2278           DINodeArray RetainedNodes, DITypeArray ThrownTypes,
2279           DINodeArray Annotations, StringRef TargetFuncName,
2280           bool UsesKeyInstructions, StorageType Storage,
2281           bool ShouldCreate = true) {
2282     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
2283                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
2284                    ScopeLine, ContainingType, VirtualIndex, ThisAdjustment,
2285                    Flags, SPFlags, Unit, TemplateParams.get(), Declaration,
2286                    RetainedNodes.get(), ThrownTypes.get(), Annotations.get(),
2287                    getCanonicalMDString(Context, TargetFuncName),
2288                    UsesKeyInstructions, Storage, ShouldCreate);
2289   }
2290 
2291   LLVM_ABI static DISubprogram *
2292   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
2293           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
2294           unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
2295           int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
2296           Metadata *TemplateParams, Metadata *Declaration,
2297           Metadata *RetainedNodes, Metadata *ThrownTypes, Metadata *Annotations,
2298           MDString *TargetFuncName, bool UsesKeyInstructions,
2299           StorageType Storage, bool ShouldCreate = true);
2300 
cloneImpl()2301   TempDISubprogram cloneImpl() const {
2302     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
2303                         getFile(), getLine(), getType(), getScopeLine(),
2304                         getContainingType(), getVirtualIndex(),
2305                         getThisAdjustment(), getFlags(), getSPFlags(),
2306                         getUnit(), getTemplateParams(), getDeclaration(),
2307                         getRetainedNodes(), getThrownTypes(), getAnnotations(),
2308                         getTargetFuncName(), getKeyInstructionsEnabled());
2309   }
2310 
2311 public:
2312   DEFINE_MDNODE_GET(
2313       DISubprogram,
2314       (DIScope * Scope, StringRef Name, StringRef LinkageName, DIFile *File,
2315        unsigned Line, DISubroutineType *Type, unsigned ScopeLine,
2316        DIType *ContainingType, unsigned VirtualIndex, int ThisAdjustment,
2317        DIFlags Flags, DISPFlags SPFlags, DICompileUnit *Unit,
2318        DITemplateParameterArray TemplateParams = nullptr,
2319        DISubprogram *Declaration = nullptr, DINodeArray RetainedNodes = nullptr,
2320        DITypeArray ThrownTypes = nullptr, DINodeArray Annotations = nullptr,
2321        StringRef TargetFuncName = "", bool UsesKeyInstructions = false),
2322       (Scope, Name, LinkageName, File, Line, Type, ScopeLine, ContainingType,
2323        VirtualIndex, ThisAdjustment, Flags, SPFlags, Unit, TemplateParams,
2324        Declaration, RetainedNodes, ThrownTypes, Annotations, TargetFuncName,
2325        UsesKeyInstructions))
2326 
2327   DEFINE_MDNODE_GET(
2328       DISubprogram,
2329       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
2330        unsigned Line, Metadata *Type, unsigned ScopeLine,
2331        Metadata *ContainingType, unsigned VirtualIndex, int ThisAdjustment,
2332        DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
2333        Metadata *TemplateParams = nullptr, Metadata *Declaration = nullptr,
2334        Metadata *RetainedNodes = nullptr, Metadata *ThrownTypes = nullptr,
2335        Metadata *Annotations = nullptr, MDString *TargetFuncName = nullptr,
2336        bool UsesKeyInstructions = false),
2337       (Scope, Name, LinkageName, File, Line, Type, ScopeLine, ContainingType,
2338        VirtualIndex, ThisAdjustment, Flags, SPFlags, Unit, TemplateParams,
2339        Declaration, RetainedNodes, ThrownTypes, Annotations, TargetFuncName,
2340        UsesKeyInstructions))
2341 
clone()2342   TempDISubprogram clone() const { return cloneImpl(); }
2343 
2344   /// Returns a new temporary DISubprogram with updated Flags
cloneWithFlags(DIFlags NewFlags)2345   TempDISubprogram cloneWithFlags(DIFlags NewFlags) const {
2346     auto NewSP = clone();
2347     NewSP->Flags = NewFlags;
2348     return NewSP;
2349   }
2350 
getKeyInstructionsEnabled()2351   bool getKeyInstructionsEnabled() const { return SubclassData1; }
2352 
2353 public:
getLine()2354   unsigned getLine() const { return Line; }
getVirtuality()2355   unsigned getVirtuality() const { return getSPFlags() & SPFlagVirtuality; }
getVirtualIndex()2356   unsigned getVirtualIndex() const { return VirtualIndex; }
getThisAdjustment()2357   int getThisAdjustment() const { return ThisAdjustment; }
getScopeLine()2358   unsigned getScopeLine() const { return ScopeLine; }
setScopeLine(unsigned L)2359   void setScopeLine(unsigned L) {
2360     assert(isDistinct());
2361     ScopeLine = L;
2362   }
getFlags()2363   DIFlags getFlags() const { return Flags; }
getSPFlags()2364   DISPFlags getSPFlags() const { return SPFlags; }
isLocalToUnit()2365   bool isLocalToUnit() const { return getSPFlags() & SPFlagLocalToUnit; }
isDefinition()2366   bool isDefinition() const { return getSPFlags() & SPFlagDefinition; }
isOptimized()2367   bool isOptimized() const { return getSPFlags() & SPFlagOptimized; }
isMainSubprogram()2368   bool isMainSubprogram() const { return getSPFlags() & SPFlagMainSubprogram; }
2369 
isArtificial()2370   bool isArtificial() const { return getFlags() & FlagArtificial; }
isPrivate()2371   bool isPrivate() const {
2372     return (getFlags() & FlagAccessibility) == FlagPrivate;
2373   }
isProtected()2374   bool isProtected() const {
2375     return (getFlags() & FlagAccessibility) == FlagProtected;
2376   }
isPublic()2377   bool isPublic() const {
2378     return (getFlags() & FlagAccessibility) == FlagPublic;
2379   }
isExplicit()2380   bool isExplicit() const { return getFlags() & FlagExplicit; }
isPrototyped()2381   bool isPrototyped() const { return getFlags() & FlagPrototyped; }
areAllCallsDescribed()2382   bool areAllCallsDescribed() const {
2383     return getFlags() & FlagAllCallsDescribed;
2384   }
isPure()2385   bool isPure() const { return getSPFlags() & SPFlagPure; }
isElemental()2386   bool isElemental() const { return getSPFlags() & SPFlagElemental; }
isRecursive()2387   bool isRecursive() const { return getSPFlags() & SPFlagRecursive; }
isObjCDirect()2388   bool isObjCDirect() const { return getSPFlags() & SPFlagObjCDirect; }
2389 
2390   /// Check if this is deleted member function.
2391   ///
2392   /// Return true if this subprogram is a C++11 special
2393   /// member function declared deleted.
isDeleted()2394   bool isDeleted() const { return getSPFlags() & SPFlagDeleted; }
2395 
2396   /// Check if this is reference-qualified.
2397   ///
2398   /// Return true if this subprogram is a C++11 reference-qualified non-static
2399   /// member function (void foo() &).
isLValueReference()2400   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
2401 
2402   /// Check if this is rvalue-reference-qualified.
2403   ///
2404   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
2405   /// non-static member function (void foo() &&).
isRValueReference()2406   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
2407 
2408   /// Check if this is marked as noreturn.
2409   ///
2410   /// Return true if this subprogram is C++11 noreturn or C11 _Noreturn
isNoReturn()2411   bool isNoReturn() const { return getFlags() & FlagNoReturn; }
2412 
2413   // Check if this routine is a compiler-generated thunk.
2414   //
2415   // Returns true if this subprogram is a thunk generated by the compiler.
isThunk()2416   bool isThunk() const { return getFlags() & FlagThunk; }
2417 
getScope()2418   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
2419 
getName()2420   StringRef getName() const { return getStringOperand(2); }
getLinkageName()2421   StringRef getLinkageName() const { return getStringOperand(3); }
2422   /// Only used by clients of CloneFunction, and only right after the cloning.
replaceLinkageName(MDString * LN)2423   void replaceLinkageName(MDString *LN) { replaceOperandWith(3, LN); }
2424 
getType()2425   DISubroutineType *getType() const {
2426     return cast_or_null<DISubroutineType>(getRawType());
2427   }
getContainingType()2428   DIType *getContainingType() const {
2429     return cast_or_null<DIType>(getRawContainingType());
2430   }
replaceType(DISubroutineType * Ty)2431   void replaceType(DISubroutineType *Ty) {
2432     assert(isDistinct() && "Only distinct nodes can mutate");
2433     replaceOperandWith(4, Ty);
2434   }
2435 
getUnit()2436   DICompileUnit *getUnit() const {
2437     return cast_or_null<DICompileUnit>(getRawUnit());
2438   }
replaceUnit(DICompileUnit * CU)2439   void replaceUnit(DICompileUnit *CU) { replaceOperandWith(5, CU); }
getTemplateParams()2440   DITemplateParameterArray getTemplateParams() const {
2441     return cast_or_null<MDTuple>(getRawTemplateParams());
2442   }
getDeclaration()2443   DISubprogram *getDeclaration() const {
2444     return cast_or_null<DISubprogram>(getRawDeclaration());
2445   }
replaceDeclaration(DISubprogram * Decl)2446   void replaceDeclaration(DISubprogram *Decl) { replaceOperandWith(6, Decl); }
getRetainedNodes()2447   DINodeArray getRetainedNodes() const {
2448     return cast_or_null<MDTuple>(getRawRetainedNodes());
2449   }
getThrownTypes()2450   DITypeArray getThrownTypes() const {
2451     return cast_or_null<MDTuple>(getRawThrownTypes());
2452   }
getAnnotations()2453   DINodeArray getAnnotations() const {
2454     return cast_or_null<MDTuple>(getRawAnnotations());
2455   }
getTargetFuncName()2456   StringRef getTargetFuncName() const {
2457     return (getRawTargetFuncName()) ? getStringOperand(12) : StringRef();
2458   }
2459 
getRawScope()2460   Metadata *getRawScope() const { return getOperand(1); }
getRawName()2461   MDString *getRawName() const { return getOperandAs<MDString>(2); }
getRawLinkageName()2462   MDString *getRawLinkageName() const { return getOperandAs<MDString>(3); }
getRawType()2463   Metadata *getRawType() const { return getOperand(4); }
getRawUnit()2464   Metadata *getRawUnit() const { return getOperand(5); }
getRawDeclaration()2465   Metadata *getRawDeclaration() const { return getOperand(6); }
getRawRetainedNodes()2466   Metadata *getRawRetainedNodes() const { return getOperand(7); }
getRawContainingType()2467   Metadata *getRawContainingType() const {
2468     return getNumOperands() > 8 ? getOperandAs<Metadata>(8) : nullptr;
2469   }
getRawTemplateParams()2470   Metadata *getRawTemplateParams() const {
2471     return getNumOperands() > 9 ? getOperandAs<Metadata>(9) : nullptr;
2472   }
getRawThrownTypes()2473   Metadata *getRawThrownTypes() const {
2474     return getNumOperands() > 10 ? getOperandAs<Metadata>(10) : nullptr;
2475   }
getRawAnnotations()2476   Metadata *getRawAnnotations() const {
2477     return getNumOperands() > 11 ? getOperandAs<Metadata>(11) : nullptr;
2478   }
getRawTargetFuncName()2479   MDString *getRawTargetFuncName() const {
2480     return getNumOperands() > 12 ? getOperandAs<MDString>(12) : nullptr;
2481   }
2482 
replaceRawLinkageName(MDString * LinkageName)2483   void replaceRawLinkageName(MDString *LinkageName) {
2484     replaceOperandWith(3, LinkageName);
2485   }
replaceRetainedNodes(DINodeArray N)2486   void replaceRetainedNodes(DINodeArray N) {
2487     replaceOperandWith(7, N.get());
2488   }
2489 
2490   /// Check if this subprogram describes the given function.
2491   ///
2492   /// FIXME: Should this be looking through bitcasts?
2493   LLVM_ABI bool describes(const Function *F) const;
2494 
classof(const Metadata * MD)2495   static bool classof(const Metadata *MD) {
2496     return MD->getMetadataID() == DISubprogramKind;
2497   }
2498 };
2499 
2500 /// Debug location.
2501 ///
2502 /// A debug location in source code, used for debug info and otherwise.
2503 ///
2504 /// Uses the SubclassData1, SubclassData16 and SubclassData32
2505 /// Metadata slots.
2506 
2507 class DILocation : public MDNode {
2508   friend class LLVMContextImpl;
2509   friend class MDNode;
2510 #ifdef EXPERIMENTAL_KEY_INSTRUCTIONS
2511   uint64_t AtomGroup : 61;
2512   uint64_t AtomRank : 3;
2513 #endif
2514 
2515   DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
2516              unsigned Column, uint64_t AtomGroup, uint8_t AtomRank,
2517              ArrayRef<Metadata *> MDs, bool ImplicitCode);
~DILocation()2518   ~DILocation() { dropAllReferences(); }
2519 
2520   LLVM_ABI static DILocation *
2521   getImpl(LLVMContext &Context, unsigned Line, unsigned Column, Metadata *Scope,
2522           Metadata *InlinedAt, bool ImplicitCode, uint64_t AtomGroup,
2523           uint8_t AtomRank, StorageType Storage, bool ShouldCreate = true);
2524   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
2525                              unsigned Column, DILocalScope *Scope,
2526                              DILocation *InlinedAt, bool ImplicitCode,
2527                              uint64_t AtomGroup, uint8_t AtomRank,
2528                              StorageType Storage, bool ShouldCreate = true) {
2529     return getImpl(Context, Line, Column, static_cast<Metadata *>(Scope),
2530                    static_cast<Metadata *>(InlinedAt), ImplicitCode, AtomGroup,
2531                    AtomRank, Storage, ShouldCreate);
2532   }
2533 
cloneImpl()2534   TempDILocation cloneImpl() const {
2535     // Get the raw scope/inlinedAt since it is possible to invoke this on
2536     // a DILocation containing temporary metadata.
2537     return getTemporary(getContext(), getLine(), getColumn(), getRawScope(),
2538                         getRawInlinedAt(), isImplicitCode(), getAtomGroup(),
2539                         getAtomRank());
2540   }
2541 
2542 public:
getAtomGroup()2543   uint64_t getAtomGroup() const {
2544 #ifdef EXPERIMENTAL_KEY_INSTRUCTIONS
2545     return AtomGroup;
2546 #else
2547     return 0;
2548 #endif
2549   }
getAtomRank()2550   uint8_t getAtomRank() const {
2551 #ifdef EXPERIMENTAL_KEY_INSTRUCTIONS
2552     return AtomRank;
2553 #else
2554     return 0;
2555 #endif
2556   }
2557 
getWithoutAtom()2558   const DILocation *getWithoutAtom() const {
2559     if (!getAtomGroup() && !getAtomRank())
2560       return this;
2561     return get(getContext(), getLine(), getColumn(), getScope(), getInlinedAt(),
2562                isImplicitCode());
2563   }
2564 
2565   // Disallow replacing operands.
2566   void replaceOperandWith(unsigned I, Metadata *New) = delete;
2567 
2568   DEFINE_MDNODE_GET(DILocation,
2569                     (unsigned Line, unsigned Column, Metadata *Scope,
2570                      Metadata *InlinedAt = nullptr, bool ImplicitCode = false,
2571                      uint64_t AtomGroup = 0, uint8_t AtomRank = 0),
2572                     (Line, Column, Scope, InlinedAt, ImplicitCode, AtomGroup,
2573                      AtomRank))
2574   DEFINE_MDNODE_GET(DILocation,
2575                     (unsigned Line, unsigned Column, DILocalScope *Scope,
2576                      DILocation *InlinedAt = nullptr, bool ImplicitCode = false,
2577                      uint64_t AtomGroup = 0, uint8_t AtomRank = 0),
2578                     (Line, Column, Scope, InlinedAt, ImplicitCode, AtomGroup,
2579                      AtomRank))
2580 
2581   /// Return a (temporary) clone of this.
clone()2582   TempDILocation clone() const { return cloneImpl(); }
2583 
getLine()2584   unsigned getLine() const { return SubclassData32; }
getColumn()2585   unsigned getColumn() const { return SubclassData16; }
getScope()2586   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
2587 
2588   /// Return the linkage name of Subprogram. If the linkage name is empty,
2589   /// return scope name (the demangled name).
getSubprogramLinkageName()2590   StringRef getSubprogramLinkageName() const {
2591     DISubprogram *SP = getScope()->getSubprogram();
2592     if (!SP)
2593       return "";
2594     auto Name = SP->getLinkageName();
2595     if (!Name.empty())
2596       return Name;
2597     return SP->getName();
2598   }
2599 
getInlinedAt()2600   DILocation *getInlinedAt() const {
2601     return cast_or_null<DILocation>(getRawInlinedAt());
2602   }
2603 
2604   /// Check if the location corresponds to an implicit code.
2605   /// When the ImplicitCode flag is true, it means that the Instruction
2606   /// with this DILocation has been added by the front-end but it hasn't been
2607   /// written explicitly by the user (e.g. cleanup stuff in C++ put on a closing
2608   /// bracket). It's useful for code coverage to not show a counter on "empty"
2609   /// lines.
isImplicitCode()2610   bool isImplicitCode() const { return SubclassData1; }
setImplicitCode(bool ImplicitCode)2611   void setImplicitCode(bool ImplicitCode) { SubclassData1 = ImplicitCode; }
2612 
getFile()2613   DIFile *getFile() const { return getScope()->getFile(); }
getFilename()2614   StringRef getFilename() const { return getScope()->getFilename(); }
getDirectory()2615   StringRef getDirectory() const { return getScope()->getDirectory(); }
getSource()2616   std::optional<StringRef> getSource() const { return getScope()->getSource(); }
2617 
2618   /// Get the scope where this is inlined.
2619   ///
2620   /// Walk through \a getInlinedAt() and return \a getScope() from the deepest
2621   /// location.
getInlinedAtScope()2622   DILocalScope *getInlinedAtScope() const {
2623     if (auto *IA = getInlinedAt())
2624       return IA->getInlinedAtScope();
2625     return getScope();
2626   }
2627 
2628   /// Get the DWARF discriminator.
2629   ///
2630   /// DWARF discriminators distinguish identical file locations between
2631   /// instructions that are on different basic blocks.
2632   ///
2633   /// There are 3 components stored in discriminator, from lower bits:
2634   ///
2635   /// Base discriminator: assigned by AddDiscriminators pass to identify IRs
2636   ///                     that are defined by the same source line, but
2637   ///                     different basic blocks.
2638   /// Duplication factor: assigned by optimizations that will scale down
2639   ///                     the execution frequency of the original IR.
2640   /// Copy Identifier: assigned by optimizations that clones the IR.
2641   ///                  Each copy of the IR will be assigned an identifier.
2642   ///
2643   /// Encoding:
2644   ///
2645   /// The above 3 components are encoded into a 32bit unsigned integer in
2646   /// order. If the lowest bit is 1, the current component is empty, and the
2647   /// next component will start in the next bit. Otherwise, the current
2648   /// component is non-empty, and its content starts in the next bit. The
2649   /// value of each components is either 5 bit or 12 bit: if the 7th bit
2650   /// is 0, the bit 2~6 (5 bits) are used to represent the component; if the
2651   /// 7th bit is 1, the bit 2~6 (5 bits) and 8~14 (7 bits) are combined to
2652   /// represent the component. Thus, the number of bits used for a component
2653   /// is either 0 (if it and all the next components are empty); 1 - if it is
2654   /// empty; 7 - if its value is up to and including 0x1f (lsb and msb are both
2655   /// 0); or 14, if its value is up to and including 0x1ff. Note that the last
2656   /// component is also capped at 0x1ff, even in the case when both first
2657   /// components are 0, and we'd technically have 29 bits available.
2658   ///
2659   /// For precise control over the data being encoded in the discriminator,
2660   /// use encodeDiscriminator/decodeDiscriminator.
2661 
2662   inline unsigned getDiscriminator() const;
2663 
2664   // For the regular discriminator, it stands for all empty components if all
2665   // the lowest 3 bits are non-zero and all higher 29 bits are unused(zero by
2666   // default). Here we fully leverage the higher 29 bits for pseudo probe use.
2667   // This is the format:
2668   // [2:0] - 0x7
2669   // [31:3] - pseudo probe fields guaranteed to be non-zero as a whole
2670   // So if the lower 3 bits is non-zero and the others has at least one
2671   // non-zero bit, it guarantees to be a pseudo probe discriminator
isPseudoProbeDiscriminator(unsigned Discriminator)2672   inline static bool isPseudoProbeDiscriminator(unsigned Discriminator) {
2673     return ((Discriminator & 0x7) == 0x7) && (Discriminator & 0xFFFFFFF8);
2674   }
2675 
2676   /// Returns a new DILocation with updated \p Discriminator.
2677   inline const DILocation *cloneWithDiscriminator(unsigned Discriminator) const;
2678 
2679   /// Returns a new DILocation with updated base discriminator \p BD. Only the
2680   /// base discriminator is set in the new DILocation, the other encoded values
2681   /// are elided.
2682   /// If the discriminator cannot be encoded, the function returns std::nullopt.
2683   inline std::optional<const DILocation *>
2684   cloneWithBaseDiscriminator(unsigned BD) const;
2685 
2686   /// Returns the duplication factor stored in the discriminator, or 1 if no
2687   /// duplication factor (or 0) is encoded.
2688   inline unsigned getDuplicationFactor() const;
2689 
2690   /// Returns the copy identifier stored in the discriminator.
2691   inline unsigned getCopyIdentifier() const;
2692 
2693   /// Returns the base discriminator stored in the discriminator.
2694   inline unsigned getBaseDiscriminator() const;
2695 
2696   /// Returns a new DILocation with duplication factor \p DF * current
2697   /// duplication factor encoded in the discriminator. The current duplication
2698   /// factor is as defined by getDuplicationFactor().
2699   /// Returns std::nullopt if encoding failed.
2700   inline std::optional<const DILocation *>
2701   cloneByMultiplyingDuplicationFactor(unsigned DF) const;
2702 
2703   /// Attempts to merge \p LocA and \p LocB into a single location; see
2704   /// DebugLoc::getMergedLocation for more details.
2705   /// NB: When merging the locations of instructions, prefer to use
2706   /// DebugLoc::getMergedLocation(), as an instruction's DebugLoc may contain
2707   /// additional metadata that will not be preserved when merging the unwrapped
2708   /// DILocations.
2709   LLVM_ABI static DILocation *getMergedLocation(DILocation *LocA,
2710                                                 DILocation *LocB);
2711 
2712   /// Try to combine the vector of locations passed as input in a single one.
2713   /// This function applies getMergedLocation() repeatedly left-to-right.
2714   /// NB: When merging the locations of instructions, prefer to use
2715   /// DebugLoc::getMergedLocations(), as an instruction's DebugLoc may contain
2716   /// additional metadata that will not be preserved when merging the unwrapped
2717   /// DILocations.
2718   ///
2719   /// \p Locs: The locations to be merged.
2720   LLVM_ABI static DILocation *getMergedLocations(ArrayRef<DILocation *> Locs);
2721 
2722   /// Return the masked discriminator value for an input discrimnator value D
2723   /// (i.e. zero out the (B+1)-th and above bits for D (B is 0-base).
2724   // Example: an input of (0x1FF, 7) returns 0xFF.
getMaskedDiscriminator(unsigned D,unsigned B)2725   static unsigned getMaskedDiscriminator(unsigned D, unsigned B) {
2726     return (D & getN1Bits(B));
2727   }
2728 
2729   /// Return the bits used for base discriminators.
getBaseDiscriminatorBits()2730   static unsigned getBaseDiscriminatorBits() { return getBaseFSBitEnd(); }
2731 
2732   /// Returns the base discriminator for a given encoded discriminator \p D.
2733   static unsigned
2734   getBaseDiscriminatorFromDiscriminator(unsigned D,
2735                                         bool IsFSDiscriminator = false) {
2736     // Extract the dwarf base discriminator if it's encoded in the pseudo probe
2737     // discriminator.
2738     if (isPseudoProbeDiscriminator(D)) {
2739       auto DwarfBaseDiscriminator =
2740           PseudoProbeDwarfDiscriminator::extractDwarfBaseDiscriminator(D);
2741       if (DwarfBaseDiscriminator)
2742         return *DwarfBaseDiscriminator;
2743       // Return the probe id instead of zero for a pseudo probe discriminator.
2744       // This should help differenciate callsites with same line numbers to
2745       // achieve a decent AutoFDO profile under -fpseudo-probe-for-profiling,
2746       // where the original callsite dwarf discriminator is overwritten by
2747       // callsite probe information.
2748       return PseudoProbeDwarfDiscriminator::extractProbeIndex(D);
2749     }
2750 
2751     if (IsFSDiscriminator)
2752       return getMaskedDiscriminator(D, getBaseDiscriminatorBits());
2753     return getUnsignedFromPrefixEncoding(D);
2754   }
2755 
2756   /// Raw encoding of the discriminator. APIs such as cloneWithDuplicationFactor
2757   /// have certain special case behavior (e.g. treating empty duplication factor
2758   /// as the value '1').
2759   /// This API, in conjunction with cloneWithDiscriminator, may be used to
2760   /// encode the raw values provided.
2761   ///
2762   /// \p BD: base discriminator
2763   /// \p DF: duplication factor
2764   /// \p CI: copy index
2765   ///
2766   /// The return is std::nullopt if the values cannot be encoded in 32 bits -
2767   /// for example, values for BD or DF larger than 12 bits. Otherwise, the
2768   /// return is the encoded value.
2769   LLVM_ABI static std::optional<unsigned>
2770   encodeDiscriminator(unsigned BD, unsigned DF, unsigned CI);
2771 
2772   /// Raw decoder for values in an encoded discriminator D.
2773   LLVM_ABI static void decodeDiscriminator(unsigned D, unsigned &BD,
2774                                            unsigned &DF, unsigned &CI);
2775 
2776   /// Returns the duplication factor for a given encoded discriminator \p D, or
2777   /// 1 if no value or 0 is encoded.
getDuplicationFactorFromDiscriminator(unsigned D)2778   static unsigned getDuplicationFactorFromDiscriminator(unsigned D) {
2779     if (EnableFSDiscriminator)
2780       return 1;
2781     D = getNextComponentInDiscriminator(D);
2782     unsigned Ret = getUnsignedFromPrefixEncoding(D);
2783     if (Ret == 0)
2784       return 1;
2785     return Ret;
2786   }
2787 
2788   /// Returns the copy identifier for a given encoded discriminator \p D.
getCopyIdentifierFromDiscriminator(unsigned D)2789   static unsigned getCopyIdentifierFromDiscriminator(unsigned D) {
2790     return getUnsignedFromPrefixEncoding(
2791         getNextComponentInDiscriminator(getNextComponentInDiscriminator(D)));
2792   }
2793 
getRawScope()2794   Metadata *getRawScope() const { return getOperand(0); }
getRawInlinedAt()2795   Metadata *getRawInlinedAt() const {
2796     if (getNumOperands() == 2)
2797       return getOperand(1);
2798     return nullptr;
2799   }
2800 
classof(const Metadata * MD)2801   static bool classof(const Metadata *MD) {
2802     return MD->getMetadataID() == DILocationKind;
2803   }
2804 };
2805 
2806 class DILexicalBlockBase : public DILocalScope {
2807 protected:
2808   LLVM_ABI DILexicalBlockBase(LLVMContext &C, unsigned ID, StorageType Storage,
2809                               ArrayRef<Metadata *> Ops);
2810   ~DILexicalBlockBase() = default;
2811 
2812 public:
getScope()2813   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
2814 
getRawScope()2815   Metadata *getRawScope() const { return getOperand(1); }
2816 
replaceScope(DIScope * Scope)2817   void replaceScope(DIScope *Scope) {
2818     assert(!isUniqued());
2819     setOperand(1, Scope);
2820   }
2821 
classof(const Metadata * MD)2822   static bool classof(const Metadata *MD) {
2823     return MD->getMetadataID() == DILexicalBlockKind ||
2824            MD->getMetadataID() == DILexicalBlockFileKind;
2825   }
2826 };
2827 
2828 /// Debug lexical block.
2829 ///
2830 /// Uses the SubclassData32 Metadata slot.
2831 class DILexicalBlock : public DILexicalBlockBase {
2832   friend class LLVMContextImpl;
2833   friend class MDNode;
2834 
2835   uint16_t Column;
2836 
DILexicalBlock(LLVMContext & C,StorageType Storage,unsigned Line,unsigned Column,ArrayRef<Metadata * > Ops)2837   DILexicalBlock(LLVMContext &C, StorageType Storage, unsigned Line,
2838                  unsigned Column, ArrayRef<Metadata *> Ops)
2839       : DILexicalBlockBase(C, DILexicalBlockKind, Storage, Ops),
2840         Column(Column) {
2841     SubclassData32 = Line;
2842     assert(Column < (1u << 16) && "Expected 16-bit column");
2843   }
2844   ~DILexicalBlock() = default;
2845 
2846   static DILexicalBlock *getImpl(LLVMContext &Context, DILocalScope *Scope,
2847                                  DIFile *File, unsigned Line, unsigned Column,
2848                                  StorageType Storage,
2849                                  bool ShouldCreate = true) {
2850     return getImpl(Context, static_cast<Metadata *>(Scope),
2851                    static_cast<Metadata *>(File), Line, Column, Storage,
2852                    ShouldCreate);
2853   }
2854 
2855   LLVM_ABI static DILexicalBlock *getImpl(LLVMContext &Context, Metadata *Scope,
2856                                           Metadata *File, unsigned Line,
2857                                           unsigned Column, StorageType Storage,
2858                                           bool ShouldCreate = true);
2859 
cloneImpl()2860   TempDILexicalBlock cloneImpl() const {
2861     return getTemporary(getContext(), getScope(), getFile(), getLine(),
2862                         getColumn());
2863   }
2864 
2865 public:
2866   DEFINE_MDNODE_GET(DILexicalBlock,
2867                     (DILocalScope * Scope, DIFile *File, unsigned Line,
2868                      unsigned Column),
2869                     (Scope, File, Line, Column))
2870   DEFINE_MDNODE_GET(DILexicalBlock,
2871                     (Metadata * Scope, Metadata *File, unsigned Line,
2872                      unsigned Column),
2873                     (Scope, File, Line, Column))
2874 
clone()2875   TempDILexicalBlock clone() const { return cloneImpl(); }
2876 
getLine()2877   unsigned getLine() const { return SubclassData32; }
getColumn()2878   unsigned getColumn() const { return Column; }
2879 
classof(const Metadata * MD)2880   static bool classof(const Metadata *MD) {
2881     return MD->getMetadataID() == DILexicalBlockKind;
2882   }
2883 };
2884 
2885 class DILexicalBlockFile : public DILexicalBlockBase {
2886   friend class LLVMContextImpl;
2887   friend class MDNode;
2888 
DILexicalBlockFile(LLVMContext & C,StorageType Storage,unsigned Discriminator,ArrayRef<Metadata * > Ops)2889   DILexicalBlockFile(LLVMContext &C, StorageType Storage,
2890                      unsigned Discriminator, ArrayRef<Metadata *> Ops)
2891       : DILexicalBlockBase(C, DILexicalBlockFileKind, Storage, Ops) {
2892     SubclassData32 = Discriminator;
2893   }
2894   ~DILexicalBlockFile() = default;
2895 
2896   static DILexicalBlockFile *getImpl(LLVMContext &Context, DILocalScope *Scope,
2897                                      DIFile *File, unsigned Discriminator,
2898                                      StorageType Storage,
2899                                      bool ShouldCreate = true) {
2900     return getImpl(Context, static_cast<Metadata *>(Scope),
2901                    static_cast<Metadata *>(File), Discriminator, Storage,
2902                    ShouldCreate);
2903   }
2904 
2905   LLVM_ABI static DILexicalBlockFile *getImpl(LLVMContext &Context,
2906                                               Metadata *Scope, Metadata *File,
2907                                               unsigned Discriminator,
2908                                               StorageType Storage,
2909                                               bool ShouldCreate = true);
2910 
cloneImpl()2911   TempDILexicalBlockFile cloneImpl() const {
2912     return getTemporary(getContext(), getScope(), getFile(),
2913                         getDiscriminator());
2914   }
2915 
2916 public:
2917   DEFINE_MDNODE_GET(DILexicalBlockFile,
2918                     (DILocalScope * Scope, DIFile *File,
2919                      unsigned Discriminator),
2920                     (Scope, File, Discriminator))
2921   DEFINE_MDNODE_GET(DILexicalBlockFile,
2922                     (Metadata * Scope, Metadata *File, unsigned Discriminator),
2923                     (Scope, File, Discriminator))
2924 
clone()2925   TempDILexicalBlockFile clone() const { return cloneImpl(); }
getDiscriminator()2926   unsigned getDiscriminator() const { return SubclassData32; }
2927 
classof(const Metadata * MD)2928   static bool classof(const Metadata *MD) {
2929     return MD->getMetadataID() == DILexicalBlockFileKind;
2930   }
2931 };
2932 
getDiscriminator()2933 unsigned DILocation::getDiscriminator() const {
2934   if (auto *F = dyn_cast<DILexicalBlockFile>(getScope()))
2935     return F->getDiscriminator();
2936   return 0;
2937 }
2938 
2939 const DILocation *
cloneWithDiscriminator(unsigned Discriminator)2940 DILocation::cloneWithDiscriminator(unsigned Discriminator) const {
2941   DIScope *Scope = getScope();
2942   // Skip all parent DILexicalBlockFile that already have a discriminator
2943   // assigned. We do not want to have nested DILexicalBlockFiles that have
2944   // multiple discriminators because only the leaf DILexicalBlockFile's
2945   // dominator will be used.
2946   for (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope);
2947        LBF && LBF->getDiscriminator() != 0;
2948        LBF = dyn_cast<DILexicalBlockFile>(Scope))
2949     Scope = LBF->getScope();
2950   DILexicalBlockFile *NewScope =
2951       DILexicalBlockFile::get(getContext(), Scope, getFile(), Discriminator);
2952   return DILocation::get(getContext(), getLine(), getColumn(), NewScope,
2953                          getInlinedAt(), isImplicitCode(), getAtomGroup(),
2954                          getAtomRank());
2955 }
2956 
getBaseDiscriminator()2957 unsigned DILocation::getBaseDiscriminator() const {
2958   return getBaseDiscriminatorFromDiscriminator(getDiscriminator(),
2959                                                EnableFSDiscriminator);
2960 }
2961 
getDuplicationFactor()2962 unsigned DILocation::getDuplicationFactor() const {
2963   return getDuplicationFactorFromDiscriminator(getDiscriminator());
2964 }
2965 
getCopyIdentifier()2966 unsigned DILocation::getCopyIdentifier() const {
2967   return getCopyIdentifierFromDiscriminator(getDiscriminator());
2968 }
2969 
2970 std::optional<const DILocation *>
cloneWithBaseDiscriminator(unsigned D)2971 DILocation::cloneWithBaseDiscriminator(unsigned D) const {
2972   unsigned BD, DF, CI;
2973 
2974   if (EnableFSDiscriminator) {
2975     BD = getBaseDiscriminator();
2976     if (D == BD)
2977       return this;
2978     return cloneWithDiscriminator(D);
2979   }
2980 
2981   decodeDiscriminator(getDiscriminator(), BD, DF, CI);
2982   if (D == BD)
2983     return this;
2984   if (std::optional<unsigned> Encoded = encodeDiscriminator(D, DF, CI))
2985     return cloneWithDiscriminator(*Encoded);
2986   return std::nullopt;
2987 }
2988 
2989 std::optional<const DILocation *>
cloneByMultiplyingDuplicationFactor(unsigned DF)2990 DILocation::cloneByMultiplyingDuplicationFactor(unsigned DF) const {
2991   assert(!EnableFSDiscriminator && "FSDiscriminator should not call this.");
2992   // Do no interfere with pseudo probes. Pseudo probe doesn't need duplication
2993   // factor support as samples collected on cloned probes will be aggregated.
2994   // Also pseudo probe at a callsite uses the dwarf discriminator to store
2995   // pseudo probe related information, such as the probe id.
2996   if (isPseudoProbeDiscriminator(getDiscriminator()))
2997     return this;
2998 
2999   DF *= getDuplicationFactor();
3000   if (DF <= 1)
3001     return this;
3002 
3003   unsigned BD = getBaseDiscriminator();
3004   unsigned CI = getCopyIdentifier();
3005   if (std::optional<unsigned> D = encodeDiscriminator(BD, DF, CI))
3006     return cloneWithDiscriminator(*D);
3007   return std::nullopt;
3008 }
3009 
3010 /// Debug lexical block.
3011 ///
3012 /// Uses the SubclassData1 Metadata slot.
3013 class DINamespace : public DIScope {
3014   friend class LLVMContextImpl;
3015   friend class MDNode;
3016 
3017   DINamespace(LLVMContext &Context, StorageType Storage, bool ExportSymbols,
3018               ArrayRef<Metadata *> Ops);
3019   ~DINamespace() = default;
3020 
3021   static DINamespace *getImpl(LLVMContext &Context, DIScope *Scope,
3022                               StringRef Name, bool ExportSymbols,
3023                               StorageType Storage, bool ShouldCreate = true) {
3024     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
3025                    ExportSymbols, Storage, ShouldCreate);
3026   }
3027   LLVM_ABI static DINamespace *getImpl(LLVMContext &Context, Metadata *Scope,
3028                                        MDString *Name, bool ExportSymbols,
3029                                        StorageType Storage,
3030                                        bool ShouldCreate = true);
3031 
cloneImpl()3032   TempDINamespace cloneImpl() const {
3033     return getTemporary(getContext(), getScope(), getName(),
3034                         getExportSymbols());
3035   }
3036 
3037 public:
3038   DEFINE_MDNODE_GET(DINamespace,
3039                     (DIScope * Scope, StringRef Name, bool ExportSymbols),
3040                     (Scope, Name, ExportSymbols))
3041   DEFINE_MDNODE_GET(DINamespace,
3042                     (Metadata * Scope, MDString *Name, bool ExportSymbols),
3043                     (Scope, Name, ExportSymbols))
3044 
clone()3045   TempDINamespace clone() const { return cloneImpl(); }
3046 
getExportSymbols()3047   bool getExportSymbols() const { return SubclassData1; }
getScope()3048   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
getName()3049   StringRef getName() const { return getStringOperand(2); }
3050 
getRawScope()3051   Metadata *getRawScope() const { return getOperand(1); }
getRawName()3052   MDString *getRawName() const { return getOperandAs<MDString>(2); }
3053 
classof(const Metadata * MD)3054   static bool classof(const Metadata *MD) {
3055     return MD->getMetadataID() == DINamespaceKind;
3056   }
3057 };
3058 
3059 /// Represents a module in the programming language, for example, a Clang
3060 /// module, or a Fortran module.
3061 ///
3062 /// Uses the SubclassData1 and SubclassData32 Metadata slots.
3063 class DIModule : public DIScope {
3064   friend class LLVMContextImpl;
3065   friend class MDNode;
3066 
3067   DIModule(LLVMContext &Context, StorageType Storage, unsigned LineNo,
3068            bool IsDecl, ArrayRef<Metadata *> Ops);
3069   ~DIModule() = default;
3070 
3071   static DIModule *getImpl(LLVMContext &Context, DIFile *File, DIScope *Scope,
3072                            StringRef Name, StringRef ConfigurationMacros,
3073                            StringRef IncludePath, StringRef APINotesFile,
3074                            unsigned LineNo, bool IsDecl, StorageType Storage,
3075                            bool ShouldCreate = true) {
3076     return getImpl(Context, File, Scope, getCanonicalMDString(Context, Name),
3077                    getCanonicalMDString(Context, ConfigurationMacros),
3078                    getCanonicalMDString(Context, IncludePath),
3079                    getCanonicalMDString(Context, APINotesFile), LineNo, IsDecl,
3080                    Storage, ShouldCreate);
3081   }
3082   LLVM_ABI static DIModule *
3083   getImpl(LLVMContext &Context, Metadata *File, Metadata *Scope, MDString *Name,
3084           MDString *ConfigurationMacros, MDString *IncludePath,
3085           MDString *APINotesFile, unsigned LineNo, bool IsDecl,
3086           StorageType Storage, bool ShouldCreate = true);
3087 
cloneImpl()3088   TempDIModule cloneImpl() const {
3089     return getTemporary(getContext(), getFile(), getScope(), getName(),
3090                         getConfigurationMacros(), getIncludePath(),
3091                         getAPINotesFile(), getLineNo(), getIsDecl());
3092   }
3093 
3094 public:
3095   DEFINE_MDNODE_GET(DIModule,
3096                     (DIFile * File, DIScope *Scope, StringRef Name,
3097                      StringRef ConfigurationMacros, StringRef IncludePath,
3098                      StringRef APINotesFile, unsigned LineNo,
3099                      bool IsDecl = false),
3100                     (File, Scope, Name, ConfigurationMacros, IncludePath,
3101                      APINotesFile, LineNo, IsDecl))
3102   DEFINE_MDNODE_GET(DIModule,
3103                     (Metadata * File, Metadata *Scope, MDString *Name,
3104                      MDString *ConfigurationMacros, MDString *IncludePath,
3105                      MDString *APINotesFile, unsigned LineNo,
3106                      bool IsDecl = false),
3107                     (File, Scope, Name, ConfigurationMacros, IncludePath,
3108                      APINotesFile, LineNo, IsDecl))
3109 
clone()3110   TempDIModule clone() const { return cloneImpl(); }
3111 
getScope()3112   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
getName()3113   StringRef getName() const { return getStringOperand(2); }
getConfigurationMacros()3114   StringRef getConfigurationMacros() const { return getStringOperand(3); }
getIncludePath()3115   StringRef getIncludePath() const { return getStringOperand(4); }
getAPINotesFile()3116   StringRef getAPINotesFile() const { return getStringOperand(5); }
getLineNo()3117   unsigned getLineNo() const { return SubclassData32; }
getIsDecl()3118   bool getIsDecl() const { return SubclassData1; }
3119 
getRawScope()3120   Metadata *getRawScope() const { return getOperand(1); }
getRawName()3121   MDString *getRawName() const { return getOperandAs<MDString>(2); }
getRawConfigurationMacros()3122   MDString *getRawConfigurationMacros() const {
3123     return getOperandAs<MDString>(3);
3124   }
getRawIncludePath()3125   MDString *getRawIncludePath() const { return getOperandAs<MDString>(4); }
getRawAPINotesFile()3126   MDString *getRawAPINotesFile() const { return getOperandAs<MDString>(5); }
3127 
classof(const Metadata * MD)3128   static bool classof(const Metadata *MD) {
3129     return MD->getMetadataID() == DIModuleKind;
3130   }
3131 };
3132 
3133 /// Base class for template parameters.
3134 ///
3135 /// Uses the SubclassData1 Metadata slot.
3136 class DITemplateParameter : public DINode {
3137 protected:
DITemplateParameter(LLVMContext & Context,unsigned ID,StorageType Storage,unsigned Tag,bool IsDefault,ArrayRef<Metadata * > Ops)3138   DITemplateParameter(LLVMContext &Context, unsigned ID, StorageType Storage,
3139                       unsigned Tag, bool IsDefault, ArrayRef<Metadata *> Ops)
3140       : DINode(Context, ID, Storage, Tag, Ops) {
3141     SubclassData1 = IsDefault;
3142   }
3143   ~DITemplateParameter() = default;
3144 
3145 public:
getName()3146   StringRef getName() const { return getStringOperand(0); }
getType()3147   DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
3148 
getRawName()3149   MDString *getRawName() const { return getOperandAs<MDString>(0); }
getRawType()3150   Metadata *getRawType() const { return getOperand(1); }
isDefault()3151   bool isDefault() const { return SubclassData1; }
3152 
classof(const Metadata * MD)3153   static bool classof(const Metadata *MD) {
3154     return MD->getMetadataID() == DITemplateTypeParameterKind ||
3155            MD->getMetadataID() == DITemplateValueParameterKind;
3156   }
3157 };
3158 
3159 class DITemplateTypeParameter : public DITemplateParameter {
3160   friend class LLVMContextImpl;
3161   friend class MDNode;
3162 
3163   DITemplateTypeParameter(LLVMContext &Context, StorageType Storage,
3164                           bool IsDefault, ArrayRef<Metadata *> Ops);
3165   ~DITemplateTypeParameter() = default;
3166 
3167   static DITemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
3168                                           DIType *Type, bool IsDefault,
3169                                           StorageType Storage,
3170                                           bool ShouldCreate = true) {
3171     return getImpl(Context, getCanonicalMDString(Context, Name), Type,
3172                    IsDefault, Storage, ShouldCreate);
3173   }
3174   LLVM_ABI static DITemplateTypeParameter *
3175   getImpl(LLVMContext &Context, MDString *Name, Metadata *Type, bool IsDefault,
3176           StorageType Storage, bool ShouldCreate = true);
3177 
cloneImpl()3178   TempDITemplateTypeParameter cloneImpl() const {
3179     return getTemporary(getContext(), getName(), getType(), isDefault());
3180   }
3181 
3182 public:
3183   DEFINE_MDNODE_GET(DITemplateTypeParameter,
3184                     (StringRef Name, DIType *Type, bool IsDefault),
3185                     (Name, Type, IsDefault))
3186   DEFINE_MDNODE_GET(DITemplateTypeParameter,
3187                     (MDString * Name, Metadata *Type, bool IsDefault),
3188                     (Name, Type, IsDefault))
3189 
clone()3190   TempDITemplateTypeParameter clone() const { return cloneImpl(); }
3191 
classof(const Metadata * MD)3192   static bool classof(const Metadata *MD) {
3193     return MD->getMetadataID() == DITemplateTypeParameterKind;
3194   }
3195 };
3196 
3197 class DITemplateValueParameter : public DITemplateParameter {
3198   friend class LLVMContextImpl;
3199   friend class MDNode;
3200 
DITemplateValueParameter(LLVMContext & Context,StorageType Storage,unsigned Tag,bool IsDefault,ArrayRef<Metadata * > Ops)3201   DITemplateValueParameter(LLVMContext &Context, StorageType Storage,
3202                            unsigned Tag, bool IsDefault,
3203                            ArrayRef<Metadata *> Ops)
3204       : DITemplateParameter(Context, DITemplateValueParameterKind, Storage, Tag,
3205                             IsDefault, Ops) {}
3206   ~DITemplateValueParameter() = default;
3207 
3208   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
3209                                            StringRef Name, DIType *Type,
3210                                            bool IsDefault, Metadata *Value,
3211                                            StorageType Storage,
3212                                            bool ShouldCreate = true) {
3213     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), Type,
3214                    IsDefault, Value, Storage, ShouldCreate);
3215   }
3216   LLVM_ABI static DITemplateValueParameter *
3217   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
3218           bool IsDefault, Metadata *Value, StorageType Storage,
3219           bool ShouldCreate = true);
3220 
cloneImpl()3221   TempDITemplateValueParameter cloneImpl() const {
3222     return getTemporary(getContext(), getTag(), getName(), getType(),
3223                         isDefault(), getValue());
3224   }
3225 
3226 public:
3227   DEFINE_MDNODE_GET(DITemplateValueParameter,
3228                     (unsigned Tag, StringRef Name, DIType *Type, bool IsDefault,
3229                      Metadata *Value),
3230                     (Tag, Name, Type, IsDefault, Value))
3231   DEFINE_MDNODE_GET(DITemplateValueParameter,
3232                     (unsigned Tag, MDString *Name, Metadata *Type,
3233                      bool IsDefault, Metadata *Value),
3234                     (Tag, Name, Type, IsDefault, Value))
3235 
clone()3236   TempDITemplateValueParameter clone() const { return cloneImpl(); }
3237 
getValue()3238   Metadata *getValue() const { return getOperand(2); }
3239 
classof(const Metadata * MD)3240   static bool classof(const Metadata *MD) {
3241     return MD->getMetadataID() == DITemplateValueParameterKind;
3242   }
3243 };
3244 
3245 /// Base class for variables.
3246 ///
3247 /// Uses the SubclassData32 Metadata slot.
3248 class DIVariable : public DINode {
3249   unsigned Line;
3250 
3251 protected:
3252   LLVM_ABI DIVariable(LLVMContext &C, unsigned ID, StorageType Storage,
3253                       signed Line, ArrayRef<Metadata *> Ops,
3254                       uint32_t AlignInBits = 0);
3255   ~DIVariable() = default;
3256 
3257 public:
getLine()3258   unsigned getLine() const { return Line; }
getScope()3259   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
getName()3260   StringRef getName() const { return getStringOperand(1); }
getFile()3261   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
getType()3262   DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
getAlignInBits()3263   uint32_t getAlignInBits() const { return SubclassData32; }
getAlignInBytes()3264   uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
3265   /// Determines the size of the variable's type.
3266   LLVM_ABI std::optional<uint64_t> getSizeInBits() const;
3267 
3268   /// Return the signedness of this variable's type, or std::nullopt if this
3269   /// type is neither signed nor unsigned.
getSignedness()3270   std::optional<DIBasicType::Signedness> getSignedness() const {
3271     if (auto *BT = dyn_cast<DIBasicType>(getType()))
3272       return BT->getSignedness();
3273     return std::nullopt;
3274   }
3275 
getFilename()3276   StringRef getFilename() const {
3277     if (auto *F = getFile())
3278       return F->getFilename();
3279     return "";
3280   }
3281 
getDirectory()3282   StringRef getDirectory() const {
3283     if (auto *F = getFile())
3284       return F->getDirectory();
3285     return "";
3286   }
3287 
getSource()3288   std::optional<StringRef> getSource() const {
3289     if (auto *F = getFile())
3290       return F->getSource();
3291     return std::nullopt;
3292   }
3293 
getRawScope()3294   Metadata *getRawScope() const { return getOperand(0); }
getRawName()3295   MDString *getRawName() const { return getOperandAs<MDString>(1); }
getRawFile()3296   Metadata *getRawFile() const { return getOperand(2); }
getRawType()3297   Metadata *getRawType() const { return getOperand(3); }
3298 
classof(const Metadata * MD)3299   static bool classof(const Metadata *MD) {
3300     return MD->getMetadataID() == DILocalVariableKind ||
3301            MD->getMetadataID() == DIGlobalVariableKind;
3302   }
3303 };
3304 
3305 /// DWARF expression.
3306 ///
3307 /// This is (almost) a DWARF expression that modifies the location of a
3308 /// variable, or the location of a single piece of a variable, or (when using
3309 /// DW_OP_stack_value) is the constant variable value.
3310 ///
3311 /// TODO: Co-allocate the expression elements.
3312 /// TODO: Separate from MDNode, or otherwise drop Distinct and Temporary
3313 /// storage types.
3314 class DIExpression : public MDNode {
3315   friend class LLVMContextImpl;
3316   friend class MDNode;
3317 
3318   std::vector<uint64_t> Elements;
3319 
DIExpression(LLVMContext & C,StorageType Storage,ArrayRef<uint64_t> Elements)3320   DIExpression(LLVMContext &C, StorageType Storage, ArrayRef<uint64_t> Elements)
3321       : MDNode(C, DIExpressionKind, Storage, {}),
3322         Elements(Elements.begin(), Elements.end()) {}
3323   ~DIExpression() = default;
3324 
3325   LLVM_ABI static DIExpression *getImpl(LLVMContext &Context,
3326                                         ArrayRef<uint64_t> Elements,
3327                                         StorageType Storage,
3328                                         bool ShouldCreate = true);
3329 
cloneImpl()3330   TempDIExpression cloneImpl() const {
3331     return getTemporary(getContext(), getElements());
3332   }
3333 
3334 public:
3335   DEFINE_MDNODE_GET(DIExpression, (ArrayRef<uint64_t> Elements), (Elements))
3336 
clone()3337   TempDIExpression clone() const { return cloneImpl(); }
3338 
getElements()3339   ArrayRef<uint64_t> getElements() const { return Elements; }
3340 
getNumElements()3341   unsigned getNumElements() const { return Elements.size(); }
3342 
getElement(unsigned I)3343   uint64_t getElement(unsigned I) const {
3344     assert(I < Elements.size() && "Index out of range");
3345     return Elements[I];
3346   }
3347 
3348   enum SignedOrUnsignedConstant { SignedConstant, UnsignedConstant };
3349   /// Determine whether this represents a constant value, if so
3350   // return it's sign information.
3351   LLVM_ABI std::optional<SignedOrUnsignedConstant> isConstant() const;
3352 
3353   /// Return the number of unique location operands referred to (via
3354   /// DW_OP_LLVM_arg) in this expression; this is not necessarily the number of
3355   /// instances of DW_OP_LLVM_arg within the expression.
3356   /// For example, for the expression:
3357   ///   (DW_OP_LLVM_arg 0, DW_OP_LLVM_arg 1, DW_OP_plus,
3358   ///    DW_OP_LLVM_arg 0, DW_OP_mul)
3359   /// This function would return 2, as there are two unique location operands
3360   /// (0 and 1).
3361   LLVM_ABI uint64_t getNumLocationOperands() const;
3362 
3363   using element_iterator = ArrayRef<uint64_t>::iterator;
3364 
elements_begin()3365   element_iterator elements_begin() const { return getElements().begin(); }
elements_end()3366   element_iterator elements_end() const { return getElements().end(); }
3367 
3368   /// A lightweight wrapper around an expression operand.
3369   ///
3370   /// TODO: Store arguments directly and change \a DIExpression to store a
3371   /// range of these.
3372   class ExprOperand {
3373     const uint64_t *Op = nullptr;
3374 
3375   public:
3376     ExprOperand() = default;
ExprOperand(const uint64_t * Op)3377     explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
3378 
get()3379     const uint64_t *get() const { return Op; }
3380 
3381     /// Get the operand code.
getOp()3382     uint64_t getOp() const { return *Op; }
3383 
3384     /// Get an argument to the operand.
3385     ///
3386     /// Never returns the operand itself.
getArg(unsigned I)3387     uint64_t getArg(unsigned I) const { return Op[I + 1]; }
3388 
getNumArgs()3389     unsigned getNumArgs() const { return getSize() - 1; }
3390 
3391     /// Return the size of the operand.
3392     ///
3393     /// Return the number of elements in the operand (1 + args).
3394     LLVM_ABI unsigned getSize() const;
3395 
3396     /// Append the elements of this operand to \p V.
appendToVector(SmallVectorImpl<uint64_t> & V)3397     void appendToVector(SmallVectorImpl<uint64_t> &V) const {
3398       V.append(get(), get() + getSize());
3399     }
3400   };
3401 
3402   /// An iterator for expression operands.
3403   class expr_op_iterator {
3404     ExprOperand Op;
3405 
3406   public:
3407     using iterator_category = std::input_iterator_tag;
3408     using value_type = ExprOperand;
3409     using difference_type = std::ptrdiff_t;
3410     using pointer = value_type *;
3411     using reference = value_type &;
3412 
3413     expr_op_iterator() = default;
expr_op_iterator(element_iterator I)3414     explicit expr_op_iterator(element_iterator I) : Op(I) {}
3415 
getBase()3416     element_iterator getBase() const { return Op.get(); }
3417     const ExprOperand &operator*() const { return Op; }
3418     const ExprOperand *operator->() const { return &Op; }
3419 
3420     expr_op_iterator &operator++() {
3421       increment();
3422       return *this;
3423     }
3424     expr_op_iterator operator++(int) {
3425       expr_op_iterator T(*this);
3426       increment();
3427       return T;
3428     }
3429 
3430     /// Get the next iterator.
3431     ///
3432     /// \a std::next() doesn't work because this is technically an
3433     /// input_iterator, but it's a perfectly valid operation.  This is an
3434     /// accessor to provide the same functionality.
getNext()3435     expr_op_iterator getNext() const { return ++expr_op_iterator(*this); }
3436 
3437     bool operator==(const expr_op_iterator &X) const {
3438       return getBase() == X.getBase();
3439     }
3440     bool operator!=(const expr_op_iterator &X) const {
3441       return getBase() != X.getBase();
3442     }
3443 
3444   private:
increment()3445     void increment() { Op = ExprOperand(getBase() + Op.getSize()); }
3446   };
3447 
3448   /// Visit the elements via ExprOperand wrappers.
3449   ///
3450   /// These range iterators visit elements through \a ExprOperand wrappers.
3451   /// This is not guaranteed to be a valid range unless \a isValid() gives \c
3452   /// true.
3453   ///
3454   /// \pre \a isValid() gives \c true.
3455   /// @{
expr_op_begin()3456   expr_op_iterator expr_op_begin() const {
3457     return expr_op_iterator(elements_begin());
3458   }
expr_op_end()3459   expr_op_iterator expr_op_end() const {
3460     return expr_op_iterator(elements_end());
3461   }
expr_ops()3462   iterator_range<expr_op_iterator> expr_ops() const {
3463     return {expr_op_begin(), expr_op_end()};
3464   }
3465   /// @}
3466 
3467   LLVM_ABI bool isValid() const;
3468 
classof(const Metadata * MD)3469   static bool classof(const Metadata *MD) {
3470     return MD->getMetadataID() == DIExpressionKind;
3471   }
3472 
3473   /// Return whether the first element a DW_OP_deref.
3474   LLVM_ABI bool startsWithDeref() const;
3475 
3476   /// Return whether there is exactly one operator and it is a DW_OP_deref;
3477   LLVM_ABI bool isDeref() const;
3478 
3479   using FragmentInfo = DbgVariableFragmentInfo;
3480 
3481   /// Return the number of bits that have an active value, i.e. those that
3482   /// aren't known to be zero/sign (depending on the type of Var) and which
3483   /// are within the size of this fragment (if it is one). If we can't deduce
3484   /// anything from the expression this will return the size of Var.
3485   LLVM_ABI std::optional<uint64_t> getActiveBits(DIVariable *Var);
3486 
3487   /// Retrieve the details of this fragment expression.
3488   LLVM_ABI static std::optional<FragmentInfo>
3489   getFragmentInfo(expr_op_iterator Start, expr_op_iterator End);
3490 
3491   /// Retrieve the details of this fragment expression.
getFragmentInfo()3492   std::optional<FragmentInfo> getFragmentInfo() const {
3493     return getFragmentInfo(expr_op_begin(), expr_op_end());
3494   }
3495 
3496   /// Return whether this is a piece of an aggregate variable.
isFragment()3497   bool isFragment() const { return getFragmentInfo().has_value(); }
3498 
3499   /// Return whether this is an implicit location description.
3500   LLVM_ABI bool isImplicit() const;
3501 
3502   /// Return whether the location is computed on the expression stack, meaning
3503   /// it cannot be a simple register location.
3504   LLVM_ABI bool isComplex() const;
3505 
3506   /// Return whether the evaluated expression makes use of a single location at
3507   /// the start of the expression, i.e. if it contains only a single
3508   /// DW_OP_LLVM_arg op as its first operand, or if it contains none.
3509   LLVM_ABI bool isSingleLocationExpression() const;
3510 
3511   /// Returns a reference to the elements contained in this expression, skipping
3512   /// past the leading `DW_OP_LLVM_arg, 0` if one is present.
3513   /// Similar to `convertToNonVariadicExpression`, but faster and cheaper - it
3514   /// does not check whether the expression is a single-location expression, and
3515   /// it returns elements rather than creating a new DIExpression.
3516   LLVM_ABI std::optional<ArrayRef<uint64_t>>
3517   getSingleLocationExpressionElements() const;
3518 
3519   /// Removes all elements from \p Expr that do not apply to an undef debug
3520   /// value, which includes every operator that computes the value/location on
3521   /// the DWARF stack, including any DW_OP_LLVM_arg elements (making the result
3522   /// of this function always a single-location expression) while leaving
3523   /// everything that defines what the computed value applies to, i.e. the
3524   /// fragment information.
3525   LLVM_ABI static const DIExpression *
3526   convertToUndefExpression(const DIExpression *Expr);
3527 
3528   /// If \p Expr is a non-variadic expression (i.e. one that does not contain
3529   /// DW_OP_LLVM_arg), returns \p Expr converted to variadic form by adding a
3530   /// leading [DW_OP_LLVM_arg, 0] to the expression; otherwise returns \p Expr.
3531   LLVM_ABI static const DIExpression *
3532   convertToVariadicExpression(const DIExpression *Expr);
3533 
3534   /// If \p Expr is a valid single-location expression, i.e. it refers to only a
3535   /// single debug operand at the start of the expression, then return that
3536   /// expression in a non-variadic form by removing DW_OP_LLVM_arg from the
3537   /// expression if it is present; otherwise returns std::nullopt.
3538   /// See also `getSingleLocationExpressionElements` above, which skips
3539   /// checking `isSingleLocationExpression` and returns a list of elements
3540   /// rather than a DIExpression.
3541   LLVM_ABI static std::optional<const DIExpression *>
3542   convertToNonVariadicExpression(const DIExpression *Expr);
3543 
3544   /// Inserts the elements of \p Expr into \p Ops modified to a canonical form,
3545   /// which uses DW_OP_LLVM_arg (i.e. is a variadic expression) and folds the
3546   /// implied derefence from the \p IsIndirect flag into the expression. This
3547   /// allows us to check equivalence between expressions with differing
3548   /// directness or variadicness.
3549   LLVM_ABI static void canonicalizeExpressionOps(SmallVectorImpl<uint64_t> &Ops,
3550                                                  const DIExpression *Expr,
3551                                                  bool IsIndirect);
3552 
3553   /// Determines whether two debug values should produce equivalent DWARF
3554   /// expressions, using their DIExpressions and directness, ignoring the
3555   /// differences between otherwise identical expressions in variadic and
3556   /// non-variadic form and not considering the debug operands.
3557   /// \p FirstExpr is the DIExpression for the first debug value.
3558   /// \p FirstIndirect should be true if the first debug value is indirect; in
3559   /// IR this should be true for dbg.declare intrinsics and false for
3560   /// dbg.values, and in MIR this should be true only for DBG_VALUE instructions
3561   /// whose second operand is an immediate value.
3562   /// \p SecondExpr and \p SecondIndirect have the same meaning as the prior
3563   /// arguments, but apply to the second debug value.
3564   LLVM_ABI static bool isEqualExpression(const DIExpression *FirstExpr,
3565                                          bool FirstIndirect,
3566                                          const DIExpression *SecondExpr,
3567                                          bool SecondIndirect);
3568 
3569   /// Append \p Ops with operations to apply the \p Offset.
3570   LLVM_ABI static void appendOffset(SmallVectorImpl<uint64_t> &Ops,
3571                                     int64_t Offset);
3572 
3573   /// If this is a constant offset, extract it. If there is no expression,
3574   /// return true with an offset of zero.
3575   LLVM_ABI bool extractIfOffset(int64_t &Offset) const;
3576 
3577   /// Assuming that the expression operates on an address, extract a constant
3578   /// offset and the successive ops. Return false if the expression contains
3579   /// any incompatible ops (including non-zero DW_OP_LLVM_args - only a single
3580   /// address operand to the expression is permitted).
3581   ///
3582   /// We don't try very hard to interpret the expression because we assume that
3583   /// foldConstantMath has canonicalized the expression.
3584   LLVM_ABI bool
3585   extractLeadingOffset(int64_t &OffsetInBytes,
3586                        SmallVectorImpl<uint64_t> &RemainingOps) const;
3587 
3588   /// Returns true iff this DIExpression contains at least one instance of
3589   /// `DW_OP_LLVM_arg, n` for all n in [0, N).
3590   LLVM_ABI bool hasAllLocationOps(unsigned N) const;
3591 
3592   /// Checks if the last 4 elements of the expression are DW_OP_constu <DWARF
3593   /// Address Space> DW_OP_swap DW_OP_xderef and extracts the <DWARF Address
3594   /// Space>.
3595   LLVM_ABI static const DIExpression *
3596   extractAddressClass(const DIExpression *Expr, unsigned &AddrClass);
3597 
3598   /// Used for DIExpression::prepend.
3599   enum PrependOps : uint8_t {
3600     ApplyOffset = 0,
3601     DerefBefore = 1 << 0,
3602     DerefAfter = 1 << 1,
3603     StackValue = 1 << 2,
3604     EntryValue = 1 << 3
3605   };
3606 
3607   /// Prepend \p DIExpr with a deref and offset operation and optionally turn it
3608   /// into a stack value or/and an entry value.
3609   LLVM_ABI static DIExpression *prepend(const DIExpression *Expr, uint8_t Flags,
3610                                         int64_t Offset = 0);
3611 
3612   /// Prepend \p DIExpr with the given opcodes and optionally turn it into a
3613   /// stack value.
3614   LLVM_ABI static DIExpression *prependOpcodes(const DIExpression *Expr,
3615                                                SmallVectorImpl<uint64_t> &Ops,
3616                                                bool StackValue = false,
3617                                                bool EntryValue = false);
3618 
3619   /// Append the opcodes \p Ops to \p DIExpr. Unlike \ref appendToStack, the
3620   /// returned expression is a stack value only if \p DIExpr is a stack value.
3621   /// If \p DIExpr describes a fragment, the returned expression will describe
3622   /// the same fragment.
3623   LLVM_ABI static DIExpression *append(const DIExpression *Expr,
3624                                        ArrayRef<uint64_t> Ops);
3625 
3626   /// Convert \p DIExpr into a stack value if it isn't one already by appending
3627   /// DW_OP_deref if needed, and appending \p Ops to the resulting expression.
3628   /// If \p DIExpr describes a fragment, the returned expression will describe
3629   /// the same fragment.
3630   LLVM_ABI static DIExpression *appendToStack(const DIExpression *Expr,
3631                                               ArrayRef<uint64_t> Ops);
3632 
3633   /// Create a copy of \p Expr by appending the given list of \p Ops to each
3634   /// instance of the operand `DW_OP_LLVM_arg, \p ArgNo`. This is used to
3635   /// modify a specific location used by \p Expr, such as when salvaging that
3636   /// location.
3637   LLVM_ABI static DIExpression *appendOpsToArg(const DIExpression *Expr,
3638                                                ArrayRef<uint64_t> Ops,
3639                                                unsigned ArgNo,
3640                                                bool StackValue = false);
3641 
3642   /// Create a copy of \p Expr with each instance of
3643   /// `DW_OP_LLVM_arg, \p OldArg` replaced with `DW_OP_LLVM_arg, \p NewArg`,
3644   /// and each instance of `DW_OP_LLVM_arg, Arg` with `DW_OP_LLVM_arg, Arg - 1`
3645   /// for all Arg > \p OldArg.
3646   /// This is used when replacing one of the operands of a debug value list
3647   /// with another operand in the same list and deleting the old operand.
3648   LLVM_ABI static DIExpression *replaceArg(const DIExpression *Expr,
3649                                            uint64_t OldArg, uint64_t NewArg);
3650 
3651   /// Create a DIExpression to describe one part of an aggregate variable that
3652   /// is fragmented across multiple Values. The DW_OP_LLVM_fragment operation
3653   /// will be appended to the elements of \c Expr. If \c Expr already contains
3654   /// a \c DW_OP_LLVM_fragment \c OffsetInBits is interpreted as an offset
3655   /// into the existing fragment.
3656   ///
3657   /// \param OffsetInBits Offset of the piece in bits.
3658   /// \param SizeInBits   Size of the piece in bits.
3659   /// \return             Creating a fragment expression may fail if \c Expr
3660   ///                     contains arithmetic operations that would be
3661   ///                     truncated.
3662   LLVM_ABI static std::optional<DIExpression *>
3663   createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits,
3664                            unsigned SizeInBits);
3665 
3666   /// Determine the relative position of the fragments passed in.
3667   /// Returns -1 if this is entirely before Other, 0 if this and Other overlap,
3668   /// 1 if this is entirely after Other.
fragmentCmp(const FragmentInfo & A,const FragmentInfo & B)3669   static int fragmentCmp(const FragmentInfo &A, const FragmentInfo &B) {
3670     uint64_t l1 = A.OffsetInBits;
3671     uint64_t l2 = B.OffsetInBits;
3672     uint64_t r1 = l1 + A.SizeInBits;
3673     uint64_t r2 = l2 + B.SizeInBits;
3674     if (r1 <= l2)
3675       return -1;
3676     else if (r2 <= l1)
3677       return 1;
3678     else
3679       return 0;
3680   }
3681 
3682   /// Computes a fragment, bit-extract operation if needed, and new constant
3683   /// offset to describe a part of a variable covered by some memory.
3684   ///
3685   /// The memory region starts at:
3686   ///   \p SliceStart + \p SliceOffsetInBits
3687   /// And is size:
3688   ///   \p SliceSizeInBits
3689   ///
3690   /// The location of the existing variable fragment \p VarFrag is:
3691   ///   \p DbgPtr + \p DbgPtrOffsetInBits + \p DbgExtractOffsetInBits.
3692   ///
3693   /// It is intended that these arguments are derived from a debug record:
3694   /// - \p DbgPtr is the (single) DIExpression operand.
3695   /// - \p DbgPtrOffsetInBits is the constant offset applied to \p DbgPtr.
3696   /// - \p DbgExtractOffsetInBits is the offset from a
3697   ///   DW_OP_LLVM_bit_extract_[sz]ext operation.
3698   ///
3699   /// Results and return value:
3700   /// - Return false if the result can't be calculated for any reason.
3701   /// - \p Result is set to nullopt if the intersect equals \p VarFarg.
3702   /// - \p Result contains a zero-sized fragment if there's no intersect.
3703   /// - \p OffsetFromLocationInBits is set to the difference between the first
3704   ///   bit of the variable location and the first bit of the slice. The
3705   ///   magnitude of a negative value therefore indicates the number of bits
3706   ///   into the variable fragment that the memory region begins.
3707   ///
3708   /// We don't pass in a debug record directly to get the constituent parts
3709   /// and offsets because different debug records store the information in
3710   /// different places (dbg_assign has two DIExpressions - one contains the
3711   /// fragment info for the entire intrinsic).
3712   LLVM_ABI static bool calculateFragmentIntersect(
3713       const DataLayout &DL, const Value *SliceStart, uint64_t SliceOffsetInBits,
3714       uint64_t SliceSizeInBits, const Value *DbgPtr, int64_t DbgPtrOffsetInBits,
3715       int64_t DbgExtractOffsetInBits, DIExpression::FragmentInfo VarFrag,
3716       std::optional<DIExpression::FragmentInfo> &Result,
3717       int64_t &OffsetFromLocationInBits);
3718 
3719   using ExtOps = std::array<uint64_t, 6>;
3720 
3721   /// Returns the ops for a zero- or sign-extension in a DIExpression.
3722   LLVM_ABI static ExtOps getExtOps(unsigned FromSize, unsigned ToSize,
3723                                    bool Signed);
3724 
3725   /// Append a zero- or sign-extension to \p Expr. Converts the expression to a
3726   /// stack value if it isn't one already.
3727   LLVM_ABI static DIExpression *appendExt(const DIExpression *Expr,
3728                                           unsigned FromSize, unsigned ToSize,
3729                                           bool Signed);
3730 
3731   /// Check if fragments overlap between a pair of FragmentInfos.
fragmentsOverlap(const FragmentInfo & A,const FragmentInfo & B)3732   static bool fragmentsOverlap(const FragmentInfo &A, const FragmentInfo &B) {
3733     return fragmentCmp(A, B) == 0;
3734   }
3735 
3736   /// Determine the relative position of the fragments described by this
3737   /// DIExpression and \p Other. Calls static fragmentCmp implementation.
fragmentCmp(const DIExpression * Other)3738   int fragmentCmp(const DIExpression *Other) const {
3739     auto Fragment1 = *getFragmentInfo();
3740     auto Fragment2 = *Other->getFragmentInfo();
3741     return fragmentCmp(Fragment1, Fragment2);
3742   }
3743 
3744   /// Check if fragments overlap between this DIExpression and \p Other.
fragmentsOverlap(const DIExpression * Other)3745   bool fragmentsOverlap(const DIExpression *Other) const {
3746     if (!isFragment() || !Other->isFragment())
3747       return true;
3748     return fragmentCmp(Other) == 0;
3749   }
3750 
3751   /// Check if the expression consists of exactly one entry value operand.
3752   /// (This is the only configuration of entry values that is supported.)
3753   LLVM_ABI bool isEntryValue() const;
3754 
3755   /// Try to shorten an expression with an initial constant operand.
3756   /// Returns a new expression and constant on success, or the original
3757   /// expression and constant on failure.
3758   LLVM_ABI std::pair<DIExpression *, const ConstantInt *>
3759   constantFold(const ConstantInt *CI);
3760 
3761   /// Try to shorten an expression with constant math operations that can be
3762   /// evaluated at compile time. Returns a new expression on success, or the old
3763   /// expression if there is nothing to be reduced.
3764   LLVM_ABI DIExpression *foldConstantMath();
3765 };
3766 
3767 inline bool operator==(const DIExpression::FragmentInfo &A,
3768                        const DIExpression::FragmentInfo &B) {
3769   return std::tie(A.SizeInBits, A.OffsetInBits) ==
3770          std::tie(B.SizeInBits, B.OffsetInBits);
3771 }
3772 
3773 inline bool operator<(const DIExpression::FragmentInfo &A,
3774                       const DIExpression::FragmentInfo &B) {
3775   return std::tie(A.SizeInBits, A.OffsetInBits) <
3776          std::tie(B.SizeInBits, B.OffsetInBits);
3777 }
3778 
3779 template <> struct DenseMapInfo<DIExpression::FragmentInfo> {
3780   using FragInfo = DIExpression::FragmentInfo;
3781   static const uint64_t MaxVal = std::numeric_limits<uint64_t>::max();
3782 
3783   static inline FragInfo getEmptyKey() { return {MaxVal, MaxVal}; }
3784 
3785   static inline FragInfo getTombstoneKey() { return {MaxVal - 1, MaxVal - 1}; }
3786 
3787   static unsigned getHashValue(const FragInfo &Frag) {
3788     return (Frag.SizeInBits & 0xffff) << 16 | (Frag.OffsetInBits & 0xffff);
3789   }
3790 
3791   static bool isEqual(const FragInfo &A, const FragInfo &B) { return A == B; }
3792 };
3793 
3794 /// Holds a DIExpression and keeps track of how many operands have been consumed
3795 /// so far.
3796 class DIExpressionCursor {
3797   DIExpression::expr_op_iterator Start, End;
3798 
3799 public:
3800   DIExpressionCursor(const DIExpression *Expr) {
3801     if (!Expr) {
3802       assert(Start == End);
3803       return;
3804     }
3805     Start = Expr->expr_op_begin();
3806     End = Expr->expr_op_end();
3807   }
3808 
3809   DIExpressionCursor(ArrayRef<uint64_t> Expr)
3810       : Start(Expr.begin()), End(Expr.end()) {}
3811 
3812   DIExpressionCursor(const DIExpressionCursor &) = default;
3813 
3814   /// Consume one operation.
3815   std::optional<DIExpression::ExprOperand> take() {
3816     if (Start == End)
3817       return std::nullopt;
3818     return *(Start++);
3819   }
3820 
3821   /// Consume N operations.
3822   void consume(unsigned N) { std::advance(Start, N); }
3823 
3824   /// Return the current operation.
3825   std::optional<DIExpression::ExprOperand> peek() const {
3826     if (Start == End)
3827       return std::nullopt;
3828     return *(Start);
3829   }
3830 
3831   /// Return the next operation.
3832   std::optional<DIExpression::ExprOperand> peekNext() const {
3833     if (Start == End)
3834       return std::nullopt;
3835 
3836     auto Next = Start.getNext();
3837     if (Next == End)
3838       return std::nullopt;
3839 
3840     return *Next;
3841   }
3842 
3843   std::optional<DIExpression::ExprOperand> peekNextN(unsigned N) const {
3844     if (Start == End)
3845       return std::nullopt;
3846     DIExpression::expr_op_iterator Nth = Start;
3847     for (unsigned I = 0; I < N; I++) {
3848       Nth = Nth.getNext();
3849       if (Nth == End)
3850         return std::nullopt;
3851     }
3852     return *Nth;
3853   }
3854 
3855   void assignNewExpr(ArrayRef<uint64_t> Expr) {
3856     this->Start = DIExpression::expr_op_iterator(Expr.begin());
3857     this->End = DIExpression::expr_op_iterator(Expr.end());
3858   }
3859 
3860   /// Determine whether there are any operations left in this expression.
3861   operator bool() const { return Start != End; }
3862 
3863   DIExpression::expr_op_iterator begin() const { return Start; }
3864   DIExpression::expr_op_iterator end() const { return End; }
3865 
3866   /// Retrieve the fragment information, if any.
3867   std::optional<DIExpression::FragmentInfo> getFragmentInfo() const {
3868     return DIExpression::getFragmentInfo(Start, End);
3869   }
3870 };
3871 
3872 /// Global variables.
3873 ///
3874 /// TODO: Remove DisplayName.  It's always equal to Name.
3875 class DIGlobalVariable : public DIVariable {
3876   friend class LLVMContextImpl;
3877   friend class MDNode;
3878 
3879   bool IsLocalToUnit;
3880   bool IsDefinition;
3881 
3882   DIGlobalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
3883                    bool IsLocalToUnit, bool IsDefinition, uint32_t AlignInBits,
3884                    ArrayRef<Metadata *> Ops)
3885       : DIVariable(C, DIGlobalVariableKind, Storage, Line, Ops, AlignInBits),
3886         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition) {}
3887   ~DIGlobalVariable() = default;
3888 
3889   static DIGlobalVariable *
3890   getImpl(LLVMContext &Context, DIScope *Scope, StringRef Name,
3891           StringRef LinkageName, DIFile *File, unsigned Line, DIType *Type,
3892           bool IsLocalToUnit, bool IsDefinition,
3893           DIDerivedType *StaticDataMemberDeclaration, MDTuple *TemplateParams,
3894           uint32_t AlignInBits, DINodeArray Annotations, StorageType Storage,
3895           bool ShouldCreate = true) {
3896     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
3897                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
3898                    IsLocalToUnit, IsDefinition, StaticDataMemberDeclaration,
3899                    cast_or_null<Metadata>(TemplateParams), AlignInBits,
3900                    Annotations.get(), Storage, ShouldCreate);
3901   }
3902   LLVM_ABI static DIGlobalVariable *
3903   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
3904           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
3905           bool IsLocalToUnit, bool IsDefinition,
3906           Metadata *StaticDataMemberDeclaration, Metadata *TemplateParams,
3907           uint32_t AlignInBits, Metadata *Annotations, StorageType Storage,
3908           bool ShouldCreate = true);
3909 
3910   TempDIGlobalVariable cloneImpl() const {
3911     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
3912                         getFile(), getLine(), getType(), isLocalToUnit(),
3913                         isDefinition(), getStaticDataMemberDeclaration(),
3914                         getTemplateParams(), getAlignInBits(),
3915                         getAnnotations());
3916   }
3917 
3918 public:
3919   DEFINE_MDNODE_GET(
3920       DIGlobalVariable,
3921       (DIScope * Scope, StringRef Name, StringRef LinkageName, DIFile *File,
3922        unsigned Line, DIType *Type, bool IsLocalToUnit, bool IsDefinition,
3923        DIDerivedType *StaticDataMemberDeclaration, MDTuple *TemplateParams,
3924        uint32_t AlignInBits, DINodeArray Annotations),
3925       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
3926        StaticDataMemberDeclaration, TemplateParams, AlignInBits, Annotations))
3927   DEFINE_MDNODE_GET(
3928       DIGlobalVariable,
3929       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
3930        unsigned Line, Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
3931        Metadata *StaticDataMemberDeclaration, Metadata *TemplateParams,
3932        uint32_t AlignInBits, Metadata *Annotations),
3933       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
3934        StaticDataMemberDeclaration, TemplateParams, AlignInBits, Annotations))
3935 
3936   TempDIGlobalVariable clone() const { return cloneImpl(); }
3937 
3938   bool isLocalToUnit() const { return IsLocalToUnit; }
3939   bool isDefinition() const { return IsDefinition; }
3940   StringRef getDisplayName() const { return getStringOperand(4); }
3941   StringRef getLinkageName() const { return getStringOperand(5); }
3942   DIDerivedType *getStaticDataMemberDeclaration() const {
3943     return cast_or_null<DIDerivedType>(getRawStaticDataMemberDeclaration());
3944   }
3945   DINodeArray getAnnotations() const {
3946     return cast_or_null<MDTuple>(getRawAnnotations());
3947   }
3948 
3949   MDString *getRawLinkageName() const { return getOperandAs<MDString>(5); }
3950   Metadata *getRawStaticDataMemberDeclaration() const { return getOperand(6); }
3951   Metadata *getRawTemplateParams() const { return getOperand(7); }
3952   MDTuple *getTemplateParams() const { return getOperandAs<MDTuple>(7); }
3953   Metadata *getRawAnnotations() const { return getOperand(8); }
3954 
3955   static bool classof(const Metadata *MD) {
3956     return MD->getMetadataID() == DIGlobalVariableKind;
3957   }
3958 };
3959 
3960 /// Debug common block.
3961 ///
3962 /// Uses the SubclassData32 Metadata slot.
3963 class DICommonBlock : public DIScope {
3964   friend class LLVMContextImpl;
3965   friend class MDNode;
3966 
3967   DICommonBlock(LLVMContext &Context, StorageType Storage, unsigned LineNo,
3968                 ArrayRef<Metadata *> Ops);
3969 
3970   static DICommonBlock *getImpl(LLVMContext &Context, DIScope *Scope,
3971                                 DIGlobalVariable *Decl, StringRef Name,
3972                                 DIFile *File, unsigned LineNo,
3973                                 StorageType Storage, bool ShouldCreate = true) {
3974     return getImpl(Context, Scope, Decl, getCanonicalMDString(Context, Name),
3975                    File, LineNo, Storage, ShouldCreate);
3976   }
3977   LLVM_ABI static DICommonBlock *getImpl(LLVMContext &Context, Metadata *Scope,
3978                                          Metadata *Decl, MDString *Name,
3979                                          Metadata *File, unsigned LineNo,
3980                                          StorageType Storage,
3981                                          bool ShouldCreate = true);
3982 
3983   TempDICommonBlock cloneImpl() const {
3984     return getTemporary(getContext(), getScope(), getDecl(), getName(),
3985                         getFile(), getLineNo());
3986   }
3987 
3988 public:
3989   DEFINE_MDNODE_GET(DICommonBlock,
3990                     (DIScope * Scope, DIGlobalVariable *Decl, StringRef Name,
3991                      DIFile *File, unsigned LineNo),
3992                     (Scope, Decl, Name, File, LineNo))
3993   DEFINE_MDNODE_GET(DICommonBlock,
3994                     (Metadata * Scope, Metadata *Decl, MDString *Name,
3995                      Metadata *File, unsigned LineNo),
3996                     (Scope, Decl, Name, File, LineNo))
3997 
3998   TempDICommonBlock clone() const { return cloneImpl(); }
3999 
4000   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
4001   DIGlobalVariable *getDecl() const {
4002     return cast_or_null<DIGlobalVariable>(getRawDecl());
4003   }
4004   StringRef getName() const { return getStringOperand(2); }
4005   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
4006   unsigned getLineNo() const { return SubclassData32; }
4007 
4008   Metadata *getRawScope() const { return getOperand(0); }
4009   Metadata *getRawDecl() const { return getOperand(1); }
4010   MDString *getRawName() const { return getOperandAs<MDString>(2); }
4011   Metadata *getRawFile() const { return getOperand(3); }
4012 
4013   static bool classof(const Metadata *MD) {
4014     return MD->getMetadataID() == DICommonBlockKind;
4015   }
4016 };
4017 
4018 /// Local variable.
4019 ///
4020 /// TODO: Split up flags.
4021 class DILocalVariable : public DIVariable {
4022   friend class LLVMContextImpl;
4023   friend class MDNode;
4024 
4025   unsigned Arg : 16;
4026   DIFlags Flags;
4027 
4028   DILocalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
4029                   unsigned Arg, DIFlags Flags, uint32_t AlignInBits,
4030                   ArrayRef<Metadata *> Ops)
4031       : DIVariable(C, DILocalVariableKind, Storage, Line, Ops, AlignInBits),
4032         Arg(Arg), Flags(Flags) {
4033     assert(Arg < (1 << 16) && "DILocalVariable: Arg out of range");
4034   }
4035   ~DILocalVariable() = default;
4036 
4037   static DILocalVariable *getImpl(LLVMContext &Context, DIScope *Scope,
4038                                   StringRef Name, DIFile *File, unsigned Line,
4039                                   DIType *Type, unsigned Arg, DIFlags Flags,
4040                                   uint32_t AlignInBits, DINodeArray Annotations,
4041                                   StorageType Storage,
4042                                   bool ShouldCreate = true) {
4043     return getImpl(Context, Scope, getCanonicalMDString(Context, Name), File,
4044                    Line, Type, Arg, Flags, AlignInBits, Annotations.get(),
4045                    Storage, ShouldCreate);
4046   }
4047   LLVM_ABI static DILocalVariable *
4048   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, Metadata *File,
4049           unsigned Line, Metadata *Type, unsigned Arg, DIFlags Flags,
4050           uint32_t AlignInBits, Metadata *Annotations, StorageType Storage,
4051           bool ShouldCreate = true);
4052 
4053   TempDILocalVariable cloneImpl() const {
4054     return getTemporary(getContext(), getScope(), getName(), getFile(),
4055                         getLine(), getType(), getArg(), getFlags(),
4056                         getAlignInBits(), getAnnotations());
4057   }
4058 
4059 public:
4060   DEFINE_MDNODE_GET(DILocalVariable,
4061                     (DILocalScope * Scope, StringRef Name, DIFile *File,
4062                      unsigned Line, DIType *Type, unsigned Arg, DIFlags Flags,
4063                      uint32_t AlignInBits, DINodeArray Annotations),
4064                     (Scope, Name, File, Line, Type, Arg, Flags, AlignInBits,
4065                      Annotations))
4066   DEFINE_MDNODE_GET(DILocalVariable,
4067                     (Metadata * Scope, MDString *Name, Metadata *File,
4068                      unsigned Line, Metadata *Type, unsigned Arg, DIFlags Flags,
4069                      uint32_t AlignInBits, Metadata *Annotations),
4070                     (Scope, Name, File, Line, Type, Arg, Flags, AlignInBits,
4071                      Annotations))
4072 
4073   TempDILocalVariable clone() const { return cloneImpl(); }
4074 
4075   /// Get the local scope for this variable.
4076   ///
4077   /// Variables must be defined in a local scope.
4078   DILocalScope *getScope() const {
4079     return cast<DILocalScope>(DIVariable::getScope());
4080   }
4081 
4082   bool isParameter() const { return Arg; }
4083   unsigned getArg() const { return Arg; }
4084   DIFlags getFlags() const { return Flags; }
4085 
4086   DINodeArray getAnnotations() const {
4087     return cast_or_null<MDTuple>(getRawAnnotations());
4088   }
4089   Metadata *getRawAnnotations() const { return getOperand(4); }
4090 
4091   bool isArtificial() const { return getFlags() & FlagArtificial; }
4092   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
4093 
4094   /// Check that a location is valid for this variable.
4095   ///
4096   /// Check that \c DL exists, is in the same subprogram, and has the same
4097   /// inlined-at location as \c this.  (Otherwise, it's not a valid attachment
4098   /// to a \a DbgInfoIntrinsic.)
4099   bool isValidLocationForIntrinsic(const DILocation *DL) const {
4100     return DL && getScope()->getSubprogram() == DL->getScope()->getSubprogram();
4101   }
4102 
4103   static bool classof(const Metadata *MD) {
4104     return MD->getMetadataID() == DILocalVariableKind;
4105   }
4106 };
4107 
4108 /// Label.
4109 ///
4110 /// Uses the SubclassData32 Metadata slot.
4111 class DILabel : public DINode {
4112   friend class LLVMContextImpl;
4113   friend class MDNode;
4114 
4115   unsigned Column;
4116   std::optional<unsigned> CoroSuspendIdx;
4117   bool IsArtificial;
4118 
4119   DILabel(LLVMContext &C, StorageType Storage, unsigned Line, unsigned Column,
4120           bool IsArtificial, std::optional<unsigned> CoroSuspendIdx,
4121           ArrayRef<Metadata *> Ops);
4122   ~DILabel() = default;
4123 
4124   static DILabel *getImpl(LLVMContext &Context, DIScope *Scope, StringRef Name,
4125                           DIFile *File, unsigned Line, unsigned Column,
4126                           bool IsArtificial,
4127                           std::optional<unsigned> CoroSuspendIdx,
4128                           StorageType Storage, bool ShouldCreate = true) {
4129     return getImpl(Context, Scope, getCanonicalMDString(Context, Name), File,
4130                    Line, Column, IsArtificial, CoroSuspendIdx, Storage,
4131                    ShouldCreate);
4132   }
4133   LLVM_ABI static DILabel *
4134   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, Metadata *File,
4135           unsigned Line, unsigned Column, bool IsArtificial,
4136           std::optional<unsigned> CoroSuspendIdx, StorageType Storage,
4137           bool ShouldCreate = true);
4138 
4139   TempDILabel cloneImpl() const {
4140     return getTemporary(getContext(), getScope(), getName(), getFile(),
4141                         getLine(), getColumn(), isArtificial(),
4142                         getCoroSuspendIdx());
4143   }
4144 
4145 public:
4146   DEFINE_MDNODE_GET(DILabel,
4147                     (DILocalScope * Scope, StringRef Name, DIFile *File,
4148                      unsigned Line, unsigned Column, bool IsArtificial,
4149                      std::optional<unsigned> CoroSuspendIdx),
4150                     (Scope, Name, File, Line, Column, IsArtificial,
4151                      CoroSuspendIdx))
4152   DEFINE_MDNODE_GET(DILabel,
4153                     (Metadata * Scope, MDString *Name, Metadata *File,
4154                      unsigned Line, unsigned Column, bool IsArtificial,
4155                      std::optional<unsigned> CoroSuspendIdx),
4156                     (Scope, Name, File, Line, Column, IsArtificial,
4157                      CoroSuspendIdx))
4158 
4159   TempDILabel clone() const { return cloneImpl(); }
4160 
4161   /// Get the local scope for this label.
4162   ///
4163   /// Labels must be defined in a local scope.
4164   DILocalScope *getScope() const {
4165     return cast_or_null<DILocalScope>(getRawScope());
4166   }
4167   unsigned getLine() const { return SubclassData32; }
4168   unsigned getColumn() const { return Column; }
4169   StringRef getName() const { return getStringOperand(1); }
4170   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
4171   bool isArtificial() const { return IsArtificial; }
4172   std::optional<unsigned> getCoroSuspendIdx() const { return CoroSuspendIdx; }
4173 
4174   Metadata *getRawScope() const { return getOperand(0); }
4175   MDString *getRawName() const { return getOperandAs<MDString>(1); }
4176   Metadata *getRawFile() const { return getOperand(2); }
4177 
4178   /// Check that a location is valid for this label.
4179   ///
4180   /// Check that \c DL exists, is in the same subprogram, and has the same
4181   /// inlined-at location as \c this.  (Otherwise, it's not a valid attachment
4182   /// to a \a DbgInfoIntrinsic.)
4183   bool isValidLocationForIntrinsic(const DILocation *DL) const {
4184     return DL && getScope()->getSubprogram() == DL->getScope()->getSubprogram();
4185   }
4186 
4187   static bool classof(const Metadata *MD) {
4188     return MD->getMetadataID() == DILabelKind;
4189   }
4190 };
4191 
4192 class DIObjCProperty : public DINode {
4193   friend class LLVMContextImpl;
4194   friend class MDNode;
4195 
4196   unsigned Line;
4197   unsigned Attributes;
4198 
4199   DIObjCProperty(LLVMContext &C, StorageType Storage, unsigned Line,
4200                  unsigned Attributes, ArrayRef<Metadata *> Ops);
4201   ~DIObjCProperty() = default;
4202 
4203   static DIObjCProperty *
4204   getImpl(LLVMContext &Context, StringRef Name, DIFile *File, unsigned Line,
4205           StringRef GetterName, StringRef SetterName, unsigned Attributes,
4206           DIType *Type, StorageType Storage, bool ShouldCreate = true) {
4207     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
4208                    getCanonicalMDString(Context, GetterName),
4209                    getCanonicalMDString(Context, SetterName), Attributes, Type,
4210                    Storage, ShouldCreate);
4211   }
4212   LLVM_ABI static DIObjCProperty *
4213   getImpl(LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
4214           MDString *GetterName, MDString *SetterName, unsigned Attributes,
4215           Metadata *Type, StorageType Storage, bool ShouldCreate = true);
4216 
4217   TempDIObjCProperty cloneImpl() const {
4218     return getTemporary(getContext(), getName(), getFile(), getLine(),
4219                         getGetterName(), getSetterName(), getAttributes(),
4220                         getType());
4221   }
4222 
4223 public:
4224   DEFINE_MDNODE_GET(DIObjCProperty,
4225                     (StringRef Name, DIFile *File, unsigned Line,
4226                      StringRef GetterName, StringRef SetterName,
4227                      unsigned Attributes, DIType *Type),
4228                     (Name, File, Line, GetterName, SetterName, Attributes,
4229                      Type))
4230   DEFINE_MDNODE_GET(DIObjCProperty,
4231                     (MDString * Name, Metadata *File, unsigned Line,
4232                      MDString *GetterName, MDString *SetterName,
4233                      unsigned Attributes, Metadata *Type),
4234                     (Name, File, Line, GetterName, SetterName, Attributes,
4235                      Type))
4236 
4237   TempDIObjCProperty clone() const { return cloneImpl(); }
4238 
4239   unsigned getLine() const { return Line; }
4240   unsigned getAttributes() const { return Attributes; }
4241   StringRef getName() const { return getStringOperand(0); }
4242   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
4243   StringRef getGetterName() const { return getStringOperand(2); }
4244   StringRef getSetterName() const { return getStringOperand(3); }
4245   DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
4246 
4247   StringRef getFilename() const {
4248     if (auto *F = getFile())
4249       return F->getFilename();
4250     return "";
4251   }
4252 
4253   StringRef getDirectory() const {
4254     if (auto *F = getFile())
4255       return F->getDirectory();
4256     return "";
4257   }
4258 
4259   MDString *getRawName() const { return getOperandAs<MDString>(0); }
4260   Metadata *getRawFile() const { return getOperand(1); }
4261   MDString *getRawGetterName() const { return getOperandAs<MDString>(2); }
4262   MDString *getRawSetterName() const { return getOperandAs<MDString>(3); }
4263   Metadata *getRawType() const { return getOperand(4); }
4264 
4265   static bool classof(const Metadata *MD) {
4266     return MD->getMetadataID() == DIObjCPropertyKind;
4267   }
4268 };
4269 
4270 /// An imported module (C++ using directive or similar).
4271 ///
4272 /// Uses the SubclassData32 Metadata slot.
4273 class DIImportedEntity : public DINode {
4274   friend class LLVMContextImpl;
4275   friend class MDNode;
4276 
4277   DIImportedEntity(LLVMContext &C, StorageType Storage, unsigned Tag,
4278                    unsigned Line, ArrayRef<Metadata *> Ops)
4279       : DINode(C, DIImportedEntityKind, Storage, Tag, Ops) {
4280     SubclassData32 = Line;
4281   }
4282   ~DIImportedEntity() = default;
4283 
4284   static DIImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
4285                                    DIScope *Scope, DINode *Entity, DIFile *File,
4286                                    unsigned Line, StringRef Name,
4287                                    DINodeArray Elements, StorageType Storage,
4288                                    bool ShouldCreate = true) {
4289     return getImpl(Context, Tag, Scope, Entity, File, Line,
4290                    getCanonicalMDString(Context, Name), Elements.get(), Storage,
4291                    ShouldCreate);
4292   }
4293   LLVM_ABI static DIImportedEntity *
4294   getImpl(LLVMContext &Context, unsigned Tag, Metadata *Scope, Metadata *Entity,
4295           Metadata *File, unsigned Line, MDString *Name, Metadata *Elements,
4296           StorageType Storage, bool ShouldCreate = true);
4297 
4298   TempDIImportedEntity cloneImpl() const {
4299     return getTemporary(getContext(), getTag(), getScope(), getEntity(),
4300                         getFile(), getLine(), getName(), getElements());
4301   }
4302 
4303 public:
4304   DEFINE_MDNODE_GET(DIImportedEntity,
4305                     (unsigned Tag, DIScope *Scope, DINode *Entity, DIFile *File,
4306                      unsigned Line, StringRef Name = "",
4307                      DINodeArray Elements = nullptr),
4308                     (Tag, Scope, Entity, File, Line, Name, Elements))
4309   DEFINE_MDNODE_GET(DIImportedEntity,
4310                     (unsigned Tag, Metadata *Scope, Metadata *Entity,
4311                      Metadata *File, unsigned Line, MDString *Name,
4312                      Metadata *Elements = nullptr),
4313                     (Tag, Scope, Entity, File, Line, Name, Elements))
4314 
4315   TempDIImportedEntity clone() const { return cloneImpl(); }
4316 
4317   unsigned getLine() const { return SubclassData32; }
4318   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
4319   DINode *getEntity() const { return cast_or_null<DINode>(getRawEntity()); }
4320   StringRef getName() const { return getStringOperand(2); }
4321   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
4322   DINodeArray getElements() const {
4323     return cast_or_null<MDTuple>(getRawElements());
4324   }
4325 
4326   Metadata *getRawScope() const { return getOperand(0); }
4327   Metadata *getRawEntity() const { return getOperand(1); }
4328   MDString *getRawName() const { return getOperandAs<MDString>(2); }
4329   Metadata *getRawFile() const { return getOperand(3); }
4330   Metadata *getRawElements() const { return getOperand(4); }
4331 
4332   static bool classof(const Metadata *MD) {
4333     return MD->getMetadataID() == DIImportedEntityKind;
4334   }
4335 };
4336 
4337 /// A pair of DIGlobalVariable and DIExpression.
4338 class DIGlobalVariableExpression : public MDNode {
4339   friend class LLVMContextImpl;
4340   friend class MDNode;
4341 
4342   DIGlobalVariableExpression(LLVMContext &C, StorageType Storage,
4343                              ArrayRef<Metadata *> Ops)
4344       : MDNode(C, DIGlobalVariableExpressionKind, Storage, Ops) {}
4345   ~DIGlobalVariableExpression() = default;
4346 
4347   LLVM_ABI static DIGlobalVariableExpression *
4348   getImpl(LLVMContext &Context, Metadata *Variable, Metadata *Expression,
4349           StorageType Storage, bool ShouldCreate = true);
4350 
4351   TempDIGlobalVariableExpression cloneImpl() const {
4352     return getTemporary(getContext(), getVariable(), getExpression());
4353   }
4354 
4355 public:
4356   DEFINE_MDNODE_GET(DIGlobalVariableExpression,
4357                     (Metadata * Variable, Metadata *Expression),
4358                     (Variable, Expression))
4359 
4360   TempDIGlobalVariableExpression clone() const { return cloneImpl(); }
4361 
4362   Metadata *getRawVariable() const { return getOperand(0); }
4363 
4364   DIGlobalVariable *getVariable() const {
4365     return cast_or_null<DIGlobalVariable>(getRawVariable());
4366   }
4367 
4368   Metadata *getRawExpression() const { return getOperand(1); }
4369 
4370   DIExpression *getExpression() const {
4371     return cast<DIExpression>(getRawExpression());
4372   }
4373 
4374   static bool classof(const Metadata *MD) {
4375     return MD->getMetadataID() == DIGlobalVariableExpressionKind;
4376   }
4377 };
4378 
4379 /// Macro Info DWARF-like metadata node.
4380 ///
4381 /// A metadata node with a DWARF macro info (i.e., a constant named
4382 /// \c DW_MACINFO_*, defined in llvm/BinaryFormat/Dwarf.h).  Called \a
4383 /// DIMacroNode
4384 /// because it's potentially used for non-DWARF output.
4385 ///
4386 /// Uses the SubclassData16 Metadata slot.
4387 class DIMacroNode : public MDNode {
4388   friend class LLVMContextImpl;
4389   friend class MDNode;
4390 
4391 protected:
4392   DIMacroNode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned MIType,
4393               ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = {})
4394       : MDNode(C, ID, Storage, Ops1, Ops2) {
4395     assert(MIType < 1u << 16);
4396     SubclassData16 = MIType;
4397   }
4398   ~DIMacroNode() = default;
4399 
4400   template <class Ty> Ty *getOperandAs(unsigned I) const {
4401     return cast_or_null<Ty>(getOperand(I));
4402   }
4403 
4404   StringRef getStringOperand(unsigned I) const {
4405     if (auto *S = getOperandAs<MDString>(I))
4406       return S->getString();
4407     return StringRef();
4408   }
4409 
4410   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
4411     if (S.empty())
4412       return nullptr;
4413     return MDString::get(Context, S);
4414   }
4415 
4416 public:
4417   unsigned getMacinfoType() const { return SubclassData16; }
4418 
4419   static bool classof(const Metadata *MD) {
4420     switch (MD->getMetadataID()) {
4421     default:
4422       return false;
4423     case DIMacroKind:
4424     case DIMacroFileKind:
4425       return true;
4426     }
4427   }
4428 };
4429 
4430 /// Macro
4431 ///
4432 /// Uses the SubclassData32 Metadata slot.
4433 class DIMacro : public DIMacroNode {
4434   friend class LLVMContextImpl;
4435   friend class MDNode;
4436 
4437   DIMacro(LLVMContext &C, StorageType Storage, unsigned MIType, unsigned Line,
4438           ArrayRef<Metadata *> Ops)
4439       : DIMacroNode(C, DIMacroKind, Storage, MIType, Ops) {
4440     SubclassData32 = Line;
4441   }
4442   ~DIMacro() = default;
4443 
4444   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
4445                           StringRef Name, StringRef Value, StorageType Storage,
4446                           bool ShouldCreate = true) {
4447     return getImpl(Context, MIType, Line, getCanonicalMDString(Context, Name),
4448                    getCanonicalMDString(Context, Value), Storage, ShouldCreate);
4449   }
4450   LLVM_ABI static DIMacro *getImpl(LLVMContext &Context, unsigned MIType,
4451                                    unsigned Line, MDString *Name,
4452                                    MDString *Value, StorageType Storage,
4453                                    bool ShouldCreate = true);
4454 
4455   TempDIMacro cloneImpl() const {
4456     return getTemporary(getContext(), getMacinfoType(), getLine(), getName(),
4457                         getValue());
4458   }
4459 
4460 public:
4461   DEFINE_MDNODE_GET(DIMacro,
4462                     (unsigned MIType, unsigned Line, StringRef Name,
4463                      StringRef Value = ""),
4464                     (MIType, Line, Name, Value))
4465   DEFINE_MDNODE_GET(DIMacro,
4466                     (unsigned MIType, unsigned Line, MDString *Name,
4467                      MDString *Value),
4468                     (MIType, Line, Name, Value))
4469 
4470   TempDIMacro clone() const { return cloneImpl(); }
4471 
4472   unsigned getLine() const { return SubclassData32; }
4473 
4474   StringRef getName() const { return getStringOperand(0); }
4475   StringRef getValue() const { return getStringOperand(1); }
4476 
4477   MDString *getRawName() const { return getOperandAs<MDString>(0); }
4478   MDString *getRawValue() const { return getOperandAs<MDString>(1); }
4479 
4480   static bool classof(const Metadata *MD) {
4481     return MD->getMetadataID() == DIMacroKind;
4482   }
4483 };
4484 
4485 /// Macro file
4486 ///
4487 /// Uses the SubclassData32 Metadata slot.
4488 class DIMacroFile : public DIMacroNode {
4489   friend class LLVMContextImpl;
4490   friend class MDNode;
4491 
4492   DIMacroFile(LLVMContext &C, StorageType Storage, unsigned MIType,
4493               unsigned Line, ArrayRef<Metadata *> Ops)
4494       : DIMacroNode(C, DIMacroFileKind, Storage, MIType, Ops) {
4495     SubclassData32 = Line;
4496   }
4497   ~DIMacroFile() = default;
4498 
4499   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
4500                               unsigned Line, DIFile *File,
4501                               DIMacroNodeArray Elements, StorageType Storage,
4502                               bool ShouldCreate = true) {
4503     return getImpl(Context, MIType, Line, static_cast<Metadata *>(File),
4504                    Elements.get(), Storage, ShouldCreate);
4505   }
4506 
4507   LLVM_ABI static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
4508                                        unsigned Line, Metadata *File,
4509                                        Metadata *Elements, StorageType Storage,
4510                                        bool ShouldCreate = true);
4511 
4512   TempDIMacroFile cloneImpl() const {
4513     return getTemporary(getContext(), getMacinfoType(), getLine(), getFile(),
4514                         getElements());
4515   }
4516 
4517 public:
4518   DEFINE_MDNODE_GET(DIMacroFile,
4519                     (unsigned MIType, unsigned Line, DIFile *File,
4520                      DIMacroNodeArray Elements),
4521                     (MIType, Line, File, Elements))
4522   DEFINE_MDNODE_GET(DIMacroFile,
4523                     (unsigned MIType, unsigned Line, Metadata *File,
4524                      Metadata *Elements),
4525                     (MIType, Line, File, Elements))
4526 
4527   TempDIMacroFile clone() const { return cloneImpl(); }
4528 
4529   void replaceElements(DIMacroNodeArray Elements) {
4530 #ifndef NDEBUG
4531     for (DIMacroNode *Op : getElements())
4532       assert(is_contained(Elements->operands(), Op) &&
4533              "Lost a macro node during macro node list replacement");
4534 #endif
4535     replaceOperandWith(1, Elements.get());
4536   }
4537 
4538   unsigned getLine() const { return SubclassData32; }
4539   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
4540 
4541   DIMacroNodeArray getElements() const {
4542     return cast_or_null<MDTuple>(getRawElements());
4543   }
4544 
4545   Metadata *getRawFile() const { return getOperand(0); }
4546   Metadata *getRawElements() const { return getOperand(1); }
4547 
4548   static bool classof(const Metadata *MD) {
4549     return MD->getMetadataID() == DIMacroFileKind;
4550   }
4551 };
4552 
4553 /// List of ValueAsMetadata, to be used as an argument to a dbg.value
4554 /// intrinsic.
4555 class DIArgList : public Metadata, ReplaceableMetadataImpl {
4556   friend class ReplaceableMetadataImpl;
4557   friend class LLVMContextImpl;
4558   using iterator = SmallVectorImpl<ValueAsMetadata *>::iterator;
4559 
4560   SmallVector<ValueAsMetadata *, 4> Args;
4561 
4562   DIArgList(LLVMContext &Context, ArrayRef<ValueAsMetadata *> Args)
4563       : Metadata(DIArgListKind, Uniqued), ReplaceableMetadataImpl(Context),
4564         Args(Args) {
4565     track();
4566   }
4567   ~DIArgList() { untrack(); }
4568 
4569   LLVM_ABI void track();
4570   LLVM_ABI void untrack();
4571   void dropAllReferences(bool Untrack);
4572 
4573 public:
4574   LLVM_ABI static DIArgList *get(LLVMContext &Context,
4575                                  ArrayRef<ValueAsMetadata *> Args);
4576 
4577   ArrayRef<ValueAsMetadata *> getArgs() const { return Args; }
4578 
4579   iterator args_begin() { return Args.begin(); }
4580   iterator args_end() { return Args.end(); }
4581 
4582   static bool classof(const Metadata *MD) {
4583     return MD->getMetadataID() == DIArgListKind;
4584   }
4585 
4586   SmallVector<DbgVariableRecord *> getAllDbgVariableRecordUsers() {
4587     return ReplaceableMetadataImpl::getAllDbgVariableRecordUsers();
4588   }
4589 
4590   LLVM_ABI void handleChangedOperand(void *Ref, Metadata *New);
4591 };
4592 
4593 /// Identifies a unique instance of a variable.
4594 ///
4595 /// Storage for identifying a potentially inlined instance of a variable,
4596 /// or a fragment thereof. This guarantees that exactly one variable instance
4597 /// may be identified by this class, even when that variable is a fragment of
4598 /// an aggregate variable and/or there is another inlined instance of the same
4599 /// source code variable nearby.
4600 /// This class does not necessarily uniquely identify that variable: it is
4601 /// possible that a DebugVariable with different parameters may point to the
4602 /// same variable instance, but not that one DebugVariable points to multiple
4603 /// variable instances.
4604 class DebugVariable {
4605   using FragmentInfo = DIExpression::FragmentInfo;
4606 
4607   const DILocalVariable *Variable;
4608   std::optional<FragmentInfo> Fragment;
4609   const DILocation *InlinedAt;
4610 
4611   /// Fragment that will overlap all other fragments. Used as default when
4612   /// caller demands a fragment.
4613   LLVM_ABI static const FragmentInfo DefaultFragment;
4614 
4615 public:
4616   LLVM_ABI DebugVariable(const DbgVariableIntrinsic *DII);
4617   LLVM_ABI DebugVariable(const DbgVariableRecord *DVR);
4618 
4619   DebugVariable(const DILocalVariable *Var,
4620                 std::optional<FragmentInfo> FragmentInfo,
4621                 const DILocation *InlinedAt)
4622       : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
4623 
4624   DebugVariable(const DILocalVariable *Var, const DIExpression *DIExpr,
4625                 const DILocation *InlinedAt)
4626       : Variable(Var),
4627         Fragment(DIExpr ? DIExpr->getFragmentInfo() : std::nullopt),
4628         InlinedAt(InlinedAt) {}
4629 
4630   const DILocalVariable *getVariable() const { return Variable; }
4631   std::optional<FragmentInfo> getFragment() const { return Fragment; }
4632   const DILocation *getInlinedAt() const { return InlinedAt; }
4633 
4634   FragmentInfo getFragmentOrDefault() const {
4635     return Fragment.value_or(DefaultFragment);
4636   }
4637 
4638   static bool isDefaultFragment(const FragmentInfo F) {
4639     return F == DefaultFragment;
4640   }
4641 
4642   bool operator==(const DebugVariable &Other) const {
4643     return std::tie(Variable, Fragment, InlinedAt) ==
4644            std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
4645   }
4646 
4647   bool operator<(const DebugVariable &Other) const {
4648     return std::tie(Variable, Fragment, InlinedAt) <
4649            std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
4650   }
4651 };
4652 
4653 template <> struct DenseMapInfo<DebugVariable> {
4654   using FragmentInfo = DIExpression::FragmentInfo;
4655 
4656   /// Empty key: no key should be generated that has no DILocalVariable.
4657   static inline DebugVariable getEmptyKey() {
4658     return DebugVariable(nullptr, std::nullopt, nullptr);
4659   }
4660 
4661   /// Difference in tombstone is that the Optional is meaningful.
4662   static inline DebugVariable getTombstoneKey() {
4663     return DebugVariable(nullptr, {{0, 0}}, nullptr);
4664   }
4665 
4666   static unsigned getHashValue(const DebugVariable &D) {
4667     unsigned HV = 0;
4668     const std::optional<FragmentInfo> Fragment = D.getFragment();
4669     if (Fragment)
4670       HV = DenseMapInfo<FragmentInfo>::getHashValue(*Fragment);
4671 
4672     return hash_combine(D.getVariable(), HV, D.getInlinedAt());
4673   }
4674 
4675   static bool isEqual(const DebugVariable &A, const DebugVariable &B) {
4676     return A == B;
4677   }
4678 };
4679 
4680 /// Identifies a unique instance of a whole variable (discards/ignores fragment
4681 /// information).
4682 class DebugVariableAggregate : public DebugVariable {
4683 public:
4684   LLVM_ABI DebugVariableAggregate(const DbgVariableIntrinsic *DVI);
4685   DebugVariableAggregate(const DebugVariable &V)
4686       : DebugVariable(V.getVariable(), std::nullopt, V.getInlinedAt()) {}
4687 };
4688 
4689 template <>
4690 struct DenseMapInfo<DebugVariableAggregate>
4691     : public DenseMapInfo<DebugVariable> {};
4692 } // end namespace llvm
4693 
4694 #undef DEFINE_MDNODE_GET_UNPACK_IMPL
4695 #undef DEFINE_MDNODE_GET_UNPACK
4696 #undef DEFINE_MDNODE_GET
4697 
4698 #endif // LLVM_IR_DEBUGINFOMETADATA_H
4699