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