LLVM 20.0.0git
DebugInfoMetadata.h
Go to the documentation of this file.
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"
19#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
23#include "llvm/IR/Constants.h"
25#include "llvm/IR/Metadata.h"
26#include "llvm/IR/PseudoProbe.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
62namespace llvm {
63
64namespace dwarf {
65enum Tag : uint16_t;
66}
67
68class DbgVariableIntrinsic;
69class DbgVariableRecord;
70
71extern cl::opt<bool> EnableFSDiscriminator;
72
74 const MDTuple *N = nullptr;
75
76public:
77 DITypeRefArray() = default;
78 DITypeRefArray(const MDTuple *N) : N(N) {}
79
80 explicit operator bool() const { return get(); }
81 explicit operator MDTuple *() const { return get(); }
82
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.
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;
104 explicit iterator(MDNode::op_iterator I) : I(I) {}
105
106 DIType *operator*() const { return cast_or_null<DIType>(*I); }
107
109 ++I;
110 return *this;
111 }
112
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.
124 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
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.
135class DINode : public MDNode {
136 friend class LLVMContextImpl;
137 friend class MDNode;
138
139protected:
140 DINode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
141 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = std::nullopt)
142 : MDNode(C, ID, Storage, Ops1, Ops2) {
143 assert(Tag < 1u << 16);
145 }
146 ~DINode() = default;
147
148 template <class Ty> Ty *getOperandAs(unsigned I) const {
149 return cast_or_null<Ty>(getOperand(I));
150 }
151
152 StringRef getStringOperand(unsigned I) const {
153 if (auto *S = getOperandAs<MDString>(I))
154 return S->getString();
155 return StringRef();
156 }
157
159 if (S.empty())
160 return nullptr;
161 return MDString::get(Context, S);
162 }
163
164 /// Allow subclasses to mutate the tag.
165 void setTag(unsigned Tag) { SubclassData16 = Tag; }
166
167public:
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.
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
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.
236class GenericDINode : public DINode {
237 friend class LLVMContextImpl;
238 friend class MDNode;
239
241 unsigned Tag, ArrayRef<Metadata *> Ops1,
243 : DINode(C, GenericDINodeKind, Storage, Tag, Ops1, Ops2) {
244 setHash(Hash);
245 }
247
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
262 TempGenericDINode cloneImpl() const {
264 SmallVector<Metadata *, 4>(dwarf_operands()));
265 }
266
267public:
268 unsigned getHash() const { return SubclassData32; }
269
271 (unsigned Tag, StringRef Header,
273 (Tag, Header, DwarfOps))
275 (unsigned Tag, MDString *Header,
278
279 /// Return a (temporary) clone of this.
280 TempGenericDINode clone() const { return cloneImpl(); }
281
282 dwarf::Tag getTag() const;
283 StringRef getHeader() const { return getStringOperand(0); }
284 MDString *getRawHeader() const { return getOperandAs<MDString>(0); }
285
286 op_iterator dwarf_op_begin() const { return op_begin() + 1; }
287 op_iterator dwarf_op_end() const { return op_end(); }
290 }
291
292 unsigned getNumDwarfOperands() const { return getNumOperands() - 1; }
293 const MDOperand &getDwarfOperand(unsigned I) const {
294 return getOperand(I + 1);
295 }
296 void replaceDwarfOperandWith(unsigned I, Metadata *New) {
297 replaceOperandWith(I + 1, New);
298 }
299
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).
309class DIAssignID : public MDNode {
310 friend class LLVMContextImpl;
311 friend class MDNode;
312
314 : MDNode(C, DIAssignIDKind, Storage, std::nullopt) {}
315
317
318 static DIAssignID *getImpl(LLVMContext &Context, StorageType Storage,
319 bool ShouldCreate = true);
320
321 TempDIAssignID cloneImpl() const { return getTemporary(getContext()); }
322
323public:
324 // This node has no operands to replace.
325 void replaceOperandWith(unsigned I, Metadata *New) = delete;
326
328 return Context.getReplaceableUses()->getAllDbgVariableRecordUsers();
329 }
330
332 return getImpl(Context, Distinct);
333 }
334 static TempDIAssignID getTemporary(LLVMContext &Context) {
335 return TempDIAssignID(getImpl(Context, Temporary));
336 }
337 // NOTE: Do not define get(LLVMContext&) - see class comment.
338
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.
348class DISubrange : public DINode {
349 friend class LLVMContextImpl;
350 friend class MDNode;
351
353
354 ~DISubrange() = default;
355
356 static DISubrange *getImpl(LLVMContext &Context, int64_t Count,
358 bool ShouldCreate = true);
359
360 static DISubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
362 bool ShouldCreate = true);
363
364 static DISubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
365 Metadata *LowerBound, Metadata *UpperBound,
367 bool ShouldCreate = true);
368
369 TempDISubrange cloneImpl() const {
370 return getTemporary(getContext(), getRawCountNode(), getRawLowerBound(),
371 getRawUpperBound(), getRawStride());
372 }
373
374public:
375 DEFINE_MDNODE_GET(DISubrange, (int64_t Count, int64_t LowerBound = 0),
376 (Count, LowerBound))
377
380
383 Metadata *UpperBound, Metadata *Stride),
384 (CountNode, LowerBound, UpperBound, Stride))
385
386 TempDISubrange clone() const { return cloneImpl(); }
387
388 Metadata *getRawCountNode() const { return getOperand(0).get(); }
389
390 Metadata *getRawLowerBound() const { return getOperand(1).get(); }
391
392 Metadata *getRawUpperBound() const { return getOperand(2).get(); }
393
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
406 static bool classof(const Metadata *MD) {
407 return MD->getMetadataID() == DISubrangeKind;
408 }
409};
410
411class DIGenericSubrange : public DINode {
412 friend class LLVMContextImpl;
413 friend class MDNode;
414
417
418 ~DIGenericSubrange() = default;
419
420 static DIGenericSubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
421 Metadata *LowerBound, Metadata *UpperBound,
423 bool ShouldCreate = true);
424
425 TempDIGenericSubrange cloneImpl() const {
428 }
429
430public:
432 (Metadata * CountNode, Metadata *LowerBound,
433 Metadata *UpperBound, Metadata *Stride),
434 (CountNode, LowerBound, UpperBound, Stride))
435
436 TempDIGenericSubrange clone() const { return cloneImpl(); }
437
438 Metadata *getRawCountNode() const { return getOperand(0).get(); }
439 Metadata *getRawLowerBound() const { return getOperand(1).get(); }
440 Metadata *getRawUpperBound() const { return getOperand(2).get(); }
441 Metadata *getRawStride() const { return getOperand(3).get(); }
442
444
445 BoundType getCount() const;
446 BoundType getLowerBound() const;
447 BoundType getUpperBound() const;
448 BoundType getStride() const;
449
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.
459class DIEnumerator : public DINode {
460 friend class LLVMContextImpl;
461 friend class MDNode;
462
463 APInt Value;
469 Ops) {}
470 ~DIEnumerator() = default;
471
472 static DIEnumerator *getImpl(LLVMContext &Context, const APInt &Value,
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
482 TempDIEnumerator cloneImpl() const {
484 }
485
486public:
488 (int64_t Value, bool IsUnsigned, StringRef Name),
491 (int64_t Value, bool IsUnsigned, MDString *Name),
499
500 TempDIEnumerator clone() const { return cloneImpl(); }
501
502 const APInt &getValue() const { return Value; }
503 bool isUnsigned() const { return SubclassData32; }
504 StringRef getName() const { return getStringOperand(0); }
505
506 MDString *getRawName() const { return getOperandAs<MDString>(0); }
507
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.
519class DIScope : public DINode {
520protected:
523 : DINode(C, ID, Storage, Tag, Ops) {}
524 ~DIScope() = default;
525
526public:
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.
543 return isa<DIFile>(this) ? const_cast<DIScope *>(this)
544 : static_cast<Metadata *>(getOperand(0));
545 }
546
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.
573class DIFile : public DIScope {
574 friend class LLVMContextImpl;
575 friend class MDNode;
576
577public:
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.
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.
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.
597 /// The string value of the checksum.
599
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); }
606 StringRef getKindAsString() const { return getChecksumKindAsString(Kind); }
607 };
608
609private:
610 std::optional<ChecksumInfo<MDString *>> Checksum;
611 /// An optional source. A nullptr means none.
612 MDString *Source;
613
615 std::optional<ChecksumInfo<MDString *>> CS, MDString *Src,
617 ~DIFile() = default;
618
619 static DIFile *getImpl(LLVMContext &Context, StringRef Filename,
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
638 TempDIFile cloneImpl() const {
640 getChecksum(), getSource());
641 }
642
643public:
646 std::optional<ChecksumInfo<StringRef>> CS = std::nullopt,
647 std::optional<StringRef> Source = std::nullopt),
648 (Filename, Directory, CS, Source))
651 std::optional<ChecksumInfo<MDString *>> CS = std::nullopt,
652 MDString *Source = nullptr),
653 (Filename, Directory, CS, Source))
654
655 TempDIFile clone() const { return cloneImpl(); }
656
657 StringRef getFilename() const { return getStringOperand(0); }
658 StringRef getDirectory() const { return getStringOperand(1); }
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 }
665 std::optional<StringRef> getSource() const {
666 return Source ? std::optional<StringRef>(Source->getString())
667 : std::nullopt;
668 }
669
670 MDString *getRawFilename() const { return getOperandAs<MDString>(0); }
671 MDString *getRawDirectory() const { return getOperandAs<MDString>(1); }
672 std::optional<ChecksumInfo<MDString *>> getRawChecksum() const {
673 return Checksum;
674 }
675 MDString *getRawSource() const { return Source; }
676
677 static StringRef getChecksumKindAsString(ChecksumKind CSKind);
678 static std::optional<ChecksumKind> getChecksumKind(StringRef CSKindStr);
679
680 static bool classof(const Metadata *MD) {
681 return MD->getMetadataID() == DIFileKind;
682 }
683};
684
686 if (auto *F = getFile())
687 return F->getFilename();
688 return "";
689}
690
692 if (auto *F = getFile())
693 return F->getDirectory();
694 return "";
695}
696
697std::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.
710class DIType : public DIScope {
711 unsigned Line;
712 DIFlags Flags;
713 uint64_t SizeInBits;
714 uint64_t OffsetInBits;
715
716protected:
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
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.
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
742public:
743 TempDIType clone() const {
744 return TempDIType(cast<DIType>(MDNode::clone().release()));
745 }
746
747 unsigned getLine() const { return Line; }
748 uint64_t getSizeInBits() const { return SizeInBits; }
749 uint32_t getAlignInBits() const;
750 uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
751 uint64_t getOffsetInBits() const { return OffsetInBits; }
752 DIFlags getFlags() const { return Flags; }
753
754 DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
755 StringRef getName() const { return getStringOperand(2); }
756
757 Metadata *getRawScope() const { return getOperand(1); }
758 MDString *getRawName() const { return getOperandAs<MDString>(2); }
759
760 /// Returns a new temporary DIType with updated Flags
761 TempDIType cloneWithFlags(DIFlags NewFlags) const {
762 auto NewTy = clone();
763 NewTy->Flags = NewFlags;
764 return NewTy;
765 }
766
767 bool isPrivate() const {
768 return (getFlags() & FlagAccessibility) == FlagPrivate;
769 }
770 bool isProtected() const {
771 return (getFlags() & FlagAccessibility) == FlagProtected;
772 }
773 bool isPublic() const {
774 return (getFlags() & FlagAccessibility) == FlagPublic;
775 }
776 bool isForwardDecl() const { return getFlags() & FlagFwdDecl; }
777 bool isAppleBlockExtension() const { return getFlags() & FlagAppleBlock; }
778 bool isVirtual() const { return getFlags() & FlagVirtual; }
779 bool isArtificial() const { return getFlags() & FlagArtificial; }
780 bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
781 bool isObjcClassComplete() const {
782 return getFlags() & FlagObjcClassComplete;
783 }
784 bool isVector() const { return getFlags() & FlagVector; }
785 bool isBitField() const { return getFlags() & FlagBitField; }
786 bool isStaticMember() const { return getFlags() & FlagStaticMember; }
787 bool isLValueReference() const { return getFlags() & FlagLValueReference; }
788 bool isRValueReference() const { return getFlags() & FlagRValueReference; }
789 bool isTypePassByValue() const { return getFlags() & FlagTypePassByValue; }
791 return getFlags() & FlagTypePassByReference;
792 }
793 bool isBigEndian() const { return getFlags() & FlagBigEndian; }
794 bool isLittleEndian() const { return getFlags() & FlagLittleEndian; }
795 bool getExportSymbols() const { return getFlags() & FlagExportSymbols; }
796
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.
815class DIBasicType : public DIType {
816 friend class LLVMContextImpl;
817 friend class MDNode;
818
819 unsigned Encoding;
820
822 uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding,
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,
831 uint32_t AlignInBits, unsigned Encoding,
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,
842 bool ShouldCreate = true);
843
844 TempDIBasicType cloneImpl() const {
847 }
848
849public:
851 (Tag, Name, 0, 0, 0, FlagZero))
854 (Tag, Name, SizeInBits, 0, 0, FlagZero))
856 (unsigned Tag, MDString *Name, uint64_t SizeInBits),
857 (Tag, Name, SizeInBits, 0, 0, FlagZero))
860 uint32_t AlignInBits, unsigned Encoding, DIFlags Flags),
863 (unsigned Tag, MDString *Name, uint64_t SizeInBits,
864 uint32_t AlignInBits, unsigned Encoding, DIFlags Flags),
865 (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags))
866
867 TempDIBasicType clone() const { return cloneImpl(); }
868
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
877 static bool classof(const Metadata *MD) {
878 return MD->getMetadataID() == DIBasicTypeKind;
879 }
880};
881
882/// String type, Fortran CHARACTER(n)
883class DIStringType : public DIType {
884 friend class LLVMContextImpl;
885 friend class MDNode;
886
887 unsigned Encoding;
888
890 uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding,
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,
899 Metadata *StrLenExp, Metadata *StrLocationExp,
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,
911 unsigned Encoding, StorageType Storage,
912 bool ShouldCreate = true);
913
914 TempDIStringType cloneImpl() const {
919 }
920
921public:
925 (Tag, Name, nullptr, nullptr, nullptr, SizeInBits,
926 AlignInBits, 0))
931 unsigned Encoding),
938 unsigned Encoding),
941
942 TempDIStringType clone() const { return cloneImpl(); }
943
944 static bool classof(const Metadata *MD) {
945 return MD->getMetadataID() == DIStringTypeKind;
946 }
947
949 return cast_or_null<DIVariable>(getRawStringLength());
950 }
951
953 return cast_or_null<DIExpression>(getRawStringLengthExp());
954 }
955
957 return cast_or_null<DIExpression>(getRawStringLocationExp());
958 }
959
960 unsigned getEncoding() const { return Encoding; }
961
962 Metadata *getRawStringLength() const { return getOperand(3); }
963
965
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.).
975class DIDerivedType : public DIType {
976public:
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
987 PtrAuthData(unsigned FromRawData) : RawData(FromRawData) {}
988 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
997 unsigned key() { return (RawData >> 0) & 0b1111; }
998 bool isAddressDiscriminated() { return (RawData >> 4) & 1; }
999 unsigned extraDiscriminator() { return (RawData >> 5) & 0xffff; }
1000 bool isaPointer() { return (RawData >> 21) & 1; }
1001 bool authenticatesNullValues() { return (RawData >> 22) & 1; }
1002 };
1003
1004private:
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
1015 std::optional<unsigned> DWARFAddressSpace,
1016 std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1018 : DIType(C, DIDerivedTypeKind, Storage, Tag, Line, SizeInBits,
1020 DWARFAddressSpace(DWARFAddressSpace) {
1021 if (PtrAuthData)
1023 }
1024 ~DIDerivedType() = default;
1025 static DIDerivedType *
1026 getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, DIFile *File,
1029 std::optional<unsigned> DWARFAddressSpace,
1030 std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1032 bool ShouldCreate = true) {
1033 return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
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,
1042 std::optional<unsigned> DWARFAddressSpace,
1043 std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1045 bool ShouldCreate = true);
1046
1047 TempDIDerivedType cloneImpl() const {
1048 return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
1051 getDWARFAddressSpace(), getPtrAuthData(), getFlags(),
1053 }
1054
1055public:
1057 (unsigned Tag, MDString *Name, Metadata *File,
1058 unsigned Line, Metadata *Scope, Metadata *BaseType,
1061 std::optional<unsigned> DWARFAddressSpace,
1062 std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1063 Metadata *ExtraData = nullptr,
1064 Metadata *Annotations = nullptr),
1066 AlignInBits, OffsetInBits, DWARFAddressSpace, PtrAuthData,
1069 (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
1072 std::optional<unsigned> DWARFAddressSpace,
1073 std::optional<PtrAuthData> PtrAuthData, DIFlags Flags,
1075 DINodeArray Annotations = nullptr),
1077 AlignInBits, OffsetInBits, DWARFAddressSpace, PtrAuthData,
1079
1080 TempDIDerivedType clone() const { return cloneImpl(); }
1081
1082 /// Get the base type this is derived from.
1083 DIType *getBaseType() const { return cast_or_null<DIType>(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.
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).
1103 Metadata *getRawExtraData() const { return getOperand(4); }
1104
1105 /// Get the template parameters from a template alias.
1106 DITemplateParameterArray getTemplateParams() const {
1107 return cast_or_null<MDTuple>(getExtraData());
1108 }
1109
1110 /// Get annotations associated with this derived type.
1111 DINodeArray getAnnotations() const {
1112 return cast_or_null<MDTuple>(getRawAnnotations());
1113 }
1114 Metadata *getRawAnnotations() const { return getOperand(5); }
1115
1116 /// Get casted version of extra data.
1117 /// @{
1118 DIType *getClassType() const;
1119
1121 return dyn_cast_or_null<DIObjCProperty>(getExtraData());
1122 }
1123
1124 uint32_t getVBPtrOffset() const;
1125
1127
1128 Constant *getConstant() const;
1129
1131 /// @}
1132
1133 static bool classof(const Metadata *MD) {
1134 return MD->getMetadataID() == DIDerivedTypeKind;
1135 }
1136};
1137
1140 return Lhs.RawData == Rhs.RawData;
1141}
1142
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.
1152class DICompositeType : public DIType {
1153 friend class LLVMContextImpl;
1154 friend class MDNode;
1155
1156 unsigned RuntimeLang;
1157
1159 unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits,
1162 : DIType(C, DICompositeTypeKind, Storage, Tag, Line, SizeInBits,
1164 RuntimeLang(RuntimeLang) {}
1165 ~DICompositeType() = default;
1166
1167 /// Change fields in place.
1168 void mutate(unsigned Tag, unsigned Line, unsigned RuntimeLang,
1170 DIFlags Flags) {
1171 assert(isDistinct() && "Only distinct nodes can mutate");
1172 assert(getRawIdentifier() && "Only ODR-uniqued nodes should mutate");
1173 this->RuntimeLang = RuntimeLang;
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,
1181 DINodeArray Elements, unsigned RuntimeLang, DIType *VTableHolder,
1182 DITemplateParameterArray TemplateParams, StringRef Identifier,
1183 DIDerivedType *Discriminator, Metadata *DataLocation,
1185 DINodeArray Annotations, StorageType Storage,
1186 bool ShouldCreate = true) {
1187 return getImpl(
1188 Context, Tag, getCanonicalMDString(Context, Name), File, Line, Scope,
1190 RuntimeLang, VTableHolder, TemplateParams.get(),
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,
1198 DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
1202 Metadata *Annotations, StorageType Storage, bool ShouldCreate = true);
1203
1204 TempDICompositeType cloneImpl() const {
1205 return getTemporary(
1212 }
1213
1214public:
1217 (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
1220 DINodeArray Elements, unsigned RuntimeLang, DIType *VTableHolder,
1221 DITemplateParameterArray TemplateParams = nullptr,
1223 Metadata *DataLocation = nullptr, Metadata *Associated = nullptr,
1224 Metadata *Allocated = nullptr, Metadata *Rank = nullptr,
1225 DINodeArray Annotations = nullptr),
1229 Annotations))
1232 (unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
1235 Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
1238 Metadata *Associated = nullptr, Metadata *Allocated = nullptr,
1239 Metadata *Rank = nullptr, Metadata *Annotations = nullptr),
1243 Annotations))
1244
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,
1259 unsigned RuntimeLang, Metadata *VTableHolder,
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,
1280 unsigned RuntimeLang, Metadata *VTableHolder,
1284
1285 DIType *getBaseType() const { return cast_or_null<DIType>(getRawBaseType()); }
1286 DINodeArray getElements() const {
1287 return cast_or_null<MDTuple>(getRawElements());
1288 }
1290 return cast_or_null<DIType>(getRawVTableHolder());
1291 }
1292 DITemplateParameterArray getTemplateParams() const {
1293 return cast_or_null<MDTuple>(getRawTemplateParams());
1294 }
1296 unsigned getRuntimeLang() const { return RuntimeLang; }
1297
1298 Metadata *getRawBaseType() const { return getOperand(3); }
1299 Metadata *getRawElements() const { return getOperand(4); }
1302 MDString *getRawIdentifier() const { return getOperandAs<MDString>(7); }
1305 return getOperandAs<DIDerivedType>(8);
1306 }
1309 return dyn_cast_or_null<DIVariable>(getRawDataLocation());
1310 }
1312 return dyn_cast_or_null<DIExpression>(getRawDataLocation());
1313 }
1314 Metadata *getRawAssociated() const { return getOperand(10); }
1316 return dyn_cast_or_null<DIVariable>(getRawAssociated());
1317 }
1319 return dyn_cast_or_null<DIExpression>(getRawAssociated());
1320 }
1321 Metadata *getRawAllocated() const { return getOperand(11); }
1323 return dyn_cast_or_null<DIVariable>(getRawAllocated());
1324 }
1326 return dyn_cast_or_null<DIExpression>(getRawAllocated());
1327 }
1328 Metadata *getRawRank() const { return getOperand(12); }
1330 if (auto *MD = dyn_cast_or_null<ConstantAsMetadata>(getRawRank()))
1331 return dyn_cast_or_null<ConstantInt>(MD->getValue());
1332 return nullptr;
1333 }
1335 return dyn_cast_or_null<DIExpression>(getRawRank());
1336 }
1337
1338 Metadata *getRawAnnotations() const { return getOperand(13); }
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 /// @{
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
1360 }
1361
1362 void replaceTemplateParams(DITemplateParameterArray TemplateParams) {
1364 }
1365 /// @}
1366
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.
1375class 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
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,
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,
1396 bool ShouldCreate = true);
1397
1398 TempDISubroutineType cloneImpl() const {
1400 }
1401
1402public:
1405 (Flags, CC, TypeArray))
1409
1410 TempDISubroutineType clone() const { return cloneImpl(); }
1411 // Returns a new temporary DISubroutineType with updated CC
1412 TempDISubroutineType cloneWithCC(uint8_t CC) const {
1413 auto NewTy = clone();
1414 NewTy->CC = CC;
1415 return NewTy;
1416 }
1417
1418 uint8_t getCC() const { return CC; }
1419
1421 return cast_or_null<MDTuple>(getRawTypeArray());
1422 }
1423
1424 Metadata *getRawTypeArray() const { return getOperand(3); }
1425
1426 static bool classof(const Metadata *MD) {
1427 return MD->getMetadataID() == DISubroutineTypeKind;
1428 }
1429};
1430
1431/// Compile unit.
1432class DICompileUnit : public DIScope {
1433 friend class LLVMContextImpl;
1434 friend class MDNode;
1435
1436public:
1437 enum DebugEmissionKind : unsigned {
1444
1445 enum class DebugNameTableKind : unsigned {
1446 Default = 0,
1447 GNU = 1,
1448 None = 2,
1449 Apple = 3,
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
1458private:
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
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,
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
1508 TempDICompileUnit cloneImpl() const {
1509 return getTemporary(
1516 }
1517
1518public:
1519 static void get() = delete;
1520 static void getIfExists() = delete;
1521
1525 bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
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,
1533 (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
1535 GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
1536 DebugInfoForProfiling, (unsigned)NameTableKind, RangesBaseAddress,
1537 SysRoot, SDK))
1541 bool IsOptimized, MDString *Flags, unsigned RuntimeVersion,
1545 bool SplitDebugInlining, bool DebugInfoForProfiling,
1546 unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
1548 (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
1550 GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
1551 DebugInfoForProfiling, NameTableKind, RangesBaseAddress, SysRoot, SDK))
1552
1553 TempDICompileUnit clone() const { return cloneImpl(); }
1554
1555 unsigned getSourceLanguage() const { return SourceLanguage; }
1556 bool isOptimized() const { return IsOptimized; }
1557 unsigned getRuntimeVersion() const { return RuntimeVersion; }
1559 return (DebugEmissionKind)EmissionKind;
1560 }
1562 return EmissionKind == DebugDirectivesOnly;
1563 }
1564 bool getDebugInfoForProfiling() const { return DebugInfoForProfiling; }
1566 return (DebugNameTableKind)NameTableKind;
1567 }
1568 bool getRangesBaseAddress() const { return RangesBaseAddress; }
1570 StringRef getFlags() const { return getStringOperand(2); }
1572 DICompositeTypeArray getEnumTypes() const {
1573 return cast_or_null<MDTuple>(getRawEnumTypes());
1574 }
1575 DIScopeArray getRetainedTypes() const {
1576 return cast_or_null<MDTuple>(getRawRetainedTypes());
1577 }
1578 DIGlobalVariableExpressionArray getGlobalVariables() const {
1579 return cast_or_null<MDTuple>(getRawGlobalVariables());
1580 }
1581 DIImportedEntityArray getImportedEntities() const {
1582 return cast_or_null<MDTuple>(getRawImportedEntities());
1583 }
1584 DIMacroNodeArray getMacros() const {
1585 return cast_or_null<MDTuple>(getRawMacros());
1586 }
1587 uint64_t getDWOId() const { return DWOId; }
1588 void setDWOId(uint64_t DwoId) { DWOId = DwoId; }
1589 bool getSplitDebugInlining() const { return SplitDebugInlining; }
1590 void setSplitDebugInlining(bool SplitDebugInlining) {
1591 this->SplitDebugInlining = SplitDebugInlining;
1592 }
1594 StringRef getSDK() const { return getStringOperand(10); }
1595
1596 MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
1597 MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
1599 return getOperandAs<MDString>(3);
1600 }
1601 Metadata *getRawEnumTypes() const { return getOperand(4); }
1605 Metadata *getRawMacros() const { return getOperand(8); }
1606 MDString *getRawSysRoot() const { return getOperandAs<MDString>(9); }
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 /// @{
1615 void replaceEnumTypes(DICompositeTypeArray N) {
1616 replaceOperandWith(4, N.get());
1617 }
1618 void replaceRetainedTypes(DITypeArray N) { replaceOperandWith(5, N.get()); }
1619 void replaceGlobalVariables(DIGlobalVariableExpressionArray N) {
1620 replaceOperandWith(6, N.get());
1621 }
1622 void replaceImportedEntities(DIImportedEntityArray N) {
1623 replaceOperandWith(7, N.get());
1624 }
1625 void replaceMacros(DIMacroNodeArray N) { replaceOperandWith(8, N.get()); }
1626 /// @}
1627
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.
1638class DILocalScope : public DIScope {
1639protected:
1642 : DIScope(C, ID, Storage, Tag, Ops) {}
1643 ~DILocalScope() = default;
1644
1645public:
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 *
1656 LLVMContext &Ctx,
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.
1664
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.
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
1686public:
1687 /// Debug info subprogram flags.
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
1713private:
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,
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(),
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,
1748 bool ShouldCreate = true);
1749
1750 TempDISubprogram cloneImpl() const {
1752 getFile(), getLine(), getType(), getScopeLine(),
1753 getContainingType(), getVirtualIndex(),
1754 getThisAdjustment(), getFlags(), getSPFlags(),
1755 getUnit(), getTemplateParams(), getDeclaration(),
1756 getRetainedNodes(), getThrownTypes(), getAnnotations(),
1757 getTargetFuncName());
1758 }
1759
1760public:
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,
1771 (Scope, Name, LinkageName, File, Line, Type, ScopeLine, ContainingType,
1772 VirtualIndex, ThisAdjustment, Flags, SPFlags, Unit, TemplateParams,
1774
1778 unsigned Line, Metadata *Type, unsigned ScopeLine,
1779 Metadata *ContainingType, unsigned VirtualIndex, int ThisAdjustment,
1780 DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
1784 (Scope, Name, LinkageName, File, Line, Type, ScopeLine, ContainingType,
1785 VirtualIndex, ThisAdjustment, Flags, SPFlags, Unit, TemplateParams,
1787
1788 TempDISubprogram clone() const { return cloneImpl(); }
1789
1790 /// Returns a new temporary DISubprogram with updated Flags
1791 TempDISubprogram cloneWithFlags(DIFlags NewFlags) const {
1792 auto NewSP = clone();
1793 NewSP->Flags = NewFlags;
1794 return NewSP;
1795 }
1796
1797public:
1798 unsigned getLine() const { return Line; }
1799 unsigned getVirtuality() const { return getSPFlags() & SPFlagVirtuality; }
1800 unsigned getVirtualIndex() const { return VirtualIndex; }
1801 int getThisAdjustment() const { return ThisAdjustment; }
1802 unsigned getScopeLine() const { return ScopeLine; }
1803 void setScopeLine(unsigned L) {
1804 assert(isDistinct());
1805 ScopeLine = L;
1806 }
1807 DIFlags getFlags() const { return Flags; }
1808 DISPFlags getSPFlags() const { return SPFlags; }
1809 bool isLocalToUnit() const { return getSPFlags() & SPFlagLocalToUnit; }
1810 bool isDefinition() const { return getSPFlags() & SPFlagDefinition; }
1811 bool isOptimized() const { return getSPFlags() & SPFlagOptimized; }
1812 bool isMainSubprogram() const { return getSPFlags() & SPFlagMainSubprogram; }
1813
1814 bool isArtificial() const { return getFlags() & FlagArtificial; }
1815 bool isPrivate() const {
1816 return (getFlags() & FlagAccessibility) == FlagPrivate;
1817 }
1818 bool isProtected() const {
1819 return (getFlags() & FlagAccessibility) == FlagProtected;
1820 }
1821 bool isPublic() const {
1822 return (getFlags() & FlagAccessibility) == FlagPublic;
1823 }
1824 bool isExplicit() const { return getFlags() & FlagExplicit; }
1825 bool isPrototyped() const { return getFlags() & FlagPrototyped; }
1826 bool areAllCallsDescribed() const {
1827 return getFlags() & FlagAllCallsDescribed;
1828 }
1829 bool isPure() const { return getSPFlags() & SPFlagPure; }
1830 bool isElemental() const { return getSPFlags() & SPFlagElemental; }
1831 bool isRecursive() const { return getSPFlags() & SPFlagRecursive; }
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.
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() &).
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() &&).
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
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.
1860 bool isThunk() const { return getFlags() & FlagThunk; }
1861
1862 DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
1863
1864 StringRef getName() const { return getStringOperand(2); }
1865 StringRef getLinkageName() const { return getStringOperand(3); }
1866 /// Only used by clients of CloneFunction, and only right after the cloning.
1867 void replaceLinkageName(MDString *LN) { replaceOperandWith(3, LN); }
1868
1869 DISubroutineType *getType() const {
1870 return cast_or_null<DISubroutineType>(getRawType());
1871 }
1872 DIType *getContainingType() const {
1873 return cast_or_null<DIType>(getRawContainingType());
1874 }
1875 void replaceType(DISubroutineType *Ty) {
1876 assert(isDistinct() && "Only distinct nodes can mutate");
1877 replaceOperandWith(4, Ty);
1878 }
1879
1880 DICompileUnit *getUnit() const {
1881 return cast_or_null<DICompileUnit>(getRawUnit());
1882 }
1883 void replaceUnit(DICompileUnit *CU) { replaceOperandWith(5, CU); }
1884 DITemplateParameterArray getTemplateParams() const {
1885 return cast_or_null<MDTuple>(getRawTemplateParams());
1886 }
1887 DISubprogram *getDeclaration() const {
1888 return cast_or_null<DISubprogram>(getRawDeclaration());
1889 }
1890 void replaceDeclaration(DISubprogram *Decl) { replaceOperandWith(6, Decl); }
1891 DINodeArray getRetainedNodes() const {
1892 return cast_or_null<MDTuple>(getRawRetainedNodes());
1893 }
1894 DITypeArray getThrownTypes() const {
1895 return cast_or_null<MDTuple>(getRawThrownTypes());
1896 }
1897 DINodeArray getAnnotations() const {
1898 return cast_or_null<MDTuple>(getRawAnnotations());
1899 }
1900 StringRef getTargetFuncName() const {
1901 return (getRawTargetFuncName()) ? getStringOperand(12) : StringRef();
1902 }
1903
1904 Metadata *getRawScope() const { return getOperand(1); }
1905 MDString *getRawName() const { return getOperandAs<MDString>(2); }
1906 MDString *getRawLinkageName() const { return getOperandAs<MDString>(3); }
1907 Metadata *getRawType() const { return getOperand(4); }
1908 Metadata *getRawUnit() const { return getOperand(5); }
1909 Metadata *getRawDeclaration() const { return getOperand(6); }
1910 Metadata *getRawRetainedNodes() const { return getOperand(7); }
1911 Metadata *getRawContainingType() const {
1912 return getNumOperands() > 8 ? getOperandAs<Metadata>(8) : nullptr;
1913 }
1914 Metadata *getRawTemplateParams() const {
1915 return getNumOperands() > 9 ? getOperandAs<Metadata>(9) : nullptr;
1916 }
1917 Metadata *getRawThrownTypes() const {
1918 return getNumOperands() > 10 ? getOperandAs<Metadata>(10) : nullptr;
1919 }
1920 Metadata *getRawAnnotations() const {
1921 return getNumOperands() > 11 ? getOperandAs<Metadata>(11) : nullptr;
1922 }
1923 MDString *getRawTargetFuncName() const {
1924 return getNumOperands() > 12 ? getOperandAs<MDString>(12) : nullptr;
1925 }
1926
1927 void replaceRawLinkageName(MDString *LinkageName) {
1929 }
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
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
1951class DILocation : public MDNode {
1952 friend class LLVMContextImpl;
1953 friend class MDNode;
1954
1956 unsigned Column, ArrayRef<Metadata *> MDs, bool ImplicitCode);
1958
1959 static DILocation *getImpl(LLVMContext &Context, unsigned Line,
1960 unsigned Column, Metadata *Scope,
1962 StorageType Storage, bool ShouldCreate = true);
1963 static DILocation *getImpl(LLVMContext &Context, unsigned Line,
1964 unsigned Column, DILocalScope *Scope,
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
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
1979public:
1980 // Disallow replacing operands.
1981 void replaceOperandWith(unsigned I, Metadata *New) = delete;
1982
1984 (unsigned Line, unsigned Column, Metadata *Scope,
1985 Metadata *InlinedAt = nullptr, bool ImplicitCode = false),
1988 (unsigned Line, unsigned Column, DILocalScope *Scope,
1990 bool ImplicitCode = false),
1992
1993 /// Return a (temporary) clone of this.
1994 TempDILocation clone() const { return cloneImpl(); }
1995
1996 unsigned getLine() const { return SubclassData32; }
1997 unsigned getColumn() const { return SubclassData16; }
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).
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
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.
2022 bool isImplicitCode() const { return SubclassData1; }
2023 void setImplicitCode(bool ImplicitCode) { SubclassData1 = ImplicitCode; }
2024
2025 DIFile *getFile() const { return getScope()->getFile(); }
2026 StringRef getFilename() const { return getScope()->getFilename(); }
2027 StringRef getDirectory() const { return getScope()->getDirectory(); }
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.
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
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 *>
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.
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.
2140 static unsigned getMaskedDiscriminator(unsigned D, unsigned B) {
2141 return (D & getN1Bits(B));
2142 }
2143
2144 /// Return the bits used for base discriminators.
2145 static unsigned getBaseDiscriminatorBits() { return getBaseFSBitEnd(); }
2146
2147 /// Returns the base discriminator for a given encoded discriminator \p D.
2148 static unsigned
2150 bool IsFSDiscriminator = false) {
2151 // Extract the dwarf base discriminator if it's encoded in the pseudo probe
2152 // discriminator.
2154 auto DwarfBaseDiscriminator =
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.
2164 }
2165
2166 if (IsFSDiscriminator)
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.
2193 static unsigned getDuplicationFactorFromDiscriminator(unsigned D) {
2195 return 1;
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.
2204 static unsigned getCopyIdentifierFromDiscriminator(unsigned D) {
2207 }
2208
2209 Metadata *getRawScope() const { return getOperand(0); }
2211 if (getNumOperands() == 2)
2212 return getOperand(1);
2213 return nullptr;
2214 }
2215
2216 static bool classof(const Metadata *MD) {
2217 return MD->getMetadataID() == DILocationKind;
2218 }
2219};
2220
2222protected:
2226
2227public:
2228 DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
2229
2230 Metadata *getRawScope() const { return getOperand(1); }
2231
2232 void replaceScope(DIScope *Scope) {
2233 assert(!isUniqued());
2234 setOperand(1, Scope);
2235 }
2236
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.
2247 friend class LLVMContextImpl;
2248 friend class MDNode;
2249
2250 uint16_t Column;
2251
2253 unsigned Column, ArrayRef<Metadata *> Ops)
2254 : DILexicalBlockBase(C, DILexicalBlockKind, Storage, Ops),
2255 Column(Column) {
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,
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
2274 TempDILexicalBlock cloneImpl() const {
2276 getColumn());
2277 }
2278
2279public:
2281 (DILocalScope * Scope, DIFile *File, unsigned Line,
2282 unsigned Column),
2283 (Scope, File, Line, Column))
2286 unsigned Column),
2287 (Scope, File, Line, Column))
2288
2289 TempDILexicalBlock clone() const { return cloneImpl(); }
2290
2291 unsigned getLine() const { return SubclassData32; }
2292 unsigned getColumn() const { return Column; }
2293
2294 static bool classof(const Metadata *MD) {
2295 return MD->getMetadataID() == DILexicalBlockKind;
2296 }
2297};
2298
2300 friend class LLVMContextImpl;
2301 friend class MDNode;
2302
2304 unsigned Discriminator, ArrayRef<Metadata *> Ops)
2305 : DILexicalBlockBase(C, DILexicalBlockFileKind, Storage, Ops) {
2307 }
2308 ~DILexicalBlockFile() = default;
2309
2310 static DILexicalBlockFile *getImpl(LLVMContext &Context, DILocalScope *Scope,
2311 DIFile *File, unsigned Discriminator,
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,
2322 bool ShouldCreate = true);
2323
2324 TempDILexicalBlockFile cloneImpl() const {
2325 return getTemporary(getContext(), getScope(), getFile(),
2327 }
2328
2329public:
2332 unsigned Discriminator),
2337
2338 TempDILexicalBlockFile clone() const { return cloneImpl(); }
2339 unsigned getDiscriminator() const { return SubclassData32; }
2340
2341 static bool classof(const Metadata *MD) {
2342 return MD->getMetadataID() == DILexicalBlockFileKind;
2343 }
2344};
2345
2346unsigned DILocation::getDiscriminator() const {
2347 if (auto *F = dyn_cast<DILexicalBlockFile>(getScope()))
2348 return F->getDiscriminator();
2349 return 0;
2350}
2351
2352const DILocation *
2353DILocation::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
2370 return getBaseDiscriminatorFromDiscriminator(getDiscriminator(),
2372}
2373
2375 return getDuplicationFactorFromDiscriminator(getDiscriminator());
2376}
2377
2379 return getCopyIdentifierFromDiscriminator(getDiscriminator());
2380}
2381
2382std::optional<const DILocation *>
2384 unsigned BD, DF, CI;
2385
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
2401std::optional<const DILocation *>
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
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.
2425class DINamespace : public DIScope {
2426 friend class LLVMContextImpl;
2427 friend class MDNode;
2428
2431 ~DINamespace() = default;
2432
2433 static DINamespace *getImpl(LLVMContext &Context, DIScope *Scope,
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,
2441 StorageType Storage, bool ShouldCreate = true);
2442
2443 TempDINamespace cloneImpl() const {
2444 return getTemporary(getContext(), getScope(), getName(),
2446 }
2447
2448public:
2455
2456 TempDINamespace clone() const { return cloneImpl(); }
2457
2458 bool getExportSymbols() const { return SubclassData1; }
2459 DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
2460 StringRef getName() const { return getStringOperand(2); }
2461
2462 Metadata *getRawScope() const { return getOperand(1); }
2463 MDString *getRawName() const { return getOperandAs<MDString>(2); }
2464
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.
2474class 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,
2485 unsigned LineNo, bool IsDecl, StorageType Storage,
2486 bool ShouldCreate = true) {
2487 return getImpl(Context, File, Scope, getCanonicalMDString(Context, Name),
2490 getCanonicalMDString(Context, APINotesFile), LineNo, IsDecl,
2491 Storage, ShouldCreate);
2492 }
2493 static DIModule *getImpl(LLVMContext &Context, Metadata *File,
2496 MDString *APINotesFile, unsigned LineNo, bool IsDecl,
2497 StorageType Storage, bool ShouldCreate = true);
2498
2499 TempDIModule cloneImpl() const {
2501 getConfigurationMacros(), getIncludePath(),
2502 getAPINotesFile(), getLineNo(), getIsDecl());
2503 }
2504
2505public:
2509 StringRef APINotesFile, unsigned LineNo,
2510 bool IsDecl = false),
2512 APINotesFile, LineNo, IsDecl))
2517 bool IsDecl = false),
2519 APINotesFile, LineNo, IsDecl))
2520
2521 TempDIModule clone() const { return cloneImpl(); }
2522
2523 DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
2524 StringRef getName() const { return getStringOperand(2); }
2525 StringRef getConfigurationMacros() const { return getStringOperand(3); }
2526 StringRef getIncludePath() const { return getStringOperand(4); }
2527 StringRef getAPINotesFile() const { return getStringOperand(5); }
2528 unsigned getLineNo() const { return SubclassData32; }
2529 bool getIsDecl() const { return SubclassData1; }
2530
2531 Metadata *getRawScope() const { return getOperand(1); }
2532 MDString *getRawName() const { return getOperandAs<MDString>(2); }
2533 MDString *getRawConfigurationMacros() const {
2534 return getOperandAs<MDString>(3);
2535 }
2536 MDString *getRawIncludePath() const { return getOperandAs<MDString>(4); }
2537 MDString *getRawAPINotesFile() const { return getOperandAs<MDString>(5); }
2538
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.
2548protected:
2550 unsigned Tag, bool IsDefault, ArrayRef<Metadata *> Ops)
2551 : DINode(Context, ID, Storage, Tag, Ops) {
2552 SubclassData1 = IsDefault;
2553 }
2555
2556public:
2557 StringRef getName() const { return getStringOperand(0); }
2558 DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
2559
2560 MDString *getRawName() const { return getOperandAs<MDString>(0); }
2561 Metadata *getRawType() const { return getOperand(1); }
2562 bool isDefault() const { return SubclassData1; }
2563
2564 static bool classof(const Metadata *MD) {
2565 return MD->getMetadataID() == DITemplateTypeParameterKind ||
2566 MD->getMetadataID() == DITemplateValueParameterKind;
2567 }
2568};
2569
2571 friend class LLVMContextImpl;
2572 friend class MDNode;
2573
2576 ~DITemplateTypeParameter() = default;
2577
2578 static DITemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
2579 DIType *Type, bool IsDefault,
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,
2588 bool ShouldCreate = true);
2589
2590 TempDITemplateTypeParameter cloneImpl() const {
2591 return getTemporary(getContext(), getName(), getType(), isDefault());
2592 }
2593
2594public:
2597 (Name, Type, IsDefault))
2601
2602 TempDITemplateTypeParameter clone() const { return cloneImpl(); }
2603
2604 static bool classof(const Metadata *MD) {
2605 return MD->getMetadataID() == DITemplateTypeParameterKind;
2606 }
2607};
2608
2610 friend class LLVMContextImpl;
2611 friend class MDNode;
2612
2614 unsigned Tag, bool IsDefault,
2616 : DITemplateParameter(Context, DITemplateValueParameterKind, Storage, Tag,
2617 IsDefault, Ops) {}
2618 ~DITemplateValueParameter() = default;
2619
2620 static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
2622 bool IsDefault, Metadata *Value,
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,
2632 bool ShouldCreate = true);
2633
2634 TempDITemplateValueParameter cloneImpl() const {
2635 return getTemporary(getContext(), getTag(), getName(), getType(),
2636 isDefault(), getValue());
2637 }
2638
2639public:
2641 (unsigned Tag, StringRef Name, DIType *Type, bool IsDefault,
2642 Metadata *Value),
2643 (Tag, Name, Type, IsDefault, Value))
2648
2649 TempDITemplateValueParameter clone() const { return cloneImpl(); }
2650
2651 Metadata *getValue() const { return getOperand(2); }
2652
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.
2661class DIVariable : public DINode {
2662 unsigned Line;
2663
2664protected:
2665 DIVariable(LLVMContext &C, unsigned ID, StorageType Storage, signed Line,
2666 ArrayRef<Metadata *> Ops, uint32_t AlignInBits = 0);
2667 ~DIVariable() = default;
2668
2669public:
2670 unsigned getLine() const { return Line; }
2671 DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
2672 StringRef getName() const { return getStringOperand(1); }
2673 DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
2674 DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
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.
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
2689 if (auto *F = getFile())
2690 return F->getFilename();
2691 return "";
2692 }
2693
2695 if (auto *F = getFile())
2696 return F->getDirectory();
2697 return "";
2698 }
2699
2700 std::optional<StringRef> getSource() const {
2701 if (auto *F = getFile())
2702 return F->getSource();
2703 return std::nullopt;
2704 }
2705
2706 Metadata *getRawScope() const { return getOperand(0); }
2707 MDString *getRawName() const { return getOperandAs<MDString>(1); }
2708 Metadata *getRawFile() const { return getOperand(2); }
2709 Metadata *getRawType() const { return getOperand(3); }
2710
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.
2726class DIExpression : public MDNode {
2727 friend class LLVMContextImpl;
2728 friend class MDNode;
2729
2730 std::vector<uint64_t> Elements;
2731
2733 : MDNode(C, DIExpressionKind, Storage, std::nullopt),
2734 Elements(Elements.begin(), Elements.end()) {}
2735 ~DIExpression() = default;
2736
2737 static DIExpression *getImpl(LLVMContext &Context,
2739 bool ShouldCreate = true);
2740
2741 TempDIExpression cloneImpl() const {
2742 return getTemporary(getContext(), getElements());
2743 }
2744
2745public:
2747
2748 TempDIExpression clone() const { return cloneImpl(); }
2749
2750 ArrayRef<uint64_t> getElements() const { return Elements; }
2751
2752 unsigned getNumElements() const { return Elements.size(); }
2753
2754 uint64_t getElement(unsigned I) const {
2755 assert(I < Elements.size() && "Index out of range");
2756 return Elements[I];
2757 }
2758
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).
2773
2775
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.
2784 const uint64_t *Op = nullptr;
2785
2786 public:
2787 ExprOperand() = default;
2788 explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
2789
2790 const uint64_t *get() const { return Op; }
2791
2792 /// Get the operand code.
2793 uint64_t getOp() const { return *Op; }
2794
2795 /// Get an argument to the operand.
2796 ///
2797 /// Never returns the operand itself.
2798 uint64_t getArg(unsigned I) const { return Op[I + 1]; }
2799
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.
2809 V.append(get(), get() + getSize());
2810 }
2811 };
2812
2813 /// An iterator for expression operands.
2816
2817 public:
2818 using iterator_category = std::input_iterator_tag;
2820 using difference_type = std::ptrdiff_t;
2823
2824 expr_op_iterator() = default;
2826
2827 element_iterator getBase() const { return Op.get(); }
2828 const ExprOperand &operator*() const { return Op; }
2829 const ExprOperand *operator->() const { return &Op; }
2830
2832 increment();
2833 return *this;
2834 }
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.
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:
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 /// @{
2869 }
2872 }
2874 return {expr_op_begin(), expr_op_end()};
2875 }
2876 /// @}
2877
2878 bool isValid() const;
2879
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
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,
2901
2902 /// Retrieve the details of this fragment expression.
2903 std::optional<FragmentInfo> getFragmentInfo() const {
2905 }
2906
2907 /// Return whether this is a piece of an aggregate variable.
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 *
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 *>
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.
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 {
3008 DerefBefore = 1 << 0,
3009 DerefAfter = 1 << 1,
3010 StackValue = 1 << 2,
3011 EntryValue = 1 << 3
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,
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.
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.
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.
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.
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.
3168};
3169
3172 return std::tie(A.SizeInBits, A.OffsetInBits) ==
3173 std::tie(B.SizeInBits, B.OffsetInBits);
3174}
3175
3178 return std::tie(A.SizeInBits, A.OffsetInBits) <
3179 std::tie(B.SizeInBits, B.OffsetInBits);
3180}
3181
3182template <> struct DenseMapInfo<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.
3201
3202public:
3204 if (!Expr) {
3205 assert(Start == End);
3206 return;
3207 }
3208 Start = Expr->expr_op_begin();
3209 End = Expr->expr_op_end();
3210 }
3211
3213 : Start(Expr.begin()), End(Expr.end()) {}
3214
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;
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
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; }
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.
3279 friend class LLVMContextImpl;
3280 friend class MDNode;
3281
3282 bool IsLocalToUnit;
3283 bool IsDefinition;
3284
3286 bool IsLocalToUnit, bool IsDefinition, uint32_t AlignInBits,
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,
3295 bool IsLocalToUnit, bool IsDefinition,
3298 bool ShouldCreate = true) {
3299 return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
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,
3311 bool ShouldCreate = true);
3312
3313 TempDIGlobalVariable cloneImpl() const {
3318 getAnnotations());
3319 }
3320
3321public:
3325 unsigned Line, DIType *Type, bool IsLocalToUnit, bool IsDefinition,
3327 uint32_t AlignInBits, DINodeArray Annotations),
3328 (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
3333 unsigned Line, Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
3336 (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
3338
3339 TempDIGlobalVariable clone() const { return cloneImpl(); }
3340
3341 bool isLocalToUnit() const { return IsLocalToUnit; }
3342 bool isDefinition() const { return IsDefinition; }
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); }
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.
3366class DICommonBlock : public DIScope {
3367 friend class LLVMContextImpl;
3368 friend class MDNode;
3369
3372
3373 static DICommonBlock *getImpl(LLVMContext &Context, DIScope *Scope,
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,
3382 unsigned LineNo, StorageType Storage,
3383 bool ShouldCreate = true);
3384
3385 TempDICommonBlock cloneImpl() const {
3387 getFile(), getLineNo());
3388 }
3389
3390public:
3393 DIFile *File, unsigned LineNo),
3394 (Scope, Decl, Name, File, LineNo))
3397 Metadata *File, unsigned LineNo),
3399
3400 TempDICommonBlock clone() const { return cloneImpl(); }
3401
3402 DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
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.
3424 friend class LLVMContextImpl;
3425 friend class MDNode;
3426
3427 unsigned Arg : 16;
3428 DIFlags Flags;
3429
3431 unsigned Arg, DIFlags Flags, uint32_t AlignInBits,
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,
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,
3454 bool ShouldCreate = true);
3455
3456 TempDILocalVariable cloneImpl() const {
3458 getLine(), getType(), getArg(), getFlags(),
3460 }
3461
3462public:
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))
3471 unsigned Line, Metadata *Type, unsigned Arg, DIFlags Flags,
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.
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.)
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.
3514class DILabel : public DINode {
3515 friend class LLVMContextImpl;
3516 friend class MDNode;
3517
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 {
3534 getLine());
3535 }
3536
3537public:
3540 unsigned Line),
3541 (Scope, Name, File, Line))
3544 unsigned 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.
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.)
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
3577class DIObjCProperty : public DINode {
3578 friend class LLVMContextImpl;
3579 friend class MDNode;
3580
3581 unsigned Line;
3582 unsigned Attributes;
3583
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,
3594 getCanonicalMDString(Context, SetterName), Attributes, Type,
3595 Storage, ShouldCreate);
3596 }
3597 static DIObjCProperty *getImpl(LLVMContext &Context, MDString *Name,
3598 Metadata *File, unsigned Line,
3600 unsigned Attributes, Metadata *Type,
3601 StorageType Storage, bool ShouldCreate = true);
3602
3603 TempDIObjCProperty cloneImpl() const {
3604 return getTemporary(getContext(), getName(), getFile(), getLine(),
3606 getType());
3607 }
3608
3609public:
3611 (StringRef Name, DIFile *File, unsigned Line,
3613 unsigned Attributes, DIType *Type),
3614 (Name, File, Line, GetterName, SetterName, Attributes,
3615 Type))
3617 (MDString * Name, Metadata *File, unsigned Line,
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()); }
3631 DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
3632
3634 if (auto *F = getFile())
3635 return F->getFilename();
3636 return "";
3637 }
3638
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///