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