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