1 //===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains support for constructing a dwarf compile unit.
11 //===----------------------------------------------------------------------===//
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"
55 DwarfCompileUnit::DwarfCompileUnit(unsigned UID
, const DICompileUnit
*Node
,
56 AsmPrinter
*A
, DwarfDebug
*DW
,
58 : DwarfUnit(dwarf::DW_TAG_compile_unit
, Node
, A
, DW
, DWU
), UniqueID(UID
) {
59 insertDIE(Node
, &getUnitDie());
60 MacroLabelBegin
= Asm
->createTempSymbol("cu_macro_begin");
63 /// addLabelAddress - Add a dwarf label attribute data and value using
64 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
65 void 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
);
76 DD
->addArangeLabel(SymbolCU(this, Label
));
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
,
85 void DwarfCompileUnit::addLocalLabelAddress(DIE
&Die
,
86 dwarf::Attribute Attribute
,
87 const MCSymbol
*Label
) {
89 DD
->addArangeLabel(SymbolCU(this, Label
));
92 Die
.addValue(DIEValueAllocator
, Attribute
, dwarf::DW_FORM_addr
,
95 Die
.addValue(DIEValueAllocator
, Attribute
, dwarf::DW_FORM_addr
,
99 unsigned 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.
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();
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
);
113 DIE
*DwarfCompileUnit::getOrCreateGlobalVariableDIE(
114 const DIGlobalVariable
*GV
, ArrayRef
<GlobalExpr
> GlobalExprs
) {
115 // Check for pre-existence.
116 if (DIE
*Die
= getDIE(GV
))
121 auto *GVContext
= GV
->getScope();
122 const DIType
*GTy
= GV
->getType();
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
);
131 DIE
*VariableDIE
= &createAndAddDIE(GV
->getTag(), *ContextDIE
, GV
);
132 DIScope
*DeclContext
;
133 if (auto *SDMDecl
= GV
->getStaticDataMemberDeclaration()) {
134 DeclContext
= SDMDecl
->getScope();
135 assert(SDMDecl
->isStaticMember() && "Expected static member decl");
136 assert(GV
->isDefinition());
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
!= SDMDecl
->getBaseType())
143 addType(*VariableDIE
, GTy
);
145 DeclContext
= GV
->getScope();
146 // Add name and type.
147 addString(*VariableDIE
, dwarf::DW_AT_name
, GV
->getDisplayName());
148 addType(*VariableDIE
, GTy
);
151 if (!GV
->isLocalToUnit())
152 addFlag(*VariableDIE
, dwarf::DW_AT_external
);
154 // Add line number info.
155 addSourceLine(*VariableDIE
, GV
);
158 if (!GV
->isDefinition())
159 addFlag(*VariableDIE
, dwarf::DW_AT_declaration
);
161 addGlobalName(GV
->getName(), *VariableDIE
, DeclContext
);
163 if (uint32_t AlignInBytes
= GV
->getAlignInBytes())
164 addUInt(*VariableDIE
, dwarf::DW_AT_alignment
, dwarf::DW_FORM_udata
,
167 if (MDTuple
*TP
= GV
->getTemplateParams())
168 addTemplateParams(*VariableDIE
, DINodeArray(TP
));
171 addLocationAttribute(VariableDIE
, GV
, GlobalExprs
);
176 void 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
;
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));
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())
200 // Nothing to describe without address or constant.
201 if (!Global
&& (!Expr
|| !Expr
->isConstant()))
204 if (Global
&& Global
->isThreadLocal() &&
205 !Asm
->getObjFileLowering().supportDebugThreadLocalLocation())
209 addToAccelTable
= true;
210 Loc
= new (DIEValueAllocator
) DIELoc
;
211 DwarfExpr
= std::make_unique
<DIEDwarfExpression
>(*Asm
, *this, *Loc
);
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
) {
227 NVPTXAddressSpace
= LocalNVPTXAddressSpace
;
230 DwarfExpr
->addFragmentOffset(Expr
);
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.
239 // FIXME: Make this work with -gsplit-dwarf.
240 unsigned PointerSize
= Asm
->getDataLayout().getPointerSize();
241 assert((PointerSize
== 4 || PointerSize
== 8) &&
242 "Add support for other sizes if necessary");
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
));
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));
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
);
264 DD
->addArangeLabel(SymbolCU(this, Sym
));
265 addOpAddress(*Loc
, Sym
);
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
);
276 if (Asm
->TM
.getTargetTriple().isNVPTX() && DD
->tuneForGDB()) {
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
);
286 addBlock(*VariableDIE
, dwarf::DW_AT_location
, DwarfExpr
->finalize());
288 if (DD
->useAllLinkageNames())
289 addLinkageName(*VariableDIE
, GV
->getLinkageName());
291 if (addToAccelTable
) {
292 DD
->addAccelName(*CUNode
, GV
->getName(), *VariableDIE
);
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
);
302 DIE
*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());
308 if (DIE
*NDie
= getDIE(CB
))
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());
315 addSourceLine(NDie
, CB
->getLineNo(), CB
->getFile());
316 if (DIGlobalVariable
*V
= CB
->getDecl())
317 getCU().addLocationAttribute(&NDie
, V
, GlobalExprs
);
321 void DwarfCompileUnit::addRange(RangeSpan Range
) {
322 bool SameAsPrevCU
= this == DD
->getPrevCU();
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().End
->getSection() !=
330 &Range
.End
->getSection())) {
331 CURanges
.push_back(Range
);
335 CURanges
.back().End
= Range
.End
;
338 void DwarfCompileUnit::initStmtList() {
339 if (CUNode
->isDebugDirectivesOnly())
342 // Define start line table label for each Compile Unit.
343 MCSymbol
*LineTableStartSym
;
344 const TargetLoweringObjectFile
&TLOF
= Asm
->getObjFileLowering();
345 if (DD
->useSectionsAsReferences()) {
346 LineTableStartSym
= TLOF
.getDwarfLineSection()->getBeginSymbol();
349 Asm
->OutStreamer
->getDwarfLineTableSymbol(getUniqueID());
352 // DW_AT_stmt_list is a offset of line number information for this
353 // compile unit in debug_line section. For split dwarf this is
354 // left in the skeleton CU and so not included.
355 // The line table entries are not always emitted in assembly, so it
356 // is not okay to use line_table_start here.
358 addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list
, LineTableStartSym
,
359 TLOF
.getDwarfLineSection()->getBeginSymbol());
362 void DwarfCompileUnit::applyStmtList(DIE
&D
) {
363 D
.addValue(DIEValueAllocator
, *StmtListValue
);
366 void DwarfCompileUnit::attachLowHighPC(DIE
&D
, const MCSymbol
*Begin
,
367 const MCSymbol
*End
) {
368 assert(Begin
&& "Begin label should not be null!");
369 assert(End
&& "End label should not be null!");
370 assert(Begin
->isDefined() && "Invalid starting label");
371 assert(End
->isDefined() && "Invalid end label");
373 addLabelAddress(D
, dwarf::DW_AT_low_pc
, Begin
);
374 if (DD
->getDwarfVersion() < 4)
375 addLabelAddress(D
, dwarf::DW_AT_high_pc
, End
);
377 addLabelDelta(D
, dwarf::DW_AT_high_pc
, End
, Begin
);
380 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
381 // and DW_AT_high_pc attributes. If there are global variables in this
382 // scope then create and insert DIEs for these variables.
383 DIE
&DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram
*SP
) {
384 DIE
*SPDie
= getOrCreateSubprogramDIE(SP
, includeMinimalInlineScopes());
386 attachLowHighPC(*SPDie
, Asm
->getFunctionBegin(), Asm
->getFunctionEnd());
387 if (DD
->useAppleExtensionAttributes() &&
388 !DD
->getCurrentFunction()->getTarget().Options
.DisableFramePointerElim(
389 *DD
->getCurrentFunction()))
390 addFlag(*SPDie
, dwarf::DW_AT_APPLE_omit_frame_ptr
);
392 // Only include DW_AT_frame_base in full debug info
393 if (!includeMinimalInlineScopes()) {
394 if (Asm
->MF
->getTarget().getTargetTriple().isNVPTX()) {
395 DIELoc
*Loc
= new (DIEValueAllocator
) DIELoc
;
396 addUInt(*Loc
, dwarf::DW_FORM_data1
, dwarf::DW_OP_call_frame_cfa
);
397 addBlock(*SPDie
, dwarf::DW_AT_frame_base
, Loc
);
399 const TargetRegisterInfo
*RI
= Asm
->MF
->getSubtarget().getRegisterInfo();
400 MachineLocation
Location(RI
->getFrameRegister(*Asm
->MF
));
401 if (Register::isPhysicalRegister(Location
.getReg()))
402 addAddress(*SPDie
, dwarf::DW_AT_frame_base
, Location
);
406 // Add name to the name table, we do this here because we're guaranteed
407 // to have concrete versions of our DW_TAG_subprogram nodes.
408 DD
->addSubprogramNames(*CUNode
, SP
, *SPDie
);
413 // Construct a DIE for this scope.
414 void DwarfCompileUnit::constructScopeDIE(
415 LexicalScope
*Scope
, SmallVectorImpl
<DIE
*> &FinalChildren
) {
416 if (!Scope
|| !Scope
->getScopeNode())
419 auto *DS
= Scope
->getScopeNode();
421 assert((Scope
->getInlinedAt() || !isa
<DISubprogram
>(DS
)) &&
422 "Only handle inlined subprograms here, use "
423 "constructSubprogramScopeDIE for non-inlined "
426 SmallVector
<DIE
*, 8> Children
;
428 // We try to create the scope DIE first, then the children DIEs. This will
429 // avoid creating un-used children then removing them later when we find out
430 // the scope DIE is null.
432 if (Scope
->getParent() && isa
<DISubprogram
>(DS
)) {
433 ScopeDIE
= constructInlinedScopeDIE(Scope
);
436 // We create children when the scope DIE is not null.
437 createScopeChildrenDIE(Scope
, Children
);
439 // Early exit when we know the scope DIE is going to be null.
440 if (DD
->isLexicalScopeDIENull(Scope
))
443 bool HasNonScopeChildren
= false;
445 // We create children here when we know the scope DIE is not going to be
446 // null and the children will be added to the scope DIE.
447 createScopeChildrenDIE(Scope
, Children
, &HasNonScopeChildren
);
449 // If there are only other scopes as children, put them directly in the
450 // parent instead, as this scope would serve no purpose.
451 if (!HasNonScopeChildren
) {
452 FinalChildren
.insert(FinalChildren
.end(),
453 std::make_move_iterator(Children
.begin()),
454 std::make_move_iterator(Children
.end()));
457 ScopeDIE
= constructLexicalScopeDIE(Scope
);
458 assert(ScopeDIE
&& "Scope DIE should not be null.");
462 for (auto &I
: Children
)
463 ScopeDIE
->addChild(std::move(I
));
465 FinalChildren
.push_back(std::move(ScopeDIE
));
468 void DwarfCompileUnit::addScopeRangeList(DIE
&ScopeDIE
,
469 SmallVector
<RangeSpan
, 2> Range
) {
470 const TargetLoweringObjectFile
&TLOF
= Asm
->getObjFileLowering();
472 // Emit the offset into .debug_ranges or .debug_rnglists as a relocatable
473 // label. emitDIE() will handle emitting it appropriately.
474 const MCSymbol
*RangeSectionSym
=
475 DD
->getDwarfVersion() >= 5
476 ? TLOF
.getDwarfRnglistsSection()->getBeginSymbol()
477 : TLOF
.getDwarfRangesSection()->getBeginSymbol();
479 HasRangeLists
= true;
481 // Add the range list to the set of ranges to be emitted.
483 (DD
->getDwarfVersion() < 5 && Skeleton
? Skeleton
->DU
: DU
)
484 ->addRange(*(Skeleton
? Skeleton
: this), std::move(Range
));
486 uint32_t Index
= IndexAndList
.first
;
487 auto &List
= *IndexAndList
.second
;
489 // Under fission, ranges are specified by constant offsets relative to the
490 // CU's DW_AT_GNU_ranges_base.
491 // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
492 // fission until we support the forms using the .debug_addr section
493 // (DW_RLE_startx_endx etc.).
494 if (DD
->getDwarfVersion() >= 5)
495 addUInt(ScopeDIE
, dwarf::DW_AT_ranges
, dwarf::DW_FORM_rnglistx
, Index
);
496 else if (isDwoUnit())
497 addSectionDelta(ScopeDIE
, dwarf::DW_AT_ranges
, List
.getSym(),
500 addSectionLabel(ScopeDIE
, dwarf::DW_AT_ranges
, List
.getSym(),
504 void DwarfCompileUnit::attachRangesOrLowHighPC(
505 DIE
&Die
, SmallVector
<RangeSpan
, 2> Ranges
) {
506 if (Ranges
.size() == 1 || !DD
->useRangesSection()) {
507 const RangeSpan
&Front
= Ranges
.front();
508 const RangeSpan
&Back
= Ranges
.back();
509 attachLowHighPC(Die
, Front
.Begin
, Back
.End
);
511 addScopeRangeList(Die
, std::move(Ranges
));
514 void DwarfCompileUnit::attachRangesOrLowHighPC(
515 DIE
&Die
, const SmallVectorImpl
<InsnRange
> &Ranges
) {
516 SmallVector
<RangeSpan
, 2> List
;
517 List
.reserve(Ranges
.size());
518 for (const InsnRange
&R
: Ranges
)
520 {DD
->getLabelBeforeInsn(R
.first
), DD
->getLabelAfterInsn(R
.second
)});
521 attachRangesOrLowHighPC(Die
, std::move(List
));
524 // This scope represents inlined body of a function. Construct DIE to
525 // represent this concrete inlined copy of the function.
526 DIE
*DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope
*Scope
) {
527 assert(Scope
->getScopeNode());
528 auto *DS
= Scope
->getScopeNode();
529 auto *InlinedSP
= getDISubprogram(DS
);
530 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
531 // was inlined from another compile unit.
532 DIE
*OriginDIE
= getAbstractSPDies()[InlinedSP
];
533 assert(OriginDIE
&& "Unable to find original DIE for an inlined subprogram.");
535 auto ScopeDIE
= DIE::get(DIEValueAllocator
, dwarf::DW_TAG_inlined_subroutine
);
536 addDIEEntry(*ScopeDIE
, dwarf::DW_AT_abstract_origin
, *OriginDIE
);
538 attachRangesOrLowHighPC(*ScopeDIE
, Scope
->getRanges());
540 // Add the call site information to the DIE.
541 const DILocation
*IA
= Scope
->getInlinedAt();
542 addUInt(*ScopeDIE
, dwarf::DW_AT_call_file
, None
,
543 getOrCreateSourceID(IA
->getFile()));
544 addUInt(*ScopeDIE
, dwarf::DW_AT_call_line
, None
, IA
->getLine());
546 addUInt(*ScopeDIE
, dwarf::DW_AT_call_column
, None
, IA
->getColumn());
547 if (IA
->getDiscriminator() && DD
->getDwarfVersion() >= 4)
548 addUInt(*ScopeDIE
, dwarf::DW_AT_GNU_discriminator
, None
,
549 IA
->getDiscriminator());
551 // Add name to the name table, we do this here because we're guaranteed
552 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
553 DD
->addSubprogramNames(*CUNode
, InlinedSP
, *ScopeDIE
);
558 // Construct new DW_TAG_lexical_block for this scope and attach
559 // DW_AT_low_pc/DW_AT_high_pc labels.
560 DIE
*DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope
*Scope
) {
561 if (DD
->isLexicalScopeDIENull(Scope
))
564 auto ScopeDIE
= DIE::get(DIEValueAllocator
, dwarf::DW_TAG_lexical_block
);
565 if (Scope
->isAbstractScope())
568 attachRangesOrLowHighPC(*ScopeDIE
, Scope
->getRanges());
573 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
574 DIE
*DwarfCompileUnit::constructVariableDIE(DbgVariable
&DV
, bool Abstract
) {
575 auto D
= constructVariableDIEImpl(DV
, Abstract
);
580 DIE
*DwarfCompileUnit::constructLabelDIE(DbgLabel
&DL
,
581 const LexicalScope
&Scope
) {
582 auto LabelDie
= DIE::get(DIEValueAllocator
, DL
.getTag());
583 insertDIE(DL
.getLabel(), LabelDie
);
584 DL
.setDIE(*LabelDie
);
586 if (Scope
.isAbstractScope())
587 applyLabelAttributes(DL
, *LabelDie
);
592 DIE
*DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable
&DV
,
594 // Define variable debug information entry.
595 auto VariableDie
= DIE::get(DIEValueAllocator
, DV
.getTag());
596 insertDIE(DV
.getVariable(), VariableDie
);
599 applyVariableAttributes(DV
, *VariableDie
);
603 // Add variable address.
605 unsigned Offset
= DV
.getDebugLocListIndex();
607 addLocationList(*VariableDie
, dwarf::DW_AT_location
, Offset
);
611 // Check if variable has a single location description.
612 if (auto *DVal
= DV
.getValueLoc()) {
613 if (DVal
->isLocation())
614 addVariableAddress(DV
, *VariableDie
, DVal
->getLoc());
615 else if (DVal
->isInt()) {
616 auto *Expr
= DV
.getSingleExpression();
617 if (Expr
&& Expr
->getNumElements()) {
618 DIELoc
*Loc
= new (DIEValueAllocator
) DIELoc
;
619 DIEDwarfExpression
DwarfExpr(*Asm
, *this, *Loc
);
620 // If there is an expression, emit raw unsigned bytes.
621 DwarfExpr
.addFragmentOffset(Expr
);
622 DwarfExpr
.addUnsignedConstant(DVal
->getInt());
623 DwarfExpr
.addExpression(Expr
);
624 addBlock(*VariableDie
, dwarf::DW_AT_location
, DwarfExpr
.finalize());
626 addConstantValue(*VariableDie
, DVal
->getInt(), DV
.getType());
627 } else if (DVal
->isConstantFP()) {
628 addConstantFPValue(*VariableDie
, DVal
->getConstantFP());
629 } else if (DVal
->isConstantInt()) {
630 addConstantValue(*VariableDie
, DVal
->getConstantInt(), DV
.getType());
635 // .. else use frame index.
636 if (!DV
.hasFrameIndexExprs())
639 Optional
<unsigned> NVPTXAddressSpace
;
640 DIELoc
*Loc
= new (DIEValueAllocator
) DIELoc
;
641 DIEDwarfExpression
DwarfExpr(*Asm
, *this, *Loc
);
642 for (auto &Fragment
: DV
.getFrameIndexExprs()) {
643 unsigned FrameReg
= 0;
644 const DIExpression
*Expr
= Fragment
.Expr
;
645 const TargetFrameLowering
*TFI
= Asm
->MF
->getSubtarget().getFrameLowering();
646 int Offset
= TFI
->getFrameIndexReference(*Asm
->MF
, Fragment
.FI
, FrameReg
);
647 DwarfExpr
.addFragmentOffset(Expr
);
648 SmallVector
<uint64_t, 8> Ops
;
649 DIExpression::appendOffset(Ops
, Offset
);
651 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
652 // cuda-gdb requires DW_AT_address_class for all variables to be able to
653 // correctly interpret address space of the variable address.
654 // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
655 // sequence for the NVPTX + gdb target.
656 unsigned LocalNVPTXAddressSpace
;
657 if (Asm
->TM
.getTargetTriple().isNVPTX() && DD
->tuneForGDB()) {
658 const DIExpression
*NewExpr
=
659 DIExpression::extractAddressClass(Expr
, LocalNVPTXAddressSpace
);
660 if (NewExpr
!= Expr
) {
662 NVPTXAddressSpace
= LocalNVPTXAddressSpace
;
666 Ops
.append(Expr
->elements_begin(), Expr
->elements_end());
667 DIExpressionCursor
Cursor(Ops
);
668 DwarfExpr
.setMemoryLocationKind();
669 if (const MCSymbol
*FrameSymbol
= Asm
->getFunctionFrameSymbol())
670 addOpAddress(*Loc
, FrameSymbol
);
672 DwarfExpr
.addMachineRegExpression(
673 *Asm
->MF
->getSubtarget().getRegisterInfo(), Cursor
, FrameReg
);
674 DwarfExpr
.addExpression(std::move(Cursor
));
676 if (Asm
->TM
.getTargetTriple().isNVPTX() && DD
->tuneForGDB()) {
678 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
679 // cuda-gdb requires DW_AT_address_class for all variables to be able to
680 // correctly interpret address space of the variable address.
681 const unsigned NVPTX_ADDR_local_space
= 6;
682 addUInt(*VariableDie
, dwarf::DW_AT_address_class
, dwarf::DW_FORM_data1
,
683 NVPTXAddressSpace
? *NVPTXAddressSpace
: NVPTX_ADDR_local_space
);
685 addBlock(*VariableDie
, dwarf::DW_AT_location
, DwarfExpr
.finalize());
686 if (DwarfExpr
.TagOffset
)
687 addUInt(*VariableDie
, dwarf::DW_AT_LLVM_tag_offset
, dwarf::DW_FORM_data1
,
688 *DwarfExpr
.TagOffset
);
693 DIE
*DwarfCompileUnit::constructVariableDIE(DbgVariable
&DV
,
694 const LexicalScope
&Scope
,
695 DIE
*&ObjectPointer
) {
696 auto Var
= constructVariableDIE(DV
, Scope
.isAbstractScope());
697 if (DV
.isObjectPointer())
702 /// Return all DIVariables that appear in count: expressions.
703 static SmallVector
<const DIVariable
*, 2> dependencies(DbgVariable
*Var
) {
704 SmallVector
<const DIVariable
*, 2> Result
;
705 auto *Array
= dyn_cast
<DICompositeType
>(Var
->getType());
706 if (!Array
|| Array
->getTag() != dwarf::DW_TAG_array_type
)
708 for (auto *El
: Array
->getElements()) {
709 if (auto *Subrange
= dyn_cast
<DISubrange
>(El
)) {
710 auto Count
= Subrange
->getCount();
711 if (auto *Dependency
= Count
.dyn_cast
<DIVariable
*>())
712 Result
.push_back(Dependency
);
718 /// Sort local variables so that variables appearing inside of helper
719 /// expressions come first.
720 static SmallVector
<DbgVariable
*, 8>
721 sortLocalVars(SmallVectorImpl
<DbgVariable
*> &Input
) {
722 SmallVector
<DbgVariable
*, 8> Result
;
723 SmallVector
<PointerIntPair
<DbgVariable
*, 1>, 8> WorkList
;
724 // Map back from a DIVariable to its containing DbgVariable.
725 SmallDenseMap
<const DILocalVariable
*, DbgVariable
*> DbgVar
;
726 // Set of DbgVariables in Result.
727 SmallDenseSet
<DbgVariable
*, 8> Visited
;
728 // For cycle detection.
729 SmallDenseSet
<DbgVariable
*, 8> Visiting
;
731 // Initialize the worklist and the DIVariable lookup table.
732 for (auto Var
: reverse(Input
)) {
733 DbgVar
.insert({Var
->getVariable(), Var
});
734 WorkList
.push_back({Var
, 0});
737 // Perform a stable topological sort by doing a DFS.
738 while (!WorkList
.empty()) {
739 auto Item
= WorkList
.back();
740 DbgVariable
*Var
= Item
.getPointer();
741 bool visitedAllDependencies
= Item
.getInt();
744 // Dependency is in a different lexical scope or a global.
749 if (Visited
.count(Var
))
752 // Add to Result if all dependencies are visited.
753 if (visitedAllDependencies
) {
755 Result
.push_back(Var
);
760 auto Res
= Visiting
.insert(Var
);
762 assert(false && "dependency cycle in local variables");
766 // Push dependencies and this node onto the worklist, so that this node is
767 // visited again after all of its dependencies are handled.
768 WorkList
.push_back({Var
, 1});
769 for (auto *Dependency
: dependencies(Var
)) {
770 auto Dep
= dyn_cast_or_null
<const DILocalVariable
>(Dependency
);
771 WorkList
.push_back({DbgVar
[Dep
], 0});
777 DIE
*DwarfCompileUnit::createScopeChildrenDIE(LexicalScope
*Scope
,
778 SmallVectorImpl
<DIE
*> &Children
,
779 bool *HasNonScopeChildren
) {
780 assert(Children
.empty());
781 DIE
*ObjectPointer
= nullptr;
783 // Emit function arguments (order is significant).
784 auto Vars
= DU
->getScopeVariables().lookup(Scope
);
785 for (auto &DV
: Vars
.Args
)
786 Children
.push_back(constructVariableDIE(*DV
.second
, *Scope
, ObjectPointer
));
788 // Emit local variables.
789 auto Locals
= sortLocalVars(Vars
.Locals
);
790 for (DbgVariable
*DV
: Locals
)
791 Children
.push_back(constructVariableDIE(*DV
, *Scope
, ObjectPointer
));
793 // Skip imported directives in gmlt-like data.
794 if (!includeMinimalInlineScopes()) {
795 // There is no need to emit empty lexical block DIE.
796 for (const auto *IE
: ImportedEntities
[Scope
->getScopeNode()])
798 constructImportedEntityDIE(cast
<DIImportedEntity
>(IE
)));
801 if (HasNonScopeChildren
)
802 *HasNonScopeChildren
= !Children
.empty();
804 for (DbgLabel
*DL
: DU
->getScopeLabels().lookup(Scope
))
805 Children
.push_back(constructLabelDIE(*DL
, *Scope
));
807 for (LexicalScope
*LS
: Scope
->getChildren())
808 constructScopeDIE(LS
, Children
);
810 return ObjectPointer
;
813 DIE
&DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram
*Sub
,
814 LexicalScope
*Scope
) {
815 DIE
&ScopeDIE
= updateSubprogramScopeDIE(Sub
);
818 assert(!Scope
->getInlinedAt());
819 assert(!Scope
->isAbstractScope());
820 // Collect lexical scope children first.
821 // ObjectPointer might be a local (non-argument) local variable if it's a
822 // block's synthetic this pointer.
823 if (DIE
*ObjectPointer
= createAndAddScopeChildren(Scope
, ScopeDIE
))
824 addDIEEntry(ScopeDIE
, dwarf::DW_AT_object_pointer
, *ObjectPointer
);
827 // If this is a variadic function, add an unspecified parameter.
828 DITypeRefArray FnArgs
= Sub
->getType()->getTypeArray();
830 // If we have a single element of null, it is a function that returns void.
831 // If we have more than one elements and the last one is null, it is a
832 // variadic function.
833 if (FnArgs
.size() > 1 && !FnArgs
[FnArgs
.size() - 1] &&
834 !includeMinimalInlineScopes())
836 DIE::get(DIEValueAllocator
, dwarf::DW_TAG_unspecified_parameters
));
841 DIE
*DwarfCompileUnit::createAndAddScopeChildren(LexicalScope
*Scope
,
843 // We create children when the scope DIE is not null.
844 SmallVector
<DIE
*, 8> Children
;
845 DIE
*ObjectPointer
= createScopeChildrenDIE(Scope
, Children
);
848 for (auto &I
: Children
)
849 ScopeDIE
.addChild(std::move(I
));
851 return ObjectPointer
;
854 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
855 LexicalScope
*Scope
) {
856 DIE
*&AbsDef
= getAbstractSPDies()[Scope
->getScopeNode()];
860 auto *SP
= cast
<DISubprogram
>(Scope
->getScopeNode());
863 DwarfCompileUnit
*ContextCU
= this;
865 if (includeMinimalInlineScopes())
866 ContextDIE
= &getUnitDie();
867 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
868 // the important distinction that the debug node is not associated with the
869 // DIE (since the debug node will be associated with the concrete DIE, if
870 // any). It could be refactored to some common utility function.
871 else if (auto *SPDecl
= SP
->getDeclaration()) {
872 ContextDIE
= &getUnitDie();
873 getOrCreateSubprogramDIE(SPDecl
);
875 ContextDIE
= getOrCreateContextDIE(SP
->getScope());
876 // The scope may be shared with a subprogram that has already been
877 // constructed in another CU, in which case we need to construct this
878 // subprogram in the same CU.
879 ContextCU
= DD
->lookupCU(ContextDIE
->getUnitDie());
882 // Passing null as the associated node because the abstract definition
883 // shouldn't be found by lookup.
884 AbsDef
= &ContextCU
->createAndAddDIE(dwarf::DW_TAG_subprogram
, *ContextDIE
, nullptr);
885 ContextCU
->applySubprogramAttributesToDefinition(SP
, *AbsDef
);
887 if (!ContextCU
->includeMinimalInlineScopes())
888 ContextCU
->addUInt(*AbsDef
, dwarf::DW_AT_inline
, None
, dwarf::DW_INL_inlined
);
889 if (DIE
*ObjectPointer
= ContextCU
->createAndAddScopeChildren(Scope
, *AbsDef
))
890 ContextCU
->addDIEEntry(*AbsDef
, dwarf::DW_AT_object_pointer
, *ObjectPointer
);
893 /// Whether to use the GNU analog for a DWARF5 tag, attribute, or location atom.
894 static bool useGNUAnalogForDwarf5Feature(DwarfDebug
*DD
) {
895 return DD
->getDwarfVersion() == 4 && DD
->tuneForGDB();
898 dwarf::Tag
DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag
) const {
899 if (!useGNUAnalogForDwarf5Feature(DD
))
902 case dwarf::DW_TAG_call_site
:
903 return dwarf::DW_TAG_GNU_call_site
;
904 case dwarf::DW_TAG_call_site_parameter
:
905 return dwarf::DW_TAG_GNU_call_site_parameter
;
907 llvm_unreachable("DWARF5 tag with no GNU analog");
912 DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr
) const {
913 if (!useGNUAnalogForDwarf5Feature(DD
))
916 case dwarf::DW_AT_call_all_calls
:
917 return dwarf::DW_AT_GNU_all_call_sites
;
918 case dwarf::DW_AT_call_target
:
919 return dwarf::DW_AT_GNU_call_site_target
;
920 case dwarf::DW_AT_call_origin
:
921 return dwarf::DW_AT_abstract_origin
;
922 case dwarf::DW_AT_call_pc
:
923 return dwarf::DW_AT_low_pc
;
924 case dwarf::DW_AT_call_value
:
925 return dwarf::DW_AT_GNU_call_site_value
;
926 case dwarf::DW_AT_call_tail_call
:
927 return dwarf::DW_AT_GNU_tail_call
;
929 llvm_unreachable("DWARF5 attribute with no GNU analog");
934 DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc
) const {
935 if (!useGNUAnalogForDwarf5Feature(DD
))
938 case dwarf::DW_OP_entry_value
:
939 return dwarf::DW_OP_GNU_entry_value
;
941 llvm_unreachable("DWARF5 location atom with no GNU analog");
945 DIE
&DwarfCompileUnit::constructCallSiteEntryDIE(
946 DIE
&ScopeDIE
, const DISubprogram
*CalleeSP
, bool IsTail
,
947 const MCSymbol
*PCAddr
, const MCExpr
*PCOffset
, unsigned CallReg
) {
948 // Insert a call site entry DIE within ScopeDIE.
949 DIE
&CallSiteDIE
= createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site
),
954 addAddress(CallSiteDIE
, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target
),
955 MachineLocation(CallReg
));
957 DIE
*CalleeDIE
= getOrCreateSubprogramDIE(CalleeSP
);
958 assert(CalleeDIE
&& "Could not create DIE for call site entry origin");
959 addDIEEntry(CallSiteDIE
, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin
),
964 // Attach DW_AT_call_tail_call to tail calls for standards compliance.
965 addFlag(CallSiteDIE
, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call
));
967 // Attach the return PC to allow the debugger to disambiguate call paths
968 // from one function to another.
969 if (DD
->getDwarfVersion() == 4 && DD
->tuneForGDB()) {
970 assert(PCAddr
&& "Missing PC information for a call");
971 addLabelAddress(CallSiteDIE
, dwarf::DW_AT_low_pc
, PCAddr
);
972 } else if (!IsTail
|| DD
->tuneForGDB()) {
973 assert(PCOffset
&& "Missing return PC information for a call");
974 addAddressExpr(CallSiteDIE
, dwarf::DW_AT_call_return_pc
, PCOffset
);
980 void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
981 DIE
&CallSiteDIE
, SmallVector
<DbgCallSiteParam
, 4> &Params
) {
982 for (const auto &Param
: Params
) {
983 unsigned Register
= Param
.getRegister();
984 auto CallSiteDieParam
=
985 DIE::get(DIEValueAllocator
,
986 getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter
));
987 insertDIE(CallSiteDieParam
);
988 addAddress(*CallSiteDieParam
, dwarf::DW_AT_location
,
989 MachineLocation(Register
));
991 DIELoc
*Loc
= new (DIEValueAllocator
) DIELoc
;
992 DIEDwarfExpression
DwarfExpr(*Asm
, *this, *Loc
);
993 DwarfExpr
.setCallSiteParamValueFlag();
995 DwarfDebug::emitDebugLocValue(*Asm
, nullptr, Param
.getValue(), DwarfExpr
);
997 addBlock(*CallSiteDieParam
, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value
),
998 DwarfExpr
.finalize());
1000 CallSiteDIE
.addChild(CallSiteDieParam
);
1004 DIE
*DwarfCompileUnit::constructImportedEntityDIE(
1005 const DIImportedEntity
*Module
) {
1006 DIE
*IMDie
= DIE::get(DIEValueAllocator
, (dwarf::Tag
)Module
->getTag());
1007 insertDIE(Module
, IMDie
);
1009 auto *Entity
= Module
->getEntity();
1010 if (auto *NS
= dyn_cast
<DINamespace
>(Entity
))
1011 EntityDie
= getOrCreateNameSpace(NS
);
1012 else if (auto *M
= dyn_cast
<DIModule
>(Entity
))
1013 EntityDie
= getOrCreateModule(M
);
1014 else if (auto *SP
= dyn_cast
<DISubprogram
>(Entity
))
1015 EntityDie
= getOrCreateSubprogramDIE(SP
);
1016 else if (auto *T
= dyn_cast
<DIType
>(Entity
))
1017 EntityDie
= getOrCreateTypeDIE(T
);
1018 else if (auto *GV
= dyn_cast
<DIGlobalVariable
>(Entity
))
1019 EntityDie
= getOrCreateGlobalVariableDIE(GV
, {});
1021 EntityDie
= getDIE(Entity
);
1023 addSourceLine(*IMDie
, Module
->getLine(), Module
->getFile());
1024 addDIEEntry(*IMDie
, dwarf::DW_AT_import
, *EntityDie
);
1025 StringRef Name
= Module
->getName();
1027 addString(*IMDie
, dwarf::DW_AT_name
, Name
);
1032 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram
*SP
) {
1033 DIE
*D
= getDIE(SP
);
1034 if (DIE
*AbsSPDIE
= getAbstractSPDies().lookup(SP
)) {
1036 // If this subprogram has an abstract definition, reference that
1037 addDIEEntry(*D
, dwarf::DW_AT_abstract_origin
, *AbsSPDIE
);
1039 assert(D
|| includeMinimalInlineScopes());
1041 // And attach the attributes
1042 applySubprogramAttributesToDefinition(SP
, *D
);
1046 void DwarfCompileUnit::finishEntityDefinition(const DbgEntity
*Entity
) {
1047 DbgEntity
*AbsEntity
= getExistingAbstractEntity(Entity
->getEntity());
1049 auto *Die
= Entity
->getDIE();
1050 /// Label may be used to generate DW_AT_low_pc, so put it outside
1052 const DbgLabel
*Label
= nullptr;
1053 if (AbsEntity
&& AbsEntity
->getDIE()) {
1054 addDIEEntry(*Die
, dwarf::DW_AT_abstract_origin
, *AbsEntity
->getDIE());
1055 Label
= dyn_cast
<const DbgLabel
>(Entity
);
1057 if (const DbgVariable
*Var
= dyn_cast
<const DbgVariable
>(Entity
))
1058 applyVariableAttributes(*Var
, *Die
);
1059 else if ((Label
= dyn_cast
<const DbgLabel
>(Entity
)))
1060 applyLabelAttributes(*Label
, *Die
);
1062 llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
1066 if (const auto *Sym
= Label
->getSymbol())
1067 addLabelAddress(*Die
, dwarf::DW_AT_low_pc
, Sym
);
1070 DbgEntity
*DwarfCompileUnit::getExistingAbstractEntity(const DINode
*Node
) {
1071 auto &AbstractEntities
= getAbstractEntities();
1072 auto I
= AbstractEntities
.find(Node
);
1073 if (I
!= AbstractEntities
.end())
1074 return I
->second
.get();
1078 void DwarfCompileUnit::createAbstractEntity(const DINode
*Node
,
1079 LexicalScope
*Scope
) {
1080 assert(Scope
&& Scope
->isAbstractScope());
1081 auto &Entity
= getAbstractEntities()[Node
];
1082 if (isa
<const DILocalVariable
>(Node
)) {
1083 Entity
= std::make_unique
<DbgVariable
>(
1084 cast
<const DILocalVariable
>(Node
), nullptr /* IA */);;
1085 DU
->addScopeVariable(Scope
, cast
<DbgVariable
>(Entity
.get()));
1086 } else if (isa
<const DILabel
>(Node
)) {
1087 Entity
= std::make_unique
<DbgLabel
>(
1088 cast
<const DILabel
>(Node
), nullptr /* IA */);
1089 DU
->addScopeLabel(Scope
, cast
<DbgLabel
>(Entity
.get()));
1093 void DwarfCompileUnit::emitHeader(bool UseOffsets
) {
1094 // Don't bother labeling the .dwo unit, as its offset isn't used.
1095 if (!Skeleton
&& !DD
->useSectionsAsReferences()) {
1096 LabelBegin
= Asm
->createTempSymbol("cu_begin");
1097 Asm
->OutStreamer
->EmitLabel(LabelBegin
);
1100 dwarf::UnitType UT
= Skeleton
? dwarf::DW_UT_split_compile
1101 : DD
->useSplitDwarf() ? dwarf::DW_UT_skeleton
1102 : dwarf::DW_UT_compile
;
1103 DwarfUnit::emitCommonHeader(UseOffsets
, UT
);
1104 if (DD
->getDwarfVersion() >= 5 && UT
!= dwarf::DW_UT_compile
)
1105 Asm
->emitInt64(getDWOId());
1108 bool DwarfCompileUnit::hasDwarfPubSections() const {
1109 switch (CUNode
->getNameTableKind()) {
1110 case DICompileUnit::DebugNameTableKind::None
:
1112 // Opting in to GNU Pubnames/types overrides the default to ensure these are
1113 // generated for things like Gold's gdb_index generation.
1114 case DICompileUnit::DebugNameTableKind::GNU
:
1116 case DICompileUnit::DebugNameTableKind::Default
:
1117 return DD
->tuneForGDB() && !includeMinimalInlineScopes() &&
1118 !CUNode
->isDebugDirectivesOnly() &&
1119 DD
->getAccelTableKind() != AccelTableKind::Apple
&&
1120 DD
->getDwarfVersion() < 5;
1122 llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
1125 /// addGlobalName - Add a new global name to the compile unit.
1126 void DwarfCompileUnit::addGlobalName(StringRef Name
, const DIE
&Die
,
1127 const DIScope
*Context
) {
1128 if (!hasDwarfPubSections())
1130 std::string FullName
= getParentContextString(Context
) + Name
.str();
1131 GlobalNames
[FullName
] = &Die
;
1134 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name
,
1135 const DIScope
*Context
) {
1136 if (!hasDwarfPubSections())
1138 std::string FullName
= getParentContextString(Context
) + Name
.str();
1139 // Insert, allowing the entry to remain as-is if it's already present
1140 // This way the CU-level type DIE is preferred over the "can't describe this
1141 // type as a unit offset because it's not really in the CU at all, it's only
1143 GlobalNames
.insert(std::make_pair(std::move(FullName
), &getUnitDie()));
1146 /// Add a new global type to the unit.
1147 void DwarfCompileUnit::addGlobalType(const DIType
*Ty
, const DIE
&Die
,
1148 const DIScope
*Context
) {
1149 if (!hasDwarfPubSections())
1151 std::string FullName
= getParentContextString(Context
) + Ty
->getName().str();
1152 GlobalTypes
[FullName
] = &Die
;
1155 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType
*Ty
,
1156 const DIScope
*Context
) {
1157 if (!hasDwarfPubSections())
1159 std::string FullName
= getParentContextString(Context
) + Ty
->getName().str();
1160 // Insert, allowing the entry to remain as-is if it's already present
1161 // This way the CU-level type DIE is preferred over the "can't describe this
1162 // type as a unit offset because it's not really in the CU at all, it's only
1164 GlobalTypes
.insert(std::make_pair(std::move(FullName
), &getUnitDie()));
1167 void DwarfCompileUnit::addVariableAddress(const DbgVariable
&DV
, DIE
&Die
,
1168 MachineLocation Location
) {
1169 if (DV
.hasComplexAddress())
1170 addComplexAddress(DV
, Die
, dwarf::DW_AT_location
, Location
);
1172 addAddress(Die
, dwarf::DW_AT_location
, Location
);
1175 /// Add an address attribute to a die based on the location provided.
1176 void DwarfCompileUnit::addAddress(DIE
&Die
, dwarf::Attribute Attribute
,
1177 const MachineLocation
&Location
) {
1178 DIELoc
*Loc
= new (DIEValueAllocator
) DIELoc
;
1179 DIEDwarfExpression
DwarfExpr(*Asm
, *this, *Loc
);
1180 if (Location
.isIndirect())
1181 DwarfExpr
.setMemoryLocationKind();
1183 DIExpressionCursor
Cursor({});
1184 const TargetRegisterInfo
&TRI
= *Asm
->MF
->getSubtarget().getRegisterInfo();
1185 if (!DwarfExpr
.addMachineRegExpression(TRI
, Cursor
, Location
.getReg()))
1187 DwarfExpr
.addExpression(std::move(Cursor
));
1189 // Now attach the location information to the DIE.
1190 addBlock(Die
, Attribute
, DwarfExpr
.finalize());
1193 /// Start with the address based on the location provided, and generate the
1194 /// DWARF information necessary to find the actual variable given the extra
1195 /// address information encoded in the DbgVariable, starting from the starting
1196 /// location. Add the DWARF information to the die.
1197 void DwarfCompileUnit::addComplexAddress(const DbgVariable
&DV
, DIE
&Die
,
1198 dwarf::Attribute Attribute
,
1199 const MachineLocation
&Location
) {
1200 DIELoc
*Loc
= new (DIEValueAllocator
) DIELoc
;
1201 DIEDwarfExpression
DwarfExpr(*Asm
, *this, *Loc
);
1202 const DIExpression
*DIExpr
= DV
.getSingleExpression();
1203 DwarfExpr
.addFragmentOffset(DIExpr
);
1204 if (Location
.isIndirect())
1205 DwarfExpr
.setMemoryLocationKind();
1207 DIExpressionCursor
Cursor(DIExpr
);
1209 if (DIExpr
->isEntryValue()) {
1210 DwarfExpr
.setEntryValueFlag();
1211 DwarfExpr
.addEntryValueExpression(Cursor
);
1214 const TargetRegisterInfo
&TRI
= *Asm
->MF
->getSubtarget().getRegisterInfo();
1215 if (!DwarfExpr
.addMachineRegExpression(TRI
, Cursor
, Location
.getReg()))
1217 DwarfExpr
.addExpression(std::move(Cursor
));
1219 // Now attach the location information to the DIE.
1220 addBlock(Die
, Attribute
, DwarfExpr
.finalize());
1223 /// Add a Dwarf loclistptr attribute data and value.
1224 void DwarfCompileUnit::addLocationList(DIE
&Die
, dwarf::Attribute Attribute
,
1226 dwarf::Form Form
= DD
->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1227 : dwarf::DW_FORM_data4
;
1228 Die
.addValue(DIEValueAllocator
, Attribute
, Form
, DIELocList(Index
));
1231 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable
&Var
,
1233 StringRef Name
= Var
.getName();
1235 addString(VariableDie
, dwarf::DW_AT_name
, Name
);
1236 const auto *DIVar
= Var
.getVariable();
1238 if (uint32_t AlignInBytes
= DIVar
->getAlignInBytes())
1239 addUInt(VariableDie
, dwarf::DW_AT_alignment
, dwarf::DW_FORM_udata
,
1242 addSourceLine(VariableDie
, DIVar
);
1243 addType(VariableDie
, Var
.getType());
1244 if (Var
.isArtificial())
1245 addFlag(VariableDie
, dwarf::DW_AT_artificial
);
1248 void DwarfCompileUnit::applyLabelAttributes(const DbgLabel
&Label
,
1250 StringRef Name
= Label
.getName();
1252 addString(LabelDie
, dwarf::DW_AT_name
, Name
);
1253 const auto *DILabel
= Label
.getLabel();
1254 addSourceLine(LabelDie
, DILabel
);
1257 /// Add a Dwarf expression attribute data and value.
1258 void DwarfCompileUnit::addExpr(DIELoc
&Die
, dwarf::Form Form
,
1259 const MCExpr
*Expr
) {
1260 Die
.addValue(DIEValueAllocator
, (dwarf::Attribute
)0, Form
, DIEExpr(Expr
));
1263 void DwarfCompileUnit::addAddressExpr(DIE
&Die
, dwarf::Attribute Attribute
,
1264 const MCExpr
*Expr
) {
1265 Die
.addValue(DIEValueAllocator
, Attribute
, dwarf::DW_FORM_addr
,
1269 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
1270 const DISubprogram
*SP
, DIE
&SPDie
) {
1271 auto *SPDecl
= SP
->getDeclaration();
1272 auto *Context
= SPDecl
? SPDecl
->getScope() : SP
->getScope();
1273 applySubprogramAttributes(SP
, SPDie
, includeMinimalInlineScopes());
1274 addGlobalName(SP
->getName(), SPDie
, Context
);
1277 bool DwarfCompileUnit::isDwoUnit() const {
1278 return DD
->useSplitDwarf() && Skeleton
;
1281 void DwarfCompileUnit::finishNonUnitTypeDIE(DIE
& D
, const DICompositeType
*CTy
) {
1282 constructTypeDIE(D
, CTy
);
1285 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1286 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly
||
1287 (DD
->useSplitDwarf() && !Skeleton
);
1290 void DwarfCompileUnit::addAddrTableBase() {
1291 const TargetLoweringObjectFile
&TLOF
= Asm
->getObjFileLowering();
1292 MCSymbol
*Label
= DD
->getAddressPool().getLabel();
1293 addSectionLabel(getUnitDie(),
1294 getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
1295 : dwarf::DW_AT_GNU_addr_base
,
1296 Label
, TLOF
.getDwarfAddrSection()->getBeginSymbol());
1299 void DwarfCompileUnit::addBaseTypeRef(DIEValueList
&Die
, int64_t Idx
) {
1300 Die
.addValue(DIEValueAllocator
, (dwarf::Attribute
)0, dwarf::DW_FORM_udata
,
1301 new (DIEValueAllocator
) DIEBaseTypeRef(this, Idx
));
1304 void DwarfCompileUnit::createBaseTypeDIEs() {
1305 // Insert the base_type DIEs directly after the CU so that their offsets will
1306 // fit in the fixed size ULEB128 used inside the location expressions.
1307 // Maintain order by iterating backwards and inserting to the front of CU
1309 for (auto &Btr
: reverse(ExprRefedBaseTypes
)) {
1310 DIE
&Die
= getUnitDie().addChildFront(
1311 DIE::get(DIEValueAllocator
, dwarf::DW_TAG_base_type
));
1312 SmallString
<32> Str
;
1313 addString(Die
, dwarf::DW_AT_name
,
1314 Twine(dwarf::AttributeEncodingString(Btr
.Encoding
) +
1315 "_" + Twine(Btr
.BitSize
)).toStringRef(Str
));
1316 addUInt(Die
, dwarf::DW_AT_encoding
, dwarf::DW_FORM_data1
, Btr
.Encoding
);
1317 addUInt(Die
, dwarf::DW_AT_byte_size
, None
, Btr
.BitSize
/ 8);