LLVM 24.0.0git
DwarfUnit.cpp
Go to the documentation of this file.
1//===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
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// This file contains support for constructing a dwarf compile unit.
10//
11//===----------------------------------------------------------------------===//
12
13#include "DwarfUnit.h"
14#include "AddressPool.h"
15#include "DwarfCompileUnit.h"
16#include "DwarfExpression.h"
17#include "llvm/ADT/APFloat.h"
18#include "llvm/ADT/APInt.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/GlobalValue.h"
24#include "llvm/IR/Metadata.h"
25#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCContext.h"
27#include "llvm/MC/MCDwarf.h"
28#include "llvm/MC/MCSection.h"
29#include "llvm/MC/MCStreamer.h"
32#include <cassert>
33#include <cstdint>
34#include <limits>
35#include <string>
36
37using namespace llvm;
38
39#define DEBUG_TYPE "dwarfdebug"
40
44
45void DIEDwarfExpression::emitOp(uint8_t Op, const char* Comment) {
46 CU.addUInt(getActiveDIE(), dwarf::DW_FORM_data1, Op);
47}
48
49void DIEDwarfExpression::emitSigned(int64_t Value) {
50 CU.addSInt(getActiveDIE(), dwarf::DW_FORM_sdata, Value);
51}
52
53void DIEDwarfExpression::emitUnsigned(uint64_t Value) {
54 CU.addUInt(getActiveDIE(), dwarf::DW_FORM_udata, Value);
55}
56
57void DIEDwarfExpression::emitData1(uint8_t Value) {
58 CU.addUInt(getActiveDIE(), dwarf::DW_FORM_data1, Value);
59}
60
61void DIEDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
62 CU.addBaseTypeRef(getActiveDIE(), Idx);
63}
64
65void DIEDwarfExpression::emitRelocatedAddress(const MCSymbol *Sym) {
66 CU.addLabel(getActiveDIE(), dwarf::DW_FORM_addr, Sym);
67}
68
70 assert(!IsBuffering && "Already buffering?");
71 IsBuffering = true;
72}
73
74void DIEDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
75
77 return TmpDIE.computeSize(AP.getDwarfFormParams());
78}
79
80void DIEDwarfExpression::commitTemporaryBuffer() { OutDIE.takeValues(TmpDIE); }
81
82bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
83 llvm::Register MachineReg) {
84 return MachineReg == TRI.getFrameRegister(*AP.MF);
85}
86
88 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU,
89 unsigned UniqueID)
90 : DIEUnit(UnitTag), UniqueID(UniqueID), CUNode(Node), Asm(A), DD(DW),
91 DU(DWU) {}
92
94 DwarfDebug *DW, DwarfFile *DWU, unsigned UniqueID,
95 MCDwarfDwoLineTable *SplitLineTable)
96 : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU, UniqueID),
97 CU(CU), SplitLineTable(SplitLineTable) {}
98
100 for (DIEBlock *B : DIEBlocks)
101 B->~DIEBlock();
102 for (DIELoc *L : DIELocs)
103 L->~DIELoc();
104}
105
106int64_t DwarfUnit::getDefaultLowerBound() const {
107 switch (getSourceLanguage()) {
108 default:
109 break;
110
111 // The languages below have valid values in all DWARF versions.
112 case dwarf::DW_LANG_C:
113 case dwarf::DW_LANG_C89:
114 case dwarf::DW_LANG_C_plus_plus:
115 return 0;
116
117 case dwarf::DW_LANG_Fortran77:
118 case dwarf::DW_LANG_Fortran90:
119 return 1;
120
121 // The languages below have valid values only if the DWARF version >= 3.
122 case dwarf::DW_LANG_C99:
123 case dwarf::DW_LANG_ObjC:
124 case dwarf::DW_LANG_ObjC_plus_plus:
125 if (DD->getDwarfVersion() >= 3)
126 return 0;
127 break;
128
129 case dwarf::DW_LANG_Fortran95:
130 if (DD->getDwarfVersion() >= 3)
131 return 1;
132 break;
133
134 // Starting with DWARF v4, all defined languages have valid values.
135 case dwarf::DW_LANG_D:
136 case dwarf::DW_LANG_Java:
137 case dwarf::DW_LANG_Python:
138 case dwarf::DW_LANG_UPC:
139 if (DD->getDwarfVersion() >= 4)
140 return 0;
141 break;
142
143 case dwarf::DW_LANG_Ada83:
144 case dwarf::DW_LANG_Ada95:
145 case dwarf::DW_LANG_Cobol74:
146 case dwarf::DW_LANG_Cobol85:
147 case dwarf::DW_LANG_Modula2:
148 case dwarf::DW_LANG_Pascal83:
149 case dwarf::DW_LANG_PLI:
150 if (DD->getDwarfVersion() >= 4)
151 return 1;
152 break;
153
154 // The languages below are new in DWARF v5.
155 case dwarf::DW_LANG_BLISS:
156 case dwarf::DW_LANG_C11:
157 case dwarf::DW_LANG_C_plus_plus_03:
158 case dwarf::DW_LANG_C_plus_plus_11:
159 case dwarf::DW_LANG_C_plus_plus_14:
160 case dwarf::DW_LANG_Dylan:
161 case dwarf::DW_LANG_Go:
162 case dwarf::DW_LANG_Haskell:
163 case dwarf::DW_LANG_OCaml:
164 case dwarf::DW_LANG_OpenCL:
165 case dwarf::DW_LANG_RenderScript:
166 case dwarf::DW_LANG_Rust:
167 case dwarf::DW_LANG_Swift:
168 if (DD->getDwarfVersion() >= 5)
169 return 0;
170 break;
171
172 case dwarf::DW_LANG_Fortran03:
173 case dwarf::DW_LANG_Fortran08:
174 case dwarf::DW_LANG_Julia:
175 case dwarf::DW_LANG_Modula3:
176 if (DD->getDwarfVersion() >= 5)
177 return 1;
178 break;
179 }
180
181 return -1;
182}
183
184/// Check whether the DIE for this MDNode can be shared across CUs.
186 // When the MDNode can be part of the type system, the DIE can be shared
187 // across CUs.
188 // Combining type units and cross-CU DIE sharing is lower value (since
189 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
190 // level already) but may be implementable for some value in projects
191 // building multiple independent libraries with LTO and then linking those
192 // together.
193
194 // Prevent generation of cross-CU references for DWARF v2 due to conflicts
195 // resulting from the FAQ recommendation: "If you are producing DWARF V2,
196 // please use the DWARF V3 definition of DW_FORM_ref_addr."
197 // (https://dwarfstd.org/faq.html)
198 if (DD->getDwarfVersion() == 2)
199 return false;
200 if (isDwoUnit() && !DD->shareAcrossDWOCUs())
201 return false;
202 return (isa<DIType>(D) ||
203 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
204 !DD->generateTypeUnits();
205}
206
209 return DU->getDIE(D);
210 return MDNodeToDieMap.lookup(D);
211}
212
215 DU->insertDIE(Desc, D);
216 return;
217 }
218 MDNodeToDieMap.insert(std::make_pair(Desc, D));
219}
220
222 MDNodeToDieMap.insert(std::make_pair(nullptr, D));
223}
224
226 if (DD->getDwarfVersion() >= 4)
227 addAttribute(Die, Attribute, dwarf::DW_FORM_flag_present, DIEInteger(1));
228 else
229 addAttribute(Die, Attribute, dwarf::DW_FORM_flag, DIEInteger(1));
230}
231
233 std::optional<dwarf::Form> Form, uint64_t Integer) {
234 if (!Form)
235 Form = DIEInteger::BestForm(false, Integer);
236 assert(Form != dwarf::DW_FORM_implicit_const &&
237 "DW_FORM_implicit_const is used only for signed integers");
239}
240
245
246void DwarfUnit::addIntToBlock(DIEBlock &Block, const APInt &Val) {
247 // Get the raw data form of the large APInt.
248 const uint64_t *Ptr64 = Val.getRawData();
249
250 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
251 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
252
253 // Output the constant to DWARF one byte at a time.
254 for (int i = 0; i < NumBytes; i++) {
255 uint8_t c;
256 if (LittleEndian)
257 c = Ptr64[i / 8] >> (8 * (i & 7));
258 else
259 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
260 addUInt(Block, dwarf::DW_FORM_data1, c);
261 }
262}
263
264void DwarfUnit::addIntAsBlock(DIE &Die, dwarf::Attribute Attribute,
265 const APInt &Val, bool Unsigned) {
266 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
267
268 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
269 // Normally we want to use DW_FORM_block* here. However, for some
270 // attributes, this form may be used for an expression. In this
271 // case, we can switch to DW_FORM_data16, but only if there are 16
272 // bytes or less, and only for DWARF 5.
273 std::optional<dwarf::Form> Form;
274 std::optional<APInt> Widened;
276 if (NumBytes > 16 || DD->getDwarfVersion() < 5) {
277 return;
278 }
279
280 // Widen if less than 128 bits.
281 if (Val.getActiveBits() < 128) {
282 if (Unsigned)
283 Widened = Val.zext(128);
284 else
285 Widened = Val.sext(128);
286 }
287
288 Form = dwarf::DW_FORM_data16;
289 }
290
291 addIntToBlock(*Block, Widened ? *Widened : Val);
292 Block->computeSize(Asm->getDwarfFormParams());
293
294 if (!Form.has_value()) {
295 Form = Block->BestForm();
296 }
297 addBlock(Die, Attribute, *Form, Block);
298}
299
301 bool Unsigned, std::optional<dwarf::Form> Form) {
302 unsigned CIBitWidth = Val.getBitWidth();
303 if (CIBitWidth <= 64) {
304 if (Unsigned)
305 addUInt(Die, Attribute, Form, Val.getZExtValue());
306 else
307 addSInt(Die, Attribute, Form, Val.getSExtValue());
308 return;
309 }
310
311 addIntAsBlock(Die, Attribute, Val, Unsigned);
312}
313
315 std::optional<dwarf::Form> Form, int64_t Integer) {
316 if (!Form)
317 Form = DIEInteger::BestForm(true, Integer);
319}
320
321void DwarfUnit::addSInt(DIEValueList &Die, std::optional<dwarf::Form> Form,
322 int64_t Integer) {
323 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
324}
325
328 if (CUNode->isDebugDirectivesOnly())
329 return;
330
331 if (DD->useInlineStrings()) {
332 addAttribute(Die, Attribute, dwarf::DW_FORM_string,
335 return;
336 }
337 dwarf::Form IxForm =
338 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp;
339
340 auto StringPoolEntry =
341 useSegmentedStringOffsetsTable() || IxForm == dwarf::DW_FORM_GNU_str_index
342 ? DU->getStringPool().getIndexedEntry(*Asm, String)
343 : DU->getStringPool().getEntry(*Asm, String);
344
345 // For DWARF v5 and beyond, use the smallest strx? form possible.
347 IxForm = dwarf::DW_FORM_strx1;
348 unsigned Index = StringPoolEntry.getIndex();
349 if (Index > 0xffffff)
350 IxForm = dwarf::DW_FORM_strx4;
351 else if (Index > 0xffff)
352 IxForm = dwarf::DW_FORM_strx3;
353 else if (Index > 0xff)
354 IxForm = dwarf::DW_FORM_strx2;
355 }
356 addAttribute(Die, Attribute, IxForm, DIEString(StringPoolEntry));
357}
358
360 dwarf::Form Form, const MCSymbol *Label) {
361 addAttribute(Die, Attribute, Form, DIELabel(Label));
362}
363
364void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
365 addLabel(Die, (dwarf::Attribute)0, Form, Label);
366}
367
369 uint64_t Integer) {
370 addUInt(Die, Attribute, DD->getDwarfSectionOffsetForm(), Integer);
371}
372
373unsigned DwarfTypeUnit::getOrCreateSourceID(const DIFile *File) {
374 if (!SplitLineTable)
375 return getCU().getOrCreateSourceID(File);
376 if (!UsedLineTable) {
377 UsedLineTable = true;
378 // This is a split type unit that needs a line table.
379 addSectionOffset(getUnitDie(), dwarf::DW_AT_stmt_list, 0);
380 }
381 return SplitLineTable->getFile(
382 File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File),
383 Asm->OutContext.getDwarfVersion(), File->getSource());
384}
385
387 bool UseAddrOffsetFormOrExpressions =
388 DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
389
390 const MCSymbol *Base = nullptr;
391 if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
392 Base = DD->getSectionLabel(&Label->getSection());
393
394 uint32_t Index = DD->getAddressPool().getIndex(Base ? Base : Label);
395
396 if (DD->getDwarfVersion() >= 5) {
397 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addrx);
398 addUInt(Die, dwarf::DW_FORM_addrx, Index);
399 } else {
400 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
401 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, Index);
402 }
403
404 if (Base && Base != Label) {
405 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_const4u);
406 addLabelDelta(Die, (dwarf::Attribute)0, Label, Base);
407 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
408 }
409}
410
412 if (DD->getDwarfVersion() >= 5) {
413 addPoolOpAddress(Die, Sym);
414 return;
415 }
416
417 if (DD->useSplitDwarf()) {
418 addPoolOpAddress(Die, Sym);
419 return;
420 }
421
422 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
423 addLabel(Die, dwarf::DW_FORM_addr, Sym);
424}
425
427 const MCSymbol *Hi, const MCSymbol *Lo) {
428 addAttribute(Die, Attribute, dwarf::DW_FORM_data4,
430}
431
435
436void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
437 // Flag the type unit reference as a declaration so that if it contains
438 // members (implicit special members, static data member definitions, member
439 // declarations for definitions in this CU, etc) consumers don't get confused
440 // and think this is a full definition.
441 addFlag(Die, dwarf::DW_AT_declaration);
442
443 addAttribute(Die, dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
444 DIEInteger(Signature));
445}
446
448 DIEEntry Entry) {
449 const DIEUnit *CU = Die.getUnit();
450 const DIEUnit *EntryCU = Entry.getEntry().getUnit();
451 if (!CU)
452 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
453 CU = getUnitDie().getUnit();
454 if (!EntryCU)
455 EntryCU = getUnitDie().getUnit();
456 assert(EntryCU == CU || !DD->useSplitDwarf() || DD->shareAcrossDWOCUs() ||
457 !static_cast<const DwarfUnit*>(CU)->isDwoUnit());
459 EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
460 Entry);
461}
462
464 DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, Tag));
465 if (N)
466 insertDIE(N, &Die);
467 return Die;
468}
469
471 Loc->computeSize(Asm->getDwarfFormParams());
472 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
473 addAttribute(Die, Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
474}
475
477 DIEBlock *Block) {
478 Block->computeSize(Asm->getDwarfFormParams());
479 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
480 addAttribute(Die, Attribute, Form, Block);
481}
482
487
489 const DIExpression *Expr) {
491 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
492 DwarfExpr.setMemoryLocationKind();
493 DwarfExpr.addExpression(Expr);
494 addBlock(Die, Attribute, DwarfExpr.finalize());
495}
496
497void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, unsigned Column,
498 const DIFile *File) {
499 if (Line == 0)
500 return;
501
502 unsigned FileID = getOrCreateSourceID(File);
503 addUInt(Die, dwarf::DW_AT_decl_file, std::nullopt, FileID);
504 addUInt(Die, dwarf::DW_AT_decl_line, std::nullopt, Line);
505
506 if (Column != 0)
507 addUInt(Die, dwarf::DW_AT_decl_column, std::nullopt, Column);
508}
509
511 assert(V);
512
513 addSourceLine(Die, V->getLine(), /*Column*/ 0, V->getFile());
514}
515
517 assert(G);
518
519 addSourceLine(Die, G->getLine(), /*Column*/ 0, G->getFile());
520}
521
523 assert(SP);
524
525 addSourceLine(Die, SP->getLine(), /*Column*/ 0, SP->getFile());
526}
527
529 assert(L);
530
531 addSourceLine(Die, L->getLine(), L->getColumn(), L->getFile());
532}
533
534void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
535 assert(Ty);
536
537 addSourceLine(Die, Ty->getLine(), /*Column*/ 0, Ty->getFile());
538}
539
541 assert(Ty);
542
543 addSourceLine(Die, Ty->getLine(), /*Column*/ 0, Ty->getFile());
544}
545
547 assert(P);
548
549 addSourceLine(Die, P->getLine(), /*Column*/ 0, P->getFile());
550}
551
553 // Pass this down to addConstantValue as an unsigned bag of bits.
554 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
555}
556
558 const DIType *Ty) {
559 addConstantValue(Die, CI->getValue(), Ty);
560}
561
562void DwarfUnit::addConstantValue(DIE &Die, uint64_t Val, const DIType *Ty) {
563 addConstantValue(Die, DD->isUnsignedDIType(Ty), Val);
564}
565
566void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
567 // FIXME: This is a bit conservative/simple - it emits negative values always
568 // sign extended to 64 bits rather than minimizing the number of bytes.
569 addUInt(Die, dwarf::DW_AT_const_value,
570 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
571}
572
573void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
574 addConstantValue(Die, Val, DD->isUnsignedDIType(Ty));
575}
576
577void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
578 unsigned CIBitWidth = Val.getBitWidth();
579 if (CIBitWidth <= 64) {
581 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
582 return;
583 }
584
585 addIntAsBlock(Die, dwarf::DW_AT_const_value, Val, Unsigned);
586}
587
589 if (!LinkageName.empty())
590 addString(Die,
591 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
592 : dwarf::DW_AT_MIPS_linkage_name,
594}
595
596void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
597 // Add template parameters.
598 for (const auto *Element : TParams) {
599 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
600 constructTemplateTypeParameterDIE(Buffer, TTP);
601 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
602 constructTemplateValueParameterDIE(Buffer, TVP);
603 }
604}
605
606/// Add thrown types.
607void DwarfUnit::addThrownTypes(DIE &Die, DINodeArray ThrownTypes) {
608 for (const auto *Ty : ThrownTypes) {
609 DIE &TT = createAndAddDIE(dwarf::DW_TAG_thrown_type, Die);
610 addType(TT, cast<DIType>(Ty));
611 }
612}
613
615 if ((Flags & DINode::FlagAccessibility) == DINode::FlagProtected)
616 addUInt(Die, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
618 else if ((Flags & DINode::FlagAccessibility) == DINode::FlagPrivate)
619 addUInt(Die, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
621 else if ((Flags & DINode::FlagAccessibility) == DINode::FlagPublic)
622 addUInt(Die, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
624}
625
627 if (!Context || isa<DIFile>(Context) || isa<DICompileUnit>(Context))
628 return &getUnitDie();
629 if (auto *T = dyn_cast<DIType>(Context))
630 return getOrCreateTypeDIE(T);
631 if (auto *NS = dyn_cast<DINamespace>(Context))
632 return getOrCreateNameSpace(NS);
633 if (auto *SP = dyn_cast<DISubprogram>(Context))
634 return getOrCreateSubprogramDIE(SP, nullptr);
635 if (auto *M = dyn_cast<DIModule>(Context))
636 return getOrCreateModule(M);
637 return getDIE(Context);
638}
639
641 auto *Context = Ty->getScope();
642 DIE *ContextDIE = getOrCreateContextDIE(Context);
643
644 if (DIE *TyDIE = getDIE(Ty))
645 return TyDIE;
646
647 // Create new type.
648 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
649
651
652 updateAcceleratorTables(Context, Ty, TyDIE);
653 return &TyDIE;
654}
655
656DIE *DwarfUnit::createTypeDIE(const DIScope *Context, DIE &ContextDIE,
657 const DIType *Ty) {
658 // Create new type.
659 DIE &TyDIE = createAndAddDIE(Ty->getTag(), ContextDIE, Ty);
660
661 auto construct = [&](const auto *Ty) {
662 updateAcceleratorTables(Context, Ty, TyDIE);
663 constructTypeDIE(TyDIE, Ty);
664 };
665
666 if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
667 if (DD->generateTypeUnits() && !Ty->isForwardDecl() &&
668 (Ty->getRawName() || CTy->getRawIdentifier())) {
669 // Skip updating the accelerator tables since this is not the full type.
670 if (MDString *TypeId = CTy->getRawIdentifier()) {
671 addGlobalType(Ty, TyDIE, Context);
672 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
673 } else {
674 updateAcceleratorTables(Context, Ty, TyDIE);
675 finishNonUnitTypeDIE(TyDIE, CTy);
676 }
677 return &TyDIE;
678 }
679 construct(CTy);
680 } else if (auto *FPT = dyn_cast<DIFixedPointType>(Ty))
681 construct(FPT);
682 else if (auto *BT = dyn_cast<DIBasicType>(Ty))
683 construct(BT);
684 else if (auto *ST = dyn_cast<DIStringType>(Ty))
685 construct(ST);
686 else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
687 construct(STy);
688 else if (auto *SRTy = dyn_cast<DISubrangeType>(Ty))
689 constructSubrangeDIE(TyDIE, SRTy);
690 else
691 construct(cast<DIDerivedType>(Ty));
692
693 return &TyDIE;
694}
695
697 if (!TyNode)
698 return nullptr;
699
700 auto *Ty = cast<DIType>(TyNode);
701
702 // DW_TAG_restrict_type is not supported in DWARF2
703 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
705
706 // DW_TAG_atomic_type is not supported in DWARF < 5
707 if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
709
710 // Construct the context before querying for the existence of the DIE in case
711 // such construction creates the DIE.
712 auto *Context = Ty->getScope();
713 DIE *ContextDIE = getOrCreateContextDIE(Context);
714 assert(ContextDIE);
715
716 if (DIE *TyDIE = getDIE(Ty))
717 return TyDIE;
718
719 return static_cast<DwarfUnit *>(ContextDIE->getUnit())
720 ->createTypeDIE(Context, *ContextDIE, Ty);
721}
722
724 const DIType *Ty, const DIE &TyDIE) {
725 if (Ty->getName().empty())
726 return;
727 if (Ty->isForwardDecl())
728 return;
729
730 // add temporary record for this type to be added later
731
732 unsigned Flags = 0;
733 if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
734 // A runtime language of 0 actually means C/C++ and that any
735 // non-negative value is some version of Objective-C/C++.
736 if (CT->getRuntimeLang() == 0 || CT->isObjcClassComplete())
738 }
739
740 DD->addAccelType(*this, CUNode->getNameTableKind(), Ty->getName(), TyDIE,
741 Flags);
742
743 if (auto *CT = dyn_cast<DICompositeType>(Ty))
744 if (Ty->getName() != CT->getIdentifier() &&
745 CT->getRuntimeLang() == dwarf::DW_LANG_Swift)
746 DD->addAccelType(*this, CUNode->getNameTableKind(), CT->getIdentifier(),
747 TyDIE, Flags);
748
749 addGlobalType(Ty, TyDIE, Context);
750}
751
752void DwarfUnit::addGlobalType(const DIType *Ty, const DIE &TyDIE,
753 const DIScope *Context) {
754 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
755 isa<DINamespace>(Context) || isa<DICommonBlock>(Context))
756 addGlobalTypeImpl(Ty, TyDIE, Context);
757}
758
759void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
761 assert(Ty && "Trying to add a type that doesn't exist?");
763}
764
765// FIXME: change callsites to use the new DW_LNAME_ language codes.
767 const auto &Lang = getLanguage();
768
769 if (!Lang.hasVersionedName())
770 return static_cast<llvm::dwarf::SourceLanguage>(Lang.getName());
771
773 static_cast<llvm::dwarf::SourceLanguageName>(Lang.getName()),
774 Lang.getVersion())
776}
777
778std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
779 if (!Context)
780 return "";
781
782 // FIXME: Decide whether to implement this for non-C++ languages.
784 return "";
785
786 std::string CS;
788 while (!isa<DICompileUnit>(Context)) {
789 Parents.push_back(Context);
790 if (const DIScope *S = Context->getScope())
791 Context = S;
792 else
793 // Structure, etc types will have a NULL context if they're at the top
794 // level.
795 break;
796 }
797
798 // Reverse iterate over our list to go from the outermost construct to the
799 // innermost.
800 for (const DIScope *Ctx : llvm::reverse(Parents)) {
801 StringRef Name = Ctx->getName();
802 if (Name.empty() && isa<DINamespace>(Ctx))
803 Name = "(anonymous namespace)";
804 if (!Name.empty()) {
805 CS += Name;
806 CS += "::";
807 }
808 }
809 return CS;
810}
811
812void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
813 // Get core information.
814 StringRef Name = BTy->getName();
815 // Add name if not anonymous or intermediate type.
816 if (!Name.empty())
817 addString(Buffer, dwarf::DW_AT_name, Name);
818
819 // An unspecified type only has a name attribute.
820 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
821 return;
822
823 if (BTy->getTag() != dwarf::DW_TAG_string_type)
824 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
825 BTy->getEncoding());
826
827 uint64_t SizeInBytes = divideCeil(BTy->getSizeInBits(), 8);
828 addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, SizeInBytes);
829 if (BTy->getTag() == dwarf::Tag::DW_TAG_base_type) {
830 // DW_TAG_base_type:
831 // If the value of an object of the given type does not fully occupy the
832 // storage described by a byte size attribute, the base type entry may also
833 // have a DW_AT_bit_size [...] attribute.
834 // TODO: Do big endian targets need DW_AT_data_bit_offset? See discussion in
835 // pull request #164372.
836 if (uint64_t DataSizeInBits = BTy->getDataSizeInBits();
837 DataSizeInBits && DataSizeInBits != SizeInBytes * 8)
838 addUInt(Buffer, dwarf::DW_AT_bit_size, std::nullopt, DataSizeInBits);
839 }
840
841 if (BTy->isBigEndian())
842 addUInt(Buffer, dwarf::DW_AT_endianity, std::nullopt, dwarf::DW_END_big);
843 else if (BTy->isLittleEndian())
844 addUInt(Buffer, dwarf::DW_AT_endianity, std::nullopt, dwarf::DW_END_little);
845
846 if (uint32_t NumExtraInhabitants = BTy->getNumExtraInhabitants())
847 addUInt(Buffer, dwarf::DW_AT_LLVM_num_extra_inhabitants, std::nullopt,
848 NumExtraInhabitants);
849}
850
851void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIFixedPointType *BTy) {
852 // Base type handling.
853 constructTypeDIE(Buffer, static_cast<const DIBasicType *>(BTy));
854
855 if (BTy->isBinary())
856 addSInt(Buffer, dwarf::DW_AT_binary_scale, dwarf::DW_FORM_sdata,
857 BTy->getFactor());
858 else if (BTy->isDecimal())
859 addSInt(Buffer, dwarf::DW_AT_decimal_scale, dwarf::DW_FORM_sdata,
860 BTy->getFactor());
861 else {
862 assert(BTy->isRational());
863 DIE *ContextDIE = getOrCreateContextDIE(BTy->getScope());
864 DIE &Constant = createAndAddDIE(dwarf::DW_TAG_constant, *ContextDIE);
865
866 addInt(Constant, dwarf::DW_AT_GNU_numerator, BTy->getNumerator(),
867 !BTy->isSigned());
868 addInt(Constant, dwarf::DW_AT_GNU_denominator, BTy->getDenominator(),
869 !BTy->isSigned());
870
871 addDIEEntry(Buffer, dwarf::DW_AT_small, Constant);
872 }
873}
874
875void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIStringType *STy) {
876 // Get core information.
877 StringRef Name = STy->getName();
878 // Add name if not anonymous or intermediate type.
879 if (!Name.empty())
880 addString(Buffer, dwarf::DW_AT_name, Name);
881
882 if (DIVariable *Var = STy->getStringLength()) {
883 if (auto *VarDIE = getDIE(Var))
884 addDIEEntry(Buffer, dwarf::DW_AT_string_length, *VarDIE);
885 } else if (DIExpression *Expr = STy->getStringLengthExp()) {
886 addBlock(Buffer, dwarf::DW_AT_string_length, Expr);
887 } else {
888 uint64_t Size = STy->getSizeInBits() >> 3;
889 addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, Size);
890 }
891
892 if (DIExpression *Expr = STy->getStringLocationExp()) {
893 addBlock(Buffer, dwarf::DW_AT_data_location, Expr);
894 }
895
896 if (STy->getEncoding()) {
897 // For eventual Unicode support.
898 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
899 STy->getEncoding());
900 }
901
902 if (STy->getCharType())
903 addType(Buffer, STy->getCharType());
904}
905
906void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
907 // Get core information.
908 StringRef Name = DTy->getName();
909 uint64_t Size = DTy->getSizeInBits() >> 3;
910 uint16_t Tag = Buffer.getTag();
911
912 // Map to main type, void will not have a type.
913 const DIType *FromTy = DTy->getBaseType();
914 if (FromTy)
915 addType(Buffer, FromTy);
916
917 // Add name if not anonymous or intermediate type.
918 if (!Name.empty())
919 addString(Buffer, dwarf::DW_AT_name, Name);
920
921 addAnnotation(Buffer, DTy->getAnnotations());
922
923 // If alignment is specified for a typedef , create and insert DW_AT_alignment
924 // attribute in DW_TAG_typedef DIE.
925 if (Tag == dwarf::DW_TAG_typedef && DD->getDwarfVersion() >= 5) {
926 uint32_t AlignInBytes = DTy->getAlignInBytes();
927 if (AlignInBytes > 0)
928 addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
929 AlignInBytes);
930 }
931
932 // Add size if non-zero (derived types might be zero-sized.)
933 if (Size && Tag != dwarf::DW_TAG_pointer_type
934 && Tag != dwarf::DW_TAG_ptr_to_member_type
935 && Tag != dwarf::DW_TAG_reference_type
936 && Tag != dwarf::DW_TAG_rvalue_reference_type)
937 addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, Size);
938
939 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
940 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
941 *getOrCreateTypeDIE(cast<DIDerivedType>(DTy)->getClassType()));
942
943 addAccess(Buffer, DTy->getFlags());
944
945 // Add source line info if available and TyDesc is not a forward declaration.
946 if (!DTy->isForwardDecl())
947 addSourceLine(Buffer, DTy);
948
949 // If DWARF address space value is other than None, add it. The IR
950 // verifier checks that DWARF address space only exists for pointer
951 // or reference types.
952 if (std::optional<unsigned> AS = DTy->getDWARFAddressSpace())
953 addUInt(Buffer, Asm->getTypeAddressSpaceAttribute(), dwarf::DW_FORM_data4,
954 *AS);
955
956 // Add template alias template parameters.
957 if (Tag == dwarf::DW_TAG_template_alias)
958 addTemplateParams(Buffer, DTy->getTemplateParams());
959
960 if (auto PtrAuthData = DTy->getPtrAuthData()) {
961 addUInt(Buffer, dwarf::DW_AT_LLVM_ptrauth_key, dwarf::DW_FORM_data1,
962 PtrAuthData->key());
963 if (PtrAuthData->isAddressDiscriminated())
964 addFlag(Buffer, dwarf::DW_AT_LLVM_ptrauth_address_discriminated);
965 addUInt(Buffer, dwarf::DW_AT_LLVM_ptrauth_extra_discriminator,
966 dwarf::DW_FORM_data2, PtrAuthData->extraDiscriminator());
967 if (PtrAuthData->isaPointer())
968 addFlag(Buffer, dwarf::DW_AT_LLVM_ptrauth_isa_pointer);
969 if (PtrAuthData->authenticatesNullValues())
970 addFlag(Buffer, dwarf::DW_AT_LLVM_ptrauth_authenticates_null_values);
971 }
972}
973
974std::optional<unsigned>
976 // Args[0] is the return type.
977 std::optional<unsigned> ObjectPointerIndex;
978 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
979 const DIType *Ty = Args[i];
980 if (!Ty) {
981 assert(i == N-1 && "Unspecified parameter must be the last argument");
982 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
983 } else {
984 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
985 addType(Arg, Ty);
986 if (Ty->isArtificial())
987 addFlag(Arg, dwarf::DW_AT_artificial);
988
989 if (Ty->isObjectPointer()) {
990 assert(!ObjectPointerIndex &&
991 "Can't have more than one object pointer");
992 ObjectPointerIndex = i;
993 }
994 }
995 }
996
997 return ObjectPointerIndex;
998}
999
1000void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
1001 // Add return type. A void return won't have a type.
1002 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
1003 if (Elements.size())
1004 if (auto RTy = Elements[0])
1005 addType(Buffer, RTy);
1006
1007 bool isPrototyped = true;
1008 if (Elements.size() == 2 && !Elements[1])
1009 isPrototyped = false;
1010
1011 constructSubprogramArguments(Buffer, Elements);
1012
1013 // Add prototype flag if we're dealing with a C language and the function has
1014 // been prototyped.
1015 if (isPrototyped && dwarf::isC(getSourceLanguage()))
1016 addFlag(Buffer, dwarf::DW_AT_prototyped);
1017
1018 // Add a DW_AT_calling_convention if this has an explicit convention.
1019 if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
1020 addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
1021 CTy->getCC());
1022
1023 if (CTy->isLValueReference())
1024 addFlag(Buffer, dwarf::DW_AT_reference);
1025
1026 if (CTy->isRValueReference())
1027 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1028}
1029
1030void DwarfUnit::addAnnotation(DIE &Buffer, DINodeArray Annotations) {
1031 if (!Annotations)
1032 return;
1033
1034 for (const Metadata *Annotation : Annotations->operands()) {
1035 const MDNode *MD = cast<MDNode>(Annotation);
1036 const MDString *Name = cast<MDString>(MD->getOperand(0));
1037 const auto &Value = MD->getOperand(1);
1038
1039 DIE &AnnotationDie = createAndAddDIE(dwarf::DW_TAG_LLVM_annotation, Buffer);
1040 addString(AnnotationDie, dwarf::DW_AT_name, Name->getString());
1041 if (const auto *Data = dyn_cast<MDString>(Value))
1042 addString(AnnotationDie, dwarf::DW_AT_const_value, Data->getString());
1043 else if (const auto *Data = dyn_cast<ConstantAsMetadata>(Value))
1044 addConstantValue(AnnotationDie, Data->getValue()->getUniqueInteger(),
1045 /*Unsigned=*/true);
1046 else
1047 assert(false && "Unsupported annotation value type");
1048 }
1049}
1050
1051void DwarfUnit::addDiscriminant(DIE &Variant, Constant *Discriminant,
1052 bool IsUnsigned) {
1053 if (const auto *CI = dyn_cast_or_null<ConstantInt>(Discriminant)) {
1054 addInt(Variant, dwarf::DW_AT_discr_value, CI->getValue(), IsUnsigned);
1055 } else if (const auto *CA =
1057 // Must have an even number of operands.
1058 unsigned NElems = CA->getNumElements();
1059 if (NElems % 2 != 0) {
1060 return;
1061 }
1062
1063 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
1064
1065 auto AddInt = [&](const APInt &Val) {
1066 if (IsUnsigned)
1067 addUInt(*Block, dwarf::DW_FORM_udata, Val.getZExtValue());
1068 else
1069 addSInt(*Block, dwarf::DW_FORM_sdata, Val.getSExtValue());
1070 };
1071
1072 for (unsigned I = 0; I < NElems; I += 2) {
1073 APInt LV = CA->getElementAsAPInt(I);
1074 APInt HV = CA->getElementAsAPInt(I + 1);
1075 if (LV == HV) {
1076 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_DSC_label);
1077 AddInt(LV);
1078 } else {
1079 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_DSC_range);
1080 AddInt(LV);
1081 AddInt(HV);
1082 }
1083 }
1084 addBlock(Variant, dwarf::DW_AT_discr_list, Block);
1085 }
1086}
1087
1089 // Add name if not anonymous or intermediate type.
1090 StringRef Name = CTy->getName();
1091
1092 uint16_t Tag = Buffer.getTag();
1093
1094 switch (Tag) {
1095 case dwarf::DW_TAG_array_type:
1096 constructArrayTypeDIE(Buffer, CTy);
1097 break;
1098 case dwarf::DW_TAG_enumeration_type:
1099 constructEnumTypeDIE(Buffer, CTy);
1100 break;
1101 case dwarf::DW_TAG_variant_part:
1102 case dwarf::DW_TAG_variant:
1103 case dwarf::DW_TAG_structure_type:
1104 case dwarf::DW_TAG_union_type:
1105 case dwarf::DW_TAG_class_type:
1106 case dwarf::DW_TAG_namelist: {
1107 // Emit the discriminator for a variant part.
1108 DIDerivedType *Discriminator = nullptr;
1109 if (Tag == dwarf::DW_TAG_variant_part) {
1110 Discriminator = CTy->getDiscriminator();
1111 if (Discriminator) {
1112 // DWARF says:
1113 // If the variant part has a discriminant, the discriminant is
1114 // represented by a separate debugging information entry which is
1115 // a child of the variant part entry.
1116 // However, for a language like Ada, this yields a weird
1117 // result: a discriminant field would have to be emitted
1118 // multiple times, once per variant part. Instead, this DWARF
1119 // restriction was lifted for DWARF 6 (see
1120 // https://dwarfstd.org/issues/180123.1.html) and so we allow
1121 // this here.
1122 DIE *DiscDIE = getDIE(Discriminator);
1123 if (DiscDIE == nullptr) {
1124 DiscDIE = &constructMemberDIE(Buffer, Discriminator);
1125 }
1126 addDIEEntry(Buffer, dwarf::DW_AT_discr, *DiscDIE);
1127 }
1128 }
1129
1130 // Add template parameters to a class, structure or union types.
1131 if (Tag == dwarf::DW_TAG_class_type ||
1132 Tag == dwarf::DW_TAG_structure_type ||
1133 Tag == dwarf::DW_TAG_union_type) {
1134 if (!(DD->useSplitDwarf() && !getCU().getSkeleton()) ||
1135 CTy->isNameSimplified())
1136 addTemplateParams(Buffer, CTy->getTemplateParams());
1137 }
1138
1139 // Add elements to structure type.
1140 DINodeArray Elements = CTy->getElements();
1141 for (const auto *Element : Elements) {
1142 if (!Element)
1143 continue;
1144 if (auto *SP = dyn_cast<DISubprogram>(Element))
1145 getOrCreateSubprogramDIE(SP, nullptr);
1146 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
1147 if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1148 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1149 addType(ElemDie, DDTy->getBaseType(), dwarf::DW_AT_friend);
1150 } else if (DDTy->isStaticMember()) {
1152 } else if (Tag == dwarf::DW_TAG_variant_part) {
1153 // When emitting a variant part, wrap each member in
1154 // DW_TAG_variant.
1155 DIE &Variant = createAndAddDIE(dwarf::DW_TAG_variant, Buffer);
1156 if (Constant *CI = DDTy->getDiscriminantValue()) {
1157 addDiscriminant(Variant, CI,
1158 DD->isUnsignedDIType(Discriminator->getBaseType()));
1159 }
1160 // If the variant holds a composite type with tag
1161 // DW_TAG_variant, inline those members into the variant
1162 // DIE.
1163 if (auto *Composite =
1164 dyn_cast_or_null<DICompositeType>(DDTy->getBaseType());
1165 Composite != nullptr &&
1166 Composite->getTag() == dwarf::DW_TAG_variant) {
1167 constructTypeDIE(Variant, Composite);
1168 } else {
1169 constructMemberDIE(Variant, DDTy);
1170 }
1171 } else {
1172 constructMemberDIE(Buffer, DDTy);
1173 }
1174 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
1175 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer, Property);
1176 StringRef PropertyName = Property->getName();
1177 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1178 if (Property->getType())
1179 addType(ElemDie, Property->getType());
1180 addSourceLine(ElemDie, Property);
1181 StringRef GetterName = Property->getGetterName();
1182 if (!GetterName.empty())
1183 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1184 StringRef SetterName = Property->getSetterName();
1185 if (!SetterName.empty())
1186 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1187 if (unsigned PropertyAttributes = Property->getAttributes())
1188 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, std::nullopt,
1189 PropertyAttributes);
1190 } else if (auto *Property = dyn_cast<DIProperty>(Element)) {
1191 constructPropertyDIE(Buffer, Property);
1192 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1193 if (Composite->getTag() == dwarf::DW_TAG_variant_part) {
1194 DIE &VariantPart = createAndAddDIE(Composite->getTag(), Buffer);
1195 constructTypeDIE(VariantPart, Composite);
1196 }
1197 } else if (Tag == dwarf::DW_TAG_namelist) {
1198 auto *VarDIE = getDIE(Element);
1199 if (VarDIE) {
1200 DIE &ItemDie = createAndAddDIE(dwarf::DW_TAG_namelist_item, Buffer);
1201 addDIEEntry(ItemDie, dwarf::DW_AT_namelist_item, *VarDIE);
1202 }
1203 }
1204 }
1205
1206 if (CTy->isAppleBlockExtension())
1207 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1208
1209 if (CTy->getExportSymbols())
1210 addFlag(Buffer, dwarf::DW_AT_export_symbols);
1211
1212 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
1213 // inside C++ composite types to point to the base class with the vtable.
1214 // Rust uses DW_AT_containing_type to link a vtable to the type
1215 // for which it was created.
1216 if (auto *ContainingType = CTy->getVTableHolder())
1217 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1218 *getOrCreateTypeDIE(ContainingType));
1219
1220 if (CTy->isObjcClassComplete())
1221 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1222
1223 // Add the type's non-standard calling convention.
1224 // DW_CC_pass_by_value/DW_CC_pass_by_reference are introduced in DWARF 5.
1225 if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 5) {
1226 uint8_t CC = 0;
1227 if (CTy->isTypePassByValue())
1228 CC = dwarf::DW_CC_pass_by_value;
1229 else if (CTy->isTypePassByReference())
1230 CC = dwarf::DW_CC_pass_by_reference;
1231 if (CC)
1232 addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
1233 CC);
1234 }
1235
1236 if (auto *SpecifiedFrom = CTy->getSpecification())
1237 addDIEEntry(Buffer, dwarf::DW_AT_specification,
1238 *getOrCreateContextDIE(SpecifiedFrom));
1239
1240 break;
1241 }
1242 default:
1243 break;
1244 }
1245
1246 // Add name if not anonymous or intermediate type.
1247 if (!Name.empty())
1248 addString(Buffer, dwarf::DW_AT_name, Name);
1249
1250 // For Swift, mangled names are put into DW_AT_linkage_name.
1251 if (CTy->getRuntimeLang() == dwarf::DW_LANG_Swift && CTy->getRawIdentifier())
1252 addString(Buffer, dwarf::DW_AT_linkage_name, CTy->getIdentifier());
1253
1254 addAnnotation(Buffer, CTy->getAnnotations());
1255
1256 if (Tag == dwarf::DW_TAG_enumeration_type ||
1257 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1258 Tag == dwarf::DW_TAG_union_type) {
1259 if (auto *Var = dyn_cast_or_null<DIVariable>(CTy->getRawSizeInBits())) {
1260 if (auto *VarDIE = getDIE(Var))
1261 addDIEEntry(Buffer, dwarf::DW_AT_bit_size, *VarDIE);
1262 } else if (auto *Exp =
1264 addBlock(Buffer, dwarf::DW_AT_bit_size, Exp);
1265 } else {
1266 uint64_t Size = CTy->getSizeInBits() >> 3;
1267 // Add size if non-zero (derived types might be zero-sized.)
1268 // Ignore the size if it's a non-enum forward decl.
1269 // TODO: Do we care about size for enum forward declarations?
1270 if (Size &&
1271 (!CTy->isForwardDecl() || Tag == dwarf::DW_TAG_enumeration_type))
1272 addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, Size);
1273 else if (!CTy->isForwardDecl())
1274 // Add zero size if it is not a forward declaration.
1275 addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, 0);
1276 }
1277
1278 // If we're a forward decl, say so.
1279 if (CTy->isForwardDecl())
1280 addFlag(Buffer, dwarf::DW_AT_declaration);
1281
1282 // Add accessibility info if available.
1283 addAccess(Buffer, CTy->getFlags());
1284
1285 // Add source line info if available.
1286 if (!CTy->isForwardDecl())
1287 addSourceLine(Buffer, CTy);
1288
1289 // No harm in adding the runtime language to the declaration.
1290 unsigned RLang = CTy->getRuntimeLang();
1291 if (RLang)
1292 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1293 RLang);
1294
1295 // Add align info if available.
1296 if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1297 addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1298 AlignInBytes);
1299
1300 if (uint32_t NumExtraInhabitants = CTy->getNumExtraInhabitants())
1301 addUInt(Buffer, dwarf::DW_AT_LLVM_num_extra_inhabitants, std::nullopt,
1302 NumExtraInhabitants);
1303 }
1304}
1305
1306void DwarfUnit::constructTemplateTypeParameterDIE(
1307 DIE &Buffer, const DITemplateTypeParameter *TP) {
1308 DIE &ParamDIE =
1309 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1310 // Add the type if it exists, it could be void and therefore no type.
1311 if (TP->getType())
1312 addType(ParamDIE, TP->getType());
1313 if (!TP->getName().empty())
1314 addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1315 if (TP->isDefault() && isCompatibleWithVersion(5))
1316 addFlag(ParamDIE, dwarf::DW_AT_default_value);
1317}
1318
1319void DwarfUnit::constructTemplateValueParameterDIE(
1320 DIE &Buffer, const DITemplateValueParameter *VP) {
1321 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1322
1323 // Add the type if there is one, template template and template parameter
1324 // packs will not have a type.
1325 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1326 addType(ParamDIE, VP->getType());
1327 if (!VP->getName().empty())
1328 addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1329 if (VP->isDefault() && isCompatibleWithVersion(5))
1330 addFlag(ParamDIE, dwarf::DW_AT_default_value);
1331 if (Metadata *Val = VP->getValue()) {
1333 addConstantValue(ParamDIE, CI, VP->getType());
1334 else if (ConstantFP *CF = mdconst::dyn_extract<ConstantFP>(Val))
1335 addConstantFPValue(ParamDIE, CF);
1336 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1337 // We cannot describe the location of dllimport'd entities: the
1338 // computation of their address requires loads from the IAT.
1339 if (!GV->hasDLLImportStorageClass()) {
1340 // For declaration non-type template parameters (such as global values
1341 // and functions)
1343 addOpAddress(*Loc, Asm->getSymbol(GV));
1344 // Emit DW_OP_stack_value to use the address as the immediate value of
1345 // the parameter, rather than a pointer to it.
1346 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1347 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1348 }
1349 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1350 assert(isa<MDString>(Val));
1351 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1352 cast<MDString>(Val)->getString());
1353 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1354 addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1355 }
1356 }
1357}
1358
1360 // Construct the context before querying for the existence of the DIE in case
1361 // such construction creates the DIE.
1362 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1363
1364 if (DIE *NDie = getDIE(NS))
1365 return NDie;
1366 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1367
1368 StringRef Name = NS->getName();
1369 if (!Name.empty())
1370 addString(NDie, dwarf::DW_AT_name, NS->getName());
1371 else
1372 Name = "(anonymous namespace)";
1373 DD->addAccelNamespace(*this, CUNode->getNameTableKind(), Name, NDie);
1374 addGlobalName(Name, NDie, NS->getScope());
1375 if (NS->getExportSymbols())
1376 addFlag(NDie, dwarf::DW_AT_export_symbols);
1377 return &NDie;
1378}
1379
1381 // Construct the context before querying for the existence of the DIE in case
1382 // such construction creates the DIE.
1383 DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1384
1385 if (DIE *MDie = getDIE(M))
1386 return MDie;
1387 DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1388
1389 if (!M->getName().empty()) {
1390 addString(MDie, dwarf::DW_AT_name, M->getName());
1391 addGlobalName(M->getName(), MDie, M->getScope());
1392 }
1393 if (!M->getConfigurationMacros().empty())
1394 addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1395 M->getConfigurationMacros());
1396 if (!M->getIncludePath().empty())
1397 addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1398 if (!M->getAPINotesFile().empty())
1399 addString(MDie, dwarf::DW_AT_LLVM_apinotes, M->getAPINotesFile());
1400 if (M->getFile())
1401 addUInt(MDie, dwarf::DW_AT_decl_file, std::nullopt,
1402 getOrCreateSourceID(M->getFile()));
1403 if (M->getLineNo())
1404 addUInt(MDie, dwarf::DW_AT_decl_line, std::nullopt, M->getLineNo());
1405 if (M->getIsDecl())
1406 addFlag(MDie, dwarf::DW_AT_declaration);
1407
1408 return &MDie;
1409}
1410
1412 const Function *FnHint, bool Minimal) {
1413 // Construct the context before querying for the existence of the DIE in case
1414 // such construction creates the DIE (as is the case for member function
1415 // declarations).
1416 DIE *ContextDIE =
1418
1419 if (DIE *SPDie = getDIE(SP))
1420 return SPDie;
1421
1422 if (auto *SPDecl = SP->getDeclaration()) {
1423 if (!Minimal) {
1424 // Build the decl now to ensure it precedes the definition.
1425 getOrCreateSubprogramDIE(SPDecl, nullptr);
1426 // Check whether the DIE for SP has already been created after the call
1427 // above.
1428 // FIXME: Should the creation of definition subprogram DIE during
1429 // the creation of declaration subprogram DIE be allowed?
1430 // See https://github.com/llvm/llvm-project/pull/154636.
1431 if (DIE *SPDie = getDIE(SP))
1432 return SPDie;
1433 }
1434 }
1435
1436 // DW_TAG_inlined_subroutine may refer to this DIE.
1437 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1438
1439 // Stop here and fill this in later, depending on whether or not this
1440 // subprogram turns out to have inlined instances or not.
1441 if (SP->isDefinition())
1442 return &SPDie;
1443
1444 static_cast<DwarfUnit *>(SPDie.getUnit())
1445 ->applySubprogramAttributes(SP, SPDie);
1446 return &SPDie;
1447}
1448
1450 DIE &SPDie, bool Minimal) {
1451 DIE *DeclDie = nullptr;
1452 StringRef DeclLinkageName;
1453 if (auto *SPDecl = SP->getDeclaration()) {
1454 if (!Minimal) {
1455 DITypeArray DeclArgs, DefinitionArgs;
1456 DeclArgs = SPDecl->getType()->getTypeArray();
1457 DefinitionArgs = SP->getType()->getTypeArray();
1458
1459 if (DeclArgs.size() && DefinitionArgs.size())
1460 if (DefinitionArgs[0] != nullptr && DeclArgs[0] != DefinitionArgs[0])
1461 addType(SPDie, DefinitionArgs[0]);
1462
1463 DeclDie = getDIE(SPDecl);
1464 assert(DeclDie && "This DIE should've already been constructed when the "
1465 "definition DIE was created in "
1466 "getOrCreateSubprogramDIE");
1467 // Look at the Decl's linkage name only if we emitted it.
1468 if (DD->useAllLinkageNames())
1469 DeclLinkageName = SPDecl->getLinkageName();
1470 unsigned DeclID = getOrCreateSourceID(SPDecl->getFile());
1471 unsigned DefID = getOrCreateSourceID(SP->getFile());
1472 if (DeclID != DefID)
1473 addUInt(SPDie, dwarf::DW_AT_decl_file, std::nullopt, DefID);
1474
1475 if (SP->getLine() != SPDecl->getLine())
1476 addUInt(SPDie, dwarf::DW_AT_decl_line, std::nullopt, SP->getLine());
1477 }
1478 }
1479
1480 // Add function template parameters.
1481 if (!Minimal || SP->isNameSimplified())
1482 addTemplateParams(SPDie, SP->getTemplateParams());
1483
1484 // Add the linkage name if we have one and it isn't in the Decl.
1485 StringRef LinkageName = SP->getLinkageName();
1486 // Always emit linkage name for abstract subprograms.
1487 if (DeclLinkageName != LinkageName &&
1488 (DD->useAllLinkageNames() || DU->getAbstractScopeDIEs().lookup(SP)))
1490
1491 if (!DeclDie)
1492 return false;
1493
1494 // Refer to the function declaration where all the other attributes will be
1495 // found.
1496 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1497 return true;
1498}
1499
1501 bool SkipSPAttributes) {
1502 // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
1503 // and its source location.
1504 bool SkipSPSourceLocation = SkipSPAttributes &&
1505 !CUNode->getDebugInfoForProfiling();
1506 if (!SkipSPSourceLocation)
1507 if (applySubprogramDefinitionAttributes(SP, SPDie, SkipSPAttributes))
1508 return;
1509
1510 // Constructors and operators for anonymous aggregates do not have names.
1511 if (!SP->getName().empty())
1512 addString(SPDie, dwarf::DW_AT_name, SP->getName());
1513
1514 addAnnotation(SPDie, SP->getAnnotations());
1515
1516 if (!SkipSPSourceLocation)
1517 addSourceLine(SPDie, SP);
1518
1519 // Skip the rest of the attributes under -gmlt to save space.
1520 if (SkipSPAttributes)
1521 return;
1522
1523 // Add the prototype if we have a prototype and we have a C like
1524 // language.
1525 if (SP->isPrototyped() && dwarf::isC(getSourceLanguage()))
1526 addFlag(SPDie, dwarf::DW_AT_prototyped);
1527
1528 if (SP->isObjCDirect())
1529 addFlag(SPDie, dwarf::DW_AT_APPLE_objc_direct);
1530
1531 unsigned CC = 0;
1532 DITypeArray Args;
1533 if (const DISubroutineType *SPTy = SP->getType()) {
1534 Args = SPTy->getTypeArray();
1535 CC = SPTy->getCC();
1536 }
1537
1538 // Add a DW_AT_calling_convention if this has an explicit convention.
1539 if (CC && CC != dwarf::DW_CC_normal)
1540 addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1541
1542 // Add a return type. If this is a type like a C/C++ void type we don't add a
1543 // return type.
1544 if (Args.size())
1545 if (auto Ty = Args[0])
1546 addType(SPDie, Ty);
1547
1548 unsigned VK = SP->getVirtuality();
1549 if (VK) {
1550 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1551 if (SP->getVirtualIndex() != -1u) {
1552 DIELoc *Block = getDIELoc();
1553 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1554 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1555 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1556 }
1557 ContainingTypeMap.insert(std::make_pair(&SPDie, SP->getContainingType()));
1558 }
1559
1560 if (!SP->isDefinition()) {
1561 addFlag(SPDie, dwarf::DW_AT_declaration);
1562
1563 // Add arguments. Do not add arguments for subprogram definition. They will
1564 // be handled while processing variables.
1565 //
1566 // Encode the object pointer as an index instead of a DIE reference in order
1567 // to minimize the affect on the .debug_info size.
1568 if (std::optional<unsigned> ObjectPointerIndex =
1569 constructSubprogramArguments(SPDie, Args)) {
1570 if (getDwarfDebug().tuneForLLDB() &&
1571 getDwarfDebug().getDwarfVersion() >= 5) {
1572 // 0th index in Args is the return type, hence adjust by 1. In DWARF
1573 // we want the first parameter to be at index 0.
1574 assert(*ObjectPointerIndex > 0);
1575 addSInt(SPDie, dwarf::DW_AT_object_pointer,
1576 dwarf::DW_FORM_implicit_const, *ObjectPointerIndex - 1);
1577 }
1578 }
1579 }
1580
1581 addThrownTypes(SPDie, SP->getThrownTypes());
1582
1583 if (SP->isArtificial())
1584 addFlag(SPDie, dwarf::DW_AT_artificial);
1585
1586 if (!SP->isLocalToUnit())
1587 addFlag(SPDie, dwarf::DW_AT_external);
1588
1589 if (SP->isOptimized())
1590 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1591
1592 if (DD->useAppleExtensionAttributes())
1593 if (unsigned isa = Asm->getISAEncoding())
1594 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1595
1596 if (SP->isLValueReference())
1597 addFlag(SPDie, dwarf::DW_AT_reference);
1598
1599 if (SP->isRValueReference())
1600 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1601
1602 if (SP->isNoReturn())
1603 addFlag(SPDie, dwarf::DW_AT_noreturn);
1604
1605 addAccess(SPDie, SP->getFlags());
1606
1607 if (SP->isExplicit())
1608 addFlag(SPDie, dwarf::DW_AT_explicit);
1609
1610 if (SP->isMainSubprogram())
1611 addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1612 if (SP->isPure())
1613 addFlag(SPDie, dwarf::DW_AT_pure);
1614 if (SP->isElemental())
1615 addFlag(SPDie, dwarf::DW_AT_elemental);
1616 if (SP->isRecursive())
1617 addFlag(SPDie, dwarf::DW_AT_recursive);
1618
1619 if (!SP->getTargetFuncName().empty())
1620 addString(SPDie, dwarf::DW_AT_trampoline, SP->getTargetFuncName());
1621
1622 if (DD->getDwarfVersion() >= 5 && SP->isDeleted())
1623 addFlag(SPDie, dwarf::DW_AT_deleted);
1624}
1625
1626void DwarfUnit::constructSubrangeDIE(DIE &DW_Subrange, const DISubrangeType *SR,
1627 bool ForArray) {
1628 StringRef Name = SR->getName();
1629 if (!Name.empty())
1630 addString(DW_Subrange, dwarf::DW_AT_name, Name);
1631
1632 bool IsUnsigned = false;
1633 if (auto *BaseType = SR->getBaseType()) {
1634 addType(DW_Subrange, BaseType);
1635 IsUnsigned = DD->isUnsignedDIType(BaseType);
1636 }
1637
1638 addSourceLine(DW_Subrange, SR);
1639
1640 if (uint64_t Size = SR->getSizeInBits())
1641 addUInt(DW_Subrange, dwarf::DW_AT_byte_size, std::nullopt, Size >> 3);
1642 if (uint32_t AlignInBytes = SR->getAlignInBytes())
1643 addUInt(DW_Subrange, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1644 AlignInBytes);
1645
1646 if (SR->isBigEndian())
1647 addUInt(DW_Subrange, dwarf::DW_AT_endianity, std::nullopt,
1648 dwarf::DW_END_big);
1649 else if (SR->isLittleEndian())
1650 addUInt(DW_Subrange, dwarf::DW_AT_endianity, std::nullopt,
1651 dwarf::DW_END_little);
1652
1653 // The LowerBound value defines the lower bounds which is typically
1654 // zero for C/C++. Values are 64 bit.
1655 int64_t DefaultLowerBound = getDefaultLowerBound();
1656 dwarf::Form Form = IsUnsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata;
1657
1658 auto AddBoundTypeEntry = [&](dwarf::Attribute Attr,
1659 DISubrangeType::BoundType Bound) -> void {
1660 if (auto *BV = dyn_cast_if_present<DIVariable *>(Bound)) {
1661 if (auto *VarDIE = getDIE(BV))
1662 addDIEEntry(DW_Subrange, Attr, *VarDIE);
1663 } else if (auto *DT = dyn_cast_if_present<DIDerivedType *>(Bound)) {
1664 if (auto *DTDIE = getDIE(DT))
1665 addDIEEntry(DW_Subrange, Attr, *DTDIE);
1666 } else if (auto *BE = dyn_cast_if_present<DIExpression *>(Bound)) {
1667 addBlock(DW_Subrange, Attr, BE);
1668 } else if (auto *BI = dyn_cast_if_present<ConstantInt *>(Bound)) {
1669 const APInt &Value = BI->getValue();
1670 if (Attr == dwarf::DW_AT_GNU_bias) {
1671 if (Value != 0)
1672 addInt(DW_Subrange, Attr, Value, IsUnsigned, Form);
1673 } else if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 ||
1674 Value != DefaultLowerBound || !ForArray)
1675 addInt(DW_Subrange, Attr, Value, IsUnsigned, Form);
1676 }
1677 };
1678
1679 AddBoundTypeEntry(dwarf::DW_AT_lower_bound, SR->getLowerBound());
1680
1681 AddBoundTypeEntry(dwarf::DW_AT_upper_bound, SR->getUpperBound());
1682
1683 AddBoundTypeEntry(dwarf::DW_AT_bit_stride, SR->getStride());
1684
1685 AddBoundTypeEntry(dwarf::DW_AT_GNU_bias, SR->getBias());
1686}
1687
1688void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR) {
1689 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1690
1691 DIE *IdxTy = getIndexTyDie();
1692 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IdxTy);
1693
1694 // The LowerBound value defines the lower bounds which is typically zero for
1695 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1696 // Count == -1 then the array is unbounded and we do not emit
1697 // DW_AT_lower_bound and DW_AT_count attributes.
1698 int64_t DefaultLowerBound = getDefaultLowerBound();
1699
1700 auto AddBoundTypeEntry = [&](dwarf::Attribute Attr,
1701 DISubrange::BoundType Bound) -> void {
1702 if (auto *BV = dyn_cast_if_present<DIVariable *>(Bound)) {
1703 if (auto *VarDIE = getDIE(BV))
1704 addDIEEntry(DW_Subrange, Attr, *VarDIE);
1705 } else if (auto *BE = dyn_cast_if_present<DIExpression *>(Bound)) {
1706 addBlock(DW_Subrange, Attr, BE);
1707 } else if (auto *BI = dyn_cast_if_present<ConstantInt *>(Bound)) {
1708 if (Attr == dwarf::DW_AT_count) {
1709 if (BI->getSExtValue() != -1)
1710 addUInt(DW_Subrange, Attr, std::nullopt, BI->getSExtValue());
1711 } else if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 ||
1712 BI->getSExtValue() != DefaultLowerBound)
1713 addSInt(DW_Subrange, Attr, dwarf::DW_FORM_sdata, BI->getSExtValue());
1714 }
1715 };
1716
1717 AddBoundTypeEntry(dwarf::DW_AT_lower_bound, SR->getLowerBound());
1718
1719 AddBoundTypeEntry(dwarf::DW_AT_count, SR->getCount());
1720
1721 AddBoundTypeEntry(dwarf::DW_AT_upper_bound, SR->getUpperBound());
1722
1723 AddBoundTypeEntry(dwarf::DW_AT_byte_stride, SR->getStride());
1724}
1725
1726void DwarfUnit::constructGenericSubrangeDIE(DIE &Buffer,
1727 const DIGenericSubrange *GSR) {
1728 DIE &DwGenericSubrange =
1729 createAndAddDIE(dwarf::DW_TAG_generic_subrange, Buffer);
1730 // Get an anonymous type for index type.
1731 // FIXME: This type should be passed down from the front end
1732 // as different languages may have different sizes for indexes.
1733 DIE *IdxTy = getIndexTyDie();
1734 addDIEEntry(DwGenericSubrange, dwarf::DW_AT_type, *IdxTy);
1735
1736 int64_t DefaultLowerBound = getDefaultLowerBound();
1737
1738 auto AddBoundTypeEntry = [&](dwarf::Attribute Attr,
1739 DIGenericSubrange::BoundType Bound) -> void {
1740 if (auto *BV = dyn_cast_if_present<DIVariable *>(Bound)) {
1741 if (auto *VarDIE = getDIE(BV))
1742 addDIEEntry(DwGenericSubrange, Attr, *VarDIE);
1743 } else if (auto *BE = dyn_cast_if_present<DIExpression *>(Bound)) {
1744 if (BE->isConstant() &&
1746 *BE->isConstant()) {
1747 if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 ||
1748 static_cast<int64_t>(BE->getElement(1)) != DefaultLowerBound)
1749 addSInt(DwGenericSubrange, Attr, dwarf::DW_FORM_sdata,
1750 BE->getElement(1));
1751 } else {
1752 addBlock(DwGenericSubrange, Attr, BE);
1753 }
1754 }
1755 };
1756
1757 AddBoundTypeEntry(dwarf::DW_AT_lower_bound, GSR->getLowerBound());
1758 AddBoundTypeEntry(dwarf::DW_AT_count, GSR->getCount());
1759 AddBoundTypeEntry(dwarf::DW_AT_upper_bound, GSR->getUpperBound());
1760 AddBoundTypeEntry(dwarf::DW_AT_byte_stride, GSR->getStride());
1761}
1762
1763DIE *DwarfUnit::getIndexTyDie() {
1764 if (IndexTyDie)
1765 return IndexTyDie;
1766 // Construct an integer type to use for indexes.
1767 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1768 StringRef Name = "__ARRAY_SIZE_TYPE__";
1769 addString(*IndexTyDie, dwarf::DW_AT_name, Name);
1770 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, std::nullopt, sizeof(int64_t));
1771 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1773 DD->addAccelType(*this, CUNode->getNameTableKind(), Name, *IndexTyDie,
1774 /*Flags*/ 0);
1775 return IndexTyDie;
1776}
1777
1778/// Returns true if the vector's size differs from the sum of sizes of elements
1779/// the user specified. This can occur if the vector has been rounded up to
1780/// fit memory alignment constraints.
1781static bool hasVectorBeenPadded(const DICompositeType *CTy) {
1782 assert(CTy && CTy->isVector() && "Composite type is not a vector");
1783 const uint64_t ActualSize = CTy->getSizeInBits();
1784
1785 // Obtain the size of each element in the vector.
1786 DIType *BaseTy = CTy->getBaseType();
1787 assert(BaseTy && "Unknown vector element type.");
1788 const uint64_t ElementSize = BaseTy->getSizeInBits();
1789
1790 // Locate the number of elements in the vector.
1791 const DINodeArray Elements = CTy->getElements();
1792 assert(Elements.size() == 1 &&
1793 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type &&
1794 "Invalid vector element array, expected one element of type subrange");
1795 const auto Subrange = cast<DISubrange>(Elements[0]);
1796 const auto NumVecElements =
1797 Subrange->getCount()
1798 ? cast<ConstantInt *>(Subrange->getCount())->getSExtValue()
1799 : 0;
1800
1801 // Ensure we found the element count and that the actual size is wide
1802 // enough to contain the requested size.
1803 assert(ActualSize >= (NumVecElements * ElementSize) && "Invalid vector size");
1804 return ActualSize != (NumVecElements * ElementSize);
1805}
1806
1807void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1808 if (CTy->isVector()) {
1809 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1810 if (hasVectorBeenPadded(CTy))
1811 addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt,
1812 CTy->getSizeInBits() / CHAR_BIT);
1813 }
1814
1815 if (DIVariable *Var = CTy->getDataLocation()) {
1816 if (auto *VarDIE = getDIE(Var))
1817 addDIEEntry(Buffer, dwarf::DW_AT_data_location, *VarDIE);
1818 } else if (DIExpression *Expr = CTy->getDataLocationExp()) {
1819 addBlock(Buffer, dwarf::DW_AT_data_location, Expr);
1820 }
1821
1822 if (DIVariable *Var = CTy->getAssociated()) {
1823 if (auto *VarDIE = getDIE(Var))
1824 addDIEEntry(Buffer, dwarf::DW_AT_associated, *VarDIE);
1825 } else if (DIExpression *Expr = CTy->getAssociatedExp()) {
1826 addBlock(Buffer, dwarf::DW_AT_associated, Expr);
1827 }
1828
1829 if (DIVariable *Var = CTy->getAllocated()) {
1830 if (auto *VarDIE = getDIE(Var))
1831 addDIEEntry(Buffer, dwarf::DW_AT_allocated, *VarDIE);
1832 } else if (DIExpression *Expr = CTy->getAllocatedExp()) {
1833 addBlock(Buffer, dwarf::DW_AT_allocated, Expr);
1834 }
1835
1836 if (auto *RankConst = CTy->getRankConst()) {
1837 addSInt(Buffer, dwarf::DW_AT_rank, dwarf::DW_FORM_sdata,
1838 RankConst->getSExtValue());
1839 } else if (auto *RankExpr = CTy->getRankExp()) {
1840 addBlock(Buffer, dwarf::DW_AT_rank, RankExpr);
1841 }
1842
1843 if (auto *BitStride = CTy->getBitStrideConst()) {
1844 addUInt(Buffer, dwarf::DW_AT_bit_stride, {}, BitStride->getZExtValue());
1845 }
1846
1847 // Emit the element type.
1848 addType(Buffer, CTy->getBaseType());
1849
1850 // Add subranges to array type.
1851 DINodeArray Elements = CTy->getElements();
1852 for (DINode *E : Elements) {
1853 if (auto *Element = dyn_cast_or_null<DISubrangeType>(E)) {
1854 DIE &TyDIE = createAndAddDIE(Element->getTag(), Buffer, CTy);
1855 constructSubrangeDIE(TyDIE, Element, true);
1856 } else if (auto *Element = dyn_cast_or_null<DISubrange>(E))
1857 constructSubrangeDIE(Buffer, Element);
1858 else if (auto *Element = dyn_cast_or_null<DIGenericSubrange>(E))
1859 constructGenericSubrangeDIE(Buffer, Element);
1860 }
1861}
1862
1863void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1864 const DIType *DTy = CTy->getBaseType();
1865 bool IsUnsigned = DTy && DD->isUnsignedDIType(DTy);
1866 if (DTy) {
1867 if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 3)
1868 addType(Buffer, DTy);
1869 if (DD->getDwarfVersion() >= 4 && (CTy->getFlags() & DINode::FlagEnumClass))
1870 addFlag(Buffer, dwarf::DW_AT_enum_class);
1871 }
1872
1873 if (auto Kind = CTy->getEnumKind())
1874 addUInt(Buffer, dwarf::DW_AT_APPLE_enum_kind, dwarf::DW_FORM_data1, *Kind);
1875
1876 auto *Context = CTy->getScope();
1877 bool IndexEnumerators = !Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
1879 DINodeArray Elements = CTy->getElements();
1880
1881 // Add enumerators to enumeration type.
1882 for (const DINode *E : Elements) {
1884 if (Enum) {
1885 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1886 StringRef Name = Enum->getName();
1887 addString(Enumerator, dwarf::DW_AT_name, Name);
1888 addConstantValue(Enumerator, Enum->getValue(), IsUnsigned);
1889 if (IndexEnumerators)
1891 }
1892 }
1893}
1894
1896 for (auto &P : ContainingTypeMap) {
1897 DIE &SPDie = *P.first;
1898 const DINode *D = P.second;
1899 if (!D)
1900 continue;
1901 DIE *NDie = getDIE(D);
1902 if (!NDie)
1903 continue;
1904 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1905 }
1906}
1907
1908DIE &DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1909 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer, DT);
1910 StringRef Name = DT->getName();
1911 if (!Name.empty())
1912 addString(MemberDie, dwarf::DW_AT_name, Name);
1913
1914 addAnnotation(MemberDie, DT->getAnnotations());
1915
1916 if (DIType *Resolved = DT->getBaseType())
1917 addType(MemberDie, Resolved);
1918
1919 addSourceLine(MemberDie, DT);
1920
1921 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1922
1923 // For C++, virtual base classes are not at fixed offset. Use following
1924 // expression to extract appropriate offset from vtable.
1925 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1926
1927 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1928 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1929 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1930 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1931 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1932 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1933 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1934 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1935
1936 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1937 } else {
1938 uint64_t Size = 0;
1939 uint64_t FieldSize = 0;
1940
1941 bool IsBitfield = DT->isBitField();
1942
1943 // Handle the size.
1944 if (DT->getRawSizeInBits() == nullptr) {
1945 // No size, just ignore.
1946 } else if (auto *Var = dyn_cast<DIVariable>(DT->getRawSizeInBits())) {
1947 if (auto *VarDIE = getDIE(Var))
1948 addDIEEntry(MemberDie, dwarf::DW_AT_bit_size, *VarDIE);
1949 } else if (auto *Exp = dyn_cast<DIExpression>(DT->getRawSizeInBits())) {
1950 addBlock(MemberDie, dwarf::DW_AT_bit_size, Exp);
1951 } else {
1952 Size = DT->getSizeInBits();
1953 FieldSize = DD->getBaseTypeSize(DT);
1954 if (IsBitfield) {
1955 // Handle bitfield, assume bytes are 8 bits.
1956 if (DD->useDWARF2Bitfields())
1957 addUInt(MemberDie, dwarf::DW_AT_byte_size, std::nullopt,
1958 FieldSize / 8);
1959 addUInt(MemberDie, dwarf::DW_AT_bit_size, std::nullopt, Size);
1960 }
1961 }
1962
1963 // Handle the location. DW_AT_data_bit_offset won't allow an
1964 // expression until DWARF 6, but it can be used as an extension.
1965 // See https://dwarfstd.org/issues/250501.1.html
1966 if (auto *Var = dyn_cast_or_null<DIVariable>(DT->getRawOffsetInBits())) {
1967 if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 6) {
1968 if (auto *VarDIE = getDIE(Var))
1969 addDIEEntry(MemberDie, dwarf::DW_AT_data_bit_offset, *VarDIE);
1970 }
1971 } else if (auto *Expr =
1973 if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 6) {
1974 addBlock(MemberDie, dwarf::DW_AT_data_bit_offset, Expr);
1975 }
1976 } else {
1977 uint32_t AlignInBytes = DT->getAlignInBytes();
1978 uint64_t OffsetInBytes;
1979
1980 if (IsBitfield) {
1981 assert(DT->getOffsetInBits() <=
1982 (uint64_t)std::numeric_limits<int64_t>::max());
1983 int64_t Offset = DT->getOffsetInBits();
1984 // We can't use DT->getAlignInBits() here: AlignInBits for member type
1985 // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1986 // which can't be done with bitfields. Thus we use FieldSize here.
1987 uint32_t AlignInBits = FieldSize;
1988 uint32_t AlignMask = ~(AlignInBits - 1);
1989 // The bits from the start of the storage unit to the start of the
1990 // field.
1991 uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1992 // The byte offset of the field's aligned storage unit inside the
1993 // struct.
1994 OffsetInBytes = (Offset - StartBitOffset) / 8;
1995
1996 if (DD->useDWARF2Bitfields()) {
1997 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1998 uint64_t FieldOffset = (HiMark - FieldSize);
1999 Offset -= FieldOffset;
2000
2001 // Maybe we need to work from the other end.
2002 if (Asm->getDataLayout().isLittleEndian())
2003 Offset = FieldSize - (Offset + Size);
2004
2005 if (Offset < 0)
2006 addSInt(MemberDie, dwarf::DW_AT_bit_offset, dwarf::DW_FORM_sdata,
2007 Offset);
2008 else
2009 addUInt(MemberDie, dwarf::DW_AT_bit_offset, std::nullopt,
2010 (uint64_t)Offset);
2011 OffsetInBytes = FieldOffset >> 3;
2012 } else {
2013 addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, std::nullopt,
2014 Offset);
2015 }
2016 } else {
2017 // This is not a bitfield.
2018 OffsetInBytes = DT->getOffsetInBits() / 8;
2019 if (AlignInBytes)
2020 addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
2021 AlignInBytes);
2022 }
2023
2024 if (DD->getDwarfVersion() <= 2) {
2025 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
2026 addUInt(*MemLocationDie, dwarf::DW_FORM_data1,
2027 dwarf::DW_OP_plus_uconst);
2028 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
2029 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
2030 } else if (!IsBitfield || DD->useDWARF2Bitfields()) {
2031 // In DWARF v3, DW_FORM_data4/8 in DW_AT_data_member_location are
2032 // interpreted as location-list pointers. Interpreting constants as
2033 // pointers is not expected, so we use DW_FORM_udata to encode the
2034 // constants here.
2035 if (DD->getDwarfVersion() == 3)
2036 addUInt(MemberDie, dwarf::DW_AT_data_member_location,
2037 dwarf::DW_FORM_udata, OffsetInBytes);
2038 else
2039 addUInt(MemberDie, dwarf::DW_AT_data_member_location, std::nullopt,
2040 OffsetInBytes);
2041 }
2042 }
2043 }
2044
2045 addAccess(MemberDie, DT->getFlags());
2046
2047 if (DT->isVirtual())
2048 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
2049 dwarf::DW_VIRTUALITY_virtual);
2050
2051 // Objective-C properties.
2052 if (DINode *PNode = DT->getObjCProperty())
2053 if (DIE *PDie = getDIE(PNode))
2054 addAttribute(MemberDie, dwarf::DW_AT_APPLE_property,
2055 dwarf::DW_FORM_ref4, DIEEntry(*PDie));
2056
2057 if (DT->isArtificial())
2058 addFlag(MemberDie, dwarf::DW_AT_artificial);
2059
2060 return MemberDie;
2061}
2062
2063void DwarfUnit::constructPropertyDIE(DIE &Buffer, const DIProperty *P) {
2064 DIE &PropertyDie = createAndAddDIE(dwarf::DW_TAG_property, Buffer, P);
2065 addString(PropertyDie, dwarf::DW_AT_name, P->getName());
2066 if (DIType *Ty = P->getType())
2067 addType(PropertyDie, Ty);
2068 addSourceLine(PropertyDie, P);
2069
2070 if (DINode *BackingStorage = P->getBackingStorage()) {
2071 DIE &GetterDie =
2072 createAndAddDIE(dwarf::DW_TAG_property_getter, PropertyDie);
2073 PropertyForwardMap.insert(std::make_pair(&GetterDie, BackingStorage));
2074 }
2075}
2076
2078 for (auto &P : PropertyForwardMap) {
2079 DIE &GetterDie = *P.first;
2080 const DINode *Target = P.second;
2081 if (!Target)
2082 continue;
2083 DIE *TargetDie = getDIE(Target);
2084 if (!TargetDie)
2085 continue;
2086 addDIEEntry(GetterDie, dwarf::DW_AT_property_forward, *TargetDie);
2087 }
2088}
2089
2091 if (!DT)
2092 return nullptr;
2093
2094 // Construct the context before querying for the existence of the DIE in case
2095 // such construction creates the DIE.
2096 DIE *ContextDIE = getOrCreateContextDIE(DT->getScope());
2097 assert(dwarf::isType(ContextDIE->getTag()) &&
2098 "Static member should belong to a type.");
2099
2100 if (DIE *StaticMemberDIE = getDIE(DT))
2101 return StaticMemberDIE;
2102
2103 DwarfUnit *ContextUnit = static_cast<DwarfUnit *>(ContextDIE->getUnit());
2104 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
2105
2106 const DIType *Ty = DT->getBaseType();
2107
2108 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
2109 addType(StaticMemberDIE, Ty);
2110 ContextUnit->addSourceLine(StaticMemberDIE, DT);
2111 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
2112 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
2113
2114 // Consider the case when the static member was created by the compiler.
2115 if (DT->isArtificial())
2116 addFlag(StaticMemberDIE, dwarf::DW_AT_artificial);
2117
2118 // FIXME: We could omit private if the parent is a class_type, and
2119 // public if the parent is something else.
2120 addAccess(StaticMemberDIE, DT->getFlags());
2121
2123 addConstantValue(StaticMemberDIE, CI, Ty);
2124 else if (const ConstantFP *CFP =
2126 addConstantFPValue(StaticMemberDIE, CFP);
2127 else if (auto *CDS =
2129 assert(CDS->getElementType()->isIntegerTy() &&
2130 "Non-integer arrays not supported.");
2132 for (unsigned I = 0; I != CDS->getNumElements(); ++I)
2133 addIntToBlock(*Block, CDS->getElementAsAPInt(I));
2134 Block->computeSize(Asm->getDwarfFormParams());
2135 addBlock(StaticMemberDIE, dwarf::DW_AT_const_value, Block->BestForm(),
2136 Block);
2137 }
2138
2139 if (uint32_t AlignInBytes = DT->getAlignInBytes())
2140 addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
2141 AlignInBytes);
2142
2143 return &StaticMemberDIE;
2144}
2145
2147 // Emit size of content not including length itself
2148 if (!DD->useSectionsAsReferences())
2149 EndLabel = Asm->emitDwarfUnitLength(
2150 isDwoUnit() ? "debug_info_dwo" : "debug_info", "Length of Unit");
2151 else
2152 Asm->emitDwarfUnitLength(getHeaderSize() + getUnitDie().getSize(),
2153 "Length of Unit");
2154
2155 Asm->OutStreamer->AddComment("DWARF version number");
2156 unsigned Version = DD->getDwarfVersion();
2157 Asm->emitInt16(Version);
2158
2159 // DWARF v5 reorders the address size and adds a unit type.
2160 if (Version >= 5) {
2161 Asm->OutStreamer->AddComment("DWARF Unit Type");
2162 Asm->emitInt8(UT);
2163 Asm->OutStreamer->AddComment("Address Size (in bytes)");
2164 Asm->emitInt8(Asm->MAI.getCodePointerSize());
2165 }
2166
2167 // We share one abbreviations table across all units so it's always at the
2168 // start of the section. Use a relocatable offset where needed to ensure
2169 // linking doesn't invalidate that offset.
2170 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
2171 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2172 if (UseOffsets)
2173 Asm->emitDwarfLengthOrOffset(0);
2174 else
2175 Asm->emitDwarfSymbolReference(
2176 TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
2177
2178 if (Version <= 4) {
2179 Asm->OutStreamer->AddComment("Address Size (in bytes)");
2180 Asm->emitInt8(Asm->MAI.getCodePointerSize());
2181 }
2182}
2183
2184void DwarfTypeUnit::emitHeader(bool UseOffsets) {
2185 if (!DD->useSplitDwarf()) {
2186 LabelBegin = Asm->createTempSymbol("tu_begin");
2187 Asm->OutStreamer->emitLabel(LabelBegin);
2188 }
2189 DwarfUnit::emitCommonHeader(UseOffsets,
2190 DD->useSplitDwarf() ? dwarf::DW_UT_split_type
2191 : dwarf::DW_UT_type);
2192 Asm->OutStreamer->AddComment("Type Signature");
2193 Asm->OutStreamer->emitIntValue(TypeSignature, sizeof(TypeSignature));
2194 Asm->OutStreamer->AddComment("Type DIE Offset");
2195 // In a skeleton type unit there is no type DIE so emit a zero offset.
2196 Asm->emitDwarfLengthOrOffset(Ty ? Ty->getOffset() : 0);
2197}
2198
2199void DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
2200 const MCSymbol *Hi, const MCSymbol *Lo) {
2203}
2204
2206 const MCSymbol *Label, const MCSymbol *Sec) {
2207 // If we are in an object file and not a DWO, emit a label. Otherwise we are
2208 // in a DWO and we cannot emit relocations, so emit a section delta.
2209 if (Asm->doesDwarfUseRelocationsAcrossSections() && !isDwoUnit())
2210 addLabel(Die, Attribute, DD->getDwarfSectionOffsetForm(), Label);
2211 else
2212 addSectionDelta(Die, Attribute, Label, Sec);
2213}
2214
2215bool DwarfTypeUnit::isDwoUnit() const {
2216 // Since there are no skeleton type units, all type units are dwo type units
2217 // when split DWARF is being used.
2218 return DD->useSplitDwarf();
2219}
2220
2222 const DIScope *Context) {
2223 getCU().addGlobalNameForTypeUnit(Name, Context);
2224}
2225
2227 const DIScope *Context) {
2228 getCU().addGlobalTypeUnitType(Ty, Context);
2229}
2230
2233 return nullptr;
2234 if (isDwoUnit())
2235 return nullptr;
2236 return getSection()->getBeginSymbol();
2237}
2238
2240 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2241 addSectionLabel(getUnitDie(), dwarf::DW_AT_str_offsets_base,
2242 DU->getStringOffsetsStartSym(),
2244}
2245
2247 assert(DD->getDwarfVersion() >= 5 &&
2248 "DW_AT_rnglists_base requires DWARF version 5 or later");
2249 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2250 addSectionLabel(getUnitDie(), dwarf::DW_AT_rnglists_base,
2251 DU->getRnglistsTableBaseSym(),
2253}
2254
2255void DwarfTypeUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
2257}
2258
2259bool DwarfUnit::isCompatibleWithVersion(uint16_t Version) const {
2260 return !Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= Version;
2261}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
BitTracker BT
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static unsigned getDwarfVersion(const MachineFunction &MF)
Resolve the DWARF version the way DwarfDebug does.
Definition Analysis.cpp:545
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool hasVectorBeenPadded(const DICompositeType *CTy)
Returns true if the vector's size differs from the sum of sizes of elements the user specified.
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Register const TargetRegisterInfo * TRI
This file contains the declarations for metadata subclasses.
#define T
#define P(N)
static enum BaseType getBaseType(const Value *Val)
Return the baseType for Val which states whether Val is exclusively derived from constant/null,...
static unsigned getSize(unsigned Kind)
APInt bitcastToAPInt() const
Definition APFloat.h:1475
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition APInt.h:571
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
void resetUsedFlag(bool HasBeenUsed=false)
Definition AddressPool.h:51
Annotations lets you mark points and ranges inside source code, for tests:
Definition Annotations.h:67
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:95
MCSymbol * getSymbol(const GlobalValue *GV) const
TargetMachine & TM
Target machine description.
Definition AsmPrinter.h:98
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition AsmPrinter.h:105
const DataLayout & getDataLayout() const
Return information about data layout.
bool doesDwarfUseRelocationsAcrossSections() const
Definition AsmPrinter.h:398
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This is an important base class in LLVM.
Definition Constant.h:43
Basic type, like 'int' or 'float'.
uint32_t getDataSizeInBits() const
unsigned getEncoding() const
DIExpression * getRankExp() const
DIExpression * getAssociatedExp() const
DIVariable * getAllocated() const
DIExpression * getDataLocationExp() const
DIVariable * getAssociated() const
DIDerivedType * getDiscriminator() const
DIVariable * getDataLocation() const
unsigned getRuntimeLang() const
DIType * getSpecification() const
StringRef getIdentifier() const
DINodeArray getElements() const
DITemplateParameterArray getTemplateParams() const
DIExpression * getAllocatedExp() const
ConstantInt * getBitStrideConst() const
std::optional< uint32_t > getEnumKind() const
DIType * getVTableHolder() const
DINodeArray getAnnotations() const
ConstantInt * getRankConst() const
MDString * getRawIdentifier() const
DIType * getBaseType() const
DINodeArray getAnnotations() const
Get annotations associated with this derived type.
DITemplateParameterArray getTemplateParams() const
Get the template parameters from a template alias.
DIObjCProperty * getObjCProperty() const
LLVM_ABI Constant * getConstant() const
DIEBlock - Represents a block of values.
Definition DIE.h:1057
A simple label difference DIE.
Definition DIE.h:258
DwarfExpression implementation for singular DW_AT_location.
DIEDwarfExpression(const AsmPrinter &AP, DwarfCompileUnit &CU, DIELoc &DIE)
Definition DwarfUnit.cpp:41
A pointer to another debug information entry.
Definition DIE.h:318
A container for inline string values.
Definition DIE.h:296
An integer value DIE.
Definition DIE.h:169
static dwarf::Form BestForm(bool IsSigned, uint64_t Int)
Choose the best form for integer.
Definition DIE.h:176
A label DIE.
Definition DIE.h:222
DIELoc - Represents an expression location.
Definition DIE.h:1021
A container for string pool string values.
Definition DIE.h:276
virtual const MCSymbol * getCrossSectionRelativeBaseAddress() const
Definition DIE.h:1000
LLVM_ABI DIEUnit(dwarf::Tag UnitTag)
Definition DIE.cpp:298
MCSection * getSection() const
Return the section that this DIEUnit will be emitted into.
Definition DIE.h:1007
DIE & getUnitDie()
Definition DIE.h:1010
A list of DIE values.
Definition DIE.h:705
A structured debug information entry.
Definition DIE.h:835
DIE & addChild(DIE *Child)
Add a child to the DIE.
Definition DIE.h:945
static DIE * get(BumpPtrAllocator &Alloc, dwarf::Tag Tag)
Definition DIE.h:862
LLVM_ABI DIEUnit * getUnit() const
Climb up the parent chain to get the unit that this DIE belongs to.
Definition DIE.cpp:190
dwarf::Tag getTag() const
Definition DIE.h:868
DWARF expression.
const APInt & getDenominator() const
LLVM_ABI bool isSigned() const
const APInt & getNumerator() const
LLVM_ABI BoundType getLowerBound() const
LLVM_ABI BoundType getCount() const
LLVM_ABI BoundType getUpperBound() const
PointerUnion< DIVariable *, DIExpression * > BoundType
LLVM_ABI BoundType getStride() const
Represents a module in the programming language, for example, a Clang module, or a Fortran module.
Debug lexical block.
DIScope * getScope() const
StringRef getName() const
bool getExportSymbols() const
Tagged DWARF-like metadata node.
LLVM_ABI dwarf::Tag getTag() const
DIFlags
Debug info flags.
A property of a class or structure.
Base class for scope-like contexts.
LLVM_ABI DIScope * getScope() const
String type, Fortran CHARACTER(n)
Subprogram description. Uses SubclassData1.
BoundType getLowerBound() const
BoundType getBias() const
PointerUnion< ConstantInt *, DIVariable *, DIExpression *, DIDerivedType * > BoundType
BoundType getUpperBound() const
DIType * getBaseType() const
Get the base type this is derived from.
BoundType getStride() const
Array subrange.
LLVM_ABI BoundType getUpperBound() const
LLVM_ABI BoundType getStride() const
LLVM_ABI BoundType getLowerBound() const
LLVM_ABI BoundType getCount() const
Type array for a subprogram.
Base class for types.
bool isLittleEndian() const
uint32_t getNumExtraInhabitants() const
bool isBigEndian() const
bool isLValueReference() const
bool isBitField() const
bool isVirtual() const
bool isObjcClassComplete() const
bool isAppleBlockExtension() const
uint64_t getOffsetInBits() const
bool isVector() const
DIFlags getFlags() const
StringRef getName() const
bool isForwardDecl() const
bool isTypePassByValue() const
uint64_t getSizeInBits() const
uint32_t getAlignInBytes() const
Metadata * getRawSizeInBits() const
bool isRValueReference() const
bool isArtificial() const
bool getExportSymbols() const
DIScope * getScope() const
bool isTypePassByReference() const
Metadata * getRawOffsetInBits() const
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
static bool isUnsignedDIType(const DIType *Ty)
Return true if type encoding is unsigned.
void addGlobalNameForTypeUnit(StringRef Name, const DIScope *Context)
Add a new global name present in a type unit to this compile unit.
unsigned getOrCreateSourceID(const DIFile *File) override
Look up the source ID for the given file.
void addGlobalTypeUnitType(const DIType *Ty, const DIScope *Context)
Add a new global type present in a type unit to this compile unit.
Collects and handles dwarf debug information.
Definition DwarfDebug.h:352
std::optional< MD5::MD5Result > getMD5AsBytes(const DIFile *File) const
If the File has an MD5 checksum, return it as an MD5Result allocated in the MCContext.
uint16_t getDwarfVersion() const
Returns the Dwarf Version.
dwarf::Form getDwarfSectionOffsetForm() const
Returns a suitable DWARF form to represent a section offset, i.e.
AddressPool & getAddressPool()
Definition DwarfDebug.h:927
bool useSplitDwarf() const
Returns whether or not to change the current debug info for split DWARF.
Definition DwarfDebug.h:872
virtual void disableTemporaryBuffer()=0
Disable emission to the temporary buffer.
virtual unsigned getTemporaryBufferSize()=0
Return the emitted size, in number of bytes, for the data stored in the temporary buffer.
void setMemoryLocationKind()
Lock this down to become a memory location description.
bool addExpression(DIExpressionCursor &&Expr)
Emit all remaining operations in the DIExpressionCursor.
DwarfCompileUnit & CU
virtual void commitTemporaryBuffer()=0
Commit the data stored in the temporary buffer to the main output.
DwarfExpression(unsigned DwarfVersion, DwarfCompileUnit &CU)
virtual void enableTemporaryBuffer()=0
Start emitting data to the temporary buffer.
DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU, unsigned UniqueID, MCDwarfDwoLineTable *SplitLineTable=nullptr)
Definition DwarfUnit.cpp:93
void addGlobalTypeImpl(const DIType *Ty, const DIE &Die, const DIScope *Context) override
Add a new global type to the compile unit.
DwarfCompileUnit & getCU() override
Definition DwarfUnit.h:450
void emitHeader(bool UseOffsets) override
Emit the header for this unit, not including the initial length field.
void addGlobalName(StringRef Name, const DIE &Die, const DIScope *Context) override
Add a new global name to the compile unit.
virtual DIE * getOrCreateTypeDIE(const MDNode *TyNode)
Find existing DIE or create new DIE for the given type.
DwarfDebug & getDwarfDebug() const
Definition DwarfUnit.h:114
void addThrownTypes(DIE &Die, DINodeArray ThrownTypes)
Add thrown types.
void addStringOffsetsStart()
Add the DW_AT_str_offsets_base attribute to the unit DIE.
void addAnnotation(DIE &Buffer, DINodeArray Annotations)
Add DW_TAG_LLVM_annotation.
std::vector< DIEBlock * > DIEBlocks
A list of all the DIEBlocks in use.
Definition DwarfUnit.h:67
std::vector< DIELoc * > DIELocs
A list of all the DIELocs in use.
Definition DwarfUnit.h:70
void addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc)
Add block data.
void addTemplateParams(DIE &Buffer, DINodeArray TParams)
Add template parameters in buffer.
virtual DIE * getOrCreateContextDIE(const DIScope *Context)
Get context owner's DIE.
bool useSegmentedStringOffsetsTable() const
Definition DwarfUnit.h:294
bool applySubprogramDefinitionAttributes(const DISubprogram *SP, DIE &SPDie, bool Minimal)
DIELoc * getDIELoc()
Returns a fresh newly allocated DIELoc.
Definition DwarfUnit.h:143
void updateAcceleratorTables(const DIScope *Context, const DIType *Ty, const DIE &TyDIE)
If this is a named finished type then include it in the list of types for the accelerator tables.
void addAttribute(DIEValueList &Die, dwarf::Attribute Attribute, dwarf::Form Form, T &&Value)
Definition DwarfUnit.h:86
void addOpAddress(DIELoc &Die, const MCSymbol *Sym)
Add a dwarf op address data and value using the form given and an op of either DW_FORM_addr or DW_FOR...
void addUInt(DIEValueList &Die, dwarf::Attribute Attribute, std::optional< dwarf::Form > Form, uint64_t Integer)
Add an unsigned integer attribute data and value.
void addString(DIE &Die, dwarf::Attribute Attribute, StringRef Str)
Add a string attribute data and value.
void addConstantValue(DIE &Die, const ConstantInt *CI, const DIType *Ty)
Add constant value entry in variable DIE.
DIE * getOrCreateNameSpace(const DINamespace *NS)
void insertDIE(const DINode *Desc, DIE *D)
Insert DIE into the map.
void addAccess(DIE &Die, DINode::DIFlags Flags)
Add the accessibility attribute.
void addGlobalType(const DIType *Ty, const DIE &Die, const DIScope *Context)
DIE * createTypeDIE(const DIScope *Context, DIE &ContextDIE, const DIType *Ty)
Creates type DIE with specific context.
bool shouldPlaceInUnitDIE(const DISubprogram *SP, bool Minimal)
Definition DwarfUnit.h:350
DwarfDebug * DD
Definition DwarfUnit.h:56
DenseMap< DIE *, const DINode * > ContainingTypeMap
This map is used to keep track of subprogram DIEs that need DW_AT_containing_type attribute.
Definition DwarfUnit.h:75
const DICompileUnit * CUNode
MDNode for the compile unit.
Definition DwarfUnit.h:41
virtual unsigned getOrCreateSourceID(const DIFile *File)=0
Look up the source ID for the given file.
virtual DIE * getOrCreateSubprogramDIE(const DISubprogram *SP, const Function *FnHint, bool Minimal=false)
DIE * getOrCreateSubprogramContextDIE(const DISubprogram *SP, bool IgnoreScope)
Definition DwarfUnit.h:355
virtual void addGlobalTypeImpl(const DIType *Ty, const DIE &Die, const DIScope *Context)=0
Add a new global type to the compile unit.
void addDIETypeSignature(DIE &Die, uint64_t Signature)
Add a type's DW_AT_signature and set the declaration flag.
virtual DwarfCompileUnit & getCU()=0
DIE * getDIE(const DINode *D) const
Returns the DIE map slot for the specified debug variable.
void constructPropertyForwardDIEs()
virtual unsigned getHeaderSize() const
Compute the size of a header for this unit, not including the initial length field.
Definition DwarfUnit.h:300
MCSymbol * LabelBegin
The start of the unit within its section.
Definition DwarfUnit.h:50
void addSInt(DIEValueList &Die, dwarf::Attribute Attribute, std::optional< dwarf::Form > Form, int64_t Integer)
Add an signed integer attribute data and value.
DwarfUnit(dwarf::Tag, const DICompileUnit *Node, AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU, unsigned UniqueID=0)
Definition DwarfUnit.cpp:87
void addLabelDelta(DIEValueList &Die, dwarf::Attribute Attribute, const MCSymbol *Hi, const MCSymbol *Lo)
Add a label delta attribute data and value.
void addLinkageName(DIE &Die, StringRef LinkageName)
Add a linkage name, if it isn't empty.
std::string getParentContextString(const DIScope *Context) const
Get string containing language specific context for a global name.
void addSourceLine(DIE &Die, unsigned Line, unsigned Column, const DIFile *File)
Add location information to specified debug information entry.
void emitCommonHeader(bool UseOffsets, dwarf::UnitType UT)
Emit the common part of the header for this unit.
BumpPtrAllocator DIEValueAllocator
Definition DwarfUnit.h:44
DIE * IndexTyDie
An anonymous type for index type. Owned by DIEUnit.
Definition DwarfUnit.h:60
void addRnglistsBase()
Add the DW_AT_rnglists_base attribute to the unit DIE.
DIE * getOrCreateModule(const DIModule *M)
const DICompileUnit * getCUNode() const
Definition DwarfUnit.h:113
DIE & createAndAddDIE(dwarf::Tag Tag, DIE &Parent, const DINode *N=nullptr)
Create a DIE with the given Tag, add the DIE to its parent, and call insertDIE if MD is not null.
DwarfFile * DU
Definition DwarfUnit.h:57
std::optional< unsigned > constructSubprogramArguments(DIE &Buffer, DITypeArray Args)
Construct function argument DIEs.
void addSectionOffset(DIE &Die, dwarf::Attribute Attribute, uint64_t Integer)
Add an offset into a section attribute data and value.
void addInt(DIE &Die, dwarf::Attribute Attribute, const APInt &Integer, bool Unsigned, std::optional< dwarf::Form > Form=std::nullopt)
Add an integer attribute data and value; value may be any width.
DIE * getOrCreateStaticMemberDIE(const DIDerivedType *DT)
Create new static data member DIE.
void addLabel(DIEValueList &Die, dwarf::Attribute Attribute, dwarf::Form Form, const MCSymbol *Label)
Add a Dwarf label attribute data and value.
void addConstantFPValue(DIE &Die, const ConstantFP *CFP)
Add constant value entry in variable DIE.
void constructContainingTypeDIEs()
Construct DIEs for types that contain vtables.
unsigned UniqueID
A numeric ID unique among all CUs in the module.
Definition DwarfUnit.h:39
void addSectionLabel(DIE &Die, dwarf::Attribute Attribute, const MCSymbol *Label, const MCSymbol *Sec)
Add a Dwarf section label attribute data and value.
bool isShareableAcrossCUs(const DINode *D) const
Check whether the DIE for this MDNode can be shared across CUs.
DenseMap< DIE *, const DINode * > PropertyForwardMap
Definition DwarfUnit.h:76
llvm::dwarf::SourceLanguage getSourceLanguage() const
void addPoolOpAddress(DIEValueList &Die, const MCSymbol *Label)
~DwarfUnit() override
Definition DwarfUnit.cpp:99
DenseMap< const MDNode *, DIE * > MDNodeToDieMap
Tracks the mapping of unit level debug information variables to debug information entries.
Definition DwarfUnit.h:64
void constructTypeDIE(DIE &Buffer, const DICompositeType *CTy)
virtual void addGlobalName(StringRef Name, const DIE &Die, const DIScope *Context)=0
Add a new global name to the compile unit.
MCSymbol * EndLabel
Emitted at the end of the CU and used to compute the CU Length field.
Definition DwarfUnit.h:53
void addFlag(DIE &Die, dwarf::Attribute Attribute)
Add a flag that is true to the DIE.
AsmPrinter * Asm
Target of Dwarf emission.
Definition DwarfUnit.h:47
void addType(DIE &Entity, const DIType *Ty, dwarf::Attribute Attribute=dwarf::DW_AT_type)
Add a new type attribute to the specified entity.
void applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie, bool SkipSPAttributes=false)
void addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry)
Add a DIE attribute data and value.
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
uint16_t getDwarfVersion() const
Definition MCContext.h:814
unsigned getFile(StringRef Directory, StringRef FileName, std::optional< MD5::MD5Result > Checksum, uint16_t DwarfVersion, std::optional< StringRef > Source)
Definition MCDwarf.h:358
MCSection * getDwarfStrOffSection() const
MCSection * getDwarfRnglistsSection() const
MCSection * getDwarfAbbrevSection() const
MCSymbol * getBeginSymbol()
Definition MCSection.h:653
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
A single uniqued string.
Definition Metadata.h:733
Root of the metadata hierarchy.
Definition Metadata.h:64
Wrapper class representing virtual and physical registers.
Definition Register.h:20
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
TargetOptions Options
unsigned DebugStrictDwarf
When set to true, don't use DWARF extensions in later DWARF versions.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Target - Wrapper for Target specific information.
LLVM Value Representation.
Definition Value.h:75
Calculates the starting offsets for various sections within the .debug_names section.
Definition Dwarf.h:35
@ DW_ACCESS_private
Definition Dwarf.h:187
@ DW_ACCESS_protected
Definition Dwarf.h:186
@ DW_ACCESS_public
Definition Dwarf.h:185
Attribute
Attributes.
Definition Dwarf.h:125
SourceLanguageName
Definition Dwarf.h:229
UnitType
Constants for unit types in DWARF v5.
Definition Dwarf.h:994
bool isType(Tag T)
Definition Dwarf.h:113
@ DW_LANG_hi_user
Definition Dwarf.h:226
std::optional< SourceLanguage > toDW_LANG(SourceLanguageName name, uint32_t version)
Convert a DWARF 6 pair of language name and version to a DWARF 5 DW_LANG.
Definition Dwarf.h:237
bool isCPlusPlus(SourceLanguage S)
Definition Dwarf.h:566
TypeKind getArrayIndexTypeEncoding(SourceLanguage S)
Definition Dwarf.h:839
@ DW_DSC_range
Definition Dwarf.h:889
@ DW_DSC_label
Definition Dwarf.h:888
@ DW_FLAG_type_implementation
Definition Dwarf.h:1051
bool isC(SourceLanguage S)
Definition Dwarf.h:750
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:707
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
Op::Description Desc
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
#define N
static LLVM_ABI bool mayHaveLocationExpr(dwarf::Attribute Attr)
Identifies DWARF attributes that may contain a reference to a DWARF expression.
Definition DWARFDie.cpp:853