Bug Summary

File:build/source/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp
Warning:line 81, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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