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