Coverage Report

Created: 2019-07-24 05:18

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