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