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