Bug Summary

File:include/llvm/CodeGen/DIE.h
Warning:line 679, column 5
Forming reference to null pointer

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name DwarfCompileUnit.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/lib/CodeGen/AsmPrinter -I /build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter -I /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn358860/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/lib/CodeGen/AsmPrinter -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn358860=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-04-22-050718-5320-1 -x c++ /build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp -faddrsig

/build/llvm-toolchain-snapshot-9~svn358860/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 "DwarfDebug.h"
16#include "DwarfExpression.h"
17#include "DwarfUnit.h"
18#include "llvm/ADT/None.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/BinaryFormat/Dwarf.h"
24#include "llvm/CodeGen/AsmPrinter.h"
25#include "llvm/CodeGen/DIE.h"
26#include "llvm/CodeGen/LexicalScopes.h"
27#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineInstr.h"
29#include "llvm/CodeGen/MachineOperand.h"
30#include "llvm/CodeGen/TargetFrameLowering.h"
31#include "llvm/CodeGen/TargetRegisterInfo.h"
32#include "llvm/CodeGen/TargetSubtargetInfo.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DebugInfo.h"
35#include "llvm/IR/DebugInfoMetadata.h"
36#include "llvm/IR/GlobalVariable.h"
37#include "llvm/MC/MCSection.h"
38#include "llvm/MC/MCStreamer.h"
39#include "llvm/MC/MCSymbol.h"
40#include "llvm/MC/MachineLocation.h"
41#include "llvm/Support/Casting.h"
42#include "llvm/Target/TargetLoweringObjectFile.h"
43#include "llvm/Target/TargetMachine.h"
44#include "llvm/Target/TargetOptions.h"
45#include <algorithm>
46#include <cassert>
47#include <cstdint>
48#include <iterator>
49#include <memory>
50#include <string>
51#include <utility>
52
53using namespace llvm;
54
55DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
56 AsmPrinter *A, DwarfDebug *DW,
57 DwarfFile *DWU)
58 : DwarfUnit(dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), UniqueID(UID) {
59 insertDIE(Node, &getUnitDie());
60 MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
61}
62
63/// addLabelAddress - Add a dwarf label attribute data and value using
64/// DW_FORM_addr or DW_FORM_GNU_addr_index.
65void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
66 const MCSymbol *Label) {
67 // Don't use the address pool in non-fission or in the skeleton unit itself.
68 // FIXME: Once GDB supports this, it's probably worthwhile using the address
69 // pool from the skeleton - maybe even in non-fission (possibly fewer
70 // relocations by sharing them in the pool, but we have other ideas about how
71 // to reduce the number of relocations as well/instead).
72 if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
73 return addLocalLabelAddress(Die, Attribute, Label);
74
75 if (Label)
76 DD->addArangeLabel(SymbolCU(this, Label));
77
78 unsigned idx = DD->getAddressPool().getIndex(Label);
79 Die.addValue(DIEValueAllocator, Attribute,
80 DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
81 : dwarf::DW_FORM_GNU_addr_index,
82 DIEInteger(idx));
83}
84
85void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
86 dwarf::Attribute Attribute,
87 const MCSymbol *Label) {
88 if (Label)
89 DD->addArangeLabel(SymbolCU(this, Label));
90
91 if (Label)
92 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
93 DIELabel(Label));
94 else
95 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
96 DIEInteger(0));
97}
98
99unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
100 // If we print assembly, we can't separate .file entries according to
101 // compile units. Thus all files will belong to the default compile unit.
102
103 // FIXME: add a better feature test than hasRawTextSupport. Even better,
104 // extend .file to support this.
105 unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
106 if (!File)
107 return Asm->OutStreamer->EmitDwarfFileDirective(0, "", "", None, None, CUID);
108 return Asm->OutStreamer->EmitDwarfFileDirective(
109 0, File->getDirectory(), File->getFilename(), getMD5AsBytes(File),
110 File->getSource(), CUID);
111}
112
113DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
114 const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
115 // Check for pre-existence.
116 if (DIE *Die = getDIE(GV))
117 return Die;
118
119 assert(GV)((GV) ? static_cast<void> (0) : __assert_fail ("GV", "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 119, __PRETTY_FUNCTION__))
;
120
121 auto *GVContext = GV->getScope();
122 auto *GTy = DD->resolve(GV->getType());
123
124 // Construct the context before querying for the existence of the DIE in
125 // case such construction creates the DIE.
126 auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
127 DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
128 : getOrCreateContextDIE(GVContext);
129
130 // Add to map.
131 DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
132 DIScope *DeclContext;
133 if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
134 DeclContext = resolve(SDMDecl->getScope());
135 assert(SDMDecl->isStaticMember() && "Expected static member decl")((SDMDecl->isStaticMember() && "Expected static member decl"
) ? static_cast<void> (0) : __assert_fail ("SDMDecl->isStaticMember() && \"Expected static member decl\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 135, __PRETTY_FUNCTION__))
;
136 assert(GV->isDefinition())((GV->isDefinition()) ? static_cast<void> (0) : __assert_fail
("GV->isDefinition()", "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 136, __PRETTY_FUNCTION__))
;
137 // We need the declaration DIE that is in the static member's class.
138 DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
139 addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
140 // If the global variable's type is different from the one in the class
141 // member type, assume that it's more specific and also emit it.
142 if (GTy != DD->resolve(SDMDecl->getBaseType()))
143 addType(*VariableDIE, GTy);
144 } else {
145 DeclContext = GV->getScope();
146 // Add name and type.
147 addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
148 addType(*VariableDIE, GTy);
149
150 // Add scoping info.
151 if (!GV->isLocalToUnit())
152 addFlag(*VariableDIE, dwarf::DW_AT_external);
153
154 // Add line number info.
155 addSourceLine(*VariableDIE, GV);
156 }
157
158 if (!GV->isDefinition())
159 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
160 else
161 addGlobalName(GV->getName(), *VariableDIE, DeclContext);
162
163 if (uint32_t AlignInBytes = GV->getAlignInBytes())
164 addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
165 AlignInBytes);
166
167 if (MDTuple *TP = GV->getTemplateParams())
168 addTemplateParams(*VariableDIE, DINodeArray(TP));
169
170 // Add location.
171 addLocationAttribute(VariableDIE, GV, GlobalExprs);
172
173 return VariableDIE;
174}
175
176void DwarfCompileUnit::addLocationAttribute(
177 DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
178 bool addToAccelTable = false;
179 DIELoc *Loc = nullptr;
180 Optional<unsigned> NVPTXAddressSpace;
181 std::unique_ptr<DIEDwarfExpression> DwarfExpr;
182 for (const auto &GE : GlobalExprs) {
183 const GlobalVariable *Global = GE.Var;
184 const DIExpression *Expr = GE.Expr;
185
186 // For compatibility with DWARF 3 and earlier,
187 // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
188 // DW_AT_const_value(X).
189 if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
190 addToAccelTable = true;
191 addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
192 break;
193 }
194
195 // We cannot describe the location of dllimport'd variables: the
196 // computation of their address requires loads from the IAT.
197 if (Global && Global->hasDLLImportStorageClass())
198 continue;
199
200 // Nothing to describe without address or constant.
201 if (!Global && (!Expr || !Expr->isConstant()))
202 continue;
203
204 if (Global && Global->isThreadLocal() &&
205 !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
206 continue;
207
208 if (!Loc) {
209 addToAccelTable = true;
210 Loc = new (DIEValueAllocator) DIELoc;
211 DwarfExpr = llvm::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
212 }
213
214 if (Expr) {
215 // According to
216 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
217 // cuda-gdb requires DW_AT_address_class for all variables to be able to
218 // correctly interpret address space of the variable address.
219 // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
220 // sequence for the NVPTX + gdb target.
221 unsigned LocalNVPTXAddressSpace;
222 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
223 const DIExpression *NewExpr =
224 DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
225 if (NewExpr != Expr) {
226 Expr = NewExpr;
227 NVPTXAddressSpace = LocalNVPTXAddressSpace;
228 }
229 }
230 DwarfExpr->addFragmentOffset(Expr);
231 }
232
233 if (Global) {
234 const MCSymbol *Sym = Asm->getSymbol(Global);
235 if (Global->isThreadLocal()) {
236 if (Asm->TM.useEmulatedTLS()) {
237 // TODO: add debug info for emulated thread local mode.
238 } else {
239 // FIXME: Make this work with -gsplit-dwarf.
240 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
241 assert((PointerSize == 4 || PointerSize == 8) &&(((PointerSize == 4 || PointerSize == 8) && "Add support for other sizes if necessary"
) ? static_cast<void> (0) : __assert_fail ("(PointerSize == 4 || PointerSize == 8) && \"Add support for other sizes if necessary\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 242, __PRETTY_FUNCTION__))
242 "Add support for other sizes if necessary")(((PointerSize == 4 || PointerSize == 8) && "Add support for other sizes if necessary"
) ? static_cast<void> (0) : __assert_fail ("(PointerSize == 4 || PointerSize == 8) && \"Add support for other sizes if necessary\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 242, __PRETTY_FUNCTION__))
;
243 // Based on GCC's support for TLS:
244 if (!DD->useSplitDwarf()) {
245 // 1) Start with a constNu of the appropriate pointer size
246 addUInt(*Loc, dwarf::DW_FORM_data1,
247 PointerSize == 4 ? dwarf::DW_OP_const4u
248 : dwarf::DW_OP_const8u);
249 // 2) containing the (relocated) offset of the TLS variable
250 // within the module's TLS block.
251 addExpr(*Loc, dwarf::DW_FORM_udata,
252 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
253 } else {
254 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
255 addUInt(*Loc, dwarf::DW_FORM_udata,
256 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
257 }
258 // 3) followed by an OP to make the debugger do a TLS lookup.
259 addUInt(*Loc, dwarf::DW_FORM_data1,
260 DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
261 : dwarf::DW_OP_form_tls_address);
262 }
263 } else {
264 DD->addArangeLabel(SymbolCU(this, Sym));
265 addOpAddress(*Loc, Sym);
266 }
267 }
268 // Global variables attached to symbols are memory locations.
269 // It would be better if this were unconditional, but malformed input that
270 // mixes non-fragments and fragments for the same variable is too expensive
271 // to detect in the verifier.
272 if (DwarfExpr->isUnknownLocation())
273 DwarfExpr->setMemoryLocationKind();
274 DwarfExpr->addExpression(Expr);
275 }
276 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
277 // According to
278 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
279 // cuda-gdb requires DW_AT_address_class for all variables to be able to
280 // correctly interpret address space of the variable address.
281 const unsigned NVPTX_ADDR_global_space = 5;
282 addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
283 NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
284 }
285 if (Loc)
286 addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
287
288 if (DD->useAllLinkageNames())
289 addLinkageName(*VariableDIE, GV->getLinkageName());
290
291 if (addToAccelTable) {
292 DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
293
294 // If the linkage name is different than the name, go ahead and output
295 // that as well into the name table.
296 if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
297 DD->useAllLinkageNames())
298 DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
299 }
300}
301
302DIE *DwarfCompileUnit::getOrCreateCommonBlock(
303 const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
304 // Construct the context before querying for the existence of the DIE in case
305 // such construction creates the DIE.
306 DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
307
308 if (DIE *NDie = getDIE(CB))
309 return NDie;
310 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
311 StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
312 addString(NDie, dwarf::DW_AT_name, Name);
313 addGlobalName(Name, NDie, CB->getScope());
314 if (CB->getFile())
315 addSourceLine(NDie, CB->getLineNo(), CB->getFile());
316 if (DIGlobalVariable *V = CB->getDecl())
317 getCU().addLocationAttribute(&NDie, V, GlobalExprs);
318 return &NDie;
319}
320
321void DwarfCompileUnit::addRange(RangeSpan Range) {
322 bool SameAsPrevCU = this == DD->getPrevCU();
323 DD->setPrevCU(this);
324 // If we have no current ranges just add the range and return, otherwise,
325 // check the current section and CU against the previous section and CU we
326 // emitted into and the subprogram was contained within. If these are the
327 // same then extend our current range, otherwise add this as a new range.
328 if (CURanges.empty() || !SameAsPrevCU ||
329 (&CURanges.back().getEnd()->getSection() !=
330 &Range.getEnd()->getSection())) {
331 CURanges.push_back(Range);
332 DD->addSectionLabel(Range.getStart());
333 return;
334 }
335
336 CURanges.back().setEnd(Range.getEnd());
337}
338
339void DwarfCompileUnit::initStmtList() {
340 if (CUNode->isDebugDirectivesOnly())
341 return;
342
343 // Define start line table label for each Compile Unit.
344 MCSymbol *LineTableStartSym;
345 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
346 if (DD->useSectionsAsReferences()) {
347 LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
348 } else {
349 LineTableStartSym =
350 Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
351 }
352
353 // DW_AT_stmt_list is a offset of line number information for this
354 // compile unit in debug_line section. For split dwarf this is
355 // left in the skeleton CU and so not included.
356 // The line table entries are not always emitted in assembly, so it
357 // is not okay to use line_table_start here.
358 StmtListValue =
359 addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
360 TLOF.getDwarfLineSection()->getBeginSymbol());
361}
362
363void DwarfCompileUnit::applyStmtList(DIE &D) {
364 D.addValue(DIEValueAllocator, *StmtListValue);
365}
366
367void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
368 const MCSymbol *End) {
369 assert(Begin && "Begin label should not be null!")((Begin && "Begin label should not be null!") ? static_cast
<void> (0) : __assert_fail ("Begin && \"Begin label should not be null!\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 369, __PRETTY_FUNCTION__))
;
370 assert(End && "End label should not be null!")((End && "End label should not be null!") ? static_cast
<void> (0) : __assert_fail ("End && \"End label should not be null!\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 370, __PRETTY_FUNCTION__))
;
371 assert(Begin->isDefined() && "Invalid starting label")((Begin->isDefined() && "Invalid starting label") ?
static_cast<void> (0) : __assert_fail ("Begin->isDefined() && \"Invalid starting label\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 371, __PRETTY_FUNCTION__))
;
372 assert(End->isDefined() && "Invalid end label")((End->isDefined() && "Invalid end label") ? static_cast
<void> (0) : __assert_fail ("End->isDefined() && \"Invalid end label\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 372, __PRETTY_FUNCTION__))
;
373
374 addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
375 if (DD->getDwarfVersion() < 4)
376 addLabelAddress(D, dwarf::DW_AT_high_pc, End);
377 else
378 addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
379}
380
381// Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
382// and DW_AT_high_pc attributes. If there are global variables in this
383// scope then create and insert DIEs for these variables.
384DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
385 DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
386
387 attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
388 if (DD->useAppleExtensionAttributes() &&
389 !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
390 *DD->getCurrentFunction()))
391 addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
392
393 // Only include DW_AT_frame_base in full debug info
394 if (!includeMinimalInlineScopes()) {
395 if (Asm->MF->getTarget().getTargetTriple().isNVPTX()) {
396 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
397 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
398 addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
399 } else {
400 const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
401 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
402 if (RI->isPhysicalRegister(Location.getReg()))
403 addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
404 }
405 }
406
407 // Add name to the name table, we do this here because we're guaranteed
408 // to have concrete versions of our DW_TAG_subprogram nodes.
409 DD->addSubprogramNames(*CUNode, SP, *SPDie);
410
411 return *SPDie;
412}
413
414// Construct a DIE for this scope.
415void DwarfCompileUnit::constructScopeDIE(
416 LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
417 if (!Scope || !Scope->getScopeNode())
418 return;
419
420 auto *DS = Scope->getScopeNode();
421
422 assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&(((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
"Only handle inlined subprograms here, use " "constructSubprogramScopeDIE for non-inlined "
"subprograms") ? static_cast<void> (0) : __assert_fail
("(Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && \"Only handle inlined subprograms here, use \" \"constructSubprogramScopeDIE for non-inlined \" \"subprograms\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 425, __PRETTY_FUNCTION__))
423 "Only handle inlined subprograms here, use "(((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
"Only handle inlined subprograms here, use " "constructSubprogramScopeDIE for non-inlined "
"subprograms") ? static_cast<void> (0) : __assert_fail
("(Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && \"Only handle inlined subprograms here, use \" \"constructSubprogramScopeDIE for non-inlined \" \"subprograms\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 425, __PRETTY_FUNCTION__))
424 "constructSubprogramScopeDIE for non-inlined "(((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
"Only handle inlined subprograms here, use " "constructSubprogramScopeDIE for non-inlined "
"subprograms") ? static_cast<void> (0) : __assert_fail
("(Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && \"Only handle inlined subprograms here, use \" \"constructSubprogramScopeDIE for non-inlined \" \"subprograms\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 425, __PRETTY_FUNCTION__))
425 "subprograms")(((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
"Only handle inlined subprograms here, use " "constructSubprogramScopeDIE for non-inlined "
"subprograms") ? static_cast<void> (0) : __assert_fail
("(Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && \"Only handle inlined subprograms here, use \" \"constructSubprogramScopeDIE for non-inlined \" \"subprograms\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 425, __PRETTY_FUNCTION__))
;
426
427 SmallVector<DIE *, 8> Children;
428
429 // We try to create the scope DIE first, then the children DIEs. This will
430 // avoid creating un-used children then removing them later when we find out
431 // the scope DIE is null.
432 DIE *ScopeDIE;
433 if (Scope->getParent() && isa<DISubprogram>(DS)) {
434 ScopeDIE = constructInlinedScopeDIE(Scope);
435 if (!ScopeDIE)
436 return;
437 // We create children when the scope DIE is not null.
438 createScopeChildrenDIE(Scope, Children);
439 } else {
440 // Early exit when we know the scope DIE is going to be null.
441 if (DD->isLexicalScopeDIENull(Scope))
442 return;
443
444 bool HasNonScopeChildren = false;
445
446 // We create children here when we know the scope DIE is not going to be
447 // null and the children will be added to the scope DIE.
448 createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
449
450 // If there are only other scopes as children, put them directly in the
451 // parent instead, as this scope would serve no purpose.
452 if (!HasNonScopeChildren) {
453 FinalChildren.insert(FinalChildren.end(),
454 std::make_move_iterator(Children.begin()),
455 std::make_move_iterator(Children.end()));
456 return;
457 }
458 ScopeDIE = constructLexicalScopeDIE(Scope);
459 assert(ScopeDIE && "Scope DIE should not be null.")((ScopeDIE && "Scope DIE should not be null.") ? static_cast
<void> (0) : __assert_fail ("ScopeDIE && \"Scope DIE should not be null.\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 459, __PRETTY_FUNCTION__))
;
460 }
461
462 // Add children
463 for (auto &I : Children)
464 ScopeDIE->addChild(std::move(I));
465
466 FinalChildren.push_back(std::move(ScopeDIE));
467}
468
469void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
470 SmallVector<RangeSpan, 2> Range) {
471 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
472
473 // Emit the offset into .debug_ranges or .debug_rnglists as a relocatable
474 // label. emitDIE() will handle emitting it appropriately.
475 const MCSymbol *RangeSectionSym =
476 DD->getDwarfVersion() >= 5
477 ? TLOF.getDwarfRnglistsSection()->getBeginSymbol()
478 : TLOF.getDwarfRangesSection()->getBeginSymbol();
479
480 HasRangeLists = true;
481
482 // Add the range list to the set of ranges to be emitted.
483 auto IndexAndList =
484 (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
485 ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
486
487 uint32_t Index = IndexAndList.first;
488 auto &List = *IndexAndList.second;
489
490 // Under fission, ranges are specified by constant offsets relative to the
491 // CU's DW_AT_GNU_ranges_base.
492 // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
493 // fission until we support the forms using the .debug_addr section
494 // (DW_RLE_startx_endx etc.).
495 if (DD->getDwarfVersion() >= 5)
496 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
497 else if (isDwoUnit())
498 addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
499 RangeSectionSym);
500 else
501 addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
502 RangeSectionSym);
503}
504
505void DwarfCompileUnit::attachRangesOrLowHighPC(
506 DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
507 if (Ranges.size() == 1 || !DD->useRangesSection()) {
508 const RangeSpan &Front = Ranges.front();
509 const RangeSpan &Back = Ranges.back();
510 attachLowHighPC(Die, Front.getStart(), Back.getEnd());
511 } else
512 addScopeRangeList(Die, std::move(Ranges));
513}
514
515void DwarfCompileUnit::attachRangesOrLowHighPC(
516 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
517 SmallVector<RangeSpan, 2> List;
518 List.reserve(Ranges.size());
519 for (const InsnRange &R : Ranges)
520 List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
521 DD->getLabelAfterInsn(R.second)));
522 attachRangesOrLowHighPC(Die, std::move(List));
523}
524
525// This scope represents inlined body of a function. Construct DIE to
526// represent this concrete inlined copy of the function.
527DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
528 assert(Scope->getScopeNode())((Scope->getScopeNode()) ? static_cast<void> (0) : __assert_fail
("Scope->getScopeNode()", "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 528, __PRETTY_FUNCTION__))
;
529 auto *DS = Scope->getScopeNode();
530 auto *InlinedSP = getDISubprogram(DS);
531 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
532 // was inlined from another compile unit.
533 DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
534 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.")((OriginDIE && "Unable to find original DIE for an inlined subprogram."
) ? static_cast<void> (0) : __assert_fail ("OriginDIE && \"Unable to find original DIE for an inlined subprogram.\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 534, __PRETTY_FUNCTION__))
;
535
536 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
537 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
538
539 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
540
541 // Add the call site information to the DIE.
542 const DILocation *IA = Scope->getInlinedAt();
543 addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
544 getOrCreateSourceID(IA->getFile()));
545 addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
546 if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
547 addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
548 IA->getDiscriminator());
549
550 // Add name to the name table, we do this here because we're guaranteed
551 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
552 DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
553
554 return ScopeDIE;
555}
556
557// Construct new DW_TAG_lexical_block for this scope and attach
558// DW_AT_low_pc/DW_AT_high_pc labels.
559DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
560 if (DD->isLexicalScopeDIENull(Scope))
561 return nullptr;
562
563 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
564 if (Scope->isAbstractScope())
565 return ScopeDIE;
566
567 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
568
569 return ScopeDIE;
570}
571
572/// constructVariableDIE - Construct a DIE for the given DbgVariable.
573DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
574 auto D = constructVariableDIEImpl(DV, Abstract);
575 DV.setDIE(*D);
576 return D;
577}
578
579DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
580 const LexicalScope &Scope) {
581 auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
582 insertDIE(DL.getLabel(), LabelDie);
583 DL.setDIE(*LabelDie);
584
585 if (Scope.isAbstractScope())
586 applyLabelAttributes(DL, *LabelDie);
587
588 return LabelDie;
589}
590
591DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
592 bool Abstract) {
593 // Define variable debug information entry.
594 auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
595 insertDIE(DV.getVariable(), VariableDie);
596
597 if (Abstract) {
598 applyVariableAttributes(DV, *VariableDie);
599 return VariableDie;
600 }
601
602 // Add variable address.
603
604 unsigned Offset = DV.getDebugLocListIndex();
605 if (Offset != ~0U) {
606 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
607 return VariableDie;
608 }
609
610 // Check if variable is described by a DBG_VALUE instruction.
611 if (const MachineInstr *DVInsn = DV.getMInsn()) {
612 assert(DVInsn->getNumOperands() == 4)((DVInsn->getNumOperands() == 4) ? static_cast<void>
(0) : __assert_fail ("DVInsn->getNumOperands() == 4", "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 612, __PRETTY_FUNCTION__))
;
613 if (DVInsn->getOperand(0).isReg()) {
614 auto RegOp = DVInsn->getOperand(0);
615 auto Op1 = DVInsn->getOperand(1);
616 // If the second operand is an immediate, this is an indirect value.
617 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset")(((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset"
) ? static_cast<void> (0) : __assert_fail ("(!Op1.isImm() || (Op1.getImm() == 0)) && \"unexpected offset\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 617, __PRETTY_FUNCTION__))
;
618 MachineLocation Location(RegOp.getReg(), Op1.isImm());
619 addVariableAddress(DV, *VariableDie, Location);
620 } else if (DVInsn->getOperand(0).isImm()) {
621 // This variable is described by a single constant.
622 // Check whether it has a DIExpression.
623 auto *Expr = DV.getSingleExpression();
624 if (Expr && Expr->getNumElements()) {
625 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
626 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
627 // If there is an expression, emit raw unsigned bytes.
628 DwarfExpr.addFragmentOffset(Expr);
629 DwarfExpr.addUnsignedConstant(DVInsn->getOperand(0).getImm());
630 DwarfExpr.addExpression(Expr);
631 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
632 } else
633 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
634 } else if (DVInsn->getOperand(0).isFPImm())
635 addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
636 else if (DVInsn->getOperand(0).isCImm())
637 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
638 DV.getType());
639
640 return VariableDie;
641 }
642
643 // .. else use frame index.
644 if (!DV.hasFrameIndexExprs())
645 return VariableDie;
646
647 Optional<unsigned> NVPTXAddressSpace;
648 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
649 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
650 for (auto &Fragment : DV.getFrameIndexExprs()) {
651 unsigned FrameReg = 0;
652 const DIExpression *Expr = Fragment.Expr;
653 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
654 int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
655 DwarfExpr.addFragmentOffset(Expr);
656 SmallVector<uint64_t, 8> Ops;
657 Ops.push_back(dwarf::DW_OP_plus_uconst);
658 Ops.push_back(Offset);
659 // According to
660 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
661 // cuda-gdb requires DW_AT_address_class for all variables to be able to
662 // correctly interpret address space of the variable address.
663 // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
664 // sequence for the NVPTX + gdb target.
665 unsigned LocalNVPTXAddressSpace;
666 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
667 const DIExpression *NewExpr =
668 DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
669 if (NewExpr != Expr) {
670 Expr = NewExpr;
671 NVPTXAddressSpace = LocalNVPTXAddressSpace;
672 }
673 }
674 if (Expr)
675 Ops.append(Expr->elements_begin(), Expr->elements_end());
676 DIExpressionCursor Cursor(Ops);
677 DwarfExpr.setMemoryLocationKind();
678 if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
679 addOpAddress(*Loc, FrameSymbol);
680 else
681 DwarfExpr.addMachineRegExpression(
682 *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
683 DwarfExpr.addExpression(std::move(Cursor));
684 }
685 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
686 // According to
687 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
688 // cuda-gdb requires DW_AT_address_class for all variables to be able to
689 // correctly interpret address space of the variable address.
690 const unsigned NVPTX_ADDR_local_space = 6;
691 addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
692 NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
693 }
694 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
695
696 return VariableDie;
697}
698
699DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
700 const LexicalScope &Scope,
701 DIE *&ObjectPointer) {
702 auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
703 if (DV.isObjectPointer())
704 ObjectPointer = Var;
705 return Var;
706}
707
708/// Return all DIVariables that appear in count: expressions.
709static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
710 SmallVector<const DIVariable *, 2> Result;
711 auto *Array = dyn_cast<DICompositeType>(Var->getType());
712 if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
713 return Result;
714 for (auto *El : Array->getElements()) {
715 if (auto *Subrange = dyn_cast<DISubrange>(El)) {
716 auto Count = Subrange->getCount();
717 if (auto *Dependency = Count.dyn_cast<DIVariable *>())
718 Result.push_back(Dependency);
719 }
720 }
721 return Result;
722}
723
724/// Sort local variables so that variables appearing inside of helper
725/// expressions come first.
726static SmallVector<DbgVariable *, 8>
727sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
728 SmallVector<DbgVariable *, 8> Result;
729 SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
730 // Map back from a DIVariable to its containing DbgVariable.
731 SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
732 // Set of DbgVariables in Result.
733 SmallDenseSet<DbgVariable *, 8> Visited;
734 // For cycle detection.
735 SmallDenseSet<DbgVariable *, 8> Visiting;
736
737 // Initialize the worklist and the DIVariable lookup table.
738 for (auto Var : reverse(Input)) {
739 DbgVar.insert({Var->getVariable(), Var});
740 WorkList.push_back({Var, 0});
741 }
742
743 // Perform a stable topological sort by doing a DFS.
744 while (!WorkList.empty()) {
745 auto Item = WorkList.back();
746 DbgVariable *Var = Item.getPointer();
747 bool visitedAllDependencies = Item.getInt();
748 WorkList.pop_back();
749
750 // Dependency is in a different lexical scope or a global.
751 if (!Var)
752 continue;
753
754 // Already handled.
755 if (Visited.count(Var))
756 continue;
757
758 // Add to Result if all dependencies are visited.
759 if (visitedAllDependencies) {
760 Visited.insert(Var);
761 Result.push_back(Var);
762 continue;
763 }
764
765 // Detect cycles.
766 auto Res = Visiting.insert(Var);
767 if (!Res.second) {
768 assert(false && "dependency cycle in local variables")((false && "dependency cycle in local variables") ? static_cast
<void> (0) : __assert_fail ("false && \"dependency cycle in local variables\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 768, __PRETTY_FUNCTION__))
;
769 return Result;
770 }
771
772 // Push dependencies and this node onto the worklist, so that this node is
773 // visited again after all of its dependencies are handled.
774 WorkList.push_back({Var, 1});
775 for (auto *Dependency : dependencies(Var)) {
776 auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency);
777 WorkList.push_back({DbgVar[Dep], 0});
778 }
779 }
780 return Result;
781}
782
783DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
784 SmallVectorImpl<DIE *> &Children,
785 bool *HasNonScopeChildren) {
786 assert(Children.empty())((Children.empty()) ? static_cast<void> (0) : __assert_fail
("Children.empty()", "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 786, __PRETTY_FUNCTION__))
;
787 DIE *ObjectPointer = nullptr;
788
789 // Emit function arguments (order is significant).
790 auto Vars = DU->getScopeVariables().lookup(Scope);
791 for (auto &DV : Vars.Args)
792 Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
793
794 // Emit local variables.
795 auto Locals = sortLocalVars(Vars.Locals);
796 for (DbgVariable *DV : Locals)
797 Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
798
799 // Skip imported directives in gmlt-like data.
800 if (!includeMinimalInlineScopes()) {
801 // There is no need to emit empty lexical block DIE.
802 for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
803 Children.push_back(
804 constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
805 }
806
807 if (HasNonScopeChildren)
808 *HasNonScopeChildren = !Children.empty();
809
810 for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
811 Children.push_back(constructLabelDIE(*DL, *Scope));
812
813 for (LexicalScope *LS : Scope->getChildren())
814 constructScopeDIE(LS, Children);
815
816 return ObjectPointer;
817}
818
819DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
820 LexicalScope *Scope) {
821 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
822
823 if (Scope) {
824 assert(!Scope->getInlinedAt())((!Scope->getInlinedAt()) ? static_cast<void> (0) : __assert_fail
("!Scope->getInlinedAt()", "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 824, __PRETTY_FUNCTION__))
;
825 assert(!Scope->isAbstractScope())((!Scope->isAbstractScope()) ? static_cast<void> (0)
: __assert_fail ("!Scope->isAbstractScope()", "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 825, __PRETTY_FUNCTION__))
;
826 // Collect lexical scope children first.
827 // ObjectPointer might be a local (non-argument) local variable if it's a
828 // block's synthetic this pointer.
829 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
830 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
831 }
832
833 // If this is a variadic function, add an unspecified parameter.
834 DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
835
836 // If we have a single element of null, it is a function that returns void.
837 // If we have more than one elements and the last one is null, it is a
838 // variadic function.
839 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
840 !includeMinimalInlineScopes())
841 ScopeDIE.addChild(
842 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
843
844 return ScopeDIE;
845}
846
847DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
848 DIE &ScopeDIE) {
849 // We create children when the scope DIE is not null.
850 SmallVector<DIE *, 8> Children;
851 DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
852
853 // Add children
854 for (auto &I : Children)
855 ScopeDIE.addChild(std::move(I));
856
857 return ObjectPointer;
858}
859
860void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
861 LexicalScope *Scope) {
862 DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
863 if (AbsDef)
864 return;
865
866 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
867
868 DIE *ContextDIE;
869 DwarfCompileUnit *ContextCU = this;
870
871 if (includeMinimalInlineScopes())
872 ContextDIE = &getUnitDie();
873 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
874 // the important distinction that the debug node is not associated with the
875 // DIE (since the debug node will be associated with the concrete DIE, if
876 // any). It could be refactored to some common utility function.
877 else if (auto *SPDecl = SP->getDeclaration()) {
878 ContextDIE = &getUnitDie();
879 getOrCreateSubprogramDIE(SPDecl);
880 } else {
881 ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
882 // The scope may be shared with a subprogram that has already been
883 // constructed in another CU, in which case we need to construct this
884 // subprogram in the same CU.
885 ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
886 }
887
888 // Passing null as the associated node because the abstract definition
889 // shouldn't be found by lookup.
890 AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
891 ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
892
893 if (!ContextCU->includeMinimalInlineScopes())
894 ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
895 if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
896 ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
897}
898
899DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE,
900 const DISubprogram &CalleeSP,
901 bool IsTail,
902 const MCExpr *PCOffset) {
903 // Insert a call site entry DIE within ScopeDIE.
904 DIE &CallSiteDIE =
905 createAndAddDIE(dwarf::DW_TAG_call_site, ScopeDIE, nullptr);
906
907 // For the purposes of showing tail call frames in backtraces, a key piece of
908 // information is DW_AT_call_origin, a pointer to the callee DIE.
909 DIE *CalleeDIE = getOrCreateSubprogramDIE(&CalleeSP);
910 assert(CalleeDIE && "Could not create DIE for call site entry origin")((CalleeDIE && "Could not create DIE for call site entry origin"
) ? static_cast<void> (0) : __assert_fail ("CalleeDIE && \"Could not create DIE for call site entry origin\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 910, __PRETTY_FUNCTION__))
;
911 addDIEEntry(CallSiteDIE, dwarf::DW_AT_call_origin, *CalleeDIE);
912
913 if (IsTail) {
914 // Attach DW_AT_call_tail_call to tail calls for standards compliance.
915 addFlag(CallSiteDIE, dwarf::DW_AT_call_tail_call);
916 } else {
917 // Attach the return PC to allow the debugger to disambiguate call paths
918 // from one function to another.
919 assert(PCOffset && "Missing return PC information for a call")((PCOffset && "Missing return PC information for a call"
) ? static_cast<void> (0) : __assert_fail ("PCOffset && \"Missing return PC information for a call\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 919, __PRETTY_FUNCTION__))
;
920 addAddressExpr(CallSiteDIE, dwarf::DW_AT_call_return_pc, PCOffset);
921 }
922 return CallSiteDIE;
923}
924
925DIE *DwarfCompileUnit::constructImportedEntityDIE(
926 const DIImportedEntity *Module) {
927 DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
928 insertDIE(Module, IMDie);
929 DIE *EntityDie;
930 auto *Entity = resolve(Module->getEntity());
931 if (auto *NS = dyn_cast<DINamespace>(Entity))
932 EntityDie = getOrCreateNameSpace(NS);
933 else if (auto *M = dyn_cast<DIModule>(Entity))
934 EntityDie = getOrCreateModule(M);
935 else if (auto *SP = dyn_cast<DISubprogram>(Entity))
936 EntityDie = getOrCreateSubprogramDIE(SP);
937 else if (auto *T = dyn_cast<DIType>(Entity))
938 EntityDie = getOrCreateTypeDIE(T);
939 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
940 EntityDie = getOrCreateGlobalVariableDIE(GV, {});
941 else
942 EntityDie = getDIE(Entity);
943 assert(EntityDie)((EntityDie) ? static_cast<void> (0) : __assert_fail ("EntityDie"
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 943, __PRETTY_FUNCTION__))
;
944 addSourceLine(*IMDie, Module->getLine(), Module->getFile());
945 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
946 StringRef Name = Module->getName();
947 if (!Name.empty())
948 addString(*IMDie, dwarf::DW_AT_name, Name);
949
950 return IMDie;
951}
952
953void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
954 DIE *D = getDIE(SP);
955 if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
956 if (D)
957 // If this subprogram has an abstract definition, reference that
958 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
959 } else {
960 assert(D || includeMinimalInlineScopes())((D || includeMinimalInlineScopes()) ? static_cast<void>
(0) : __assert_fail ("D || includeMinimalInlineScopes()", "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 960, __PRETTY_FUNCTION__))
;
961 if (D)
962 // And attach the attributes
963 applySubprogramAttributesToDefinition(SP, *D);
964 }
965}
966
967void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
968 DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
969
970 auto *Die = Entity->getDIE();
971 /// Label may be used to generate DW_AT_low_pc, so put it outside
972 /// if/else block.
973 const DbgLabel *Label = nullptr;
974 if (AbsEntity && AbsEntity->getDIE()) {
975 addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
976 Label = dyn_cast<const DbgLabel>(Entity);
977 } else {
978 if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
979 applyVariableAttributes(*Var, *Die);
980 else if ((Label = dyn_cast<const DbgLabel>(Entity)))
981 applyLabelAttributes(*Label, *Die);
982 else
983 llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.")::llvm::llvm_unreachable_internal("DbgEntity must be DbgVariable or DbgLabel."
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 983)
;
984 }
985
986 if (Label)
987 if (const auto *Sym = Label->getSymbol())
988 addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
989}
990
991DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
992 auto &AbstractEntities = getAbstractEntities();
993 auto I = AbstractEntities.find(Node);
994 if (I != AbstractEntities.end())
995 return I->second.get();
996 return nullptr;
997}
998
999void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
1000 LexicalScope *Scope) {
1001 assert(Scope && Scope->isAbstractScope())((Scope && Scope->isAbstractScope()) ? static_cast
<void> (0) : __assert_fail ("Scope && Scope->isAbstractScope()"
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 1001, __PRETTY_FUNCTION__))
;
1002 auto &Entity = getAbstractEntities()[Node];
1003 if (isa<const DILocalVariable>(Node)) {
1004 Entity = llvm::make_unique<DbgVariable>(
1005 cast<const DILocalVariable>(Node), nullptr /* IA */);;
1006 DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
1007 } else if (isa<const DILabel>(Node)) {
1008 Entity = llvm::make_unique<DbgLabel>(
1009 cast<const DILabel>(Node), nullptr /* IA */);
1010 DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
1011 }
1012}
1013
1014void DwarfCompileUnit::emitHeader(bool UseOffsets) {
1015 // Don't bother labeling the .dwo unit, as its offset isn't used.
1016 if (!Skeleton && !DD->useSectionsAsReferences()) {
1017 LabelBegin = Asm->createTempSymbol("cu_begin");
1018 Asm->OutStreamer->EmitLabel(LabelBegin);
1019 }
1020
1021 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
1022 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
1023 : dwarf::DW_UT_compile;
1024 DwarfUnit::emitCommonHeader(UseOffsets, UT);
1025 if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
1026 Asm->emitInt64(getDWOId());
1027}
1028
1029bool DwarfCompileUnit::hasDwarfPubSections() const {
1030 switch (CUNode->getNameTableKind()) {
1031 case DICompileUnit::DebugNameTableKind::None:
1032 return false;
1033 // Opting in to GNU Pubnames/types overrides the default to ensure these are
1034 // generated for things like Gold's gdb_index generation.
1035 case DICompileUnit::DebugNameTableKind::GNU:
1036 return true;
1037 case DICompileUnit::DebugNameTableKind::Default:
1038 return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
1039 !CUNode->isDebugDirectivesOnly();
1040 }
1041 llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum")::llvm::llvm_unreachable_internal("Unhandled DICompileUnit::DebugNameTableKind enum"
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 1041)
;
1042}
1043
1044/// addGlobalName - Add a new global name to the compile unit.
1045void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
1046 const DIScope *Context) {
1047 if (!hasDwarfPubSections())
1048 return;
1049 std::string FullName = getParentContextString(Context) + Name.str();
1050 GlobalNames[FullName] = &Die;
1051}
1052
1053void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
1054 const DIScope *Context) {
1055 if (!hasDwarfPubSections())
1056 return;
1057 std::string FullName = getParentContextString(Context) + Name.str();
1058 // Insert, allowing the entry to remain as-is if it's already present
1059 // This way the CU-level type DIE is preferred over the "can't describe this
1060 // type as a unit offset because it's not really in the CU at all, it's only
1061 // in a type unit"
1062 GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1063}
1064
1065/// Add a new global type to the unit.
1066void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1067 const DIScope *Context) {
1068 if (!hasDwarfPubSections())
1069 return;
1070 std::string FullName = getParentContextString(Context) + Ty->getName().str();
1071 GlobalTypes[FullName] = &Die;
1072}
1073
1074void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
1075 const DIScope *Context) {
1076 if (!hasDwarfPubSections())
1077 return;
1078 std::string FullName = getParentContextString(Context) + Ty->getName().str();
1079 // Insert, allowing the entry to remain as-is if it's already present
1080 // This way the CU-level type DIE is preferred over the "can't describe this
1081 // type as a unit offset because it's not really in the CU at all, it's only
1082 // in a type unit"
1083 GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1084}
1085
1086/// addVariableAddress - Add DW_AT_location attribute for a
1087/// DbgVariable based on provided MachineLocation.
1088void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
1089 MachineLocation Location) {
1090 // addBlockByrefAddress is obsolete and will be removed soon.
1091 // The clang frontend always generates block byref variables with a
1092 // complex expression that encodes exactly what addBlockByrefAddress
1093 // would do.
1094 assert((!DV.isBlockByrefVariable() || DV.hasComplexAddress()) &&(((!DV.isBlockByrefVariable() || DV.hasComplexAddress()) &&
"block byref variable without a complex expression") ? static_cast
<void> (0) : __assert_fail ("(!DV.isBlockByrefVariable() || DV.hasComplexAddress()) && \"block byref variable without a complex expression\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 1095, __PRETTY_FUNCTION__))
1095 "block byref variable without a complex expression")(((!DV.isBlockByrefVariable() || DV.hasComplexAddress()) &&
"block byref variable without a complex expression") ? static_cast
<void> (0) : __assert_fail ("(!DV.isBlockByrefVariable() || DV.hasComplexAddress()) && \"block byref variable without a complex expression\""
, "/build/llvm-toolchain-snapshot-9~svn358860/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 1095, __PRETTY_FUNCTION__))
;
1096 if (DV.hasComplexAddress())
1097 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
1098 else
1099 addAddress(Die, dwarf::DW_AT_location, Location);
1100}
1101
1102/// Add an address attribute to a die based on the location provided.
1103void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
1104 const MachineLocation &Location) {
1105 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1106 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1107 if (Location.isIndirect())
1108 DwarfExpr.setMemoryLocationKind();
1109
1110 DIExpressionCursor Cursor({});
1111 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1112 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1113 return;
1114 DwarfExpr.addExpression(std::move(Cursor));
1115
1116 // Now attach the location information to the DIE.
1117 addBlock(Die, Attribute, DwarfExpr.finalize());
1118}
1119
1120/// Start with the address based on the location provided, and generate the
1121/// DWARF information necessary to find the actual variable given the extra
1122/// address information encoded in the DbgVariable, starting from the starting
1123/// location. Add the DWARF information to the die.
1124void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
1125 dwarf::Attribute Attribute,
1126 const MachineLocation &Location) {
1127 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1128 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1129 const DIExpression *DIExpr = DV.getSingleExpression();
1130 DwarfExpr.addFragmentOffset(DIExpr);
1131 if (Location.isIndirect())
1132 DwarfExpr.setMemoryLocationKind();
1133
1134 DIExpressionCursor Cursor(DIExpr);
1135 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1136 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1137 return;
1138 DwarfExpr.addExpression(std::move(Cursor));
1139
1140 // Now attach the location information to the DIE.
1141 addBlock(Die, Attribute, DwarfExpr.finalize());
1142}
1143
1144/// Add a Dwarf loclistptr attribute data and value.
1145void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
1146 unsigned Index) {
1147 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1148 : dwarf::DW_FORM_data4;
1149 Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
1150}
1151
1152void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
1153 DIE &VariableDie) {
1154 StringRef Name = Var.getName();
1155 if (!Name.empty())
1156 addString(VariableDie, dwarf::DW_AT_name, Name);
1157 const auto *DIVar = Var.getVariable();
1158 if (DIVar)
1159 if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
1160 addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1161 AlignInBytes);
1162
1163 addSourceLine(VariableDie, DIVar);
1164 addType(VariableDie, Var.getType());
1165 if (Var.isArtificial())
1166 addFlag(VariableDie, dwarf::DW_AT_artificial);
1167}
1168
1169void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
1170 DIE &LabelDie) {
1171 StringRef Name = Label.getName();
1172 if (!Name.empty())
1173 addString(LabelDie, dwarf::DW_AT_name, Name);
1174 const auto *DILabel = Label.getLabel();
1175 addSourceLine(LabelDie, DILabel);
1176}
1177
1178/// Add a Dwarf expression attribute data and value.
1179void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
1180 const MCExpr *Expr) {
1181 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
1182}
1183
1184void DwarfCompileUnit::addAddressExpr(DIE &Die, dwarf::Attribute Attribute,
1185 const MCExpr *Expr) {
1186 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
1187 DIEExpr(Expr));
1188}
1189
1190void DwarfCompileUnit::applySubprogramAttributesToDefinition(
1191 const DISubprogram *SP, DIE &SPDie) {
1192 auto *SPDecl = SP->getDeclaration();
1193 auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
1194 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
1195 addGlobalName(SP->getName(), SPDie, Context);
1196}
1197
1198bool DwarfCompileUnit::isDwoUnit() const {
1199 return DD->useSplitDwarf() && Skeleton;
1200}
1201
1202bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1203 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
1204 (DD->useSplitDwarf() && !Skeleton);
1205}
1206
1207void DwarfCompileUnit::addAddrTableBase() {
1208 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1209 MCSymbol *Label = DD->getAddressPool().getLabel();
1210 addSectionLabel(getUnitDie(),
1211 getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
1212 : dwarf::DW_AT_GNU_addr_base,
1213 Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
1214}
1215
1216void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
1217 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
1
Calling 'DIEValueList::addValue'
1218 new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
1219}
1220
1221void DwarfCompileUnit::createBaseTypeDIEs() {
1222 // Insert the base_type DIEs directly after the CU so that their offsets will
1223 // fit in the fixed size ULEB128 used inside the location expressions.
1224 // Maintain order by iterating backwards and inserting to the front of CU
1225 // child list.
1226 for (auto &Btr : reverse(ExprRefedBaseTypes)) {
1227 DIE &Die = getUnitDie().addChildFront(
1228 DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
1229 SmallString<32> Str;
1230 addString(Die, dwarf::DW_AT_name,
1231 Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
1232 "_" + Twine(Btr.BitSize)).toStringRef(Str));
1233 addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
1234 addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8);
1235
1236 Btr.Die = &Die;
1237 }
1238}

/build/llvm-toolchain-snapshot-9~svn358860/include/llvm/CodeGen/DIE.h

1//===- lib/CodeGen/DIE.h - DWARF Info Entries -------------------*- C++ -*-===//
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// Data structures for DWARF info entries.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DIE_H
14#define LLVM_LIB_CODEGEN_ASMPRINTER_DIE_H
15
16#include "llvm/ADT/FoldingSet.h"
17#include "llvm/ADT/PointerIntPair.h"
18#include "llvm/ADT/PointerUnion.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/iterator.h"
22#include "llvm/ADT/iterator_range.h"
23#include "llvm/BinaryFormat/Dwarf.h"
24#include "llvm/CodeGen/DwarfStringPoolEntry.h"
25#include "llvm/Support/AlignOf.h"
26#include "llvm/Support/Allocator.h"
27#include <cassert>
28#include <cstddef>
29#include <cstdint>
30#include <iterator>
31#include <new>
32#include <type_traits>
33#include <utility>
34#include <vector>
35
36namespace llvm {
37
38class AsmPrinter;
39class DIE;
40class DIEUnit;
41class DwarfCompileUnit;
42class MCExpr;
43class MCSection;
44class MCSymbol;
45class raw_ostream;
46
47//===--------------------------------------------------------------------===//
48/// Dwarf abbreviation data, describes one attribute of a Dwarf abbreviation.
49class DIEAbbrevData {
50 /// Dwarf attribute code.
51 dwarf::Attribute Attribute;
52
53 /// Dwarf form code.
54 dwarf::Form Form;
55
56 /// Dwarf attribute value for DW_FORM_implicit_const
57 int64_t Value = 0;
58
59public:
60 DIEAbbrevData(dwarf::Attribute A, dwarf::Form F)
61 : Attribute(A), Form(F) {}
62 DIEAbbrevData(dwarf::Attribute A, int64_t V)
63 : Attribute(A), Form(dwarf::DW_FORM_implicit_const), Value(V) {}
64
65 /// Accessors.
66 /// @{
67 dwarf::Attribute getAttribute() const { return Attribute; }
68 dwarf::Form getForm() const { return Form; }
69 int64_t getValue() const { return Value; }
70 /// @}
71
72 /// Used to gather unique data for the abbreviation folding set.
73 void Profile(FoldingSetNodeID &ID) const;
74};
75
76//===--------------------------------------------------------------------===//
77/// Dwarf abbreviation, describes the organization of a debug information
78/// object.
79class DIEAbbrev : public FoldingSetNode {
80 /// Unique number for node.
81 unsigned Number;
82
83 /// Dwarf tag code.
84 dwarf::Tag Tag;
85
86 /// Whether or not this node has children.
87 ///
88 /// This cheats a bit in all of the uses since the values in the standard
89 /// are 0 and 1 for no children and children respectively.
90 bool Children;
91
92 /// Raw data bytes for abbreviation.
93 SmallVector<DIEAbbrevData, 12> Data;
94
95public:
96 DIEAbbrev(dwarf::Tag T, bool C) : Tag(T), Children(C) {}
97
98 /// Accessors.
99 /// @{
100 dwarf::Tag getTag() const { return Tag; }
101 unsigned getNumber() const { return Number; }
102 bool hasChildren() const { return Children; }
103 const SmallVectorImpl<DIEAbbrevData> &getData() const { return Data; }
104 void setChildrenFlag(bool hasChild) { Children = hasChild; }
105 void setNumber(unsigned N) { Number = N; }
106 /// @}
107
108 /// Adds another set of attribute information to the abbreviation.
109 void AddAttribute(dwarf::Attribute Attribute, dwarf::Form Form) {
110 Data.push_back(DIEAbbrevData(Attribute, Form));
111 }
112
113 /// Adds attribute with DW_FORM_implicit_const value
114 void AddImplicitConstAttribute(dwarf::Attribute Attribute, int64_t Value) {
115 Data.push_back(DIEAbbrevData(Attribute, Value));
116 }
117
118 /// Used to gather unique data for the abbreviation folding set.
119 void Profile(FoldingSetNodeID &ID) const;
120
121 /// Print the abbreviation using the specified asm printer.
122 void Emit(const AsmPrinter *AP) const;
123
124 void print(raw_ostream &O) const;
125 void dump() const;
126};
127
128//===--------------------------------------------------------------------===//
129/// Helps unique DIEAbbrev objects and assigns abbreviation numbers.
130///
131/// This class will unique the DIE abbreviations for a llvm::DIE object and
132/// assign a unique abbreviation number to each unique DIEAbbrev object it
133/// finds. The resulting collection of DIEAbbrev objects can then be emitted
134/// into the .debug_abbrev section.
135class DIEAbbrevSet {
136 /// The bump allocator to use when creating DIEAbbrev objects in the uniqued
137 /// storage container.
138 BumpPtrAllocator &Alloc;
139 /// FoldingSet that uniques the abbreviations.
140 FoldingSet<DIEAbbrev> AbbreviationsSet;
141 /// A list of all the unique abbreviations in use.
142 std::vector<DIEAbbrev *> Abbreviations;
143
144public:
145 DIEAbbrevSet(BumpPtrAllocator &A) : Alloc(A) {}
146 ~DIEAbbrevSet();
147
148 /// Generate the abbreviation declaration for a DIE and return a pointer to
149 /// the generated abbreviation.
150 ///
151 /// \param Die the debug info entry to generate the abbreviation for.
152 /// \returns A reference to the uniqued abbreviation declaration that is
153 /// owned by this class.
154 DIEAbbrev &uniqueAbbreviation(DIE &Die);
155
156 /// Print all abbreviations using the specified asm printer.
157 void Emit(const AsmPrinter *AP, MCSection *Section) const;
158};
159
160//===--------------------------------------------------------------------===//
161/// An integer value DIE.
162///
163class DIEInteger {
164 uint64_t Integer;
165
166public:
167 explicit DIEInteger(uint64_t I) : Integer(I) {}
168
169 /// Choose the best form for integer.
170 static dwarf::Form BestForm(bool IsSigned, uint64_t Int) {
171 if (IsSigned) {
172 const int64_t SignedInt = Int;
173 if ((char)Int == SignedInt)
174 return dwarf::DW_FORM_data1;
175 if ((short)Int == SignedInt)
176 return dwarf::DW_FORM_data2;
177 if ((int)Int == SignedInt)
178 return dwarf::DW_FORM_data4;
179 } else {
180 if ((unsigned char)Int == Int)
181 return dwarf::DW_FORM_data1;
182 if ((unsigned short)Int == Int)
183 return dwarf::DW_FORM_data2;
184 if ((unsigned int)Int == Int)
185 return dwarf::DW_FORM_data4;
186 }
187 return dwarf::DW_FORM_data8;
188 }
189
190 uint64_t getValue() const { return Integer; }
191 void setValue(uint64_t Val) { Integer = Val; }
192
193 void EmitValue(const AsmPrinter *Asm, dwarf::Form Form) const;
194 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
195
196 void print(raw_ostream &O) const;
197};
198
199//===--------------------------------------------------------------------===//
200/// An expression DIE.
201class DIEExpr {
202 const MCExpr *Expr;
203
204public:
205 explicit DIEExpr(const MCExpr *E) : Expr(E) {}
206
207 /// Get MCExpr.
208 const MCExpr *getValue() const { return Expr; }
209
210 void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
211 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
212
213 void print(raw_ostream &O) const;
214};
215
216//===--------------------------------------------------------------------===//
217/// A label DIE.
218class DIELabel {
219 const MCSymbol *Label;
220
221public:
222 explicit DIELabel(const MCSymbol *L) : Label(L) {}
223
224 /// Get MCSymbol.
225 const MCSymbol *getValue() const { return Label; }
226
227 void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
228 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
229
230 void print(raw_ostream &O) const;
231};
232
233//===--------------------------------------------------------------------===//
234/// A BaseTypeRef DIE.
235class DIEBaseTypeRef {
236 const DwarfCompileUnit *CU;
237 const uint64_t Index;
238 static constexpr unsigned ULEB128PadSize = 4;
239
240public:
241 explicit DIEBaseTypeRef(const DwarfCompileUnit *TheCU, uint64_t Idx)
242 : CU(TheCU), Index(Idx) {}
243
244 /// EmitValue - Emit base type reference.
245 void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
246 /// SizeOf - Determine size of the base type reference in bytes.
247 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
248
249 void print(raw_ostream &O) const;
250};
251
252//===--------------------------------------------------------------------===//
253/// A simple label difference DIE.
254///
255class DIEDelta {
256 const MCSymbol *LabelHi;
257 const MCSymbol *LabelLo;
258
259public:
260 DIEDelta(const MCSymbol *Hi, const MCSymbol *Lo) : LabelHi(Hi), LabelLo(Lo) {}
261
262 void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
263 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
264
265 void print(raw_ostream &O) const;
266};
267
268//===--------------------------------------------------------------------===//
269/// A container for string pool string values.
270///
271/// This class is used with the DW_FORM_strp and DW_FORM_GNU_str_index forms.
272class DIEString {
273 DwarfStringPoolEntryRef S;
274
275public:
276 DIEString(DwarfStringPoolEntryRef S) : S(S) {}
277
278 /// Grab the string out of the object.
279 StringRef getString() const { return S.getString(); }
280
281 void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
282 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
283
284 void print(raw_ostream &O) const;
285};
286
287//===--------------------------------------------------------------------===//
288/// A container for inline string values.
289///
290/// This class is used with the DW_FORM_string form.
291class DIEInlineString {
292 StringRef S;
293
294public:
295 template <typename Allocator>
296 explicit DIEInlineString(StringRef Str, Allocator &A) : S(Str.copy(A)) {}
297
298 ~DIEInlineString() = default;
299
300 /// Grab the string out of the object.
301 StringRef getString() const { return S; }
302
303 void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
304 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
305
306 void print(raw_ostream &O) const;
307};
308
309//===--------------------------------------------------------------------===//
310/// A pointer to another debug information entry. An instance of this class can
311/// also be used as a proxy for a debug information entry not yet defined
312/// (ie. types.)
313class DIEEntry {
314 DIE *Entry;
315
316public:
317 DIEEntry() = delete;
318 explicit DIEEntry(DIE &E) : Entry(&E) {}
319
320 DIE &getEntry() const { return *Entry; }
321
322 void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
323 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
324
325 void print(raw_ostream &O) const;
326};
327
328//===--------------------------------------------------------------------===//
329/// Represents a pointer to a location list in the debug_loc
330/// section.
331class DIELocList {
332 /// Index into the .debug_loc vector.
333 size_t Index;
334
335public:
336 DIELocList(size_t I) : Index(I) {}
337
338 /// Grab the current index out.
339 size_t getValue() const { return Index; }
340
341 void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
342 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
343
344 void print(raw_ostream &O) const;
345};
346
347//===--------------------------------------------------------------------===//
348/// A debug information entry value. Some of these roughly correlate
349/// to DWARF attribute classes.
350class DIEBlock;
351class DIELoc;
352class DIEValue {
353public:
354 enum Type {
355 isNone,
356#define HANDLE_DIEVALUE(T) is##T,
357#include "llvm/CodeGen/DIEValue.def"
358 };
359
360private:
361 /// Type of data stored in the value.
362 Type Ty = isNone;
363 dwarf::Attribute Attribute = (dwarf::Attribute)0;
364 dwarf::Form Form = (dwarf::Form)0;
365
366 /// Storage for the value.
367 ///
368 /// All values that aren't standard layout (or are larger than 8 bytes)
369 /// should be stored by reference instead of by value.
370 using ValTy = AlignedCharArrayUnion<DIEInteger, DIEString, DIEExpr, DIELabel,
371 DIEDelta *, DIEEntry, DIEBlock *,
372 DIELoc *, DIELocList, DIEBaseTypeRef *>;
373
374 static_assert(sizeof(ValTy) <= sizeof(uint64_t) ||
375 sizeof(ValTy) <= sizeof(void *),
376 "Expected all large types to be stored via pointer");
377
378 /// Underlying stored value.
379 ValTy Val;
380
381 template <class T> void construct(T V) {
382 static_assert(std::is_standard_layout<T>::value ||
383 std::is_pointer<T>::value,
384 "Expected standard layout or pointer");
385 new (reinterpret_cast<void *>(Val.buffer)) T(V);
386 }
387
388 template <class T> T *get() { return reinterpret_cast<T *>(Val.buffer); }
389 template <class T> const T *get() const {
390 return reinterpret_cast<const T *>(Val.buffer);
391 }
392 template <class T> void destruct() { get<T>()->~T(); }
393
394 /// Destroy the underlying value.
395 ///
396 /// This should get optimized down to a no-op. We could skip it if we could
397 /// add a static assert on \a std::is_trivially_copyable(), but we currently
398 /// support versions of GCC that don't understand that.
399 void destroyVal() {
400 switch (Ty) {
401 case isNone:
402 return;
403#define HANDLE_DIEVALUE_SMALL(T) \
404 case is##T: \
405 destruct<DIE##T>(); \
406 return;
407#define HANDLE_DIEVALUE_LARGE(T) \
408 case is##T: \
409 destruct<const DIE##T *>(); \
410 return;
411#include "llvm/CodeGen/DIEValue.def"
412 }
413 }
414
415 /// Copy the underlying value.
416 ///
417 /// This should get optimized down to a simple copy. We need to actually
418 /// construct the value, rather than calling memcpy, to satisfy strict
419 /// aliasing rules.
420 void copyVal(const DIEValue &X) {
421 switch (Ty) {
422 case isNone:
423 return;
424#define HANDLE_DIEVALUE_SMALL(T) \
425 case is##T: \
426 construct<DIE##T>(*X.get<DIE##T>()); \
427 return;
428#define HANDLE_DIEVALUE_LARGE(T) \
429 case is##T: \
430 construct<const DIE##T *>(*X.get<const DIE##T *>()); \
431 return;
432#include "llvm/CodeGen/DIEValue.def"
433 }
434 }
435
436public:
437 DIEValue() = default;
438
439 DIEValue(const DIEValue &X) : Ty(X.Ty), Attribute(X.Attribute), Form(X.Form) {
440 copyVal(X);
441 }
442
443 DIEValue &operator=(const DIEValue &X) {
444 destroyVal();
445 Ty = X.Ty;
446 Attribute = X.Attribute;
447 Form = X.Form;
448 copyVal(X);
449 return *this;
450 }
451
452 ~DIEValue() { destroyVal(); }
453
454#define HANDLE_DIEVALUE_SMALL(T) \
455 DIEValue(dwarf::Attribute Attribute, dwarf::Form Form, const DIE##T &V) \
456 : Ty(is##T), Attribute(Attribute), Form(Form) { \
457 construct<DIE##T>(V); \
458 }
459#define HANDLE_DIEVALUE_LARGE(T) \
460 DIEValue(dwarf::Attribute Attribute, dwarf::Form Form, const DIE##T *V) \
461 : Ty(is##T), Attribute(Attribute), Form(Form) { \
462 assert(V && "Expected valid value")((V && "Expected valid value") ? static_cast<void>
(0) : __assert_fail ("V && \"Expected valid value\""
, "/build/llvm-toolchain-snapshot-9~svn358860/include/llvm/CodeGen/DIE.h"
, 462, __PRETTY_FUNCTION__))
; \
463 construct<const DIE##T *>(V); \
464 }
465#include "llvm/CodeGen/DIEValue.def"
466
467 /// Accessors.
468 /// @{
469 Type getType() const { return Ty; }
470 dwarf::Attribute getAttribute() const { return Attribute; }
471 dwarf::Form getForm() const { return Form; }
472 explicit operator bool() const { return Ty; }
473 /// @}
474
475#define HANDLE_DIEVALUE_SMALL(T) \
476 const DIE##T &getDIE##T() const { \
477 assert(getType() == is##T && "Expected " #T)((getType() == is##T && "Expected " #T) ? static_cast
<void> (0) : __assert_fail ("getType() == is##T && \"Expected \" #T"
, "/build/llvm-toolchain-snapshot-9~svn358860/include/llvm/CodeGen/DIE.h"
, 477, __PRETTY_FUNCTION__))
; \
478 return *get<DIE##T>(); \
479 }
480#define HANDLE_DIEVALUE_LARGE(T) \
481 const DIE##T &getDIE##T() const { \
482 assert(getType() == is##T && "Expected " #T)((getType() == is##T && "Expected " #T) ? static_cast
<void> (0) : __assert_fail ("getType() == is##T && \"Expected \" #T"
, "/build/llvm-toolchain-snapshot-9~svn358860/include/llvm/CodeGen/DIE.h"
, 482, __PRETTY_FUNCTION__))
; \
483 return **get<const DIE##T *>(); \
484 }
485#include "llvm/CodeGen/DIEValue.def"
486
487 /// Emit value via the Dwarf writer.
488 void EmitValue(const AsmPrinter *AP) const;
489
490 /// Return the size of a value in bytes.
491 unsigned SizeOf(const AsmPrinter *AP) const;
492
493 void print(raw_ostream &O) const;
494 void dump() const;
495};
496
497struct IntrusiveBackListNode {
498 PointerIntPair<IntrusiveBackListNode *, 1> Next;
499
500 IntrusiveBackListNode() : Next(this, true) {}
501
502 IntrusiveBackListNode *getNext() const {
503 return Next.getInt() ? nullptr : Next.getPointer();
504 }
505};
506
507struct IntrusiveBackListBase {
508 using Node = IntrusiveBackListNode;
509
510 Node *Last = nullptr;
511
512 bool empty() const { return !Last; }
513
514 void push_back(Node &N) {
515 assert(N.Next.getPointer() == &N && "Expected unlinked node")((N.Next.getPointer() == &N && "Expected unlinked node"
) ? static_cast<void> (0) : __assert_fail ("N.Next.getPointer() == &N && \"Expected unlinked node\""
, "/build/llvm-toolchain-snapshot-9~svn358860/include/llvm/CodeGen/DIE.h"
, 515, __PRETTY_FUNCTION__))
;
516 assert(N.Next.getInt() == true && "Expected unlinked node")((N.Next.getInt() == true && "Expected unlinked node"
) ? static_cast<void> (0) : __assert_fail ("N.Next.getInt() == true && \"Expected unlinked node\""
, "/build/llvm-toolchain-snapshot-9~svn358860/include/llvm/CodeGen/DIE.h"
, 516, __PRETTY_FUNCTION__))
;
517
518 if (Last) {
519 N.Next = Last->Next;
520 Last->Next.setPointerAndInt(&N, false);
521 }
522 Last = &N;
523 }
524
525 void push_front(Node &N) {
526 assert(N.Next.getPointer() == &N && "Expected unlinked node")((N.Next.getPointer() == &N && "Expected unlinked node"
) ? static_cast<void> (0) : __assert_fail ("N.Next.getPointer() == &N && \"Expected unlinked node\""
, "/build/llvm-toolchain-snapshot-9~svn358860/include/llvm/CodeGen/DIE.h"
, 526, __PRETTY_FUNCTION__))
;
527 assert(N.Next.getInt() == true && "Expected unlinked node")((N.Next.getInt() == true && "Expected unlinked node"
) ? static_cast<void> (0) : __assert_fail ("N.Next.getInt() == true && \"Expected unlinked node\""
, "/build/llvm-toolchain-snapshot-9~svn358860/include/llvm/CodeGen/DIE.h"
, 527, __PRETTY_FUNCTION__))
;
528
529 if (Last) {
530 N.Next.setPointerAndInt(Last->Next.getPointer(), false);
531 Last->Next.setPointerAndInt(&N, true);
532 } else {
533 Last = &N;
534 }
535 }
536};
537
538template <class T> class IntrusiveBackList : IntrusiveBackListBase {
539public:
540 using IntrusiveBackListBase::empty;
541
542 void push_back(T &N) { IntrusiveBackListBase::push_back(N); }
543 void push_front(T &N) { IntrusiveBackListBase::push_front(N); }
544 T &back() { return *static_cast<T *>(Last); }
545 const T &back() const { return *static_cast<T *>(Last); }
546 T &front() {
547 return *static_cast<T *>(Last ? Last->Next.getPointer() : nullptr);
548 }
549 const T &front() const {
550 return *static_cast<T *>(Last ? Last->Next.getPointer() : nullptr);
551 }
552
553 class const_iterator;
554 class iterator
555 : public iterator_facade_base<iterator, std::forward_iterator_tag, T> {
556 friend class const_iterator;
557
558 Node *N = nullptr;
559
560 public:
561 iterator() = default;
562 explicit iterator(T *N) : N(N) {}
563
564 iterator &operator++() {
565 N = N->getNext();
566 return *this;
567 }
568
569 explicit operator bool() const { return N; }
570 T &operator*() const { return *static_cast<T *>(N); }
571
572 bool operator==(const iterator &X) const { return N == X.N; }
573 bool operator!=(const iterator &X) const { return N != X.N; }
574 };
575
576 class const_iterator
577 : public iterator_facade_base<const_iterator, std::forward_iterator_tag,
578 const T> {
579 const Node *N = nullptr;
580
581 public:
582 const_iterator() = default;
583 // Placate MSVC by explicitly scoping 'iterator'.
584 const_iterator(typename IntrusiveBackList<T>::iterator X) : N(X.N) {}
585 explicit const_iterator(const T *N) : N(N) {}
586
587 const_iterator &operator++() {
588 N = N->getNext();
589 return *this;
590 }
591
592 explicit operator bool() const { return N; }
593 const T &operator*() const { return *static_cast<const T *>(N); }
594
595 bool operator==(const const_iterator &X) const { return N == X.N; }
596 bool operator!=(const const_iterator &X) const { return N != X.N; }
597 };
598
599 iterator begin() {
600 return Last ? iterator(static_cast<T *>(Last->Next.getPointer())) : end();
601 }
602 const_iterator begin() const {
603 return const_cast<IntrusiveBackList *>(this)->begin();
604 }
605 iterator end() { return iterator(); }
606 const_iterator end() const { return const_iterator(); }
607
608 static iterator toIterator(T &N) { return iterator(&N); }
609 static const_iterator toIterator(const T &N) { return const_iterator(&N); }
610};
611
612/// A list of DIE values.
613///
614/// This is a singly-linked list, but instead of reversing the order of
615/// insertion, we keep a pointer to the back of the list so we can push in
616/// order.
617///
618/// There are two main reasons to choose a linked list over a customized
619/// vector-like data structure.
620///
621/// 1. For teardown efficiency, we want DIEs to be BumpPtrAllocated. Using a
622/// linked list here makes this way easier to accomplish.
623/// 2. Carrying an extra pointer per \a DIEValue isn't expensive. 45% of DIEs
624/// have 2 or fewer values, and 90% have 5 or fewer. A vector would be
625/// over-allocated by 50% on average anyway, the same cost as the
626/// linked-list node.
627class DIEValueList {
628 struct Node : IntrusiveBackListNode {
629 DIEValue V;
630
631 explicit Node(DIEValue V) : V(V) {}
632 };
633
634 using ListTy = IntrusiveBackList<Node>;
635
636 ListTy List;
637
638public:
639 class const_value_iterator;
640 class value_iterator
641 : public iterator_adaptor_base<value_iterator, ListTy::iterator,
642 std::forward_iterator_tag, DIEValue> {
643 friend class const_value_iterator;
644
645 using iterator_adaptor =
646 iterator_adaptor_base<value_iterator, ListTy::iterator,
647 std::forward_iterator_tag, DIEValue>;
648
649 public:
650 value_iterator() = default;
651 explicit value_iterator(ListTy::iterator X) : iterator_adaptor(X) {}
652
653 explicit operator bool() const { return bool(wrapped()); }
654 DIEValue &operator*() const { return wrapped()->V; }
655 };
656
657 class const_value_iterator : public iterator_adaptor_base<
658 const_value_iterator, ListTy::const_iterator,
659 std::forward_iterator_tag, const DIEValue> {
660 using iterator_adaptor =
661 iterator_adaptor_base<const_value_iterator, ListTy::const_iterator,
662 std::forward_iterator_tag, const DIEValue>;
663
664 public:
665 const_value_iterator() = default;
666 const_value_iterator(DIEValueList::value_iterator X)
667 : iterator_adaptor(X.wrapped()) {}
668 explicit const_value_iterator(ListTy::const_iterator X)
669 : iterator_adaptor(X) {}
670
671 explicit operator bool() const { return bool(wrapped()); }
672 const DIEValue &operator*() const { return wrapped()->V; }
673 };
674
675 using value_range = iterator_range<value_iterator>;
676 using const_value_range = iterator_range<const_value_iterator>;
677
678 value_iterator addValue(BumpPtrAllocator &Alloc, const DIEValue &V) {
679 List.push_back(*new (Alloc) Node(V));
3
Forming reference to null pointer
680 return value_iterator(ListTy::toIterator(List.back()));
681 }
682 template <class T>
683 value_iterator addValue(BumpPtrAllocator &Alloc, dwarf::Attribute Attribute,
684 dwarf::Form Form, T &&Value) {
685 return addValue(Alloc, DIEValue(Attribute, Form, std::forward<T>(Value)));
2
Calling 'DIEValueList::addValue'
686 }
687
688 value_range values() {
689 return make_range(value_iterator(List.begin()), value_iterator(List.end()));
690 }
691 const_value_range values() const {
692 return make_range(const_value_iterator(List.begin()),
693 const_value_iterator(List.end()));
694 }
695};
696
697//===--------------------------------------------------------------------===//
698/// A structured debug information entry. Has an abbreviation which
699/// describes its organization.
700class DIE : IntrusiveBackListNode, public DIEValueList {
701 friend class IntrusiveBackList<DIE>;
702 friend class DIEUnit;
703
704 /// Dwarf unit relative offset.
705 unsigned Offset = 0;
706 /// Size of instance + children.
707 unsigned Size = 0;
708 unsigned AbbrevNumber = ~0u;
709 /// Dwarf tag code.
710 dwarf::Tag Tag = (dwarf::Tag)0;
711 /// Set to true to force a DIE to emit an abbreviation that says it has
712 /// children even when it doesn't. This is used for unit testing purposes.
713 bool ForceChildren = false;
714 /// Children DIEs.
715 IntrusiveBackList<DIE> Children;
716
717 /// The owner is either the parent DIE for children of other DIEs, or a
718 /// DIEUnit which contains this DIE as its unit DIE.
719 PointerUnion<DIE *, DIEUnit *> Owner;
720
721 explicit DIE(dwarf::Tag Tag) : Tag(Tag) {}
722
723public:
724 DIE() = delete;
725 DIE(const DIE &RHS) = delete;
726 DIE(DIE &&RHS) = delete;
727 DIE &operator=(const DIE &RHS) = delete;
728 DIE &operator=(const DIE &&RHS) = delete;
729
730 static DIE *get(BumpPtrAllocator &Alloc, dwarf::Tag Tag) {
731 return new (Alloc) DIE(Tag);
732 }
733
734 // Accessors.
735 unsigned getAbbrevNumber() const { return AbbrevNumber; }
736 dwarf::Tag getTag() const { return Tag; }
737 /// Get the compile/type unit relative offset of this DIE.
738 unsigned getOffset() const { return Offset; }
739 unsigned getSize() const { return Size; }
740 bool hasChildren() const { return ForceChildren || !Children.empty(); }
741 void setForceChildren(bool B) { ForceChildren = B; }
742
743 using child_iterator = IntrusiveBackList<DIE>::iterator;
744 using const_child_iterator = IntrusiveBackList<DIE>::const_iterator;
745 using child_range = iterator_range<child_iterator>;
746 using const_child_range = iterator_range<const_child_iterator>;
747
748 child_range children() {
749 return make_range(Children.begin(), Children.end());
750 }
751 const_child_range children() const {
752 return make_range(Children.begin(), Children.end());
753 }
754
755 DIE *getParent() const;
756
757 /// Generate the abbreviation for this DIE.
758 ///
759 /// Calculate the abbreviation for this, which should be uniqued and
760 /// eventually used to call \a setAbbrevNumber().
761 DIEAbbrev generateAbbrev() const;
762
763 /// Set the abbreviation number for this DIE.
764 void setAbbrevNumber(unsigned I) { AbbrevNumber = I; }
765
766 /// Get the absolute offset within the .debug_info or .debug_types section
767 /// for this DIE.
768 unsigned getDebugSectionOffset() const;
769
770 /// Compute the offset of this DIE and all its children.
771 ///
772 /// This function gets called just before we are going to generate the debug
773 /// information and gives each DIE a chance to figure out its CU relative DIE
774 /// offset, unique its abbreviation and fill in the abbreviation code, and
775 /// return the unit offset that points to where the next DIE will be emitted
776 /// within the debug unit section. After this function has been called for all
777 /// DIE objects, the DWARF can be generated since all DIEs will be able to
778 /// properly refer to other DIE objects since all DIEs have calculated their
779 /// offsets.
780 ///
781 /// \param AP AsmPrinter to use when calculating sizes.
782 /// \param AbbrevSet the abbreviation used to unique DIE abbreviations.
783 /// \param CUOffset the compile/type unit relative offset in bytes.
784 /// \returns the offset for the DIE that follows this DIE within the
785 /// current compile/type unit.
786 unsigned computeOffsetsAndAbbrevs(const AsmPrinter *AP,
787 DIEAbbrevSet &AbbrevSet, unsigned CUOffset);
788
789 /// Climb up the parent chain to get the compile unit or type unit DIE that
790 /// this DIE belongs to.
791 ///
792 /// \returns the compile or type unit DIE that owns this DIE, or NULL if
793 /// this DIE hasn't been added to a unit DIE.
794 const DIE *getUnitDie() const;
795
796 /// Climb up the parent chain to get the compile unit or type unit that this
797 /// DIE belongs to.
798 ///
799 /// \returns the DIEUnit that represents the compile or type unit that owns
800 /// this DIE, or NULL if this DIE hasn't been added to a unit DIE.
801 DIEUnit *getUnit() const;
802
803 void setOffset(unsigned O) { Offset = O; }
804 void setSize(unsigned S) { Size = S; }
805
806 /// Add a child to the DIE.
807 DIE &addChild(DIE *Child) {
808 assert(!Child->getParent() && "Child should be orphaned")((!Child->getParent() && "Child should be orphaned"
) ? static_cast<void> (0) : __assert_fail ("!Child->getParent() && \"Child should be orphaned\""
, "/build/llvm-toolchain-snapshot-9~svn358860/include/llvm/CodeGen/DIE.h"
, 808, __PRETTY_FUNCTION__))
;
809 Child->Owner = this;
810 Children.push_back(*Child);
811 return Children.back();
812 }
813
814 DIE &addChildFront(DIE *Child) {
815 assert(!Child->getParent() && "Child should be orphaned")((!Child->getParent() && "Child should be orphaned"
) ? static_cast<void> (0) : __assert_fail ("!Child->getParent() && \"Child should be orphaned\""
, "/build/llvm-toolchain-snapshot-9~svn358860/include/llvm/CodeGen/DIE.h"
, 815, __PRETTY_FUNCTION__))
;
816 Child->Owner = this;
817 Children.push_front(*Child);
818 return Children.front();
819 }
820
821 /// Find a value in the DIE with the attribute given.
822 ///
823 /// Returns a default-constructed DIEValue (where \a DIEValue::getType()
824 /// gives \a DIEValue::isNone) if no such attribute exists.
825 DIEValue findAttribute(dwarf::Attribute Attribute) const;
826
827 void print(raw_ostream &O, unsigned IndentCount = 0) const;
828 void dump() const;
829};
830
831//===--------------------------------------------------------------------===//
832/// Represents a compile or type unit.
833class DIEUnit {
834 /// The compile unit or type unit DIE. This variable must be an instance of
835 /// DIE so that we can calculate the DIEUnit from any DIE by traversing the
836 /// parent backchain and getting the Unit DIE, and then casting itself to a
837 /// DIEUnit. This allows us to be able to find the DIEUnit for any DIE without
838 /// having to store a pointer to the DIEUnit in each DIE instance.
839 DIE Die;
840 /// The section this unit will be emitted in. This may or may not be set to
841 /// a valid section depending on the client that is emitting DWARF.
842 MCSection *Section;
843 uint64_t Offset; /// .debug_info or .debug_types absolute section offset.
844 uint32_t Length; /// The length in bytes of all of the DIEs in this unit.
845 const uint16_t Version; /// The Dwarf version number for this unit.
846 const uint8_t AddrSize; /// The size in bytes of an address for this unit.
847protected:
848 virtual ~DIEUnit() = default;
849
850public:
851 DIEUnit(uint16_t Version, uint8_t AddrSize, dwarf::Tag UnitTag);
852 DIEUnit(const DIEUnit &RHS) = delete;
853 DIEUnit(DIEUnit &&RHS) = delete;
854 void operator=(const DIEUnit &RHS) = delete;
855 void operator=(const DIEUnit &&RHS) = delete;
856 /// Set the section that this DIEUnit will be emitted into.
857 ///
858 /// This function is used by some clients to set the section. Not all clients
859 /// that emit DWARF use this section variable.
860 void setSection(MCSection *Section) {
861 assert(!this->Section)((!this->Section) ? static_cast<void> (0) : __assert_fail
("!this->Section", "/build/llvm-toolchain-snapshot-9~svn358860/include/llvm/CodeGen/DIE.h"
, 861, __PRETTY_FUNCTION__))
;
862 this->Section = Section;
863 }
864
865 virtual const MCSymbol *getCrossSectionRelativeBaseAddress() const {
866 return nullptr;
867 }
868
869 /// Return the section that this DIEUnit will be emitted into.
870 ///
871 /// \returns Section pointer which can be NULL.
872 MCSection *getSection() const { return Section; }
873 void setDebugSectionOffset(unsigned O) { Offset = O; }
874 unsigned getDebugSectionOffset() const { return Offset; }
875 void setLength(uint64_t L) { Length = L; }
876 uint64_t getLength() const { return Length; }
877 uint16_t getDwarfVersion() const { return Version; }
878 uint16_t getAddressSize() const { return AddrSize; }
879 DIE &getUnitDie() { return Die; }
880 const DIE &getUnitDie() const { return Die; }
881};
882
883struct BasicDIEUnit final : DIEUnit {
884 BasicDIEUnit(uint16_t Version, uint8_t AddrSize, dwarf::Tag UnitTag)
885 : DIEUnit(Version, AddrSize, UnitTag) {}
886};
887
888//===--------------------------------------------------------------------===//
889/// DIELoc - Represents an expression location.
890//
891class DIELoc : public DIEValueList {
892 mutable unsigned Size = 0; // Size in bytes excluding size header.
893
894public:
895 DIELoc() = default;
896
897 /// ComputeSize - Calculate the size of the location expression.
898 ///
899 unsigned ComputeSize(const AsmPrinter *AP) const;
900
901 /// BestForm - Choose the best form for data.
902 ///
903 dwarf::Form BestForm(unsigned DwarfVersion) const {
904 if (DwarfVersion > 3)
905 return dwarf::DW_FORM_exprloc;
906 // Pre-DWARF4 location expressions were blocks and not exprloc.
907 if ((unsigned char)Size == Size)
908 return dwarf::DW_FORM_block1;
909 if ((unsigned short)Size == Size)
910 return dwarf::DW_FORM_block2;
911 if ((unsigned int)Size == Size)
912 return dwarf::DW_FORM_block4;
913 return dwarf::DW_FORM_block;
914 }
915
916 void EmitValue(const AsmPrinter *Asm, dwarf::Form Form) const;
917 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
918
919 void print(raw_ostream &O) const;
920};
921
922//===--------------------------------------------------------------------===//
923/// DIEBlock - Represents a block of values.
924//
925class DIEBlock : public DIEValueList {
926 mutable unsigned Size = 0; // Size in bytes excluding size header.
927
928public:
929 DIEBlock() = default;
930
931 /// ComputeSize - Calculate the size of the location expression.
932 ///
933 unsigned ComputeSize(const AsmPrinter *AP) const;
934
935 /// BestForm - Choose the best form for data.
936 ///
937 dwarf::Form BestForm() const {
938 if ((unsigned char)Size == Size)
939 return dwarf::DW_FORM_block1;
940 if ((unsigned short)Size == Size)
941 return dwarf::DW_FORM_block2;
942 if ((unsigned int)Size == Size)
943 return dwarf::DW_FORM_block4;
944 return dwarf::DW_FORM_block;
945 }
946
947 void EmitValue(const AsmPrinter *Asm, dwarf::Form Form) const;
948 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
949
950 void print(raw_ostream &O) const;
951};
952
953} // end namespace llvm
954
955#endif // LLVM_LIB_CODEGEN_ASMPRINTER_DIE_H