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