1//===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf 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 "DwarfCompileUnit.h"
14#include "AddressPool.h"
15#include "DwarfExpression.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallString.h"
18#include "llvm/BinaryFormat/Dwarf.h"
19#include "llvm/CodeGen/AsmPrinter.h"
20#include "llvm/CodeGen/DIE.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstr.h"
23#include "llvm/CodeGen/TargetFrameLowering.h"
24#include "llvm/CodeGen/TargetRegisterInfo.h"
25#include "llvm/CodeGen/TargetSubtargetInfo.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DebugInfo.h"
28#include "llvm/IR/GlobalVariable.h"
29#include "llvm/MC/MCAsmInfo.h"
30#include "llvm/MC/MCSection.h"
31#include "llvm/MC/MCStreamer.h"
32#include "llvm/MC/MCSymbol.h"
33#include "llvm/MC/MCSymbolWasm.h"
34#include "llvm/MC/MachineLocation.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Target/TargetLoweringObjectFile.h"
37#include "llvm/Target/TargetMachine.h"
38#include <optional>
39#include <string>
40#include <utility>
41
42using namespace llvm;
43
44/// Query value using AddLinkageNamesToDeclCallOriginsForTuning.
45static cl::opt<cl::boolOrDefault> AddLinkageNamesToDeclCallOrigins(
46 "add-linkage-names-to-declaration-call-origins", cl::Hidden,
47 cl::desc("Add DW_AT_linkage_name to function declaration DIEs "
48 "referenced by DW_AT_call_origin attributes. Enabled by default "
49 "for -gsce debugger tuning."));
50
51static cl::opt<bool> EmitFuncLineTableOffsetsOption(
52 "emit-func-debug-line-table-offsets", cl::Hidden,
53 cl::desc("Include line table offset in function's debug info and emit end "
54 "sequence after each function's line data."),
55 cl::init(Val: false));
56
57static bool AddLinkageNamesToDeclCallOriginsForTuning(const DwarfDebug *DD) {
58 bool EnabledByDefault = DD->tuneForSCE();
59 if (EnabledByDefault)
60 return AddLinkageNamesToDeclCallOrigins != cl::boolOrDefault::BOU_FALSE;
61 return AddLinkageNamesToDeclCallOrigins == cl::boolOrDefault::BOU_TRUE;
62}
63
64static dwarf::Tag GetCompileUnitType(UnitKind Kind, DwarfDebug *DW) {
65
66 // According to DWARF Debugging Information Format Version 5,
67 // 3.1.2 Skeleton Compilation Unit Entries:
68 // "When generating a split DWARF object file (see Section 7.3.2
69 // on page 187), the compilation unit in the .debug_info section
70 // is a "skeleton" compilation unit with the tag DW_TAG_skeleton_unit"
71 if (DW->getDwarfVersion() >= 5 && Kind == UnitKind::Skeleton)
72 return dwarf::DW_TAG_skeleton_unit;
73
74 return dwarf::DW_TAG_compile_unit;
75}
76
77DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
78 AsmPrinter *A, DwarfDebug *DW,
79 DwarfFile *DWU, UnitKind Kind)
80 : DwarfUnit(GetCompileUnitType(Kind, DW), Node, A, DW, DWU, UID) {
81 insertDIE(Desc: Node, D: &getUnitDie());
82 MacroLabelBegin = Asm->createTempSymbol(Name: "cu_macro_begin");
83 assert(CUNode);
84}
85
86/// addLabelAddress - Add a dwarf label attribute data and value using
87/// DW_FORM_addr or DW_FORM_GNU_addr_index.
88void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
89 const MCSymbol *Label) {
90 if ((Skeleton || !DD->useSplitDwarf()) && Label)
91 DD->addArangeLabel(SCU: SymbolCU(this, Label));
92
93 // Don't use the address pool in non-fission or in the skeleton unit itself.
94 if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
95 return addLocalLabelAddress(Die, Attribute, Label);
96
97 bool UseAddrOffsetFormOrExpressions =
98 DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
99
100 const MCSymbol *Base = nullptr;
101 if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
102 Base = DD->getSectionLabel(S: &Label->getSection());
103
104 if (!Base || Base == Label) {
105 unsigned idx = DD->getAddressPool().getIndex(Sym: Label);
106 addAttribute(Die, Attribute,
107 Form: DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
108 : dwarf::DW_FORM_GNU_addr_index,
109 Value: DIEInteger(idx));
110 return;
111 }
112
113 // Could be extended to work with DWARFv4 Split DWARF if that's important for
114 // someone. In that case DW_FORM_data would be used.
115 assert(DD->getDwarfVersion() >= 5 &&
116 "Addr+offset expressions are only valuable when using debug_addr (to "
117 "reduce relocations) available in DWARFv5 or higher");
118 if (DD->useAddrOffsetExpressions()) {
119 auto *Loc = new (DIEValueAllocator) DIEBlock();
120 addPoolOpAddress(Die&: *Loc, Label);
121 addBlock(Die, Attribute, Form: dwarf::DW_FORM_exprloc, Block: Loc);
122 } else
123 addAttribute(Die, Attribute, Form: dwarf::DW_FORM_LLVM_addrx_offset,
124 Value: new (DIEValueAllocator) DIEAddrOffset(
125 DD->getAddressPool().getIndex(Sym: Base), Label, Base));
126}
127
128void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
129 dwarf::Attribute Attribute,
130 const MCSymbol *Label) {
131 if (Label)
132 addAttribute(Die, Attribute, Form: dwarf::DW_FORM_addr, Value: DIELabel(Label));
133 else
134 addAttribute(Die, Attribute, Form: dwarf::DW_FORM_addr, Value: DIEInteger(0));
135}
136
137unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
138 // If we print assembly, we can't separate .file entries according to
139 // compile units. Thus all files will belong to the default compile unit.
140
141 // FIXME: add a better feature test than hasRawTextSupport. Even better,
142 // extend .file to support this.
143 unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
144 if (!File)
145 return Asm->OutStreamer->emitDwarfFileDirective(FileNo: 0, Directory: "", Filename: "", Checksum: std::nullopt,
146 Source: std::nullopt, CUID);
147
148 if (LastFile != File) {
149 LastFile = File;
150 LastFileID = Asm->OutStreamer->emitDwarfFileDirective(
151 FileNo: 0, Directory: File->getDirectory(), Filename: File->getFilename(), Checksum: DD->getMD5AsBytes(File),
152 Source: File->getSource(), CUID);
153 }
154 return LastFileID;
155}
156
157DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
158 const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
159 // Check for pre-existence.
160 if (DIE *Die = getDIE(D: GV))
161 return Die;
162
163 assert(GV);
164
165 auto *GVContext = GV->getScope();
166 const DIType *GTy = GV->getType();
167
168 auto *CB = GVContext ? dyn_cast<DICommonBlock>(Val: GVContext) : nullptr;
169 DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
170 : getOrCreateContextDIE(Ty: GVContext);
171
172 // Add to map.
173 DIE *VariableDIE = &createAndAddDIE(Tag: GV->getTag(), Parent&: *ContextDIE, N: GV);
174 DIScope *DeclContext;
175 if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
176 DeclContext = SDMDecl->getScope();
177 assert(SDMDecl->isStaticMember() && "Expected static member decl");
178 assert(GV->isDefinition());
179 // We need the declaration DIE that is in the static member's class.
180 DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(DT: SDMDecl);
181 addDIEEntry(Die&: *VariableDIE, Attribute: dwarf::DW_AT_specification, Entry&: *VariableSpecDIE);
182 // If the global variable's type is different from the one in the class
183 // member type, assume that it's more specific and also emit it.
184 if (GTy != SDMDecl->getBaseType())
185 addType(Entity&: *VariableDIE, Ty: GTy);
186 } else {
187 DeclContext = GV->getScope();
188 // Add name and type.
189 StringRef DisplayName = GV->getDisplayName();
190 if (!DisplayName.empty())
191 addString(Die&: *VariableDIE, Attribute: dwarf::DW_AT_name, Str: GV->getDisplayName());
192 if (GTy)
193 addType(Entity&: *VariableDIE, Ty: GTy);
194
195 // Add scoping info.
196 if (!GV->isLocalToUnit())
197 addFlag(Die&: *VariableDIE, Attribute: dwarf::DW_AT_external);
198
199 // Add line number info.
200 addSourceLine(Die&: *VariableDIE, G: GV);
201 }
202
203 if (!GV->isDefinition())
204 addFlag(Die&: *VariableDIE, Attribute: dwarf::DW_AT_declaration);
205 else
206 addGlobalName(Name: GV->getName(), Die: *VariableDIE, Context: DeclContext);
207
208 addAnnotation(Buffer&: *VariableDIE, Annotations: GV->getAnnotations());
209
210 if (uint32_t AlignInBytes = GV->getAlignInBytes())
211 addUInt(Die&: *VariableDIE, Attribute: dwarf::DW_AT_alignment, Form: dwarf::DW_FORM_udata,
212 Integer: AlignInBytes);
213
214 if (MDTuple *TP = GV->getTemplateParams())
215 addTemplateParams(Buffer&: *VariableDIE, TParams: DINodeArray(TP));
216
217 // Add location.
218 addLocationAttribute(ToDIE: VariableDIE, GV, GlobalExprs);
219
220 return VariableDIE;
221}
222
223void DwarfCompileUnit::addLocationAttribute(
224 DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
225 bool addToAccelTable = false;
226 DIELoc *Loc = nullptr;
227 std::optional<unsigned> TargetAddrSpace;
228 std::unique_ptr<DIEDwarfExpression> DwarfExpr;
229 const GlobalVariable *LastGlobal = nullptr;
230 for (const auto &GE : GlobalExprs) {
231 const GlobalVariable *Global = GE.Var;
232 const DIExpression *Expr = GE.Expr;
233
234 // For compatibility with DWARF 3 and earlier,
235 // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) or
236 // DW_AT_location(DW_OP_consts, X, DW_OP_stack_value) becomes
237 // DW_AT_const_value(X).
238 if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
239 addToAccelTable = true;
240 addConstantValue(
241 Die&: *VariableDIE,
242 Unsigned: DIExpression::SignedOrUnsignedConstant::UnsignedConstant ==
243 *Expr->isConstant(),
244 Val: Expr->getConstantValue());
245 break;
246 }
247
248 // We cannot describe the location of dllimport'd variables: the
249 // computation of their address requires loads from the IAT.
250 if (Global && Global->hasDLLImportStorageClass())
251 continue;
252
253 // Nothing to describe without address or constant.
254 if (!Global && (!Expr || !Expr->isConstant()))
255 continue;
256
257 if (Global && Global->isThreadLocal() &&
258 !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
259 continue;
260
261 if (!Loc) {
262 addToAccelTable = true;
263 Loc = new (DIEValueAllocator) DIELoc;
264 DwarfExpr = std::make_unique<DIEDwarfExpression>(args&: *Asm, args&: *this, args&: *Loc);
265 }
266
267 if (Expr) {
268 Expr = DD->adjustExpressionForTarget(Expr, TargetAddrSpace);
269 DwarfExpr->addFragmentOffset(Expr);
270 }
271
272 if (Global) {
273 const MCSymbol *Sym = Asm->getSymbol(GV: Global);
274 // 16-bit platforms like MSP430 and AVR take this path, so sink this
275 // assert to platforms that use it.
276 auto GetPointerSizedFormAndOp = [this]() {
277 unsigned PointerSize = Asm->MAI.getCodePointerSize();
278 assert((PointerSize == 4 || PointerSize == 8) &&
279 "Add support for other sizes if necessary");
280 struct FormAndOp {
281 dwarf::Form Form;
282 dwarf::LocationAtom Op;
283 };
284 return PointerSize == 4
285 ? FormAndOp{.Form: dwarf::DW_FORM_data4, .Op: dwarf::DW_OP_const4u}
286 : FormAndOp{.Form: dwarf::DW_FORM_data8, .Op: dwarf::DW_OP_const8u};
287 };
288 if (Global->isThreadLocal()) {
289 if (Asm->TM.getTargetTriple().isWasm()) {
290 // FIXME This is not guaranteed, but in practice, in static linking,
291 // if present, __tls_base's index is 1. This doesn't hold for dynamic
292 // linking, so TLS variables used in dynamic linking won't have
293 // correct debug info for now. See
294 // https://github.com/llvm/llvm-project/blob/19afbfe33156d211fa959dadeea46cd17b9c723c/lld/wasm/Driver.cpp#L786-L823
295 addWasmRelocBaseGlobal(Loc, GlobalName: "__tls_base", GlobalIndex: 1);
296 addOpAddress(Die&: *Loc, Sym);
297 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_plus);
298 } else if (Asm->TM.useEmulatedTLS()) {
299 // TODO: add debug info for emulated thread local mode.
300 } else {
301 // FIXME: Make this work with -gsplit-dwarf.
302 // Based on GCC's support for TLS:
303 if (!DD->useSplitDwarf()) {
304 auto FormAndOp = GetPointerSizedFormAndOp();
305 // 1) Start with a constNu of the appropriate pointer size
306 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: FormAndOp.Op);
307 // 2) containing the (relocated) offset of the TLS variable
308 // within the module's TLS block.
309 addExpr(Die&: *Loc, Form: FormAndOp.Form,
310 Expr: Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
311 } else {
312 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_GNU_const_index);
313 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_udata,
314 Integer: DD->getAddressPool().getIndex(Sym, /* TLS */ true));
315 }
316 // 3) followed by an OP to make the debugger do a TLS lookup.
317 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1,
318 Integer: DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
319 : dwarf::DW_OP_form_tls_address);
320 }
321 } else if (Asm->TM.getTargetTriple().isWasm() &&
322 Asm->TM.getRelocationModel() == Reloc::PIC_) {
323 // FIXME This is not guaranteed, but in practice, if present,
324 // __memory_base's index is 1. See
325 // https://github.com/llvm/llvm-project/blob/19afbfe33156d211fa959dadeea46cd17b9c723c/lld/wasm/Driver.cpp#L786-L823
326 addWasmRelocBaseGlobal(Loc, GlobalName: "__memory_base", GlobalIndex: 1);
327 addOpAddress(Die&: *Loc, Sym);
328 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_plus);
329 } else if ((Asm->TM.getRelocationModel() == Reloc::RWPI ||
330 Asm->TM.getRelocationModel() == Reloc::ROPI_RWPI) &&
331 !Asm->getObjFileLowering()
332 .getKindForGlobal(GO: Global, TM: Asm->TM)
333 .isReadOnly()) {
334 auto FormAndOp = GetPointerSizedFormAndOp();
335 // Constant
336 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: FormAndOp.Op);
337 // Relocation offset
338 addExpr(Die&: *Loc, Form: FormAndOp.Form,
339 Expr: Asm->getObjFileLowering().getIndirectSymViaRWPI(Sym));
340 // Base register
341 Register BaseReg = Asm->getObjFileLowering().getStaticBase();
342 unsigned DwarfBaseReg =
343 Asm->TM.getMCRegisterInfo().getDwarfRegNum(Reg: BaseReg, isEH: false);
344 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_breg0 + DwarfBaseReg);
345 // Offset from base register
346 addSInt(Die&: *Loc, Form: dwarf::DW_FORM_sdata, Integer: 0);
347 // Operation
348 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_plus);
349 } else {
350 DD->addArangeLabel(SCU: SymbolCU(this, Sym));
351 addOpAddress(Die&: *Loc, Sym);
352 }
353 LastGlobal = Global;
354 }
355 // Global variables attached to symbols are memory locations.
356 // It would be better if this were unconditional, but malformed input that
357 // mixes non-fragments and fragments for the same variable is too expensive
358 // to detect in the verifier.
359 if (DwarfExpr->isUnknownLocation())
360 DwarfExpr->setMemoryLocationKind();
361 DwarfExpr->addExpression(Expr);
362 }
363 DD->addTargetVariableAttributes(CU&: *this, Die&: *VariableDIE, TargetAddrSpace,
364 VarLocKind: DwarfDebug::VariableLocationKind::Global,
365 GV: LastGlobal);
366 if (Loc)
367 addBlock(Die&: *VariableDIE, Attribute: dwarf::DW_AT_location, Loc: DwarfExpr->finalize());
368
369 if (DD->useAllLinkageNames())
370 addLinkageName(Die&: *VariableDIE, LinkageName: GV->getLinkageName());
371
372 if (addToAccelTable) {
373 DD->addAccelName(Unit: *this, NameTableKind: CUNode->getNameTableKind(), Name: GV->getName(),
374 Die: *VariableDIE);
375
376 // If the linkage name is different than the name, go ahead and output
377 // that as well into the name table.
378 if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
379 DD->useAllLinkageNames())
380 DD->addAccelName(Unit: *this, NameTableKind: CUNode->getNameTableKind(), Name: GV->getLinkageName(),
381 Die: *VariableDIE);
382 }
383}
384
385DIE *DwarfCompileUnit::getOrCreateCommonBlock(
386 const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
387 // Check for pre-existence.
388 if (DIE *NDie = getDIE(D: CB))
389 return NDie;
390 DIE *ContextDIE = getOrCreateContextDIE(Ty: CB->getScope());
391 DIE &NDie = createAndAddDIE(Tag: dwarf::DW_TAG_common_block, Parent&: *ContextDIE, N: CB);
392 StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
393 addString(Die&: NDie, Attribute: dwarf::DW_AT_name, Str: Name);
394 addGlobalName(Name, Die: NDie, Context: CB->getScope());
395 if (CB->getFile())
396 addSourceLine(Die&: NDie, Line: CB->getLineNo(), /*Column*/ 0, File: CB->getFile());
397 if (DIGlobalVariable *V = CB->getDecl())
398 getCU().addLocationAttribute(VariableDIE: &NDie, GV: V, GlobalExprs);
399 return &NDie;
400}
401
402void DwarfCompileUnit::addRange(RangeSpan Range) {
403 DD->insertSectionLabel(S: Range.Begin);
404
405 auto *PrevCU = DD->getPrevCU();
406 bool SameAsPrevCU = this == PrevCU;
407 DD->setPrevCU(this);
408 // If we have no current ranges just add the range and return, otherwise,
409 // check the current section and CU against the previous section and CU we
410 // emitted into and the subprogram was contained within. If these are the
411 // same then extend our current range, otherwise add this as a new range.
412 if (CURanges.empty() || !SameAsPrevCU ||
413 (&CURanges.back().End->getSection() !=
414 &Range.End->getSection())) {
415 // Before a new range is added, always terminate the prior line table.
416 if (PrevCU)
417 DD->terminateLineTable(CU: PrevCU);
418 CURanges.push_back(Elt: Range);
419 return;
420 }
421
422 CURanges.back().End = Range.End;
423}
424
425void DwarfCompileUnit::initStmtList() {
426 if (CUNode->isDebugDirectivesOnly())
427 return;
428
429 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
430 if (DD->useSectionsAsReferences()) {
431 LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
432 } else {
433 LineTableStartSym =
434 Asm->OutStreamer->getDwarfLineTableSymbol(CUID: getUniqueID());
435 }
436
437 // DW_AT_stmt_list is a offset of line number information for this
438 // compile unit in debug_line section. For split dwarf this is
439 // left in the skeleton CU and so not included.
440 // The line table entries are not always emitted in assembly, so it
441 // is not okay to use line_table_start here.
442 addSectionLabel(Die&: getUnitDie(), Attribute: dwarf::DW_AT_stmt_list, Label: LineTableStartSym,
443 Sec: TLOF.getDwarfLineSection()->getBeginSymbol());
444}
445
446void DwarfCompileUnit::applyStmtList(DIE &D) {
447 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
448 addSectionLabel(Die&: D, Attribute: dwarf::DW_AT_stmt_list, Label: LineTableStartSym,
449 Sec: TLOF.getDwarfLineSection()->getBeginSymbol());
450}
451
452void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
453 const MCSymbol *End) {
454 assert(Begin && "Begin label should not be null!");
455 assert(End && "End label should not be null!");
456 assert(Begin->isDefined() && "Invalid starting label");
457 assert(End->isDefined() && "Invalid end label");
458
459 addLabelAddress(Die&: D, Attribute: dwarf::DW_AT_low_pc, Label: Begin);
460 if (DD->getDwarfVersion() >= 4 &&
461 (!isDwoUnit() || !llvm::isRangeRelaxable(Begin, End))) {
462 addLabelDelta(Die&: D, Attribute: dwarf::DW_AT_high_pc, Hi: End, Lo: Begin);
463 return;
464 }
465 addLabelAddress(Die&: D, Attribute: dwarf::DW_AT_high_pc, Label: End);
466}
467
468// Add info for Wasm-global-based relocation.
469// 'GlobalIndex' is used for split dwarf, which currently relies on a few
470// assumptions that are not guaranteed in a formal way but work in practice.
471void DwarfCompileUnit::addWasmRelocBaseGlobal(DIELoc *Loc, StringRef GlobalName,
472 uint64_t GlobalIndex) {
473 // FIXME: duplicated from Target/WebAssembly/WebAssembly.h
474 // don't want to depend on target specific headers in this code?
475 const unsigned TI_GLOBAL_RELOC = 3;
476 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
477 auto *Sym =
478 static_cast<MCSymbolWasm *>(Asm->GetExternalSymbolSymbol(Sym: GlobalName));
479 // FIXME: this repeats what WebAssemblyMCInstLower::
480 // GetExternalSymbolSymbol does, since if there's no code that
481 // refers to this symbol, we have to set it here.
482 Sym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
483 Sym->setGlobalType(wasm::WasmGlobalType{
484 .Type: static_cast<uint8_t>(PointerSize == 4 ? wasm::WASM_TYPE_I32
485 : wasm::WASM_TYPE_I64),
486 .Mutable: true});
487 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_WASM_location);
488 addSInt(Die&: *Loc, Form: dwarf::DW_FORM_sdata, Integer: TI_GLOBAL_RELOC);
489 if (!isDwoUnit()) {
490 addLabel(Die&: *Loc, Form: dwarf::DW_FORM_data4, Label: Sym);
491 } else {
492 // FIXME: when writing dwo, we need to avoid relocations. Probably
493 // the "right" solution is to treat globals the way func and data
494 // symbols are (with entries in .debug_addr).
495 // For now we hardcode the indices in the callsites. Global indices are not
496 // fixed, but in practice a few are fixed; for example, __stack_pointer is
497 // always index 0.
498 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data4, Integer: GlobalIndex);
499 }
500}
501
502// Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
503// and DW_AT_high_pc attributes. If there are global variables in this
504// scope then create and insert DIEs for these variables.
505DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP,
506 const Function &F,
507 MCSymbol *LineTableSym) {
508 DIE *SPDie = getOrCreateSubprogramDIE(SP, F: &F, Minimal: includeMinimalInlineScopes());
509 SmallVector<RangeSpan, 2> BB_List;
510 // If basic block sections are on, ranges for each basic block section has
511 // to be emitted separately.
512 for (const auto &R : Asm->MBBSectionRanges)
513 BB_List.push_back(Elt: {.Begin: R.second.BeginLabel, .End: R.second.EndLabel});
514
515 attachRangesOrLowHighPC(D&: *SPDie, Ranges: BB_List);
516
517 if (DD->useAppleExtensionAttributes() &&
518 !DD->getCurrentFunction()->disableFramePointerElim())
519 addFlag(Die&: *SPDie, Attribute: dwarf::DW_AT_APPLE_omit_frame_ptr);
520
521 if (emitFuncLineTableOffsets() && LineTableSym) {
522 MCSymbol *Symbol =
523 Asm->getObjFileLowering().getDwarfLineSection()->getBeginSymbol();
524 addSectionLabel(Die&: *SPDie, Attribute: dwarf::DW_AT_LLVM_stmt_sequence, Label: LineTableSym,
525 Sec: Symbol);
526 }
527
528 // Only include DW_AT_frame_base in full debug info
529 if (!includeMinimalInlineScopes()) {
530 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
531 TargetFrameLowering::DwarfFrameBase FrameBase =
532 TFI->getDwarfFrameBase(MF: *Asm->MF);
533 switch (FrameBase.Kind) {
534 case TargetFrameLowering::DwarfFrameBase::Register: {
535 if (Register::isPhysicalRegister(Reg: FrameBase.Location.Reg)) {
536 MachineLocation Location(FrameBase.Location.Reg);
537 addAddress(Die&: *SPDie, Attribute: dwarf::DW_AT_frame_base, Location);
538 }
539 break;
540 }
541 case TargetFrameLowering::DwarfFrameBase::CFA: {
542 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
543 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_call_frame_cfa);
544 if (FrameBase.Location.Offset != 0) {
545 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_consts);
546 addSInt(Die&: *Loc, Form: dwarf::DW_FORM_sdata, Integer: FrameBase.Location.Offset);
547 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_plus);
548 }
549 addBlock(Die&: *SPDie, Attribute: dwarf::DW_AT_frame_base, Loc);
550 break;
551 }
552 case TargetFrameLowering::DwarfFrameBase::WasmFrameBase: {
553 // FIXME: duplicated from Target/WebAssembly/WebAssembly.h
554 const unsigned TI_GLOBAL_RELOC = 3;
555 if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC) {
556 // These need to be relocatable.
557 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
558 assert(FrameBase.Location.WasmLoc.Index == 0); // Only SP so far.
559 // For now, since we only ever use index 0, this should work as-is.
560 addWasmRelocBaseGlobal(Loc, GlobalName: "__stack_pointer",
561 GlobalIndex: FrameBase.Location.WasmLoc.Index);
562 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_stack_value);
563 addBlock(Die&: *SPDie, Attribute: dwarf::DW_AT_frame_base, Loc);
564 } else {
565 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
566 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
567 DIExpressionCursor Cursor({});
568 DwarfExpr.addWasmLocation(Index: FrameBase.Location.WasmLoc.Kind,
569 Offset: FrameBase.Location.WasmLoc.Index);
570 DwarfExpr.addExpression(Expr: std::move(Cursor));
571 addBlock(Die&: *SPDie, Attribute: dwarf::DW_AT_frame_base, Loc: DwarfExpr.finalize());
572 }
573 break;
574 }
575 }
576 }
577
578 // Add name to the name table, we do this here because we're guaranteed
579 // to have concrete versions of our DW_TAG_subprogram nodes.
580 DD->addSubprogramNames(Unit: *this, NameTableKind: CUNode->getNameTableKind(), SP, Die&: *SPDie);
581
582 return *SPDie;
583}
584
585// Construct a DIE for this scope.
586void DwarfCompileUnit::constructScopeDIE(LexicalScope *Scope,
587 DIE &ParentScopeDIE) {
588 if (!Scope || !Scope->getScopeNode())
589 return;
590
591 auto *DS = Scope->getScopeNode();
592
593 assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
594 "Only handle inlined subprograms here, use "
595 "constructSubprogramScopeDIE for non-inlined "
596 "subprograms");
597
598 // Emit inlined subprograms.
599 if (Scope->getParent() && isa<DISubprogram>(Val: DS)) {
600 DIE *ScopeDIE = constructInlinedScopeDIE(Scope, ParentScopeDIE);
601 assert(ScopeDIE && "Scope DIE should not be null.");
602 createAndAddScopeChildren(Scope, ScopeDIE&: *ScopeDIE);
603 return;
604 }
605
606 // Early exit when we know the scope DIE is going to be null.
607 if (DD->isLexicalScopeDIENull(Scope))
608 return;
609
610 // Emit lexical blocks.
611 DIE *ScopeDIE = getOrCreateLexicalBlockDIE(Scope, ParentDIE&: ParentScopeDIE);
612 assert(ScopeDIE && "Scope DIE should not be null.");
613
614 createAndAddScopeChildren(Scope, ScopeDIE&: *ScopeDIE);
615}
616
617void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
618 SmallVector<RangeSpan, 2> Range) {
619
620 HasRangeLists = true;
621
622 // Add the range list to the set of ranges to be emitted.
623 auto IndexAndList =
624 (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
625 ->addRange(CU: *(Skeleton ? Skeleton : this), R: std::move(Range));
626
627 uint32_t Index = IndexAndList.first;
628 auto &List = *IndexAndList.second;
629
630 // Under fission, ranges are specified by constant offsets relative to the
631 // CU's DW_AT_GNU_ranges_base.
632 // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
633 // fission until we support the forms using the .debug_addr section
634 // (DW_RLE_startx_endx etc.).
635 if (DD->getDwarfVersion() >= 5)
636 addUInt(Die&: ScopeDIE, Attribute: dwarf::DW_AT_ranges, Form: dwarf::DW_FORM_rnglistx, Integer: Index);
637 else {
638 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
639 const MCSymbol *RangeSectionSym =
640 TLOF.getDwarfRangesSection()->getBeginSymbol();
641 addSectionLabel(Die&: ScopeDIE, Attribute: dwarf::DW_AT_ranges, Label: List.Label, Sec: RangeSectionSym);
642 }
643}
644
645void DwarfCompileUnit::attachRangesOrLowHighPC(
646 DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
647 assert(!Ranges.empty());
648 if (!DD->useRangesSection() ||
649 (Ranges.size() == 1 &&
650 (!DD->alwaysUseRanges(*this) ||
651 DD->getSectionLabel(S: &Ranges.front().Begin->getSection()) ==
652 Ranges.front().Begin))) {
653 const RangeSpan &Front = Ranges.front();
654 const RangeSpan &Back = Ranges.back();
655 attachLowHighPC(D&: Die, Begin: Front.Begin, End: Back.End);
656 } else
657 addScopeRangeList(ScopeDIE&: Die, Range: std::move(Ranges));
658}
659
660void DwarfCompileUnit::attachRangesOrLowHighPC(
661 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
662 SmallVector<RangeSpan, 2> List;
663 List.reserve(N: Ranges.size());
664 for (const InsnRange &R : Ranges) {
665 auto *BeginLabel = DD->getLabelBeforeInsn(MI: R.first);
666 auto *EndLabel = DD->getLabelAfterInsn(MI: R.second);
667
668 const auto *BeginMBB = R.first->getParent();
669 const auto *EndMBB = R.second->getParent();
670
671 const auto *MBB = BeginMBB;
672 // Basic block sections allows basic block subsets to be placed in unique
673 // sections. For each section, the begin and end label must be added to the
674 // list. If there is more than one range, debug ranges must be used.
675 // Otherwise, low/high PC can be used.
676 // FIXME: Debug Info Emission depends on block order and this assumes that
677 // the order of blocks will be frozen beyond this point.
678 do {
679 if (MBB->sameSection(MBB: EndMBB) || MBB->isEndSection()) {
680 auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionID()];
681 List.push_back(
682 Elt: {.Begin: MBB->sameSection(MBB: BeginMBB) ? BeginLabel
683 : MBBSectionRange.BeginLabel,
684 .End: MBB->sameSection(MBB: EndMBB) ? EndLabel : MBBSectionRange.EndLabel});
685 }
686 if (MBB->sameSection(MBB: EndMBB))
687 break;
688 MBB = MBB->getNextNode();
689 } while (true);
690 }
691 attachRangesOrLowHighPC(Die, Ranges: std::move(List));
692}
693
694DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope,
695 DIE &ParentScopeDIE) {
696 assert(Scope->getScopeNode());
697 auto *DS = Scope->getScopeNode();
698 auto *InlinedSP = getDISubprogram(Scope: DS);
699 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
700 // was inlined from another compile unit.
701 DIE *OriginDIE = getAbstractScopeDIEs()[InlinedSP];
702 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
703
704 auto ScopeDIE = DIE::get(Alloc&: DIEValueAllocator, Tag: dwarf::DW_TAG_inlined_subroutine);
705 ParentScopeDIE.addChild(Child: ScopeDIE);
706 addDIEEntry(Die&: *ScopeDIE, Attribute: dwarf::DW_AT_abstract_origin, Entry&: *OriginDIE);
707
708 attachRangesOrLowHighPC(Die&: *ScopeDIE, Ranges: Scope->getRanges());
709
710 // Add the call site information to the DIE.
711 const DILocation *IA = Scope->getInlinedAt();
712 addUInt(Die&: *ScopeDIE, Attribute: dwarf::DW_AT_call_file, Form: std::nullopt,
713 Integer: getOrCreateSourceID(File: IA->getFile()));
714 addUInt(Die&: *ScopeDIE, Attribute: dwarf::DW_AT_call_line, Form: std::nullopt, Integer: IA->getLine());
715 if (IA->getColumn())
716 addUInt(Die&: *ScopeDIE, Attribute: dwarf::DW_AT_call_column, Form: std::nullopt, Integer: IA->getColumn());
717 if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
718 addUInt(Die&: *ScopeDIE, Attribute: dwarf::DW_AT_GNU_discriminator, Form: std::nullopt,
719 Integer: IA->getDiscriminator());
720
721 // Add name to the name table, we do this here because we're guaranteed
722 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
723 DD->addSubprogramNames(Unit: *this, NameTableKind: CUNode->getNameTableKind(), SP: InlinedSP,
724 Die&: *ScopeDIE);
725
726 return ScopeDIE;
727}
728
729DIE *DwarfCompileUnit::getOrCreateLexicalBlockDIE(LexicalScope *Scope,
730 DIE &ParentScopeDIE) {
731 if (DD->isLexicalScopeDIENull(Scope))
732 return nullptr;
733 const auto *DS = Scope->getScopeNode();
734
735 auto ScopeDIE = DIE::get(Alloc&: DIEValueAllocator, Tag: dwarf::DW_TAG_lexical_block);
736 ParentScopeDIE.addChild(Child: ScopeDIE);
737
738 if (Scope->isAbstractScope()) {
739 assert(!getAbstractScopeDIEs().count(DS) &&
740 "Abstract DIE for this scope exists!");
741 getAbstractScopeDIEs()[DS] = ScopeDIE;
742 return ScopeDIE;
743 }
744 if (!Scope->getInlinedAt()) {
745 assert(!LexicalBlockDIEs.count(DS) &&
746 "Concrete out-of-line DIE for this scope exists!");
747 LexicalBlockDIEs[DS] = ScopeDIE;
748 } else {
749 InlinedLocalScopeDIEs[DS].push_back(Elt: ScopeDIE);
750 }
751
752 attachRangesOrLowHighPC(Die&: *ScopeDIE, Ranges: Scope->getRanges());
753
754 return ScopeDIE;
755}
756
757DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
758 auto *VariableDie = DIE::get(Alloc&: DIEValueAllocator, Tag: DV.getTag());
759 insertDIE(Desc: DV.getVariable(), D: VariableDie);
760 DV.setDIE(*VariableDie);
761 // Abstract variables don't get common attributes later, so apply them now.
762 if (Abstract) {
763 applyCommonDbgVariableAttributes(Var: DV, VariableDie&: *VariableDie);
764 } else {
765 std::visit(
766 visitor: [&](const auto &V) {
767 applyConcreteDbgVariableAttributes(V, DV, *VariableDie);
768 },
769 variants&: DV.asVariant());
770 }
771 return VariableDie;
772}
773
774static const DIType *resolveTypeQualifiers(const DIType *Ty) {
775 while (const auto *DT = dyn_cast_or_null<DIDerivedType>(Val: Ty)) {
776 switch (DT->getTag()) {
777 case dwarf::DW_TAG_typedef:
778 case dwarf::DW_TAG_const_type:
779 case dwarf::DW_TAG_volatile_type:
780 case dwarf::DW_TAG_restrict_type:
781 case dwarf::DW_TAG_atomic_type:
782 Ty = DT->getBaseType();
783 continue;
784 default:
785 return Ty;
786 }
787 }
788 return Ty;
789}
790
791bool DwarfCompileUnit::emitImplicitPointerLocation(const Loc::Single &Single,
792 const DbgVariable &DV,
793 DIE &VariableDie) {
794 const DIExpression *Expr = Single.getExpr();
795 if (!Expr)
796 return false;
797
798 // Only handle the simple case where DW_OP_LLVM_implicit_pointer is the
799 // sole operation (or followed only by DW_OP_LLVM_fragment).
800 //
801 // Multi-level implicit pointers (e.g., int **pp where both levels are
802 // optimized away) would require stacking multiple implicit_pointer ops
803 // in one expression and unwinding them into a chain of artificial DIEs.
804 // This is left for future work.
805 //
806 // Location list support (Loc::Multi) is not yet handled.
807 auto ExprOps = Expr->expr_ops();
808 auto FirstOp = ExprOps.begin();
809 if (FirstOp == ExprOps.end() ||
810 FirstOp->getOp() != dwarf::DW_OP_LLVM_implicit_pointer)
811 return false;
812
813 if (DD->getDwarfVersion() < 4)
814 return false;
815
816 const DbgValueLoc &DVal = Single.getValueLoc();
817 if (DVal.isVariadic())
818 return false;
819
820 assert(!DVal.getLocEntries().empty() &&
821 "Non-variadic value must have one entry");
822 const DbgValueLocEntry &Entry = DVal.getLocEntries()[0];
823
824 // Resolve the variable's type, stripping qualifiers and typedefs,
825 // to find the pointer or reference type underneath.
826 // The verifier rejects cyclic type references, so this loop terminates.
827 const DIDerivedType *PtrTy =
828 dyn_cast_or_null<DIDerivedType>(Val: resolveTypeQualifiers(Ty: DV.getType()));
829 if (!PtrTy)
830 return false;
831
832 if (PtrTy->getTag() != dwarf::DW_TAG_pointer_type &&
833 PtrTy->getTag() != dwarf::DW_TAG_reference_type &&
834 PtrTy->getTag() != dwarf::DW_TAG_rvalue_reference_type)
835 return false;
836
837 const DIType *PointeeTy = PtrTy->getBaseType();
838
839 // Try to reuse an existing artificial DIE for constant integer values.
840 // This avoids duplicate DIEs when multiple pointer variables reference
841 // the same constant (e.g., after ArgumentPromotion promotes the same
842 // struct member for two different pointer parameters).
843 DIE *ArtificialDIEPtr = nullptr;
844 if (Entry.isInt() && PointeeTy) {
845 auto It = ImplicitPointerDIEs.find(Val: {PointeeTy, Entry.getInt()});
846 if (It != ImplicitPointerDIEs.end())
847 ArtificialDIEPtr = It->second;
848 }
849
850 if (!ArtificialDIEPtr) {
851 // Check that the value can be described before creating a DIE for it.
852 if (!Entry.isLocation() && !Entry.isInt() && !Entry.isConstantFP())
853 return false;
854
855 DIE &ProcDIE = createAndAddDIE(Tag: dwarf::DW_TAG_dwarf_procedure, Parent&: getUnitDie());
856
857 if (Entry.isLocation()) {
858 addAddress(Die&: ProcDIE, Attribute: dwarf::DW_AT_location, Location: Entry.getLoc());
859 } else if (Entry.isInt()) {
860 if (PointeeTy)
861 addConstantValue(Die&: ProcDIE, Val: Entry.getInt(), Ty: PointeeTy);
862 } else {
863 addConstantFPValue(Die&: ProcDIE, CFP: Entry.getConstantFP());
864 }
865
866 ArtificialDIEPtr = &ProcDIE;
867
868 // Cache constant entries for de-duplication.
869 if (Entry.isInt() && PointeeTy)
870 ImplicitPointerDIEs.insert(
871 KV: {{PointeeTy, Entry.getInt()}, ArtificialDIEPtr});
872 }
873
874 auto *Loc = new (DIEValueAllocator) DIELoc;
875
876 const unsigned ImplicitPtrOp = DD->getDwarfVersion() >= 5
877 ? dwarf::DW_OP_implicit_pointer
878 : dwarf::DW_OP_GNU_implicit_pointer;
879 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: ImplicitPtrOp);
880
881 Loc->addValue(Alloc&: DIEValueAllocator, Attribute: static_cast<dwarf::Attribute>(0),
882 Form: dwarf::DW_FORM_ref_addr, Value: DIEEntry(*ArtificialDIEPtr));
883
884 addSInt(Die&: *Loc, Form: dwarf::DW_FORM_sdata, Integer: 0);
885
886 addBlock(Die&: VariableDie, Attribute: dwarf::DW_AT_location, Loc);
887 return true;
888}
889
890void DwarfCompileUnit::applyConcreteDbgVariableAttributes(
891 const Loc::Single &Single, const DbgVariable &DV, DIE &VariableDie) {
892 // Handle DW_OP_LLVM_implicit_pointer before normal location emission.
893 if (emitImplicitPointerLocation(Single, DV, VariableDie))
894 return;
895
896 const DbgValueLoc *DVal = &Single.getValueLoc();
897 if (!Single.getExpr())
898 DD->addTargetVariableAttributes(CU&: *this, Die&: VariableDie, TargetAddrSpace: std::nullopt,
899 VarLocKind: DwarfDebug::VariableLocationKind::Register);
900 if (!DVal->isVariadic()) {
901 const DbgValueLocEntry *Entry = DVal->getLocEntries().begin();
902 if (Entry->isLocation()) {
903 addVariableAddress(DV, Die&: VariableDie, Location: Entry->getLoc());
904 } else if (Entry->isInt()) {
905 auto *Expr = Single.getExpr();
906 if (Expr && Expr->getNumElements()) {
907 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
908 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
909 // If there is an expression, emit raw unsigned bytes.
910 DwarfExpr.addFragmentOffset(Expr);
911 DwarfExpr.addUnsignedConstant(Value: Entry->getInt());
912 DwarfExpr.addExpression(Expr);
913 addBlock(Die&: VariableDie, Attribute: dwarf::DW_AT_location, Loc: DwarfExpr.finalize());
914 if (DwarfExpr.TagOffset)
915 addUInt(Die&: VariableDie, Attribute: dwarf::DW_AT_LLVM_tag_offset,
916 Form: dwarf::DW_FORM_data1, Integer: *DwarfExpr.TagOffset);
917 } else
918 addConstantValue(Die&: VariableDie, Val: Entry->getInt(), Ty: DV.getType());
919 } else if (Entry->isConstantFP()) {
920 addConstantFPValue(Die&: VariableDie, CFP: Entry->getConstantFP());
921 } else if (Entry->isConstantInt()) {
922 addConstantValue(Die&: VariableDie, CI: Entry->getConstantInt(), Ty: DV.getType());
923 } else if (Entry->isGlobalAddress()) {
924 auto *Expr = Single.getExpr();
925 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
926 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
927 DwarfExpr.addFragmentOffset(Expr);
928 if (!DwarfExpr.addGlobalAddress(GV: Entry->getGlobalAddress(),
929 Offset: Entry->getGlobalOffset()))
930 return;
931 // A rejected operation leaves the expression built so far in Loc, which
932 // describes some other location rather than none. Drop it instead.
933 if (!DwarfExpr.addExpression(Expr))
934 return;
935 addBlock(Die&: VariableDie, Attribute: dwarf::DW_AT_location, Loc: DwarfExpr.finalize());
936 if (DwarfExpr.TagOffset)
937 addUInt(Die&: VariableDie, Attribute: dwarf::DW_AT_LLVM_tag_offset, Form: dwarf::DW_FORM_data1,
938 Integer: *DwarfExpr.TagOffset);
939 } else if (Entry->isTargetIndexLocation()) {
940 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
941 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
942 const DIBasicType *BT = dyn_cast<DIBasicType>(
943 Val: static_cast<const Metadata *>(DV.getVariable()->getType()));
944 DwarfDebug::emitDebugLocValue(AP: *Asm, BT, Value: *DVal, DwarfExpr);
945 addBlock(Die&: VariableDie, Attribute: dwarf::DW_AT_location, Loc: DwarfExpr.finalize());
946 }
947 return;
948 }
949 // If any of the location entries are registers with the value 0,
950 // then the location is undefined.
951 if (any_of(Range: DVal->getLocEntries(), P: [](const DbgValueLocEntry &Entry) {
952 return Entry.isLocation() && !Entry.getLoc().getReg();
953 }))
954 return;
955 const DIExpression *Expr = Single.getExpr();
956 assert(Expr && "Variadic Debug Value must have an Expression.");
957 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
958 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
959 DwarfExpr.addFragmentOffset(Expr);
960 DIExpressionCursor Cursor(Expr);
961 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
962
963 auto AddEntry = [&](const DbgValueLocEntry &Entry,
964 DIExpressionCursor &Cursor) {
965 if (Entry.isLocation()) {
966 if (!DwarfExpr.addMachineRegExpression(TRI, Expr&: Cursor,
967 MachineReg: Entry.getLoc().getReg()))
968 return false;
969 } else if (Entry.isInt()) {
970 // If there is an expression, emit raw unsigned bytes.
971 DwarfExpr.addUnsignedConstant(Value: Entry.getInt());
972 } else if (Entry.isConstantFP()) {
973 // DwarfExpression does not support arguments wider than 64 bits
974 // (see PR52584).
975 // TODO: Consider chunking expressions containing overly wide
976 // arguments into separate pointer-sized fragment expressions.
977 APInt RawBytes = Entry.getConstantFP()->getValueAPF().bitcastToAPInt();
978 if (RawBytes.getBitWidth() > 64)
979 return false;
980 DwarfExpr.addUnsignedConstant(Value: RawBytes.getZExtValue());
981 } else if (Entry.isConstantInt()) {
982 APInt RawBytes = Entry.getConstantInt()->getValue();
983 if (RawBytes.getBitWidth() > 64)
984 return false;
985 DwarfExpr.addUnsignedConstant(Value: RawBytes.getZExtValue());
986 } else if (Entry.isTargetIndexLocation()) {
987 TargetIndexLocation Loc = Entry.getTargetIndexLocation();
988 // TODO TargetIndexLocation is a target-independent. Currently
989 // only the WebAssembly-specific encoding is supported.
990 assert(Asm->TM.getTargetTriple().isWasm());
991 DwarfExpr.addWasmLocation(Index: Loc.Index, Offset: static_cast<uint64_t>(Loc.Offset));
992 } else if (Entry.isGlobalAddress()) {
993 if (!DwarfExpr.addGlobalAddress(GV: Entry.getGlobalAddress(),
994 Offset: Entry.getGlobalOffset()))
995 return false;
996 } else {
997 llvm_unreachable("Unsupported Entry type.");
998 }
999 return true;
1000 };
1001
1002 if (!DwarfExpr.addExpression(
1003 Expr: std::move(Cursor),
1004 InsertArg: [&](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
1005 return AddEntry(DVal->getLocEntries()[Idx], Cursor);
1006 }))
1007 return;
1008
1009 // Now attach the location information to the DIE.
1010 addBlock(Die&: VariableDie, Attribute: dwarf::DW_AT_location, Loc: DwarfExpr.finalize());
1011 if (DwarfExpr.TagOffset)
1012 addUInt(Die&: VariableDie, Attribute: dwarf::DW_AT_LLVM_tag_offset, Form: dwarf::DW_FORM_data1,
1013 Integer: *DwarfExpr.TagOffset);
1014}
1015
1016void DwarfCompileUnit::applyConcreteDbgVariableAttributes(
1017 const Loc::Multi &Multi, const DbgVariable &DV, DIE &VariableDie) {
1018 addLocationList(Die&: VariableDie, Attribute: dwarf::DW_AT_location,
1019 Index: Multi.getDebugLocListIndex());
1020 auto TagOffset = Multi.getDebugLocListTagOffset();
1021 if (TagOffset)
1022 addUInt(Die&: VariableDie, Attribute: dwarf::DW_AT_LLVM_tag_offset, Form: dwarf::DW_FORM_data1,
1023 Integer: *TagOffset);
1024}
1025
1026void DwarfCompileUnit::applyConcreteDbgVariableAttributes(const Loc::MMI &MMI,
1027 const DbgVariable &DV,
1028 DIE &VariableDie) {
1029 std::optional<unsigned> TargetAddrSpace;
1030 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1031 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1032 for (const auto &Fragment : MMI.getFrameIndexExprs()) {
1033 Register FrameReg;
1034 const DIExpression *Expr = Fragment.Expr;
1035 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
1036 StackOffset Offset =
1037 TFI->getFrameIndexReference(MF: *Asm->MF, FI: Fragment.FI, FrameReg);
1038 DwarfExpr.addFragmentOffset(Expr);
1039
1040 auto *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1041 SmallVector<uint64_t, 8> Ops;
1042 TRI->getOffsetOpcodes(Offset, Ops);
1043
1044 Expr = DD->adjustExpressionForTarget(Expr, TargetAddrSpace);
1045 if (Expr)
1046 Ops.append(in_start: Expr->elements_begin(), in_end: Expr->elements_end());
1047 DIExpressionCursor Cursor(Ops);
1048 DwarfExpr.setMemoryLocationKind();
1049 if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
1050 addOpAddress(Die&: *Loc, Sym: FrameSymbol);
1051 else
1052 DwarfExpr.addMachineRegExpression(
1053 TRI: *Asm->MF->getSubtarget().getRegisterInfo(), Expr&: Cursor, MachineReg: FrameReg);
1054 DwarfExpr.addExpression(Expr: std::move(Cursor));
1055 }
1056 DD->addTargetVariableAttributes(CU&: *this, Die&: VariableDie, TargetAddrSpace,
1057 VarLocKind: DwarfDebug::VariableLocationKind::FrameIndex);
1058 addBlock(Die&: VariableDie, Attribute: dwarf::DW_AT_location, Loc: DwarfExpr.finalize());
1059 if (DwarfExpr.TagOffset)
1060 addUInt(Die&: VariableDie, Attribute: dwarf::DW_AT_LLVM_tag_offset, Form: dwarf::DW_FORM_data1,
1061 Integer: *DwarfExpr.TagOffset);
1062}
1063
1064void DwarfCompileUnit::applyConcreteDbgVariableAttributes(
1065 const Loc::EntryValue &EntryValue, const DbgVariable &DV,
1066 DIE &VariableDie) {
1067 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1068 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1069 // Emit each expression as: EntryValue(Register) <other ops> <Fragment>.
1070 for (auto [Register, Expr] : EntryValue.EntryValues) {
1071 DwarfExpr.addFragmentOffset(Expr: &Expr);
1072 DIExpressionCursor Cursor(Expr.getElements());
1073 DwarfExpr.beginEntryValueExpression(ExprCursor&: Cursor);
1074 DwarfExpr.addMachineRegExpression(
1075 TRI: *Asm->MF->getSubtarget().getRegisterInfo(), Expr&: Cursor, MachineReg: Register);
1076 DwarfExpr.addExpression(Expr: std::move(Cursor));
1077 }
1078 addBlock(Die&: VariableDie, Attribute: dwarf::DW_AT_location, Loc: DwarfExpr.finalize());
1079}
1080
1081void DwarfCompileUnit::applyConcreteDbgVariableAttributes(
1082 const std::monostate &, const DbgVariable &DV, DIE &VariableDie) {}
1083
1084DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
1085 const LexicalScope &Scope,
1086 DIE *&ObjectPointer) {
1087 auto Var = constructVariableDIE(DV, Abstract: Scope.isAbstractScope());
1088 if (DV.isObjectPointer())
1089 ObjectPointer = Var;
1090 return Var;
1091}
1092
1093DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
1094 const LexicalScope &Scope) {
1095 auto LabelDie = DIE::get(Alloc&: DIEValueAllocator, Tag: DL.getTag());
1096 insertDIE(Desc: DL.getLabel(), D: LabelDie);
1097 DL.setDIE(*LabelDie);
1098
1099 if (Scope.isAbstractScope())
1100 applyLabelAttributes(Label: DL, LabelDie&: *LabelDie);
1101
1102 return LabelDie;
1103}
1104
1105/// Return all DIVariables that appear in count: expressions.
1106static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
1107 SmallVector<const DIVariable *, 2> Result;
1108 auto *Array = dyn_cast<DICompositeType>(Val: Var->getType());
1109 if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
1110 return Result;
1111 if (auto *DLVar = Array->getDataLocation())
1112 Result.push_back(Elt: DLVar);
1113 if (auto *AsVar = Array->getAssociated())
1114 Result.push_back(Elt: AsVar);
1115 if (auto *AlVar = Array->getAllocated())
1116 Result.push_back(Elt: AlVar);
1117 for (auto *El : Array->getElements()) {
1118 if (auto *Subrange = dyn_cast<DISubrange>(Val: El)) {
1119 if (auto Count = Subrange->getCount())
1120 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(Val&: Count))
1121 Result.push_back(Elt: Dependency);
1122 if (auto LB = Subrange->getLowerBound())
1123 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(Val&: LB))
1124 Result.push_back(Elt: Dependency);
1125 if (auto UB = Subrange->getUpperBound())
1126 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(Val&: UB))
1127 Result.push_back(Elt: Dependency);
1128 if (auto ST = Subrange->getStride())
1129 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(Val&: ST))
1130 Result.push_back(Elt: Dependency);
1131 } else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(Val: El)) {
1132 if (auto Count = GenericSubrange->getCount())
1133 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(Val&: Count))
1134 Result.push_back(Elt: Dependency);
1135 if (auto LB = GenericSubrange->getLowerBound())
1136 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(Val&: LB))
1137 Result.push_back(Elt: Dependency);
1138 if (auto UB = GenericSubrange->getUpperBound())
1139 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(Val&: UB))
1140 Result.push_back(Elt: Dependency);
1141 if (auto ST = GenericSubrange->getStride())
1142 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(Val&: ST))
1143 Result.push_back(Elt: Dependency);
1144 }
1145 }
1146 return Result;
1147}
1148
1149/// Sort local variables so that variables appearing inside of helper
1150/// expressions come first.
1151static SmallVector<DbgVariable *, 8>
1152sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
1153 SmallVector<DbgVariable *, 8> Result;
1154 SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
1155 // Map back from a DIVariable to its containing DbgVariable.
1156 SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
1157 // Set of DbgVariables in Result.
1158 SmallDenseSet<DbgVariable *, 8> Visited;
1159 // For cycle detection.
1160 SmallDenseSet<DbgVariable *, 8> Visiting;
1161
1162 // Initialize the worklist and the DIVariable lookup table.
1163 for (auto *Var : reverse(C&: Input)) {
1164 DbgVar.insert(KV: {Var->getVariable(), Var});
1165 WorkList.push_back(Elt: {Var, 0});
1166 }
1167
1168 // Perform a stable topological sort by doing a DFS.
1169 while (!WorkList.empty()) {
1170 auto Item = WorkList.back();
1171 DbgVariable *Var = Item.getPointer();
1172 bool visitedAllDependencies = Item.getInt();
1173 WorkList.pop_back();
1174
1175 assert(Var);
1176
1177 // Already handled.
1178 if (Visited.count(V: Var))
1179 continue;
1180
1181 // Add to Result if all dependencies are visited.
1182 if (visitedAllDependencies) {
1183 Visited.insert(V: Var);
1184 Result.push_back(Elt: Var);
1185 continue;
1186 }
1187
1188 // Detect cycles.
1189 auto Res = Visiting.insert(V: Var);
1190 if (!Res.second) {
1191 assert(false && "dependency cycle in local variables");
1192 return Result;
1193 }
1194
1195 // Push dependencies and this node onto the worklist, so that this node is
1196 // visited again after all of its dependencies are handled.
1197 WorkList.push_back(Elt: {Var, 1});
1198 for (const auto *Dependency : dependencies(Var)) {
1199 // Don't add dependency if it is in a different lexical scope or a global.
1200 if (const auto *Dep = dyn_cast<const DILocalVariable>(Val: Dependency))
1201 if (DbgVariable *Var = DbgVar.lookup(Val: Dep))
1202 WorkList.push_back(Elt: {Var, 0});
1203 }
1204 }
1205 return Result;
1206}
1207
1208DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
1209 const Function &F,
1210 LexicalScope *Scope,
1211 MCSymbol *LineTableSym) {
1212 DIE &ScopeDIE = updateSubprogramScopeDIE(SP: Sub, F, LineTableSym);
1213
1214 if (Scope) {
1215 assert(!Scope->getInlinedAt());
1216 assert(!Scope->isAbstractScope());
1217 // Collect lexical scope children first.
1218 // ObjectPointer might be a local (non-argument) local variable if it's a
1219 // block's synthetic this pointer.
1220 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
1221 addDIEEntry(Die&: ScopeDIE, Attribute: dwarf::DW_AT_object_pointer, Entry&: *ObjectPointer);
1222 }
1223
1224 // If this is a variadic function, add an unspecified parameter.
1225 auto *SPTy = Sub->getType();
1226 if (!SPTy)
1227 return ScopeDIE;
1228
1229 DITypeArray FnArgs = SPTy->getTypeArray();
1230
1231 // If we have a single element of null, it is a function that returns void.
1232 // If we have more than one elements and the last one is null, it is a
1233 // variadic function.
1234 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
1235 !includeMinimalInlineScopes())
1236 ScopeDIE.addChild(
1237 Child: DIE::get(Alloc&: DIEValueAllocator, Tag: dwarf::DW_TAG_unspecified_parameters));
1238
1239 return ScopeDIE;
1240}
1241
1242DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
1243 DIE &ScopeDIE) {
1244 DIE *ObjectPointer = nullptr;
1245
1246 // Emit function arguments (order is significant).
1247 auto Vars = DU->getScopeVariables().lookup(Val: Scope);
1248 for (auto &DV : Vars.Args)
1249 ScopeDIE.addChild(Child: constructVariableDIE(DV&: *DV.second, Scope: *Scope, ObjectPointer));
1250
1251 // Emit local variables.
1252 auto Locals = sortLocalVars(Input&: Vars.Locals);
1253 for (DbgVariable *DV : Locals)
1254 ScopeDIE.addChild(Child: constructVariableDIE(DV&: *DV, Scope: *Scope, ObjectPointer));
1255
1256 // Emit labels.
1257 for (DbgLabel *DL : DU->getScopeLabels().lookup(Val: Scope))
1258 ScopeDIE.addChild(Child: constructLabelDIE(DL&: *DL, Scope: *Scope));
1259
1260 // Track other local entities (skipped in gmlt-like data).
1261 // This creates mapping between CU and a set of local declarations that
1262 // should be emitted for subprograms in this CU.
1263 if (!includeMinimalInlineScopes() && !Scope->getInlinedAt()) {
1264 auto &LocalDecls = DD->getLocalDeclsForScope(S: Scope->getScopeNode());
1265 DeferredLocalDecls.insert_range(R&: LocalDecls);
1266 }
1267
1268 // Emit inner lexical scopes.
1269 auto skipLexicalScope = [this](LexicalScope *S) -> bool {
1270 const DILocalScope *DS = S->getScopeNode();
1271 if (isa<DISubprogram>(Val: DS))
1272 return false;
1273 // Create a concrete lexical block for a scope with an abstract lexical
1274 // block to ensure visibility of scope-local types and static variables
1275 // within the scope range.
1276 if (getAbstractScopeDIEs().lookup(Val: DS))
1277 return false;
1278 auto Vars = DU->getScopeVariables().lookup(Val: S);
1279 if (!Vars.Args.empty() || !Vars.Locals.empty())
1280 return false;
1281 return includeMinimalInlineScopes() ||
1282 DD->getLocalDeclsForScope(S: DS).empty();
1283 };
1284 for (LexicalScope *LS : Scope->getChildren()) {
1285 // If the lexical block doesn't have non-scope children or global
1286 // variables scoped to it, skip its emission and put its children directly
1287 // to the parent scope.
1288 if (skipLexicalScope(LS))
1289 createAndAddScopeChildren(Scope: LS, ScopeDIE);
1290 else
1291 constructScopeDIE(Scope: LS, ParentScopeDIE&: ScopeDIE);
1292 }
1293
1294 return ObjectPointer;
1295}
1296
1297DIE &DwarfCompileUnit::getOrCreateAbstractSubprogramDIE(
1298 const DISubprogram *SP) {
1299 if (auto *AbsDef = getAbstractScopeDIEs().lookup(Val: SP))
1300 return *AbsDef;
1301
1302 auto [ContextDIE, ContextCU] = getOrCreateAbstractSubprogramContextDIE(SP);
1303 return createAbstractSubprogramDIE(SP, ContextDIE, ContextCU);
1304}
1305
1306DIE &DwarfCompileUnit::createAbstractSubprogramDIE(
1307 const DISubprogram *SP, DIE *ContextDIE, DwarfCompileUnit *ContextCU) {
1308 // Passing null as the associated node because the abstract definition
1309 // shouldn't be found by lookup.
1310 DIE &AbsDef = ContextCU->createAndAddDIE(Tag: dwarf::DW_TAG_subprogram,
1311 Parent&: *ContextDIE, N: nullptr);
1312
1313 // Store the DIE before creating children.
1314 ContextCU->getAbstractScopeDIEs()[SP] = &AbsDef;
1315
1316 ContextCU->applySubprogramAttributesToDefinition(SP, SPDie&: AbsDef);
1317 ContextCU->addSInt(Die&: AbsDef, Attribute: dwarf::DW_AT_inline,
1318 Form: DD->getDwarfVersion() <= 4 ? std::optional<dwarf::Form>()
1319 : dwarf::DW_FORM_implicit_const,
1320 Integer: dwarf::DW_INL_inlined);
1321
1322 return AbsDef;
1323}
1324
1325std::pair<DIE *, DwarfCompileUnit *>
1326DwarfCompileUnit::getOrCreateAbstractSubprogramContextDIE(
1327 const DISubprogram *SP) {
1328 bool Minimal = includeMinimalInlineScopes();
1329 bool IgnoreScope = shouldPlaceInUnitDIE(SP, Minimal);
1330 DIE *ContextDIE = getOrCreateSubprogramContextDIE(SP, IgnoreScope);
1331
1332 if (auto *SPDecl = SP->getDeclaration())
1333 if (!Minimal)
1334 getOrCreateSubprogramDIE(SP: SPDecl, F: nullptr);
1335
1336 // The scope may be shared with a subprogram that has already been
1337 // constructed in another CU, in which case we need to construct this
1338 // subprogram in the same CU.
1339 auto *ContextCU = IgnoreScope ? this : DD->lookupCU(Die: ContextDIE->getUnitDie());
1340
1341 return std::make_pair(x&: ContextDIE, y&: ContextCU);
1342}
1343
1344void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
1345 LexicalScope *Scope) {
1346 auto *SP = cast<DISubprogram>(Val: Scope->getScopeNode());
1347
1348 // Populate subprogram DIE only once.
1349 if (!getFinalizedAbstractSubprograms().insert(Ptr: SP).second)
1350 return;
1351
1352 auto [ContextDIE, ContextCU] = getOrCreateAbstractSubprogramContextDIE(SP);
1353 DIE *AbsDef = getAbstractScopeDIEs().lookup(Val: SP);
1354 if (!AbsDef)
1355 AbsDef = &createAbstractSubprogramDIE(SP, ContextDIE, ContextCU);
1356
1357 if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, ScopeDIE&: *AbsDef))
1358 ContextCU->addDIEEntry(Die&: *AbsDef, Attribute: dwarf::DW_AT_object_pointer,
1359 Entry&: *ObjectPointer);
1360}
1361
1362bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const {
1363 return DD->getDwarfVersion() <= 4 && !DD->tuneForLLDB();
1364}
1365
1366dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const {
1367 if (!useGNUAnalogForDwarf5Feature())
1368 return Tag;
1369 switch (Tag) {
1370 case dwarf::DW_TAG_call_site:
1371 return dwarf::DW_TAG_GNU_call_site;
1372 case dwarf::DW_TAG_call_site_parameter:
1373 return dwarf::DW_TAG_GNU_call_site_parameter;
1374 default:
1375 llvm_unreachable("DWARF5 tag with no GNU analog");
1376 }
1377}
1378
1379dwarf::Attribute
1380DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const {
1381 if (!useGNUAnalogForDwarf5Feature())
1382 return Attr;
1383 switch (Attr) {
1384 case dwarf::DW_AT_call_all_calls:
1385 return dwarf::DW_AT_GNU_all_call_sites;
1386 case dwarf::DW_AT_call_target:
1387 return dwarf::DW_AT_GNU_call_site_target;
1388 case dwarf::DW_AT_call_target_clobbered:
1389 return dwarf::DW_AT_GNU_call_site_target_clobbered;
1390 case dwarf::DW_AT_call_origin:
1391 return dwarf::DW_AT_abstract_origin;
1392 case dwarf::DW_AT_call_return_pc:
1393 return dwarf::DW_AT_low_pc;
1394 case dwarf::DW_AT_call_value:
1395 return dwarf::DW_AT_GNU_call_site_value;
1396 case dwarf::DW_AT_call_tail_call:
1397 return dwarf::DW_AT_GNU_tail_call;
1398 default:
1399 llvm_unreachable("DWARF5 attribute with no GNU analog");
1400 }
1401}
1402
1403dwarf::LocationAtom
1404DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const {
1405 if (!useGNUAnalogForDwarf5Feature())
1406 return Loc;
1407 switch (Loc) {
1408 case dwarf::DW_OP_entry_value:
1409 return dwarf::DW_OP_GNU_entry_value;
1410 default:
1411 llvm_unreachable("DWARF5 location atom with no GNU analog");
1412 }
1413}
1414
1415DIE &DwarfCompileUnit::constructCallSiteEntryDIE(
1416 DIE &ScopeDIE, const DISubprogram *CalleeSP, const Function *CalleeF,
1417 bool IsTail, const MCSymbol *PCAddr, const MCSymbol *CallAddr,
1418 MachineLocation CallTarget, int64_t Offset, DIType *AllocSiteTy) {
1419 // Insert a call site entry DIE within ScopeDIE.
1420 DIE &CallSiteDIE = createAndAddDIE(Tag: getDwarf5OrGNUTag(Tag: dwarf::DW_TAG_call_site),
1421 Parent&: ScopeDIE, N: nullptr);
1422
1423 // A valid register in CallTarget indicates an indirect call.
1424 if (CallTarget.getReg()) {
1425 // Add a DW_AT_call_target location expression describing the location of
1426 // the address of the target function. If any register in the expression
1427 // (i.e., the single register we currently handle) is volatile we must use
1428 // DW_AT_call_target_clobbered instead.
1429 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1430 dwarf::Attribute Attribute = getDwarf5OrGNUAttr(
1431 Attr: TRI.isCalleeSavedPhysReg(PhysReg: CallTarget.getReg(), MF: *Asm->MF)
1432 ? dwarf::DW_AT_call_target
1433 : dwarf::DW_AT_call_target_clobbered);
1434
1435 // CallTarget is the location of the address of an indirect call. The
1436 // location may be indirect, modified by Offset.
1437 if (CallTarget.isIndirect())
1438 addMemoryLocation(Die&: CallSiteDIE, Attribute, Location: CallTarget, Offset);
1439 else
1440 addAddress(Die&: CallSiteDIE, Attribute, Location: CallTarget);
1441 } else if (CalleeSP) {
1442 DIE *CalleeDIE = getOrCreateSubprogramDIE(SP: CalleeSP, F: CalleeF);
1443 assert(CalleeDIE && "Could not create DIE for call site entry origin");
1444 addLinkageNamesToDeclarations(DD: *DD, CalleeSP: *CalleeSP, CalleeDIE&: *CalleeDIE);
1445
1446 addDIEEntry(Die&: CallSiteDIE, Attribute: getDwarf5OrGNUAttr(Attr: dwarf::DW_AT_call_origin),
1447 Entry&: *CalleeDIE);
1448 }
1449
1450 if (IsTail) {
1451 // Attach DW_AT_call_tail_call to tail calls for standards compliance.
1452 addFlag(Die&: CallSiteDIE, Attribute: getDwarf5OrGNUAttr(Attr: dwarf::DW_AT_call_tail_call));
1453
1454 // Attach the address of the branch instruction to allow the debugger to
1455 // show where the tail call occurred. This attribute has no GNU analog.
1456 //
1457 // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4
1458 // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call
1459 // site entries to figure out the PC of tail-calling branch instructions.
1460 // This means it doesn't need the compiler to emit DW_AT_call_pc, so we
1461 // don't emit it here.
1462 //
1463 // There's no need to tie non-GDB debuggers to this non-standardness, as it
1464 // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit
1465 // the standard DW_AT_call_pc info.
1466 if (!useGNUAnalogForDwarf5Feature())
1467 addLabelAddress(Die&: CallSiteDIE, Attribute: dwarf::DW_AT_call_pc, Label: CallAddr);
1468 }
1469
1470 // Attach the return PC to allow the debugger to disambiguate call paths
1471 // from one function to another.
1472 //
1473 // The return PC is only really needed when the call /isn't/ a tail call, but
1474 // GDB expects it in DWARF4 mode, even for tail calls (see the comment above
1475 // the DW_AT_call_pc emission logic for an explanation).
1476 if (!IsTail || useGNUAnalogForDwarf5Feature()) {
1477 assert(PCAddr && "Missing return PC information for a call");
1478 addLabelAddress(Die&: CallSiteDIE,
1479 Attribute: getDwarf5OrGNUAttr(Attr: dwarf::DW_AT_call_return_pc), Label: PCAddr);
1480 }
1481
1482 if (AllocSiteTy)
1483 addType(Entity&: CallSiteDIE, Ty: AllocSiteTy, Attribute: dwarf::DW_AT_LLVM_alloc_type);
1484
1485 return CallSiteDIE;
1486}
1487
1488void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
1489 DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
1490 for (const auto &Param : Params) {
1491 unsigned Register = Param.getRegister();
1492 auto CallSiteDieParam =
1493 DIE::get(Alloc&: DIEValueAllocator,
1494 Tag: getDwarf5OrGNUTag(Tag: dwarf::DW_TAG_call_site_parameter));
1495 insertDIE(D: CallSiteDieParam);
1496 addAddress(Die&: *CallSiteDieParam, Attribute: dwarf::DW_AT_location,
1497 Location: MachineLocation(Register));
1498
1499 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1500 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1501 DwarfExpr.setCallSiteParamValueFlag();
1502
1503 DwarfDebug::emitDebugLocValue(AP: *Asm, BT: nullptr, Value: Param.getValue(), DwarfExpr);
1504
1505 addBlock(Die&: *CallSiteDieParam, Attribute: getDwarf5OrGNUAttr(Attr: dwarf::DW_AT_call_value),
1506 Loc: DwarfExpr.finalize());
1507
1508 CallSiteDIE.addChild(Child: CallSiteDieParam);
1509 }
1510}
1511
1512DIE *DwarfCompileUnit::constructImportedEntityDIE(
1513 const DIImportedEntity *Module) {
1514 DIE *IMDie = DIE::get(Alloc&: DIEValueAllocator, Tag: Module->getTag());
1515 insertDIE(Desc: Module, D: IMDie);
1516 DIE *EntityDie;
1517 auto *Entity = Module->getEntity();
1518 if (auto *NS = dyn_cast<DINamespace>(Val: Entity))
1519 EntityDie = getOrCreateNameSpace(NS);
1520 else if (auto *M = dyn_cast<DIModule>(Val: Entity))
1521 EntityDie = getOrCreateModule(M);
1522 else if (auto *SP = dyn_cast<DISubprogram>(Val: Entity)) {
1523 // If there is an abstract subprogram, refer to it. Note that this assumes
1524 // that all the abstract subprograms have been already created (which is
1525 // correct until imported entities get emitted in DwarfDebug::endModule()).
1526 if (auto *AbsSPDie = getAbstractScopeDIEs().lookup(Val: SP))
1527 EntityDie = AbsSPDie;
1528 else
1529 EntityDie = getOrCreateSubprogramDIE(SP, F: nullptr);
1530 } else if (auto *T = dyn_cast<DIType>(Val: Entity))
1531 EntityDie = getOrCreateTypeDIE(TyNode: T);
1532 else if (auto *GV = dyn_cast<DIGlobalVariable>(Val: Entity))
1533 EntityDie = getOrCreateGlobalVariableDIE(GV, GlobalExprs: {});
1534 else if (auto *IE = dyn_cast<DIImportedEntity>(Val: Entity))
1535 EntityDie = getOrCreateImportedEntityDIE(IE);
1536 else
1537 EntityDie = getDIE(D: Entity);
1538 assert(EntityDie);
1539 addSourceLine(Die&: *IMDie, Line: Module->getLine(), /*Column*/ 0, File: Module->getFile());
1540 addDIEEntry(Die&: *IMDie, Attribute: dwarf::DW_AT_import, Entry&: *EntityDie);
1541 StringRef Name = Module->getName();
1542 if (!Name.empty()) {
1543 addString(Die&: *IMDie, Attribute: dwarf::DW_AT_name, Str: Name);
1544
1545 // FIXME: if consumers ever start caring about handling
1546 // unnamed import declarations such as `using ::nullptr_t`
1547 // or `using namespace std::ranges`, we could add the
1548 // import declaration into the accelerator table with the
1549 // name being the one of the entity being imported.
1550 DD->addAccelNamespace(Unit: *this, NameTableKind: CUNode->getNameTableKind(), Name, Die: *IMDie);
1551 }
1552
1553 // This is for imported module with renamed entities (such as variables and
1554 // subprograms).
1555 DINodeArray Elements = Module->getElements();
1556 for (const auto *Element : Elements) {
1557 if (!Element)
1558 continue;
1559 IMDie->addChild(
1560 Child: constructImportedEntityDIE(Module: cast<DIImportedEntity>(Val: Element)));
1561 }
1562
1563 return IMDie;
1564}
1565
1566DIE *DwarfCompileUnit::getOrCreateImportedEntityDIE(
1567 const DIImportedEntity *IE) {
1568
1569 // Check for pre-existence.
1570 if (DIE *Die = getDIE(D: IE))
1571 return Die;
1572
1573 DIE *ContextDIE = getOrCreateContextDIE(Ty: IE->getScope());
1574 assert(ContextDIE && "Empty scope for the imported entity!");
1575
1576 DIE *IMDie = constructImportedEntityDIE(Module: IE);
1577 ContextDIE->addChild(Child: IMDie);
1578 return IMDie;
1579}
1580
1581void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
1582 DIE *D = getDIE(D: SP);
1583 if (DIE *AbsSPDIE = getAbstractScopeDIEs().lookup(Val: SP)) {
1584 if (D)
1585 // If this subprogram has an abstract definition, reference that
1586 addDIEEntry(Die&: *D, Attribute: dwarf::DW_AT_abstract_origin, Entry&: *AbsSPDIE);
1587 } else {
1588 assert(D || includeMinimalInlineScopes());
1589 if (D)
1590 // And attach the attributes
1591 applySubprogramAttributesToDefinition(SP, SPDie&: *D);
1592 }
1593}
1594
1595void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
1596 DbgEntity *AbsEntity = getExistingAbstractEntity(Node: Entity->getEntity());
1597
1598 auto *Die = Entity->getDIE();
1599 /// Label may be used to generate DW_AT_low_pc, so put it outside
1600 /// if/else block.
1601 const DbgLabel *Label = nullptr;
1602 if (AbsEntity && AbsEntity->getDIE()) {
1603 addDIEEntry(Die&: *Die, Attribute: dwarf::DW_AT_abstract_origin, Entry&: *AbsEntity->getDIE());
1604 Label = dyn_cast<const DbgLabel>(Val: Entity);
1605 } else {
1606 if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Val: Entity))
1607 applyCommonDbgVariableAttributes(Var: *Var, VariableDie&: *Die);
1608 else if ((Label = dyn_cast<const DbgLabel>(Val: Entity)))
1609 applyLabelAttributes(Label: *Label, LabelDie&: *Die);
1610 else
1611 llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
1612 }
1613
1614 if (!Label)
1615 return;
1616
1617 const auto *Sym = Label->getSymbol();
1618 if (!Sym)
1619 return;
1620
1621 addLabelAddress(Die&: *Die, Attribute: dwarf::DW_AT_low_pc, Label: Sym);
1622
1623 // A TAG_label with a name and an AT_low_pc must be placed in debug_names.
1624 if (StringRef Name = Label->getName(); !Name.empty())
1625 getDwarfDebug().addAccelName(Unit: *this, NameTableKind: CUNode->getNameTableKind(), Name, Die: *Die);
1626}
1627
1628void DwarfCompileUnit::attachLexicalScopesAbstractOrigins() {
1629 auto AttachAO = [&](const DILocalScope *LS, DIE *ScopeDIE) {
1630 if (auto *AbsLSDie = getAbstractScopeDIEs().lookup(Val: LS))
1631 addDIEEntry(Die&: *ScopeDIE, Attribute: dwarf::DW_AT_abstract_origin, Entry&: *AbsLSDie);
1632 };
1633
1634 for (auto [LScope, ScopeDIE] : LexicalBlockDIEs)
1635 AttachAO(LScope, ScopeDIE);
1636 for (auto &[LScope, ScopeDIEs] : InlinedLocalScopeDIEs)
1637 for (auto *ScopeDIE : ScopeDIEs)
1638 AttachAO(LScope, ScopeDIE);
1639}
1640
1641DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
1642 auto &AbstractEntities = getAbstractEntities();
1643 auto I = AbstractEntities.find(Val: Node);
1644 if (I != AbstractEntities.end())
1645 return I->second.get();
1646 return nullptr;
1647}
1648
1649void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
1650 LexicalScope *Scope) {
1651 assert(Scope && Scope->isAbstractScope());
1652 auto &Entity = getAbstractEntities()[Node];
1653 if (isa<const DILocalVariable>(Val: Node)) {
1654 Entity = std::make_unique<DbgVariable>(args: cast<const DILocalVariable>(Val: Node),
1655 args: nullptr /* IA */);
1656 DU->addScopeVariable(LS: Scope, Var: cast<DbgVariable>(Val: Entity.get()));
1657 } else if (isa<const DILabel>(Val: Node)) {
1658 Entity = std::make_unique<DbgLabel>(
1659 args: cast<const DILabel>(Val: Node), args: nullptr /* IA */);
1660 DU->addScopeLabel(LS: Scope, Label: cast<DbgLabel>(Val: Entity.get()));
1661 }
1662}
1663
1664void DwarfCompileUnit::emitHeader(bool UseOffsets) {
1665 // Don't bother labeling the .dwo unit, as its offset isn't used.
1666 if (!Skeleton && !DD->useSectionsAsReferences()) {
1667 LabelBegin = Asm->createTempSymbol(Name: "cu_begin");
1668 Asm->OutStreamer->emitLabel(Symbol: LabelBegin);
1669 }
1670
1671 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
1672 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
1673 : dwarf::DW_UT_compile;
1674 DwarfUnit::emitCommonHeader(UseOffsets, UT);
1675 if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
1676 Asm->emitInt64(Value: getDWOId());
1677}
1678
1679bool DwarfCompileUnit::hasDwarfPubSections() const {
1680 if (!DD->shouldEmitDwarfPubSections())
1681 return false;
1682
1683 switch (CUNode->getNameTableKind()) {
1684 case DICompileUnit::DebugNameTableKind::None:
1685 return false;
1686 // Opting in to GNU Pubnames/types overrides the default to ensure these are
1687 // generated for things like Gold's gdb_index generation.
1688 case DICompileUnit::DebugNameTableKind::GNU:
1689 return true;
1690 case DICompileUnit::DebugNameTableKind::Apple:
1691 return false;
1692 case DICompileUnit::DebugNameTableKind::Default:
1693 return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
1694 !CUNode->isDebugDirectivesOnly() &&
1695 DD->getAccelTableKind() != AccelTableKind::Apple &&
1696 DD->getDwarfVersion() < 5;
1697 }
1698 llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
1699}
1700
1701/// addGlobalName - Add a new global name to the compile unit.
1702void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
1703 const DIScope *Context) {
1704 if (!hasDwarfPubSections())
1705 return;
1706 std::string FullName = getParentContextString(Context) + Name.str();
1707 GlobalNames[FullName] = &Die;
1708}
1709
1710void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
1711 const DIScope *Context) {
1712 if (!hasDwarfPubSections())
1713 return;
1714 std::string FullName = getParentContextString(Context) + Name.str();
1715 // Insert, allowing the entry to remain as-is if it's already present
1716 // This way the CU-level type DIE is preferred over the "can't describe this
1717 // type as a unit offset because it's not really in the CU at all, it's only
1718 // in a type unit"
1719 GlobalNames.insert(KV: std::make_pair(x: std::move(FullName), y: &getUnitDie()));
1720}
1721
1722/// Add a new global type to the unit.
1723void DwarfCompileUnit::addGlobalTypeImpl(const DIType *Ty, const DIE &Die,
1724 const DIScope *Context) {
1725 if (!hasDwarfPubSections())
1726 return;
1727 std::string FullName = getParentContextString(Context) + Ty->getName().str();
1728 GlobalTypes[FullName] = &Die;
1729}
1730
1731void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
1732 const DIScope *Context) {
1733 if (!hasDwarfPubSections())
1734 return;
1735 std::string FullName = getParentContextString(Context) + Ty->getName().str();
1736 // Insert, allowing the entry to remain as-is if it's already present
1737 // This way the CU-level type DIE is preferred over the "can't describe this
1738 // type as a unit offset because it's not really in the CU at all, it's only
1739 // in a type unit"
1740 GlobalTypes.insert(KV: std::make_pair(x: std::move(FullName), y: &getUnitDie()));
1741}
1742
1743void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
1744 MachineLocation Location) {
1745 auto *Single = std::get_if<Loc::Single>(ptr: &DV);
1746 if (Single && Single->getExpr())
1747 addComplexAddress(DIExpr: Single->getExpr(), Die, Attribute: dwarf::DW_AT_location, Location);
1748 else
1749 addAddress(Die, Attribute: dwarf::DW_AT_location, Location);
1750}
1751
1752void DwarfCompileUnit::addLocationWithExpr(DIE &Die, dwarf::Attribute Attribute,
1753 const MachineLocation &Location,
1754 ArrayRef<uint64_t> Expr) {
1755 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1756 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1757 if (Location.isIndirect())
1758 DwarfExpr.setMemoryLocationKind();
1759
1760 DIExpressionCursor Cursor(Expr);
1761 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1762 if (!DwarfExpr.addMachineRegExpression(TRI, Expr&: Cursor, MachineReg: Location.getReg()))
1763 return;
1764 DwarfExpr.addExpression(Expr: std::move(Cursor));
1765
1766 // Now attach the location information to the DIE.
1767 addBlock(Die, Attribute, Loc: DwarfExpr.finalize());
1768
1769 if (DwarfExpr.TagOffset)
1770 addUInt(Die, Attribute: dwarf::DW_AT_LLVM_tag_offset, Form: dwarf::DW_FORM_data1,
1771 Integer: *DwarfExpr.TagOffset);
1772}
1773
1774/// Add an address attribute to a die based on the location provided.
1775void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
1776 const MachineLocation &Location) {
1777 addLocationWithExpr(Die, Attribute, Location, Expr: {});
1778}
1779
1780/// Add a memory location exprloc to \p DIE with attribute \p Attribute
1781/// at \p Location + \p Offset.
1782void DwarfCompileUnit::addMemoryLocation(DIE &Die, dwarf::Attribute Attribute,
1783 const MachineLocation &Location,
1784 int64_t Offset) {
1785 assert(Location.isIndirect() && "Memory loc should be indirect");
1786 SmallVector<uint64_t, 3> Ops;
1787 DIExpression::appendOffset(Ops, Offset);
1788 addLocationWithExpr(Die, Attribute, Location, Expr: Ops);
1789}
1790
1791/// Start with the address based on the location provided, and generate the
1792/// DWARF information necessary to find the actual variable given the extra
1793/// address information encoded in the DbgVariable, starting from the starting
1794/// location. Add the DWARF information to the die.
1795void DwarfCompileUnit::addComplexAddress(const DIExpression *DIExpr, DIE &Die,
1796 dwarf::Attribute Attribute,
1797 const MachineLocation &Location) {
1798 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1799 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1800 DwarfExpr.addFragmentOffset(Expr: DIExpr);
1801 DwarfExpr.setLocation(Loc: Location, DIExpr);
1802
1803 DIExpressionCursor Cursor(DIExpr);
1804
1805 if (DIExpr->isEntryValue())
1806 DwarfExpr.beginEntryValueExpression(ExprCursor&: Cursor);
1807
1808 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1809 if (!DwarfExpr.addMachineRegExpression(TRI, Expr&: Cursor, MachineReg: Location.getReg()))
1810 return;
1811 DwarfExpr.addExpression(Expr: std::move(Cursor));
1812
1813 // Now attach the location information to the DIE.
1814 addBlock(Die, Attribute, Loc: DwarfExpr.finalize());
1815
1816 if (DwarfExpr.TagOffset)
1817 addUInt(Die, Attribute: dwarf::DW_AT_LLVM_tag_offset, Form: dwarf::DW_FORM_data1,
1818 Integer: *DwarfExpr.TagOffset);
1819}
1820
1821/// Add a Dwarf loclistptr attribute data and value.
1822void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
1823 unsigned Index) {
1824 dwarf::Form Form = (DD->getDwarfVersion() >= 5)
1825 ? dwarf::DW_FORM_loclistx
1826 : DD->getDwarfSectionOffsetForm();
1827 addAttribute(Die, Attribute, Form, Value: DIELocList(Index));
1828}
1829
1830void DwarfCompileUnit::applyCommonDbgVariableAttributes(const DbgVariable &Var,
1831 DIE &VariableDie) {
1832 StringRef Name = Var.getName();
1833 if (!Name.empty())
1834 addString(Die&: VariableDie, Attribute: dwarf::DW_AT_name, Str: Name);
1835 const auto *DIVar = Var.getVariable();
1836 if (DIVar) {
1837 if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
1838 addUInt(Die&: VariableDie, Attribute: dwarf::DW_AT_alignment, Form: dwarf::DW_FORM_udata,
1839 Integer: AlignInBytes);
1840 addAnnotation(Buffer&: VariableDie, Annotations: DIVar->getAnnotations());
1841 }
1842
1843 addSourceLine(Die&: VariableDie, V: DIVar);
1844 addType(Entity&: VariableDie, Ty: Var.getType());
1845 if (Var.isArtificial())
1846 addFlag(Die&: VariableDie, Attribute: dwarf::DW_AT_artificial);
1847}
1848
1849void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
1850 DIE &LabelDie) {
1851 StringRef Name = Label.getName();
1852 if (!Name.empty())
1853 addString(Die&: LabelDie, Attribute: dwarf::DW_AT_name, Str: Name);
1854 const auto *DILabel = Label.getLabel();
1855 addSourceLine(Die&: LabelDie, L: DILabel);
1856 if (DILabel->isArtificial())
1857 addFlag(Die&: LabelDie, Attribute: dwarf::DW_AT_artificial);
1858 if (DILabel->getCoroSuspendIdx())
1859 addUInt(Die&: LabelDie, Attribute: dwarf::DW_AT_LLVM_coro_suspend_idx, Form: std::nullopt,
1860 Integer: *DILabel->getCoroSuspendIdx());
1861}
1862
1863/// Add a Dwarf expression attribute data and value.
1864void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
1865 const MCExpr *Expr) {
1866 addAttribute(Die, Attribute: (dwarf::Attribute)0, Form, Value: DIEExpr(Expr));
1867}
1868
1869void DwarfCompileUnit::applySubprogramAttributesToDefinition(
1870 const DISubprogram *SP, DIE &SPDie) {
1871 auto *SPDecl = SP->getDeclaration();
1872 auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
1873 applySubprogramAttributes(SP, SPDie, SkipSPAttributes: includeMinimalInlineScopes());
1874 addGlobalName(Name: SP->getName(), Die: SPDie, Context);
1875}
1876
1877bool DwarfCompileUnit::isDwoUnit() const {
1878 return DD->useSplitDwarf() && Skeleton;
1879}
1880
1881void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1882 constructTypeDIE(Buffer&: D, CTy);
1883}
1884
1885bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1886 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
1887 (DD->useSplitDwarf() && !Skeleton);
1888}
1889
1890bool DwarfCompileUnit::emitFuncLineTableOffsets() const {
1891 return EmitFuncLineTableOffsetsOption;
1892}
1893
1894void DwarfCompileUnit::addAddrTableBase() {
1895 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1896 MCSymbol *Label = DD->getAddressPool().getLabel();
1897 addSectionLabel(Die&: getUnitDie(),
1898 Attribute: DD->getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
1899 : dwarf::DW_AT_GNU_addr_base,
1900 Label, Sec: TLOF.getDwarfAddrSection()->getBeginSymbol());
1901}
1902
1903void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
1904 addAttribute(Die, Attribute: (dwarf::Attribute)0, Form: dwarf::DW_FORM_udata,
1905 Value: new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
1906}
1907
1908void DwarfCompileUnit::createBaseTypeDIEs() {
1909 // Insert the base_type DIEs directly after the CU so that their offsets will
1910 // fit in the fixed size ULEB128 used inside the location expressions.
1911 // Maintain order by iterating backwards and inserting to the front of CU
1912 // child list.
1913 for (auto &Btr : reverse(C&: ExprRefedBaseTypes)) {
1914 DIE &Die = getUnitDie().addChildFront(
1915 Child: DIE::get(Alloc&: DIEValueAllocator, Tag: dwarf::DW_TAG_base_type));
1916 SmallString<32> Str;
1917 addString(Die, Attribute: dwarf::DW_AT_name,
1918 Str: Twine(dwarf::AttributeEncodingString(Encoding: Btr.Encoding) +
1919 "_" + Twine(Btr.BitSize)).toStringRef(Out&: Str));
1920 addUInt(Die, Attribute: dwarf::DW_AT_encoding, Form: dwarf::DW_FORM_data1, Integer: Btr.Encoding);
1921 // Round up to smallest number of bytes that contains this number of bits.
1922 // ExprRefedBaseTypes is populated with types referenced by
1923 // DW_OP_LLVM_convert operations in location expressions. These are often
1924 // byte-sized, but one common counter-example is 1-bit sized conversions
1925 // from `i1` types. TODO: Should these use DW_AT_bit_size? See
1926 // DwarfUnit::constructTypeDIE.
1927 addUInt(Die, Attribute: dwarf::DW_AT_byte_size, Form: std::nullopt,
1928 Integer: divideCeil(Numerator: Btr.BitSize, Denominator: 8));
1929 Btr.Die = &Die;
1930 }
1931}
1932
1933static const DILocalScope *getParentLocalScope(const DILexicalBlockBase *LB) {
1934 return LB->getScope()->getNonLexicalBlockFileScope();
1935}
1936
1937DIE *DwarfCompileUnit::getOrCreateLocalScopeDIE(const DILocalScope *Scope) {
1938 const DISubprogram *SP = Scope->getSubprogram();
1939 if (!SP->isDefinition())
1940 return DwarfUnit::getOrCreateContextDIE(Context: SP);
1941
1942 // Local scope DIEs are looked up in the unit where abstract and concrete
1943 // DIEs of SP are created.
1944 DwarfCompileUnit &ScopeCU = DD->getOrCreateAbstractSubprogramCU(SP, SrcCU&: *this);
1945 if (&ScopeCU != this)
1946 return ScopeCU.getOrCreateLocalScopeDIE(Scope);
1947
1948 // Once an abstract tree is created for SP, all its local entities belong to
1949 // the abstract tree. Use the closest scope that is present in it.
1950 auto &AbstractDIEs = getAbstractScopeDIEs();
1951 if (AbstractDIEs.contains(Val: SP)) {
1952 const DILocalScope *S = Scope;
1953 auto I = AbstractDIEs.find(Val: S);
1954 while (I == AbstractDIEs.end()) {
1955 S = getParentLocalScope(LB: cast<DILexicalBlockBase>(Val: S));
1956 I = AbstractDIEs.find(Val: S);
1957 }
1958 return I->second;
1959 }
1960
1961 // Until all functions are processed, it is not known whether SP gets an
1962 // abstract DIE, so local entities are collected in a pending DIE and moved
1963 // to the right place later by resolvePendingLocalScopeDIEs().
1964 if (!DD->allFunctionsProcessed())
1965 return &getOrCreatePendingLocalScopeDIE(Scope);
1966
1967 // SP has no abstract tree, so use the concrete one.
1968 if (auto *LB = dyn_cast<DILexicalBlock>(Val: Scope)) {
1969 if (DIE *ScopeDIE = LexicalBlockDIEs.lookup(Val: LB))
1970 return ScopeDIE;
1971 // If the concrete tree has no DIE for this lexical block, use the closest
1972 // enclosing scope DIE.
1973 return getOrCreateLocalScopeDIE(Scope: getParentLocalScope(LB));
1974 }
1975 return getOrCreateSubprogramDIE(SP: cast<DISubprogram>(Val: Scope), F: nullptr);
1976}
1977
1978DIE &DwarfCompileUnit::getOrCreatePendingLocalScopeDIE(
1979 const DILocalScope *Scope) {
1980 DIE *&PendingDIE = PendingLocalScopeDIEs[Scope];
1981 if (PendingDIE)
1982 return *PendingDIE;
1983
1984 // Keep the pending DIEs in the unit DIE, so that the DIEs added to them know
1985 // which unit they belong to. The tags don't matter, as these DIEs are
1986 // removed before emission.
1987 if (!PendingLocalScopesDIE)
1988 PendingLocalScopesDIE =
1989 &getUnitDie().addChildFront(Child: DIE::getPlaceholder(Alloc&: DIEValueAllocator));
1990 PendingDIE = &PendingLocalScopesDIE->addChild(
1991 Child: DIE::get(Alloc&: DIEValueAllocator, Tag: dwarf::DW_TAG_lexical_block));
1992 return *PendingDIE;
1993}
1994
1995void DwarfCompileUnit::resolvePendingLocalScopeDIEs() {
1996 assert(DD->allFunctionsProcessed() &&
1997 "Local scope DIEs can be resolved only after all functions");
1998 for (auto [Scope, PendingDIE] : PendingLocalScopeDIEs) {
1999 DIE *ScopeDIE = getOrCreateLocalScopeDIE(Scope);
2000 // Put local declarations before other children of the scope, as they
2001 // would be placed if the scope DIE existed when they were created.
2002 ScopeDIE->takeChildren(Other&: *PendingDIE, /*AtFront=*/true);
2003 }
2004 PendingLocalScopeDIEs.clear();
2005
2006 if (PendingLocalScopesDIE) {
2007 getUnitDie().removeChild(Child&: *PendingLocalScopesDIE);
2008 PendingLocalScopesDIE = nullptr;
2009 }
2010}
2011
2012DIE *DwarfCompileUnit::getOrCreateContextDIE(const DIScope *Context) {
2013 if (auto *LScope = dyn_cast_or_null<DILocalScope>(Val: Context))
2014 return getOrCreateLocalScopeDIE(Scope: LScope->getNonLexicalBlockFileScope());
2015 return DwarfUnit::getOrCreateContextDIE(Context);
2016}
2017
2018DIE *DwarfCompileUnit::getOrCreateSubprogramDIE(const DISubprogram *SP,
2019 const Function *F,
2020 bool Minimal) {
2021 if (!F && SP->isDefinition()) {
2022 // SP may belong to another CU. Determine the CU similarly
2023 // to DwarfDebug::constructAbstractSubprogramScopeDIE.
2024 DwarfCompileUnit &AbstractCU =
2025 DD->getOrCreateAbstractSubprogramCU(SP, SrcCU&: *this);
2026 if (DIE *AbstractDIE = AbstractCU.getAbstractScopeDIEs().lookup(Val: SP))
2027 return AbstractDIE;
2028
2029 // A subprogram that is neither emitted nor inlined in emitted code can
2030 // only be represented by an abstract DIE.
2031 // Abstract DIE may be necessary for the subprogram when an IR function
2032 // and all its inlined instances are optimized away, yet its local type
2033 // leaks outside the subprogram's scope (e.g., when used as a template type
2034 // parameter).
2035 if (DD->allFunctionsProcessed() && !DD->isProcessedSubprogram(SP))
2036 return &AbstractCU.getOrCreateAbstractSubprogramDIE(SP);
2037 }
2038
2039 return DwarfUnit::getOrCreateSubprogramDIE(SP, FnHint: F, Minimal);
2040}
2041
2042void DwarfCompileUnit::addLinkageNamesToDeclarations(
2043 const DwarfDebug &DD, const DISubprogram &CalleeSP, DIE &CalleeDIE) {
2044 if (AddLinkageNamesToDeclCallOriginsForTuning(DD: &DD) &&
2045 !CalleeSP.isDefinition() &&
2046 !CalleeDIE.findAttribute(Attribute: dwarf::DW_AT_linkage_name)) {
2047 addLinkageName(Die&: CalleeDIE, LinkageName: CalleeSP.getLinkageName());
2048 }
2049}
2050