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