Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
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 writing dwarf debug info into asm files.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "DwarfDebug.h"
14
#include "ByteStreamer.h"
15
#include "DIEHash.h"
16
#include "DebugLocEntry.h"
17
#include "DebugLocStream.h"
18
#include "DwarfCompileUnit.h"
19
#include "DwarfExpression.h"
20
#include "DwarfFile.h"
21
#include "DwarfUnit.h"
22
#include "llvm/ADT/APInt.h"
23
#include "llvm/ADT/DenseMap.h"
24
#include "llvm/ADT/DenseSet.h"
25
#include "llvm/ADT/MapVector.h"
26
#include "llvm/ADT/STLExtras.h"
27
#include "llvm/ADT/SmallVector.h"
28
#include "llvm/ADT/StringRef.h"
29
#include "llvm/ADT/Triple.h"
30
#include "llvm/ADT/Twine.h"
31
#include "llvm/BinaryFormat/Dwarf.h"
32
#include "llvm/CodeGen/AccelTable.h"
33
#include "llvm/CodeGen/AsmPrinter.h"
34
#include "llvm/CodeGen/DIE.h"
35
#include "llvm/CodeGen/LexicalScopes.h"
36
#include "llvm/CodeGen/MachineBasicBlock.h"
37
#include "llvm/CodeGen/MachineFunction.h"
38
#include "llvm/CodeGen/MachineInstr.h"
39
#include "llvm/CodeGen/MachineModuleInfo.h"
40
#include "llvm/CodeGen/MachineOperand.h"
41
#include "llvm/CodeGen/TargetInstrInfo.h"
42
#include "llvm/CodeGen/TargetRegisterInfo.h"
43
#include "llvm/CodeGen/TargetSubtargetInfo.h"
44
#include "llvm/DebugInfo/DWARF/DWARFExpression.h"
45
#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
46
#include "llvm/IR/Constants.h"
47
#include "llvm/IR/DebugInfoMetadata.h"
48
#include "llvm/IR/DebugLoc.h"
49
#include "llvm/IR/Function.h"
50
#include "llvm/IR/GlobalVariable.h"
51
#include "llvm/IR/Module.h"
52
#include "llvm/MC/MCAsmInfo.h"
53
#include "llvm/MC/MCContext.h"
54
#include "llvm/MC/MCDwarf.h"
55
#include "llvm/MC/MCSection.h"
56
#include "llvm/MC/MCStreamer.h"
57
#include "llvm/MC/MCSymbol.h"
58
#include "llvm/MC/MCTargetOptions.h"
59
#include "llvm/MC/MachineLocation.h"
60
#include "llvm/MC/SectionKind.h"
61
#include "llvm/Pass.h"
62
#include "llvm/Support/Casting.h"
63
#include "llvm/Support/CommandLine.h"
64
#include "llvm/Support/Debug.h"
65
#include "llvm/Support/ErrorHandling.h"
66
#include "llvm/Support/MD5.h"
67
#include "llvm/Support/MathExtras.h"
68
#include "llvm/Support/Timer.h"
69
#include "llvm/Support/raw_ostream.h"
70
#include "llvm/Target/TargetLoweringObjectFile.h"
71
#include "llvm/Target/TargetMachine.h"
72
#include "llvm/Target/TargetOptions.h"
73
#include <algorithm>
74
#include <cassert>
75
#include <cstddef>
76
#include <cstdint>
77
#include <iterator>
78
#include <string>
79
#include <utility>
80
#include <vector>
81
82
using namespace llvm;
83
84
#define DEBUG_TYPE "dwarfdebug"
85
86
static cl::opt<bool>
87
DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
88
                         cl::desc("Disable debug info printing"));
89
90
static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
91
    "use-dwarf-ranges-base-address-specifier", cl::Hidden,
92
    cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
93
94
static cl::opt<bool> GenerateARangeSection("generate-arange-section",
95
                                           cl::Hidden,
96
                                           cl::desc("Generate dwarf aranges"),
97
                                           cl::init(false));
98
99
static cl::opt<bool>
100
    GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
101
                           cl::desc("Generate DWARF4 type units."),
102
                           cl::init(false));
103
104
static cl::opt<bool> SplitDwarfCrossCuReferences(
105
    "split-dwarf-cross-cu-references", cl::Hidden,
106
    cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
107
108
enum DefaultOnOff { Default, Enable, Disable };
109
110
static cl::opt<DefaultOnOff> UnknownLocations(
111
    "use-unknown-locations", cl::Hidden,
112
    cl::desc("Make an absence of debug location information explicit."),
113
    cl::values(clEnumVal(Default, "At top of block or after label"),
114
               clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
115
    cl::init(Default));
116
117
static cl::opt<AccelTableKind> AccelTables(
118
    "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
119
    cl::values(clEnumValN(AccelTableKind::Default, "Default",
120
                          "Default for platform"),
121
               clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
122
               clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
123
               clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
124
    cl::init(AccelTableKind::Default));
125
126
static cl::opt<DefaultOnOff>
127
DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
128
                 cl::desc("Use inlined strings rather than string section."),
129
                 cl::values(clEnumVal(Default, "Default for platform"),
130
                            clEnumVal(Enable, "Enabled"),
131
                            clEnumVal(Disable, "Disabled")),
132
                 cl::init(Default));
133
134
static cl::opt<bool>
135
    NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
136
                         cl::desc("Disable emission .debug_ranges section."),
137
                         cl::init(false));
138
139
static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
140
    "dwarf-sections-as-references", cl::Hidden,
141
    cl::desc("Use sections+offset as references rather than labels."),
142
    cl::values(clEnumVal(Default, "Default for platform"),
143
               clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
144
    cl::init(Default));
145
146
enum LinkageNameOption {
147
  DefaultLinkageNames,
148
  AllLinkageNames,
149
  AbstractLinkageNames
150
};
151
152
static cl::opt<LinkageNameOption>
153
    DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
154
                      cl::desc("Which DWARF linkage-name attributes to emit."),
155
                      cl::values(clEnumValN(DefaultLinkageNames, "Default",
156
                                            "Default for platform"),
157
                                 clEnumValN(AllLinkageNames, "All", "All"),
158
                                 clEnumValN(AbstractLinkageNames, "Abstract",
159
                                            "Abstract subprograms")),
160
                      cl::init(DefaultLinkageNames));
161
162
static const char *const DWARFGroupName = "dwarf";
163
static const char *const DWARFGroupDescription = "DWARF Emission";
164
static const char *const DbgTimerName = "writer";
165
static const char *const DbgTimerDescription = "DWARF Debug Writer";
166
static constexpr unsigned ULEB128PadSize = 4;
167
168
17.0k
void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
169
17.0k
  BS.EmitInt8(
170
17.0k
      Op, Comment ? 
Twine(Comment) + " " + dwarf::OperationEncodingString(Op)143
171
17.0k
                  : 
dwarf::OperationEncodingString(Op)16.9k
);
172
17.0k
}
173
174
194
void DebugLocDwarfExpression::emitSigned(int64_t Value) {
175
194
  BS.EmitSLEB128(Value, Twine(Value));
176
194
}
177
178
12.1k
void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
179
12.1k
  BS.EmitULEB128(Value, Twine(Value));
180
12.1k
}
181
182
0
void DebugLocDwarfExpression::emitData1(uint8_t Value) {
183
0
  BS.EmitInt8(Value, Twine(Value));
184
0
}
185
186
0
void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
187
0
  assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
188
0
  BS.EmitULEB128(Idx, Twine(Idx), ULEB128PadSize);
189
0
}
190
191
bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
192
176
                                              unsigned MachineReg) {
193
176
  // This information is not available while emitting .debug_loc entries.
194
176
  return false;
195
176
}
196
197
0
bool DbgVariable::isBlockByrefVariable() const {
198
0
  assert(getVariable() && "Invalid complex DbgVariable!");
199
0
  return getVariable()->getType()->isBlockByrefStruct();
200
0
}
201
202
3.93k
const DIType *DbgVariable::getType() const {
203
3.93k
  DIType *Ty = getVariable()->getType();
204
3.93k
  // FIXME: isBlockByrefVariable should be reformulated in terms of complex
205
3.93k
  // addresses instead.
206
3.93k
  if (Ty->isBlockByrefStruct()) {
207
4
    /* Byref variables, in Blocks, are declared by the programmer as
208
4
       "SomeType VarName;", but the compiler creates a
209
4
       __Block_byref_x_VarName struct, and gives the variable VarName
210
4
       either the struct, or a pointer to the struct, as its type.  This
211
4
       is necessary for various behind-the-scenes things the compiler
212
4
       needs to do with by-reference variables in blocks.
213
4
214
4
       However, as far as the original *programmer* is concerned, the
215
4
       variable should still have type 'SomeType', as originally declared.
216
4
217
4
       The following function dives into the __Block_byref_x_VarName
218
4
       struct to find the original type of the variable.  This will be
219
4
       passed back to the code generating the type for the Debug
220
4
       Information Entry for the variable 'VarName'.  'VarName' will then
221
4
       have the original type 'SomeType' in its debug information.
222
4
223
4
       The original type 'SomeType' will be the type of the field named
224
4
       'VarName' inside the __Block_byref_x_VarName struct.
225
4
226
4
       NOTE: In order for this to not completely fail on the debugger
227
4
       side, the Debug Information Entry for the variable VarName needs to
228
4
       have a DW_AT_location that tells the debugger how to unwind through
229
4
       the pointers and __Block_byref_x_VarName struct to find the actual
230
4
       value of the variable.  The function addBlockByrefType does this.  */
231
4
    DIType *subType = Ty;
232
4
    uint16_t tag = Ty->getTag();
233
4
234
4
    if (tag == dwarf::DW_TAG_pointer_type)
235
0
      subType = cast<DIDerivedType>(Ty)->getBaseType();
236
4
237
4
    auto Elements = cast<DICompositeType>(subType)->getElements();
238
28
    for (unsigned i = 0, N = Elements.size(); i < N; 
++i24
) {
239
28
      auto *DT = cast<DIDerivedType>(Elements[i]);
240
28
      if (getName() == DT->getName())
241
4
        return DT->getBaseType();
242
28
    }
243
4
  }
244
3.93k
  
return Ty3.93k
;
245
3.93k
}
246
247
/// Get .debug_loc entry for the instruction range starting at MI.
248
5.90k
static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
249
5.90k
  const DIExpression *Expr = MI->getDebugExpression();
250
5.90k
  assert(MI->getNumOperands() == 4);
251
5.90k
  if (MI->getOperand(0).isReg()) {
252
1.68k
    auto RegOp = MI->getOperand(0);
253
1.68k
    auto Op1 = MI->getOperand(1);
254
1.68k
    // If the second operand is an immediate, this is a
255
1.68k
    // register-indirect address.
256
1.68k
    assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
257
1.68k
    MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
258
1.68k
    return DbgValueLoc(Expr, MLoc);
259
1.68k
  }
260
4.21k
  if (MI->getOperand(0).isImm())
261
4.20k
    return DbgValueLoc(Expr, MI->getOperand(0).getImm());
262
9
  if (MI->getOperand(0).isFPImm())
263
8
    return DbgValueLoc(Expr, MI->getOperand(0).getFPImm());
264
1
  if (MI->getOperand(0).isCImm())
265
1
    return DbgValueLoc(Expr, MI->getOperand(0).getCImm());
266
0
267
0
  llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
268
0
}
269
270
518
void DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) {
271
518
  assert(FrameIndexExprs.empty() && "Already initialized?");
272
518
  assert(!ValueLoc.get() && "Already initialized?");
273
518
274
518
  assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable");
275
518
  assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() &&
276
518
         "Wrong inlined-at");
277
518
278
518
  ValueLoc = llvm::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue));
279
518
  if (auto *E = DbgValue->getDebugExpression())
280
518
    if (E->getNumElements())
281
100
      FrameIndexExprs.push_back({0, E});
282
518
}
283
284
516
ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
285
516
  if (FrameIndexExprs.size() == 1)
286
513
    return FrameIndexExprs;
287
3
288
3
  assert(llvm::all_of(FrameIndexExprs,
289
3
                      [](const FrameIndexExpr &A) {
290
3
                        return A.Expr->isFragment();
291
3
                      }) &&
292
3
         "multiple FI expressions without DW_OP_LLVM_fragment");
293
3
  llvm::sort(FrameIndexExprs,
294
3
             [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
295
3
               return A.Expr->getFragmentInfo()->OffsetInBits <
296
3
                      B.Expr->getFragmentInfo()->OffsetInBits;
297
3
             });
298
3
299
3
  return FrameIndexExprs;
300
3
}
301
302
4
void DbgVariable::addMMIEntry(const DbgVariable &V) {
303
4
  assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry");
304
4
  assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry");
305
4
  assert(V.getVariable() == getVariable() && "conflicting variable");
306
4
  assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
307
4
308
4
  assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
309
4
  assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
310
4
311
4
  // FIXME: This logic should not be necessary anymore, as we now have proper
312
4
  // deduplication. However, without it, we currently run into the assertion
313
4
  // below, which means that we are likely dealing with broken input, i.e. two
314
4
  // non-fragment entries for the same variable at different frame indices.
315
4
  if (FrameIndexExprs.size()) {
316
4
    auto *Expr = FrameIndexExprs.back().Expr;
317
4
    if (!Expr || !Expr->isFragment())
318
1
      return;
319
3
  }
320
3
321
3
  for (const auto &FIE : V.FrameIndexExprs)
322
3
    // Ignore duplicate entries.
323
3
    if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
324
3
          return FIE.FI == Other.FI && 
FIE.Expr == Other.Expr0
;
325
3
        }))
326
3
      FrameIndexExprs.push_back(FIE);
327
3
328
3
  assert((FrameIndexExprs.size() == 1 ||
329
3
          llvm::all_of(FrameIndexExprs,
330
3
                       [](FrameIndexExpr &FIE) {
331
3
                         return FIE.Expr && FIE.Expr->isFragment();
332
3
                       })) &&
333
3
         "conflicting locations for variable");
334
3
}
335
336
static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
337
                                            bool GenerateTypeUnits,
338
                                            DebuggerKind Tuning,
339
35.7k
                                            const Triple &TT) {
340
35.7k
  // Honor an explicit request.
341
35.7k
  if (AccelTables != AccelTableKind::Default)
342
17
    return AccelTables;
343
35.7k
344
35.7k
  // Accelerator tables with type units are currently not supported.
345
35.7k
  if (GenerateTypeUnits)
346
20
    return AccelTableKind::None;
347
35.7k
348
35.7k
  // Accelerator tables get emitted if targetting DWARF v5 or LLDB.  DWARF v5
349
35.7k
  // always implies debug_names. For lower standard versions we use apple
350
35.7k
  // accelerator tables on apple platforms and debug_names elsewhere.
351
35.7k
  if (DwarfVersion >= 5)
352
48
    return AccelTableKind::Dwarf;
353
35.6k
  if (Tuning == DebuggerKind::LLDB)
354
18.8k
    return TT.isOSBinFormatMachO() ? 
AccelTableKind::Apple14.5k
355
18.8k
                                   : 
AccelTableKind::Dwarf4.26k
;
356
16.8k
  return AccelTableKind::None;
357
16.8k
}
358
359
DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
360
    : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
361
      InfoHolder(A, "info_string", DIEValueAllocator),
362
      SkeletonHolder(A, "skel_string", DIEValueAllocator),
363
35.7k
      IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
364
35.7k
  const Triple &TT = Asm->TM.getTargetTriple();
365
35.7k
366
35.7k
  // Make sure we know our "debugger tuning".  The target option takes
367
35.7k
  // precedence; fall back to triple-based defaults.
368
35.7k
  if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
369
12.1k
    DebuggerTuning = Asm->TM.Options.DebuggerTuning;
370
23.6k
  else if (IsDarwin)
371
7.44k
    DebuggerTuning = DebuggerKind::LLDB;
372
16.2k
  else if (TT.isPS4CPU())
373
45
    DebuggerTuning = DebuggerKind::SCE;
374
16.1k
  else
375
16.1k
    DebuggerTuning = DebuggerKind::GDB;
376
35.7k
377
35.7k
  if (DwarfInlinedStrings == Default)
378
35.7k
    UseInlineStrings = TT.isNVPTX();
379
5
  else
380
5
    UseInlineStrings = DwarfInlinedStrings == Enable;
381
35.7k
382
35.7k
  UseLocSection = !TT.isNVPTX();
383
35.7k
384
35.7k
  HasAppleExtensionAttributes = tuneForLLDB();
385
35.7k
386
35.7k
  // Handle split DWARF.
387
35.7k
  HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
388
35.7k
389
35.7k
  // SCE defaults to linkage names only for abstract subprograms.
390
35.7k
  if (DwarfLinkageNames == DefaultLinkageNames)
391
35.7k
    UseAllLinkageNames = !tuneForSCE();
392
13
  else
393
13
    UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
394
35.7k
395
35.7k
  unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
396
35.7k
  unsigned DwarfVersion = DwarfVersionNumber ? 
DwarfVersionNumber72
397
35.7k
                                    : 
MMI->getModule()->getDwarfVersion()35.7k
;
398
35.7k
  // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
399
35.7k
  DwarfVersion =
400
35.7k
      TT.isNVPTX() ? 
2255
:
(DwarfVersion 35.5k
?
DwarfVersion3.01k
:
dwarf::DWARF_VERSION32.5k
);
401
35.7k
402
35.7k
  UseRangesSection = !NoDwarfRangesSection && 
!TT.isNVPTX()35.7k
;
403
35.7k
404
35.7k
  // Use sections as references. Force for NVPTX.
405
35.7k
  if (DwarfSectionsAsReferences == Default)
406
35.7k
    UseSectionsAsReferences = TT.isNVPTX();
407
0
  else
408
0
    UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
409
35.7k
410
35.7k
  // Don't generate type units for unsupported object file formats.
411
35.7k
  GenerateTypeUnits =
412
35.7k
      A->TM.getTargetTriple().isOSBinFormatELF() && 
GenerateDwarfTypeUnits19.3k
;
413
35.7k
414
35.7k
  TheAccelTableKind = computeAccelTableKind(
415
35.7k
      DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
416
35.7k
417
35.7k
  // Work around a GDB bug. GDB doesn't support the standard opcode;
418
35.7k
  // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
419
35.7k
  // is defined as of DWARF 3.
420
35.7k
  // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
421
35.7k
  // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
422
35.7k
  UseGNUTLSOpcode = tuneForGDB() || 
DwarfVersion < 318.8k
;
423
35.7k
424
35.7k
  // GDB does not fully support the DWARF 4 representation for bitfields.
425
35.7k
  UseDWARF2Bitfields = (DwarfVersion < 4) || 
tuneForGDB()33.2k
;
426
35.7k
427
35.7k
  // The DWARF v5 string offsets table has - possibly shared - contributions
428
35.7k
  // from each compile and type unit each preceded by a header. The string
429
35.7k
  // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
430
35.7k
  // a monolithic string offsets table without any header.
431
35.7k
  UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
432
35.7k
433
35.7k
  Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
434
35.7k
}
435
436
// Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
437
35.6k
DwarfDebug::~DwarfDebug() = default;
438
439
314k
static bool isObjCClass(StringRef Name) {
440
314k
  return Name.startswith("+") || 
Name.startswith("-")314k
;
441
314k
}
442
443
23
static bool hasObjCCategory(StringRef Name) {
444
23
  if (!isObjCClass(Name))
445
0
    return false;
446
23
447
23
  return Name.find(") ") != StringRef::npos;
448
23
}
449
450
static void getObjCClassCategory(StringRef In, StringRef &Class,
451
23
                                 StringRef &Category) {
452
23
  if (!hasObjCCategory(In)) {
453
23
    Class = In.slice(In.find('[') + 1, In.find(' '));
454
23
    Category = "";
455
23
    return;
456
23
  }
457
0
458
0
  Class = In.slice(In.find('[') + 1, In.find('('));
459
0
  Category = In.slice(In.find('[') + 1, In.find(' '));
460
0
}
461
462
23
static StringRef getObjCMethodName(StringRef In) {
463
23
  return In.slice(In.find(' ') + 1, In.find(']'));
464
23
}
465
466
// Add the various names to the Dwarf accelerator table names.
467
void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
468
314k
                                    const DISubprogram *SP, DIE &Die) {
469
314k
  if (getAccelTableKind() != AccelTableKind::Apple &&
470
314k
      
CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None665
)
471
135
    return;
472
314k
473
314k
  if (!SP->isDefinition())
474
0
    return;
475
314k
476
314k
  if (SP->getName() != "")
477
314k
    addAccelName(CU, SP->getName(), Die);
478
314k
479
314k
  // If the linkage name is different than the name, go ahead and output that as
480
314k
  // well into the name table. Only do that if we are going to actually emit
481
314k
  // that name.
482
314k
  if (SP->getLinkageName() != "" && 
SP->getName() != SP->getLinkageName()713
&&
483
314k
      
(645
useAllLinkageNames()645
||
InfoHolder.getAbstractSPDies().lookup(SP)27
))
484
623
    addAccelName(CU, SP->getLinkageName(), Die);
485
314k
486
314k
  // If this is an Objective-C selector name add it to the ObjC accelerator
487
314k
  // too.
488
314k
  if (isObjCClass(SP->getName())) {
489
23
    StringRef Class, Category;
490
23
    getObjCClassCategory(SP->getName(), Class, Category);
491
23
    addAccelObjC(CU, Class, Die);
492
23
    if (Category != "")
493
0
      addAccelObjC(CU, Category, Die);
494
23
    // Also add the base method name to the name table.
495
23
    addAccelName(CU, getObjCMethodName(SP->getName()), Die);
496
23
  }
497
314k
}
498
499
/// Check whether we should create a DIE for the given Scope, return true
500
/// if we don't create a DIE (the corresponding DIE is null).
501
560
bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
502
560
  if (Scope->isAbstractScope())
503
61
    return false;
504
499
505
499
  // We don't create a DIE if there is no Range.
506
499
  const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
507
499
  if (Ranges.empty())
508
0
    return true;
509
499
510
499
  if (Ranges.size() > 1)
511
63
    return false;
512
436
513
436
  // We don't create a DIE if we have a single Range and the end label
514
436
  // is null.
515
436
  return !getLabelAfterInsn(Ranges.front().second);
516
436
}
517
518
35.3k
template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
519
35.3k
  F(CU);
520
35.3k
  if (auto *SkelCU = CU.getSkeleton())
521
55
    if (CU.getCUNode()->getSplitDebugInlining())
522
51
      F(*SkelCU);
523
35.3k
}
524
525
963
bool DwarfDebug::shareAcrossDWOCUs() const {
526
963
  return SplitDwarfCrossCuReferences;
527
963
}
528
529
void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
530
165k
                                                     LexicalScope *Scope) {
531
165k
  assert(Scope && Scope->getScopeNode());
532
165k
  assert(Scope->isAbstractScope());
533
165k
  assert(!Scope->getInlinedAt());
534
165k
535
165k
  auto *SP = cast<DISubprogram>(Scope->getScopeNode());
536
165k
537
165k
  // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
538
165k
  // was inlined from another compile unit.
539
165k
  if (useSplitDwarf() && 
!shareAcrossDWOCUs()7
&&
!SP->getUnit()->getSplitDebugInlining()5
)
540
2
    // Avoid building the original CU if it won't be used
541
2
    SrcCU.constructAbstractSubprogramScopeDIE(Scope);
542
165k
  else {
543
165k
    auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
544
165k
    if (auto *SkelCU = CU.getSkeleton()) {
545
5
      (shareAcrossDWOCUs() ? 
CU2
:
SrcCU3
)
546
5
          .constructAbstractSubprogramScopeDIE(Scope);
547
5
      if (CU.getCUNode()->getSplitDebugInlining())
548
5
        SkelCU->constructAbstractSubprogramScopeDIE(Scope);
549
5
    } else
550
165k
      CU.constructAbstractSubprogramScopeDIE(Scope);
551
165k
  }
552
165k
}
553
554
void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
555
                                            DwarfCompileUnit &CU, DIE &ScopeDIE,
556
35.3k
                                            const MachineFunction &MF) {
557
35.3k
  // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
558
35.3k
  // the subprogram is required to have one.
559
35.3k
  if (!SP.areAllCallsDescribed() || 
!SP.isDefinition()20
)
560
35.3k
    return;
561
20
562
20
  // Use DW_AT_call_all_calls to express that call site entries are present
563
20
  // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
564
20
  // because one of its requirements is not met: call site entries for
565
20
  // optimized-out calls are elided.
566
20
  CU.addFlag(ScopeDIE, dwarf::DW_AT_call_all_calls);
567
20
568
20
  const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
569
20
  assert(TII && "TargetInstrInfo not found: cannot label tail calls");
570
20
571
20
  // Emit call site entries for each call or tail call in the function.
572
20
  for (const MachineBasicBlock &MBB : MF) {
573
100
    for (const MachineInstr &MI : MBB.instrs()) {
574
100
      // Skip instructions which aren't calls. Both calls and tail-calling jump
575
100
      // instructions (e.g TAILJMPd64) are classified correctly here.
576
100
      if (!MI.isCall())
577
87
        continue;
578
13
579
13
      // TODO: Add support for targets with delay slots (see: beginInstruction).
580
13
      if (MI.hasDelaySlot())
581
0
        return;
582
13
583
13
      // If this is a direct call, find the callee's subprogram.
584
13
      const MachineOperand &CalleeOp = MI.getOperand(0);
585
13
      if (!CalleeOp.isGlobal())
586
2
        continue;
587
11
      const Function *CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
588
11
      if (!CalleeDecl || !CalleeDecl->getSubprogram())
589
0
        continue;
590
11
591
11
      // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
592
11
      // TODO: Add support for indirect calls.
593
11
594
11
      bool IsTail = TII->isTailCall(MI);
595
11
596
11
      // For tail calls, no return PC information is needed. For regular calls,
597
11
      // the return PC is needed to disambiguate paths in the call graph which
598
11
      // could lead to some target function.
599
11
      const MCExpr *PCOffset =
600
11
          IsTail ? 
nullptr3
:
getFunctionLocalOffsetAfterInsn(&MI)8
;
601
11
602
11
      assert((IsTail || PCOffset) && "Call without return PC information");
603
11
      LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
604
11
                        << CalleeDecl->getName() << (IsTail ? " [tail]" : "")
605
11
                        << "\n");
606
11
      CU.constructCallSiteEntryDIE(ScopeDIE, *CalleeDecl->getSubprogram(),
607
11
                                   IsTail, PCOffset);
608
11
    }
609
20
  }
610
20
}
611
612
2.67k
void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
613
2.67k
  if (!U.hasDwarfPubSections())
614
958
    return;
615
1.71k
616
1.71k
  U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
617
1.71k
}
618
619
void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
620
2.67k
                                      DwarfCompileUnit &NewCU) {
621
2.67k
  DIE &Die = NewCU.getUnitDie();
622
2.67k
  StringRef FN = DIUnit->getFilename();
623
2.67k
624
2.67k
  StringRef Producer = DIUnit->getProducer();
625
2.67k
  StringRef Flags = DIUnit->getFlags();
626
2.67k
  if (!Flags.empty() && 
!useAppleExtensionAttributes()2
) {
627
1
    std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
628
1
    NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
629
1
  } else
630
2.67k
    NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
631
2.67k
632
2.67k
  NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
633
2.67k
                DIUnit->getSourceLanguage());
634
2.67k
  NewCU.addString(Die, dwarf::DW_AT_name, FN);
635
2.67k
636
2.67k
  // Add DW_str_offsets_base to the unit DIE, except for split units.
637
2.67k
  if (useSegmentedStringOffsetsTable() && 
!useSplitDwarf()65
)
638
56
    NewCU.addStringOffsetsStart();
639
2.67k
640
2.67k
  if (!useSplitDwarf()) {
641
2.61k
    NewCU.initStmtList();
642
2.61k
643
2.61k
    // If we're using split dwarf the compilation dir is going to be in the
644
2.61k
    // skeleton CU and so we don't need to duplicate it here.
645
2.61k
    if (!CompilationDir.empty())
646
2.55k
      NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
647
2.61k
648
2.61k
    addGnuPubAttributes(NewCU, Die);
649
2.61k
  }
650
2.67k
651
2.67k
  if (useAppleExtensionAttributes()) {
652
2.19k
    if (DIUnit->isOptimized())
653
1.64k
      NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
654
2.19k
655
2.19k
    StringRef Flags = DIUnit->getFlags();
656
2.19k
    if (!Flags.empty())
657
1
      NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
658
2.19k
659
2.19k
    if (unsigned RVer = DIUnit->getRuntimeVersion())
660
46
      NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
661
46
                    dwarf::DW_FORM_data1, RVer);
662
2.19k
  }
663
2.67k
664
2.67k
  if (DIUnit->getDWOId()) {
665
28
    // This CU is either a clang module DWO or a skeleton CU.
666
28
    NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
667
28
                  DIUnit->getDWOId());
668
28
    if (!DIUnit->getSplitDebugFilename().empty())
669
5
      // This is a prefabricated skeleton CU.
670
5
      NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
671
5
                      DIUnit->getSplitDebugFilename());
672
28
  }
673
2.67k
}
674
// Create new DwarfCompileUnit for the given metadata node with tag
675
// DW_TAG_compile_unit.
676
DwarfCompileUnit &
677
272k
DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
678
272k
  if (auto *CU = CUMap.lookup(DIUnit))
679
270k
    return *CU;
680
2.67k
681
2.67k
  CompilationDir = DIUnit->getDirectory();
682
2.67k
683
2.67k
  auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
684
2.67k
      InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
685
2.67k
  DwarfCompileUnit &NewCU = *OwnedUnit;
686
2.67k
  InfoHolder.addUnit(std::move(OwnedUnit));
687
2.67k
688
2.67k
  for (auto *IE : DIUnit->getImportedEntities())
689
235
    NewCU.addImportedEntity(IE);
690
2.67k
691
2.67k
  // LTO with assembly output shares a single line table amongst multiple CUs.
692
2.67k
  // To avoid the compilation directory being ambiguous, let the line table
693
2.67k
  // explicitly describe the directory of all files, never relying on the
694
2.67k
  // compilation directory.
695
2.67k
  if (!Asm->OutStreamer->hasRawTextSupport() || 
SingleCU468
)
696
2.64k
    Asm->OutStreamer->emitDwarfFile0Directive(
697
2.64k
        CompilationDir, DIUnit->getFilename(),
698
2.64k
        NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(),
699
2.64k
        NewCU.getUniqueID());
700
2.67k
701
2.67k
  if (useSplitDwarf()) {
702
55
    NewCU.setSkeleton(constructSkeletonCU(NewCU));
703
55
    NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
704
2.61k
  } else {
705
2.61k
    finishUnitAttributes(DIUnit, NewCU);
706
2.61k
    NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
707
2.61k
  }
708
2.67k
709
2.67k
  // Create DIEs for function declarations used for call site debug info.
710
2.67k
  for (auto Scope : DIUnit->getRetainedTypes())
711
364
    if (auto *SP = dyn_cast_or_null<DISubprogram>(Scope))
712
32
      NewCU.getOrCreateSubprogramDIE(SP);
713
2.67k
714
2.67k
  CUMap.insert({DIUnit, &NewCU});
715
2.67k
  CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
716
2.67k
  return NewCU;
717
2.67k
}
718
719
void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
720
232
                                                  const DIImportedEntity *N) {
721
232
  if (isa<DILocalScope>(N->getScope()))
722
14
    return;
723
218
  if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
724
218
    D->addChild(TheCU.constructImportedEntityDIE(N));
725
218
}
726
727
/// Sort and unique GVEs by comparing their fragment offset.
728
static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
729
946
sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
730
946
  llvm::sort(
731
946
      GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
732
10
        // Sort order: first null exprs, then exprs without fragment
733
10
        // info, then sort by fragment offset in bits.
734
10
        // FIXME: Come up with a more comprehensive comparator so
735
10
        // the sorting isn't non-deterministic, and so the following
736
10
        // std::unique call works correctly.
737
10
        if (!A.Expr || !B.Expr)
738
0
          return !!B.Expr;
739
10
        auto FragmentA = A.Expr->getFragmentInfo();
740
10
        auto FragmentB = B.Expr->getFragmentInfo();
741
10
        if (!FragmentA || 
!FragmentB7
)
742
4
          return !!FragmentB;
743
6
        return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
744
6
      });
745
946
  GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
746
946
                         [](DwarfCompileUnit::GlobalExpr A,
747
946
                            DwarfCompileUnit::GlobalExpr B) {
748
9
                           return A.Expr == B.Expr;
749
9
                         }),
750
946
             GVEs.end());
751
946
  return GVEs;
752
946
}
753
754
// Emit all Dwarf sections that should come prior to the content. Create
755
// global DIEs and emit initial debug info sections. This is invoked by
756
// the target AsmPrinter.
757
35.7k
void DwarfDebug::beginModule() {
758
35.7k
  NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
759
35.7k
                     DWARFGroupDescription, TimePassesIsEnabled);
760
35.7k
  if (DisableDebugInfoPrinting) {
761
0
    MMI->setDebugInfoAvailability(false);
762
0
    return;
763
0
  }
764
35.7k
765
35.7k
  const Module *M = MMI->getModule();
766
35.7k
767
35.7k
  unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
768
35.7k
                                       M->debug_compile_units_end());
769
35.7k
  // Tell MMI whether we have debug info.
770
35.7k
  assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) &&
771
35.7k
         "DebugInfoAvailabilty initialized unexpectedly");
772
35.7k
  SingleCU = NumDebugCUs == 1;
773
35.7k
  DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
774
35.7k
      GVMap;
775
448k
  for (const GlobalVariable &Global : M->globals()) {
776
448k
    SmallVector<DIGlobalVariableExpression *, 1> GVs;
777
448k
    Global.getDebugInfo(GVs);
778
448k
    for (auto *GVE : GVs)
779
791
      GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
780
448k
  }
781
35.7k
782
35.7k
  // Create the symbol that designates the start of the unit's contribution
783
35.7k
  // to the string offsets table. In a split DWARF scenario, only the skeleton
784
35.7k
  // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
785
35.7k
  if (useSegmentedStringOffsetsTable())
786
55
    (useSplitDwarf() ? 
SkeletonHolder7
:
InfoHolder48
)
787
55
        .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
788
35.7k
789
35.7k
790
35.7k
  // Create the symbols that designates the start of the DWARF v5 range list
791
35.7k
  // and locations list tables. They are located past the table headers.
792
35.7k
  if (getDwarfVersion() >= 5) {
793
55
    DwarfFile &Holder = useSplitDwarf() ? 
SkeletonHolder7
:
InfoHolder48
;
794
55
    Holder.setRnglistsTableBaseSym(
795
55
        Asm->createTempSymbol("rnglists_table_base"));
796
55
    Holder.setLoclistsTableBaseSym(
797
55
        Asm->createTempSymbol("loclists_table_base"));
798
55
799
55
    if (useSplitDwarf())
800
7
      InfoHolder.setRnglistsTableBaseSym(
801
7
          Asm->createTempSymbol("rnglists_dwo_table_base"));
802
55
  }
803
35.7k
804
35.7k
  // Create the symbol that points to the first entry following the debug
805
35.7k
  // address table (.debug_addr) header.
806
35.7k
  AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
807
35.7k
808
35.7k
  for (DICompileUnit *CUNode : M->debug_compile_units()) {
809
3.55k
    // FIXME: Move local imported entities into a list attached to the
810
3.55k
    // subprogram, then this search won't be needed and a
811
3.55k
    // getImportedEntities().empty() test should go below with the rest.
812
3.55k
    bool HasNonLocalImportedEntities = llvm::any_of(
813
3.55k
        CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
814
16
          return !isa<DILocalScope>(IE->getScope());
815
16
        });
816
3.55k
817
3.55k
    if (!HasNonLocalImportedEntities && 
CUNode->getEnumTypes().empty()3.53k
&&
818
3.55k
        
CUNode->getRetainedTypes().empty()3.50k
&&
819
3.55k
        
CUNode->getGlobalVariables().empty()3.36k
&&
CUNode->getMacros().empty()2.78k
)
820
2.78k
      continue;
821
762
822
762
    DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
823
762
824
762
    // Global Variables.
825
952
    for (auto *GVE : CUNode->getGlobalVariables()) {
826
952
      // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
827
952
      // already know about the variable and it isn't adding a constant
828
952
      // expression.
829
952
      auto &GVMapEntry = GVMap[GVE->getVariable()];
830
952
      auto *Expr = GVE->getExpression();
831
952
      if (!GVMapEntry.size() || 
(788
Expr788
&&
Expr->isConstant()788
))
832
168
        GVMapEntry.push_back({nullptr, Expr});
833
952
    }
834
762
    DenseSet<DIGlobalVariable *> Processed;
835
952
    for (auto *GVE : CUNode->getGlobalVariables()) {
836
952
      DIGlobalVariable *GV = GVE->getVariable();
837
952
      if (Processed.insert(GV).second)
838
946
        CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
839
952
    }
840
762
841
762
    for (auto *Ty : CUNode->getEnumTypes()) {
842
93
      // The enum types array by design contains pointers to
843
93
      // MDNodes rather than DIRefs. Unique them here.
844
93
      CU.getOrCreateTypeDIE(cast<DIType>(Ty));
845
93
    }
846
762
    for (auto *Ty : CUNode->getRetainedTypes()) {
847
364
      // The retained types array by design contains pointers to
848
364
      // MDNodes rather than DIRefs. Unique them here.
849
364
      if (DIType *RT = dyn_cast<DIType>(Ty))
850
332
          // There is no point in force-emitting a forward declaration.
851
332
          CU.getOrCreateTypeDIE(RT);
852
364
    }
853
762
    // Emit imported_modules last so that the relevant context is already
854
762
    // available.
855
762
    for (auto *IE : CUNode->getImportedEntities())
856
232
      constructAndAddImportedEntityDIE(CU, IE);
857
762
  }
858
35.7k
}
859
860
3.21k
void DwarfDebug::finishEntityDefinitions() {
861
3.21k
  for (const auto &Entity : ConcreteEntities) {
862
1.20k
    DIE *Die = Entity->getDIE();
863
1.20k
    assert(Die);
864
1.20k
    // FIXME: Consider the time-space tradeoff of just storing the unit pointer
865
1.20k
    // in the ConcreteEntities list, rather than looking it up again here.
866
1.20k
    // DIE::getUnit isn't simple - it walks parent pointers, etc.
867
1.20k
    DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
868
1.20k
    assert(Unit);
869
1.20k
    Unit->finishEntityDefinition(Entity.get());
870
1.20k
  }
871
3.21k
}
872
873
3.21k
void DwarfDebug::finishSubprogramDefinitions() {
874
35.3k
  for (const DISubprogram *SP : ProcessedSPNodes) {
875
35.3k
    assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
876
35.3k
    forBothCUs(
877
35.3k
        getOrCreateDwarfCompileUnit(SP->getUnit()),
878
35.3k
        [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
879
35.3k
  }
880
3.21k
}
881
882
3.21k
void DwarfDebug::finalizeModuleInfo() {
883
3.21k
  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
884
3.21k
885
3.21k
  finishSubprogramDefinitions();
886
3.21k
887
3.21k
  finishEntityDefinitions();
888
3.21k
889
3.21k
  // Include the DWO file name in the hash if there's more than one CU.
890
3.21k
  // This handles ThinLTO's situation where imported CUs may very easily be
891
3.21k
  // duplicate with the same CU partially imported into another ThinLTO unit.
892
3.21k
  StringRef DWOName;
893
3.21k
  if (CUMap.size() > 1)
894
58
    DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
895
3.21k
896
3.21k
  // Handle anything that needs to be done on a per-unit basis after
897
3.21k
  // all other generation.
898
3.21k
  for (const auto &P : CUMap) {
899
2.66k
    auto &TheCU = *P.second;
900
2.66k
    if (TheCU.getCUNode()->isDebugDirectivesOnly())
901
3
      continue;
902
2.66k
    // Emit DW_AT_containing_type attribute to connect types with their
903
2.66k
    // vtable holding type.
904
2.66k
    TheCU.constructContainingTypeDIEs();
905
2.66k
906
2.66k
    // Add CU specific attributes if we need to add any.
907
2.66k
    // If we're splitting the dwarf out now that we've got the entire
908
2.66k
    // CU then add the dwo id to it.
909
2.66k
    auto *SkCU = TheCU.getSkeleton();
910
2.66k
    if (useSplitDwarf() && 
!empty(TheCU.getUnitDie().children())55
) {
911
54
      finishUnitAttributes(TheCU.getCUNode(), TheCU);
912
54
      TheCU.addString(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_name,
913
54
                      Asm->TM.Options.MCOptions.SplitDwarfFile);
914
54
      SkCU->addString(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_name,
915
54
                      Asm->TM.Options.MCOptions.SplitDwarfFile);
916
54
      // Emit a unique identifier for this CU.
917
54
      uint64_t ID =
918
54
          DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
919
54
      if (getDwarfVersion() >= 5) {
920
9
        TheCU.setDWOId(ID);
921
9
        SkCU->setDWOId(ID);
922
45
      } else {
923
45
        TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
924
45
                      dwarf::DW_FORM_data8, ID);
925
45
        SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
926
45
                      dwarf::DW_FORM_data8, ID);
927
45
      }
928
54
929
54
      if (getDwarfVersion() < 5 && 
!SkeletonHolder.getRangeLists().empty()45
) {
930
2
        const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
931
2
        SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
932
2
                              Sym, Sym);
933
2
      }
934
2.60k
    } else if (SkCU) {
935
1
      finishUnitAttributes(SkCU->getCUNode(), *SkCU);
936
1
    }
937
2.66k
938
2.66k
    // If we have code split among multiple sections or non-contiguous
939
2.66k
    // ranges of code then emit a DW_AT_ranges attribute on the unit that will
940
2.66k
    // remain in the .o file, otherwise add a DW_AT_low_pc.
941
2.66k
    // FIXME: We should use ranges allow reordering of code ala
942
2.66k
    // .subsections_via_symbols in mach-o. This would mean turning on
943
2.66k
    // ranges for all subprogram DIEs for mach-o.
944
2.66k
    DwarfCompileUnit &U = SkCU ? 
*SkCU55
:
TheCU2.60k
;
945
2.66k
946
2.66k
    if (unsigned NumRanges = TheCU.getRanges().size()) {
947
2.14k
      if (NumRanges > 1 && 
useRangesSection()90
)
948
88
        // A DW_AT_low_pc attribute may also be specified in combination with
949
88
        // DW_AT_ranges to specify the default base address for use in
950
88
        // location lists (see Section 2.6.2) and range lists (see Section
951
88
        // 2.17.3).
952
88
        U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
953
2.05k
      else
954
2.05k
        U.setBaseAddress(TheCU.getRanges().front().getStart());
955
2.14k
      U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
956
2.14k
    }
957
2.66k
958
2.66k
    // We don't keep track of which addresses are used in which CU so this
959
2.66k
    // is a bit pessimistic under LTO.
960
2.66k
    if (!AddrPool.isEmpty() &&
961
2.66k
        
(108
getDwarfVersion() >= 5108
||
962
108
         
(43
SkCU43
&&
!empty(TheCU.getUnitDie().children())43
)))
963
108
      U.addAddrTableBase();
964
2.66k
965
2.66k
    if (getDwarfVersion() >= 5) {
966
65
      if (U.hasRangeLists())
967
7
        U.addRnglistsBase();
968
65
969
65
      if (!DebugLocs.getLists().empty() && 
!useSplitDwarf()6
)
970
6
        U.addLoclistsBase();
971
65
    }
972
2.66k
973
2.66k
    auto *CUNode = cast<DICompileUnit>(P.first);
974
2.66k
    // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
975
2.66k
    if (CUNode->getMacros())
976
2
      U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
977
2
                        U.getMacroLabelBegin(),
978
2
                        TLOF.getDwarfMacinfoSection()->getBeginSymbol());
979
2.66k
  }
980
3.21k
981
3.21k
  // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
982
3.21k
  for (auto *CUNode : MMI->getModule()->debug_compile_units())
983
3.54k
    if (CUNode->getDWOId())
984
28
      getOrCreateDwarfCompileUnit(CUNode);
985
3.21k
986
3.21k
  // Compute DIE offsets and sizes.
987
3.21k
  InfoHolder.computeSizeAndOffsets();
988
3.21k
  if (useSplitDwarf())
989
49
    SkeletonHolder.computeSizeAndOffsets();
990
3.21k
}
991
992
// Emit all Dwarf sections that should come after the content.
993
35.6k
void DwarfDebug::endModule() {
994
35.6k
  assert(CurFn == nullptr);
995
35.6k
  assert(CurMI == nullptr);
996
35.6k
997
35.6k
  for (const auto &P : CUMap) {
998
2.66k
    auto &CU = *P.second;
999
2.66k
    CU.createBaseTypeDIEs();
1000
2.66k
  }
1001
35.6k
1002
35.6k
  // If we aren't actually generating debug info (check beginModule -
1003
35.6k
  // conditionalized on !DisableDebugInfoPrinting and the presence of the
1004
35.6k
  // llvm.dbg.cu metadata node)
1005
35.6k
  if (!MMI->hasDebugInfo())
1006
32.4k
    return;
1007
3.20k
1008
3.20k
  // Finalize the debug info for the module.
1009
3.20k
  finalizeModuleInfo();
1010
3.20k
1011
3.20k
  emitDebugStr();
1012
3.20k
1013
3.20k
  if (useSplitDwarf())
1014
49
    emitDebugLocDWO();
1015
3.15k
  else
1016
3.15k
    // Emit info into a debug loc section.
1017
3.15k
    emitDebugLoc();
1018
3.20k
1019
3.20k
  // Corresponding abbreviations into a abbrev section.
1020
3.20k
  emitAbbreviations();
1021
3.20k
1022
3.20k
  // Emit all the DIEs into a debug info section.
1023
3.20k
  emitDebugInfo();
1024
3.20k
1025
3.20k
  // Emit info into a debug aranges section.
1026
3.20k
  if (GenerateARangeSection)
1027
6
    emitDebugARanges();
1028
3.20k
1029
3.20k
  // Emit info into a debug ranges section.
1030
3.20k
  emitDebugRanges();
1031
3.20k
1032
3.20k
  // Emit info into a debug macinfo section.
1033
3.20k
  emitDebugMacinfo();
1034
3.20k
1035
3.20k
  if (useSplitDwarf()) {
1036
49
    emitDebugStrDWO();
1037
49
    emitDebugInfoDWO();
1038
49
    emitDebugAbbrevDWO();
1039
49
    emitDebugLineDWO();
1040
49
    emitDebugRangesDWO();
1041
49
  }
1042
3.20k
1043
3.20k
  emitDebugAddr();
1044
3.20k
1045
3.20k
  // Emit info into the dwarf accelerator table sections.
1046
3.20k
  switch (getAccelTableKind()) {
1047
3.20k
  case AccelTableKind::Apple:
1048
2.55k
    emitAccelNames();
1049
2.55k
    emitAccelObjC();
1050
2.55k
    emitAccelNamespaces();
1051
2.55k
    emitAccelTypes();
1052
2.55k
    break;
1053
3.20k
  case AccelTableKind::Dwarf:
1054
205
    emitAccelDebugNames();
1055
205
    break;
1056
3.20k
  case AccelTableKind::None:
1057
451
    break;
1058
3.20k
  case AccelTableKind::Default:
1059
0
    llvm_unreachable("Default should have already been resolved.");
1060
3.21k
  }
1061
3.21k
1062
3.21k
  // Emit the pubnames and pubtypes sections if requested.
1063
3.21k
  emitDebugPubSections();
1064
3.21k
1065
3.21k
  // clean up.
1066
3.21k
  // FIXME: AbstractVariables.clear();
1067
3.21k
}
1068
1069
void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1070
                                               const DINode *Node,
1071
90
                                               const MDNode *ScopeNode) {
1072
90
  if (CU.getExistingAbstractEntity(Node))
1073
67
    return;
1074
23
1075
23
  CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
1076
23
                                       cast<DILocalScope>(ScopeNode)));
1077
23
}
1078
1079
void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1080
1.21k
    const DINode *Node, const MDNode *ScopeNode) {
1081
1.21k
  if (CU.getExistingAbstractEntity(Node))
1082
26
    return;
1083
1.18k
1084
1.18k
  if (LexicalScope *Scope =
1085
88
          LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1086
88
    CU.createAbstractEntity(Node, Scope);
1087
1.18k
}
1088
1089
// Collect variable information from side table maintained by MF.
1090
void DwarfDebug::collectVariableInfoFromMFTable(
1091
35.3k
    DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1092
35.3k
  SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1093
35.3k
  for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1094
523
    if (!VI.Var)
1095
0
      continue;
1096
523
    assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1097
523
           "Expected inlined-at fields to agree");
1098
523
1099
523
    InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1100
523
    Processed.insert(Var);
1101
523
    LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1102
523
1103
523
    // If variable scope is not found then skip this variable.
1104
523
    if (!Scope)
1105
3
      continue;
1106
520
1107
520
    ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1108
520
    auto RegVar = llvm::make_unique<DbgVariable>(
1109
520
                    cast<DILocalVariable>(Var.first), Var.second);
1110
520
    RegVar->initializeMMI(VI.Expr, VI.Slot);
1111
520
    if (DbgVariable *DbgVar = MFVars.lookup(Var))
1112
4
      DbgVar->addMMIEntry(*RegVar);
1113
516
    else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1114
516
      MFVars.insert({Var, RegVar.get()});
1115
516
      ConcreteEntities.push_back(std::move(RegVar));
1116
516
    }
1117
520
  }
1118
35.3k
}
1119
1120
/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1121
/// enclosing lexical scope. The check ensures there are no other instructions
1122
/// in the same lexical scope preceding the DBG_VALUE and that its range is
1123
/// either open or otherwise rolls off the end of the scope.
1124
static bool validThroughout(LexicalScopes &LScopes,
1125
                            const MachineInstr *DbgValue,
1126
586
                            const MachineInstr *RangeEnd) {
1127
586
  assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1128
586
  auto MBB = DbgValue->getParent();
1129
586
  auto DL = DbgValue->getDebugLoc();
1130
586
  auto *LScope = LScopes.findLexicalScope(DL);
1131
586
  // Scope doesn't exist; this is a dead DBG_VALUE.
1132
586
  if (!LScope)
1133
4
    return false;
1134
582
  auto &LSRange = LScope->getRanges();
1135
582
  if (LSRange.size() == 0)
1136
0
    return false;
1137
582
1138
582
  // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1139
582
  const MachineInstr *LScopeBegin = LSRange.front().first;
1140
582
  // Early exit if the lexical scope begins outside of the current block.
1141
582
  if (LScopeBegin->getParent() != MBB)
1142
36
    return false;
1143
546
  MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1144
1.30k
  for (++Pred; Pred != MBB->rend(); 
++Pred757
) {
1145
986
    if (Pred->getFlag(MachineInstr::FrameSetup))
1146
42
      break;
1147
944
    auto PredDL = Pred->getDebugLoc();
1148
944
    if (!PredDL || 
Pred->isMetaInstruction()669
)
1149
681
      continue;
1150
263
    // Check whether the instruction preceding the DBG_VALUE is in the same
1151
263
    // (sub)scope as the DBG_VALUE.
1152
263
    if (DL->getScope() == PredDL->getScope())
1153
171
      return false;
1154
92
    auto *PredScope = LScopes.findLexicalScope(PredDL);
1155
92
    if (!PredScope || LScope->dominates(PredScope))
1156
16
      return false;
1157
92
  }
1158
546
1159
546
  // If the range of the DBG_VALUE is open-ended, report success.
1160
546
  
if (359
!RangeEnd359
)
1161
126
    return true;
1162
233
1163
233
  // Fail if there are instructions belonging to our scope in another block.
1164
233
  const MachineInstr *LScopeEnd = LSRange.back().second;
1165
233
  if (LScopeEnd->getParent() != MBB)
1166
35
    return false;
1167
198
1168
198
  // Single, constant DBG_VALUEs in the prologue are promoted to be live
1169
198
  // throughout the function. This is a hack, presumably for DWARF v2 and not
1170
198
  // necessarily correct. It would be much better to use a dbg.declare instead
1171
198
  // if we know the constant is live throughout the scope.
1172
198
  if (DbgValue->getOperand(0).isImm() && 
MBB->pred_empty()4
)
1173
0
    return true;
1174
198
1175
198
  return false;
1176
198
}
1177
1178
/// Build the location list for all DBG_VALUEs in the function that
1179
/// describe the same variable. The resulting DebugLocEntries will have
1180
/// strict monotonically increasing begin addresses and will never
1181
/// overlap. If the resulting list has only one entry that is valid
1182
/// throughout variable's scope return true.
1183
//
1184
// See the definition of DbgValueHistoryMap::Entry for an explanation of the
1185
// different kinds of history map entries. One thing to be aware of is that if
1186
// a debug value is ended by another entry (rather than being valid until the
1187
// end of the function), that entry's instruction may or may not be included in
1188
// the range, depending on if the entry is a clobbering entry (it has an
1189
// instruction that clobbers one or more preceding locations), or if it is an
1190
// (overlapping) debug value entry. This distinction can be seen in the example
1191
// below. The first debug value is ended by the clobbering entry 2, and the
1192
// second and third debug values are ended by the overlapping debug value entry
1193
// 4.
1194
//
1195
// Input:
1196
//
1197
//   History map entries [type, end index, mi]
1198
//
1199
// 0 |      [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1200
// 1 | |    [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1201
// 2 | |    [Clobber, $reg0 = [...], -, -]
1202
// 3   | |  [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1203
// 4        [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1204
//
1205
// Output [start, end) [Value...]:
1206
//
1207
// [0-1)    [(reg0, fragment 0, 32)]
1208
// [1-3)    [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1209
// [3-4)    [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1210
// [4-)     [(@g, fragment 0, 96)]
1211
bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1212
503
                                   const DbgValueHistoryMap::Entries &Entries) {
1213
503
  using OpenRange =
1214
503
      std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1215
503
  SmallVector<OpenRange, 4> OpenRanges;
1216
503
  bool isSafeForSingleLocation = true;
1217
503
  const MachineInstr *StartDebugMI = nullptr;
1218
503
  const MachineInstr *EndMI = nullptr;
1219
503
1220
6.97k
  for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; 
++EI6.47k
) {
1221
6.47k
    const MachineInstr *Instr = EI->getInstr();
1222
6.47k
1223
6.47k
    // Remove all values that are no longer live.
1224
6.47k
    size_t Index = std::distance(EB, EI);
1225
6.47k
    auto Last =
1226
7.99M
        remove_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1227
6.47k
    OpenRanges.erase(Last, OpenRanges.end());
1228
6.47k
1229
6.47k
    // If we are dealing with a clobbering entry, this iteration will result in
1230
6.47k
    // a location list entry starting after the clobbering instruction.
1231
6.47k
    const MCSymbol *StartLabel =
1232
6.47k
        EI->isClobber() ? 
getLabelAfterInsn(Instr)1.02k
:
getLabelBeforeInsn(Instr)5.44k
;
1233
6.47k
    assert(StartLabel &&
1234
6.47k
           "Forgot label before/after instruction starting a range!");
1235
6.47k
1236
6.47k
    const MCSymbol *EndLabel;
1237
6.47k
    if (std::next(EI) == Entries.end()) {
1238
503
      EndLabel = Asm->getFunctionEnd();
1239
503
      if (EI->isClobber())
1240
315
        EndMI = EI->getInstr();
1241
503
    }
1242
5.97k
    else if (std::next(EI)->isClobber())
1243
1.02k
      EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1244
4.94k
    else
1245
4.94k
      EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1246
6.47k
    assert(EndLabel && "Forgot label after instruction ending a range!");
1247
6.47k
1248
6.47k
    if (EI->isDbgValue())
1249
6.47k
      LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1250
6.47k
1251
6.47k
    // If this history map entry has a debug value, add that to the list of
1252
6.47k
    // open ranges and check if its location is valid for a single value
1253
6.47k
    // location.
1254
6.47k
    if (EI->isDbgValue()) {
1255
5.44k
      // Do not add undef debug values, as they are redundant information in
1256
5.44k
      // the location list entries. An undef debug results in an empty location
1257
5.44k
      // description. If there are any non-undef fragments then padding pieces
1258
5.44k
      // with empty location descriptions will automatically be inserted, and if
1259
5.44k
      // all fragments are undef then the whole location list entry is
1260
5.44k
      // redundant.
1261
5.44k
      if (!Instr->isUndefDebugValue()) {
1262
5.38k
        auto Value = getDebugLocValue(Instr);
1263
5.38k
        OpenRanges.emplace_back(EI->getEndIndex(), Value);
1264
5.38k
1265
5.38k
        // TODO: Add support for single value fragment locations.
1266
5.38k
        if (Instr->getDebugExpression()->isFragment())
1267
4.09k
          isSafeForSingleLocation = false;
1268
5.38k
1269
5.38k
        if (!StartDebugMI)
1270
459
          StartDebugMI = Instr;
1271
5.38k
      } else {
1272
62
        isSafeForSingleLocation = false;
1273
62
      }
1274
5.44k
    }
1275
6.47k
1276
6.47k
    // Location list entries with empty location descriptions are redundant
1277
6.47k
    // information in DWARF, so do not emit those.
1278
6.47k
    if (OpenRanges.empty())
1279
1.07k
      continue;
1280
5.39k
1281
5.39k
    // Omit entries with empty ranges as they do not have any effect in DWARF.
1282
5.39k
    if (StartLabel == EndLabel) {
1283
4.07k
      LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1284
4.07k
      continue;
1285
4.07k
    }
1286
1.31k
1287
1.31k
    SmallVector<DbgValueLoc, 4> Values;
1288
1.31k
    for (auto &R : OpenRanges)
1289
5.37k
      Values.push_back(R.second);
1290
1.31k
    DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1291
1.31k
1292
1.31k
    // Attempt to coalesce the ranges of two otherwise identical
1293
1.31k
    // DebugLocEntries.
1294
1.31k
    auto CurEntry = DebugLoc.rbegin();
1295
1.31k
    LLVM_DEBUG({
1296
1.31k
      dbgs() << CurEntry->getValues().size() << " Values:\n";
1297
1.31k
      for (auto &Value : CurEntry->getValues())
1298
1.31k
        Value.dump();
1299
1.31k
      dbgs() << "-----\n";
1300
1.31k
    });
1301
1.31k
1302
1.31k
    auto PrevEntry = std::next(CurEntry);
1303
1.31k
    if (PrevEntry != DebugLoc.rend() && 
PrevEntry->MergeRanges(*CurEntry)864
)
1304
625
      DebugLoc.pop_back();
1305
1.31k
  }
1306
503
1307
503
  return DebugLoc.size() == 1 && 
isSafeForSingleLocation287
&&
1308
503
         
validThroughout(LScopes, StartDebugMI, EndMI)256
;
1309
503
}
1310
1311
DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1312
                                            LexicalScope &Scope,
1313
                                            const DINode *Node,
1314
                                            const DILocation *Location,
1315
693
                                            const MCSymbol *Sym) {
1316
693
  ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1317
693
  if (isa<const DILocalVariable>(Node)) {
1318
686
    ConcreteEntities.push_back(
1319
686
        llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1320
686
                                       Location));
1321
686
    InfoHolder.addScopeVariable(&Scope,
1322
686
        cast<DbgVariable>(ConcreteEntities.back().get()));
1323
686
  } else 
if (7
isa<const DILabel>(Node)7
) {
1324
7
    ConcreteEntities.push_back(
1325
7
        llvm::make_unique<DbgLabel>(cast<const DILabel>(Node),
1326
7
                                    Location, Sym));
1327
7
    InfoHolder.addScopeLabel(&Scope,
1328
7
        cast<DbgLabel>(ConcreteEntities.back().get()));
1329
7
  }
1330
693
  return ConcreteEntities.back().get();
1331
693
}
1332
1333
// Find variables for each lexical scope.
1334
void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1335
                                   const DISubprogram *SP,
1336
35.3k
                                   DenseSet<InlinedEntity> &Processed) {
1337
35.3k
  // Grab the variable info that was squirreled away in the MMI side-table.
1338
35.3k
  collectVariableInfoFromMFTable(TheCU, Processed);
1339
35.3k
1340
35.3k
  for (const auto &I : DbgValues) {
1341
625
    InlinedEntity IV = I.first;
1342
625
    if (Processed.count(IV))
1343
8
      continue;
1344
617
1345
617
    // Instruction ranges, specifying where IV is accessible.
1346
617
    const auto &HistoryMapEntries = I.second;
1347
617
    if (HistoryMapEntries.empty())
1348
0
      continue;
1349
617
1350
617
    LexicalScope *Scope = nullptr;
1351
617
    const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1352
617
    if (const DILocation *IA = IV.second)
1353
74
      Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1354
543
    else
1355
543
      Scope = LScopes.findLexicalScope(LocalVar->getScope());
1356
617
    // If variable scope is not found then skip this variable.
1357
617
    if (!Scope)
1358
6
      continue;
1359
611
1360
611
    Processed.insert(IV);
1361
611
    DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1362
611
                                            *Scope, LocalVar, IV.second));
1363
611
1364
611
    const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1365
611
    assert(MInsn->isDebugValue() && "History must begin with debug value");
1366
611
1367
611
    // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1368
611
    // If the history map contains a single debug value, there may be an
1369
611
    // additional entry which clobbers the debug value.
1370
611
    size_t HistSize = HistoryMapEntries.size();
1371
611
    bool SingleValueWithClobber =
1372
611
        HistSize == 2 && 
HistoryMapEntries[1].isClobber()214
;
1373
611
    if (HistSize == 1 || 
SingleValueWithClobber456
) {
1374
330
      const auto *End =
1375
330
          SingleValueWithClobber ? 
HistoryMapEntries[1].getInstr()175
:
nullptr155
;
1376
330
      if (validThroughout(LScopes, MInsn, End)) {
1377
99
        RegVar->initializeDbgValue(MInsn);
1378
99
        continue;
1379
99
      }
1380
512
    }
1381
512
1382
512
    // Do not emit location lists if .debug_loc secton is disabled.
1383
512
    if (!useLocSection())
1384
9
      continue;
1385
503
1386
503
    // Handle multiple DBG_VALUE instructions describing one variable.
1387
503
    DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1388
503
1389
503
    // Build the location list for this variable.
1390
503
    SmallVector<DebugLocEntry, 8> Entries;
1391
503
    bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
1392
503
1393
503
    // Check whether buildLocationList managed to merge all locations to one
1394
503
    // that is valid throughout the variable's scope. If so, produce single
1395
503
    // value location.
1396
503
    if (isValidSingleLocation) {
1397
27
      RegVar->initializeDbgValue(Entries[0].getValues()[0]);
1398
27
      continue;
1399
27
    }
1400
476
1401
476
    // If the variable has a DIBasicType, extract it.  Basic types cannot have
1402
476
    // unique identifiers, so don't bother resolving the type with the
1403
476
    // identifier map.
1404
476
    const DIBasicType *BT = dyn_cast<DIBasicType>(
1405
476
        static_cast<const Metadata *>(LocalVar->getType()));
1406
476
1407
476
    // Finalize the entry by lowering it into a DWARF bytestream.
1408
476
    for (auto &Entry : Entries)
1409
667
      Entry.finalize(*Asm, List, BT, TheCU);
1410
476
  }
1411
35.3k
1412
35.3k
  // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1413
35.3k
  // DWARF-related DbgLabel.
1414
35.3k
  for (const auto &I : DbgLabels) {
1415
6
    InlinedEntity IL = I.first;
1416
6
    const MachineInstr *MI = I.second;
1417
6
    if (MI == nullptr)
1418
0
      continue;
1419
6
1420
6
    LexicalScope *Scope = nullptr;
1421
6
    const DILabel *Label = cast<DILabel>(IL.first);
1422
6
    // Get inlined DILocation if it is inlined label.
1423
6
    if (const DILocation *IA = IL.second)
1424
1
      Scope = LScopes.findInlinedScope(Label->getScope(), IA);
1425
5
    else
1426
5
      Scope = LScopes.findLexicalScope(Label->getScope());
1427
6
    // If label scope is not found then skip this label.
1428
6
    if (!Scope)
1429
0
      continue;
1430
6
1431
6
    Processed.insert(IL);
1432
6
    /// At this point, the temporary label is created.
1433
6
    /// Save the temporary label to DbgLabel entity to get the
1434
6
    /// actually address when generating Dwarf DIE.
1435
6
    MCSymbol *Sym = getLabelBeforeInsn(MI);
1436
6
    createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1437
6
  }
1438
35.3k
1439
35.3k
  // Collect info for variables/labels that were optimized out.
1440
35.3k
  for (const DINode *DN : SP->getRetainedNodes()) {
1441
550
    if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1442
443
      continue;
1443
107
    LexicalScope *Scope = nullptr;
1444
107
    if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1445
106
      Scope = LScopes.findLexicalScope(DV->getScope());
1446
106
    } else 
if (auto *1
DL1
= dyn_cast<DILabel>(DN)) {
1447
1
      Scope = LScopes.findLexicalScope(DL->getScope());
1448
1
    }
1449
107
1450
107
    if (Scope)
1451
76
      createConcreteEntity(TheCU, *Scope, DN, nullptr);
1452
107
  }
1453
35.3k
}
1454
1455
// Process beginning of an instruction.
1456
2.60M
void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1457
2.60M
  DebugHandlerBase::beginInstruction(MI);
1458
2.60M
  assert(CurMI);
1459
2.60M
1460
2.60M
  const auto *SP = MI->getMF()->getFunction().getSubprogram();
1461
2.60M
  if (!SP || 
SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug2.58M
)
1462
18.0k
    return;
1463
2.58M
1464
2.58M
  // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1465
2.58M
  // If the instruction is part of the function frame setup code, do not emit
1466
2.58M
  // any line record, as there is no correspondence with any user code.
1467
2.58M
  if (MI->isMetaInstruction() || 
MI->getFlag(MachineInstr::FrameSetup)2.39M
)
1468
335k
    return;
1469
2.24M
  const DebugLoc &DL = MI->getDebugLoc();
1470
2.24M
  // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1471
2.24M
  // the last line number actually emitted, to see if it was line 0.
1472
2.24M
  unsigned LastAsmLine =
1473
2.24M
      Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1474
2.24M
1475
2.24M
  // Request a label after the call in order to emit AT_return_pc information
1476
2.24M
  // in call site entries. TODO: Add support for targets with delay slots.
1477
2.24M
  if (SP->areAllCallsDescribed() && 
MI->isCall()55
&&
!MI->hasDelaySlot()13
)
1478
13
    requestLabelAfterInsn(MI);
1479
2.24M
1480
2.24M
  if (DL == PrevInstLoc) {
1481
1.10M
    // If we have an ongoing unspecified location, nothing to do here.
1482
1.10M
    if (!DL)
1483
44.7k
      return;
1484
1.05M
    // We have an explicit location, same as the previous location.
1485
1.05M
    // But we might be coming back to it after a line 0 record.
1486
1.05M
    if (LastAsmLine == 0 && 
DL.getLine() != 015.5k
) {
1487
15.5k
      // Reinstate the source location but not marked as a statement.
1488
15.5k
      const MDNode *Scope = DL.getScope();
1489
15.5k
      recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1490
15.5k
    }
1491
1.05M
    return;
1492
1.05M
  }
1493
1.14M
1494
1.14M
  if (!DL) {
1495
235k
    // We have an unspecified location, which might want to be line 0.
1496
235k
    // If we have already emitted a line-0 record, don't repeat it.
1497
235k
    if (LastAsmLine == 0)
1498
47.6k
      return;
1499
188k
    // If user said Don't Do That, don't do that.
1500
188k
    if (UnknownLocations == Disable)
1501
2
      return;
1502
188k
    // See if we have a reason to emit a line-0 record now.
1503
188k
    // Reasons to emit a line-0 record include:
1504
188k
    // - User asked for it (UnknownLocations).
1505
188k
    // - Instruction has a label, so it's referenced from somewhere else,
1506
188k
    //   possibly debug information; we want it to have a source location.
1507
188k
    // - Instruction is at the top of a block; we don't want to inherit the
1508
188k
    //   location from the physically previous (maybe unrelated) block.
1509
188k
    if (UnknownLocations == Enable || 
PrevLabel188k
||
1510
188k
        
(178k
PrevInstBB178k
&&
PrevInstBB != MI->getParent()178k
)) {
1511
49.5k
      // Preserve the file and column numbers, if we can, to save space in
1512
49.5k
      // the encoded line table.
1513
49.5k
      // Do not update PrevInstLoc, it remembers the last non-0 line.
1514
49.5k
      const MDNode *Scope = nullptr;
1515
49.5k
      unsigned Column = 0;
1516
49.5k
      if (PrevInstLoc) {
1517
49.5k
        Scope = PrevInstLoc.getScope();
1518
49.5k
        Column = PrevInstLoc.getCol();
1519
49.5k
      }
1520
49.5k
      recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1521
49.5k
    }
1522
188k
    return;
1523
188k
  }
1524
909k
1525
909k
  // We have an explicit location, different from the previous location.
1526
909k
  // Don't repeat a line-0 record, but otherwise emit the new location.
1527
909k
  // (The new location might be an explicit line 0, which we do emit.)
1528
909k
  if (DL.getLine() == 0 && 
LastAsmLine == 075.3k
)
1529
42.1k
    return;
1530
867k
  unsigned Flags = 0;
1531
867k
  if (DL == PrologEndLoc) {
1532
35.1k
    Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1533
35.1k
    PrologEndLoc = DebugLoc();
1534
35.1k
  }
1535
867k
  // If the line changed, we call that a new statement; unless we went to
1536
867k
  // line 0 and came back, in which case it is not a new statement.
1537
867k
  unsigned OldLine = PrevInstLoc ? 
PrevInstLoc.getLine()831k
:
LastAsmLine35.7k
;
1538
867k
  if (DL.getLine() && 
DL.getLine() != OldLine833k
)
1539
624k
    Flags |= DWARF2_FLAG_IS_STMT;
1540
867k
1541
867k
  const MDNode *Scope = DL.getScope();
1542
867k
  recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1543
867k
1544
867k
  // If we're not at line 0, remember this location.
1545
867k
  if (DL.getLine())
1546
833k
    PrevInstLoc = DL;
1547
867k
}
1548
1549
35.3k
static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1550
35.3k
  // First known non-DBG_VALUE and non-frame setup location marks
1551
35.3k
  // the beginning of the function body.
1552
35.3k
  for (const auto &MBB : *MF)
1553
35.9k
    for (const auto &MI : MBB)
1554
407k
      if (!MI.isMetaInstruction() && 
!MI.getFlag(MachineInstr::FrameSetup)220k
&&
1555
407k
          
MI.getDebugLoc()79.8k
)
1556
35.3k
        return MI.getDebugLoc();
1557
35.3k
  
return DebugLoc()64
;
1558
35.3k
}
1559
1560
/// Register a source line with debug info. Returns the  unique label that was
1561
/// emitted and which provides correspondence to the source line list.
1562
static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
1563
                             const MDNode *S, unsigned Flags, unsigned CUID,
1564
                             uint16_t DwarfVersion,
1565
967k
                             ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
1566
967k
  StringRef Fn;
1567
967k
  unsigned FileNo = 1;
1568
967k
  unsigned Discriminator = 0;
1569
967k
  if (auto *Scope = cast_or_null<DIScope>(S)) {
1570
967k
    Fn = Scope->getFilename();
1571
967k
    if (Line != 0 && 
DwarfVersion >= 4884k
)
1572
3.09k
      if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1573
45
        Discriminator = LBF->getDiscriminator();
1574
967k
1575
967k
    FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
1576
967k
                 .getOrCreateSourceID(Scope->getFile());
1577
967k
  }
1578
967k
  Asm.OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
1579
967k
                                         Discriminator, Fn);
1580
967k
}
1581
1582
DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
1583
35.3k
                                             unsigned CUID) {
1584
35.3k
  // Get beginning of function.
1585
35.3k
  if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) {
1586
35.3k
    // Ensure the compile unit is created if the function is called before
1587
35.3k
    // beginFunction().
1588
35.3k
    (void)getOrCreateDwarfCompileUnit(
1589
35.3k
        MF.getFunction().getSubprogram()->getUnit());
1590
35.3k
    // We'd like to list the prologue as "not statements" but GDB behaves
1591
35.3k
    // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1592
35.3k
    const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1593
35.3k
    ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
1594
35.3k
                       CUID, getDwarfVersion(), getUnits());
1595
35.3k
    return PrologEndLoc;
1596
35.3k
  }
1597
64
  return DebugLoc();
1598
64
}
1599
1600
// Gather pre-function debug information.  Assumes being called immediately
1601
// after the function entry point has been emitted.
1602
35.3k
void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
1603
35.3k
  CurFn = MF;
1604
35.3k
1605
35.3k
  auto *SP = MF->getFunction().getSubprogram();
1606
35.3k
  assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
1607
35.3k
  if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1608
0
    return;
1609
35.3k
1610
35.3k
  DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1611
35.3k
1612
35.3k
  // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1613
35.3k
  // belongs to so that we add to the correct per-cu line table in the
1614
35.3k
  // non-asm case.
1615
35.3k
  if (Asm->OutStreamer->hasRawTextSupport())
1616
474
    // Use a single line table if we are generating assembly.
1617
474
    Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1618
34.8k
  else
1619
34.8k
    Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1620
35.3k
1621
35.3k
  // Record beginning of function.
1622
35.3k
  PrologEndLoc = emitInitialLocDirective(
1623
35.3k
      *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
1624
35.3k
}
1625
1626
462k
void DwarfDebug::skippedNonDebugFunction() {
1627
462k
  // If we don't have a subprogram for this function then there will be a hole
1628
462k
  // in the range information. Keep note of this by setting the previously used
1629
462k
  // section to nullptr.
1630
462k
  PrevCU = nullptr;
1631
462k
  CurFn = nullptr;
1632
462k
}
1633
1634
// Gather and emit post-function debug information.
1635
35.3k
void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
1636
35.3k
  const DISubprogram *SP = MF->getFunction().getSubprogram();
1637
35.3k
1638
35.3k
  assert(CurFn == MF &&
1639
35.3k
      "endFunction should be called with the same function as beginFunction");
1640
35.3k
1641
35.3k
  // Set DwarfDwarfCompileUnitID in MCContext to default value.
1642
35.3k
  Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1643
35.3k
1644
35.3k
  LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1645
35.3k
  assert(!FnScope || SP == FnScope->getScopeNode());
1646
35.3k
  DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1647
35.3k
  if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
1648
7
    PrevLabel = nullptr;
1649
7
    CurFn = nullptr;
1650
7
    return;
1651
7
  }
1652
35.3k
1653
35.3k
  DenseSet<InlinedEntity> Processed;
1654
35.3k
  collectEntityInfo(TheCU, SP, Processed);
1655
35.3k
1656
35.3k
  // Add the range of this function to the list of ranges for the CU.
1657
35.3k
  TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1658
35.3k
1659
35.3k
  // Under -gmlt, skip building the subprogram if there are no inlined
1660
35.3k
  // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1661
35.3k
  // is still needed as we need its source location.
1662
35.3k
  if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1663
35.3k
      
TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly35.3k
&&
1664
35.3k
      
LScopes.getAbstractScopesList().empty()34.2k
&&
!IsDarwin13.0k
) {
1665
15
    assert(InfoHolder.getScopeVariables().empty());
1666
15
    PrevLabel = nullptr;
1667
15
    CurFn = nullptr;
1668
15
    return;
1669
15
  }
1670
35.3k
1671
#ifndef NDEBUG
1672
  size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1673
#endif
1674
  // Construct abstract scopes.
1675
165k
  
for (LexicalScope *AScope : LScopes.getAbstractScopesList())35.3k
{
1676
165k
    auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1677
165k
    for (const DINode *DN : SP->getRetainedNodes()) {
1678
92
      if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1679
2
        continue;
1680
90
1681
90
      const MDNode *Scope = nullptr;
1682
90
      if (auto *DV = dyn_cast<DILocalVariable>(DN))
1683
89
        Scope = DV->getScope();
1684
1
      else if (auto *DL = dyn_cast<DILabel>(DN))
1685
1
        Scope = DL->getScope();
1686
1
      else
1687
1
        
llvm_unreachable0
("Unexpected DI type!");
1688
90
1689
90
      // Collect info for variables/labels that were optimized out.
1690
90
      ensureAbstractEntityIsCreated(TheCU, DN, Scope);
1691
90
      assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1692
90
             && "ensureAbstractEntityIsCreated inserted abstract scopes");
1693
90
    }
1694
165k
    constructAbstractSubprogramScopeDIE(TheCU, AScope);
1695
165k
  }
1696
35.3k
1697
35.3k
  ProcessedSPNodes.insert(SP);
1698
35.3k
  DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
1699
35.3k
  if (auto *SkelCU = TheCU.getSkeleton())
1700
55
    if (!LScopes.getAbstractScopesList().empty() &&
1701
55
        
TheCU.getCUNode()->getSplitDebugInlining()7
)
1702
5
      SkelCU->constructSubprogramScopeDIE(SP, FnScope);
1703
35.3k
1704
35.3k
  // Construct call site entries.
1705
35.3k
  constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
1706
35.3k
1707
35.3k
  // Clear debug info
1708
35.3k
  // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1709
35.3k
  // DbgVariables except those that are also in AbstractVariables (since they
1710
35.3k
  // can be used cross-function)
1711
35.3k
  InfoHolder.getScopeVariables().clear();
1712
35.3k
  InfoHolder.getScopeLabels().clear();
1713
35.3k
  PrevLabel = nullptr;
1714
35.3k
  CurFn = nullptr;
1715
35.3k
}
1716
1717
// Register a source line with debug info. Returns the  unique label that was
1718
// emitted and which provides correspondence to the source line list.
1719
void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1720
932k
                                  unsigned Flags) {
1721
932k
  ::recordSourceLine(*Asm, Line, Col, S, Flags,
1722
932k
                     Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
1723
932k
                     getDwarfVersion(), getUnits());
1724
932k
}
1725
1726
//===----------------------------------------------------------------------===//
1727
// Emit Methods
1728
//===----------------------------------------------------------------------===//
1729
1730
// Emit the debug info section.
1731
3.21k
void DwarfDebug::emitDebugInfo() {
1732
3.21k
  DwarfFile &Holder = useSplitDwarf() ? 
SkeletonHolder49
:
InfoHolder3.16k
;
1733
3.21k
  Holder.emitUnits(/* UseOffsets */ false);
1734
3.21k
}
1735
1736
// Emit the abbreviation section.
1737
3.21k
void DwarfDebug::emitAbbreviations() {
1738
3.21k
  DwarfFile &Holder = useSplitDwarf() ? 
SkeletonHolder49
:
InfoHolder3.16k
;
1739
3.21k
1740
3.21k
  Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1741
3.21k
}
1742
1743
55
void DwarfDebug::emitStringOffsetsTableHeader() {
1744
55
  DwarfFile &Holder = useSplitDwarf() ? 
SkeletonHolder7
:
InfoHolder48
;
1745
55
  Holder.getStringPool().emitStringOffsetsTableHeader(
1746
55
      *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
1747
55
      Holder.getStringOffsetsStartSym());
1748
55
}
1749
1750
template <typename AccelTableT>
1751
void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
1752
10.2k
                           StringRef TableName) {
1753
10.2k
  Asm->OutStreamer->SwitchSection(Section);
1754
10.2k
1755
10.2k
  // Emit the full data.
1756
10.2k
  emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
1757
10.2k
}
void llvm::DwarfDebug::emitAccel<llvm::AccelTable<llvm::AppleAccelTableOffsetData> >(llvm::AccelTable<llvm::AppleAccelTableOffsetData>&, llvm::MCSection*, llvm::StringRef)
Line
Count
Source
1752
7.67k
                           StringRef TableName) {
1753
7.67k
  Asm->OutStreamer->SwitchSection(Section);
1754
7.67k
1755
7.67k
  // Emit the full data.
1756
7.67k
  emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
1757
7.67k
}
void llvm::DwarfDebug::emitAccel<llvm::AccelTable<llvm::AppleAccelTableTypeData> >(llvm::AccelTable<llvm::AppleAccelTableTypeData>&, llvm::MCSection*, llvm::StringRef)
Line
Count
Source
1752
2.55k
                           StringRef TableName) {
1753
2.55k
  Asm->OutStreamer->SwitchSection(Section);
1754
2.55k
1755
2.55k
  // Emit the full data.
1756
2.55k
  emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
1757
2.55k
}
1758
1759
205
void DwarfDebug::emitAccelDebugNames() {
1760
205
  // Don't emit anything if we have no compilation units to index.
1761
205
  if (getUnits().empty())
1762
1
    return;
1763
204
1764
204
  emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
1765
204
}
1766
1767
// Emit visible names into a hashed accelerator table section.
1768
2.55k
void DwarfDebug::emitAccelNames() {
1769
2.55k
  emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1770
2.55k
            "Names");
1771
2.55k
}
1772
1773
// Emit objective C classes and categories into a hashed accelerator table
1774
// section.
1775
2.55k
void DwarfDebug::emitAccelObjC() {
1776
2.55k
  emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1777
2.55k
            "ObjC");
1778
2.55k
}
1779
1780
// Emit namespace dies into a hashed accelerator table.
1781
2.55k
void DwarfDebug::emitAccelNamespaces() {
1782
2.55k
  emitAccel(AccelNamespace,
1783
2.55k
            Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1784
2.55k
            "namespac");
1785
2.55k
}
1786
1787
// Emit type dies into a hashed accelerator table.
1788
2.55k
void DwarfDebug::emitAccelTypes() {
1789
2.55k
  emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1790
2.55k
            "types");
1791
2.55k
}
1792
1793
// Public name handling.
1794
// The format for the various pubnames:
1795
//
1796
// dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1797
// for the DIE that is named.
1798
//
1799
// gnu pubnames - offset/index value/name tuples where the offset is the offset
1800
// into the CU and the index value is computed according to the type of value
1801
// for the DIE that is named.
1802
//
1803
// For type units the offset is the offset of the skeleton DIE. For split dwarf
1804
// it's the offset within the debug_info/debug_types dwo section, however, the
1805
// reference in the pubname header doesn't change.
1806
1807
/// computeIndexValue - Compute the gdb index value for the DIE and CU.
1808
static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1809
69.0k
                                                        const DIE *Die) {
1810
69.0k
  // Entities that ended up only in a Type Unit reference the CU instead (since
1811
69.0k
  // the pub entry has offsets within the CU there's no real offset that can be
1812
69.0k
  // provided anyway). As it happens all such entities (namespaces and types,
1813
69.0k
  // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
1814
69.0k
  // not to be true it would be necessary to persist this information from the
1815
69.0k
  // point at which the entry is added to the index data structure - since by
1816
69.0k
  // the time the index is built from that, the original type/namespace DIE in a
1817
69.0k
  // type unit has already been destroyed so it can't be queried for properties
1818
69.0k
  // like tag, etc.
1819
69.0k
  if (Die->getTag() == dwarf::DW_TAG_compile_unit)
1820
2
    return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
1821
2
                                          dwarf::GIEL_EXTERNAL);
1822
69.0k
  dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1823
69.0k
1824
69.0k
  // We could have a specification DIE that has our most of our knowledge,
1825
69.0k
  // look for that now.
1826
69.0k
  if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1827
8
    DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1828
8
    if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1829
8
      Linkage = dwarf::GIEL_EXTERNAL;
1830
68.9k
  } else if (Die->findAttribute(dwarf::DW_AT_external))
1831
39
    Linkage = dwarf::GIEL_EXTERNAL;
1832
69.0k
1833
69.0k
  switch (Die->getTag()) {
1834
69.0k
  case dwarf::DW_TAG_class_type:
1835
17
  case dwarf::DW_TAG_structure_type:
1836
17
  case dwarf::DW_TAG_union_type:
1837
17
  case dwarf::DW_TAG_enumeration_type:
1838
17
    return dwarf::PubIndexEntryDescriptor(
1839
17
        dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1840
17
                              ? 
dwarf::GIEL_STATIC2
1841
17
                              : 
dwarf::GIEL_EXTERNAL15
);
1842
23
  case dwarf::DW_TAG_typedef:
1843
23
  case dwarf::DW_TAG_base_type:
1844
23
  case dwarf::DW_TAG_subrange_type:
1845
23
    return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1846
23
  case dwarf::DW_TAG_namespace:
1847
10
    return dwarf::GIEK_TYPE;
1848
68.9k
  case dwarf::DW_TAG_subprogram:
1849
68.9k
    return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1850
28
  case dwarf::DW_TAG_variable:
1851
28
    return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1852
23
  case dwarf::DW_TAG_enumerator:
1853
6
    return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1854
6
                                          dwarf::GIEL_STATIC);
1855
23
  default:
1856
0
    return dwarf::GIEK_NONE;
1857
69.0k
  }
1858
69.0k
}
1859
1860
/// emitDebugPubSections - Emit visible names and types into debug pubnames and
1861
/// pubtypes sections.
1862
3.21k
void DwarfDebug::emitDebugPubSections() {
1863
3.21k
  for (const auto &NU : CUMap) {
1864
2.67k
    DwarfCompileUnit *TheU = NU.second;
1865
2.67k
    if (!TheU->hasDwarfPubSections())
1866
928
      continue;
1867
1.74k
1868
1.74k
    bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
1869
1.74k
                    DICompileUnit::DebugNameTableKind::GNU;
1870
1.74k
1871
1.74k
    Asm->OutStreamer->SwitchSection(
1872
1.74k
        GnuStyle ? 
Asm->getObjFileLowering().getDwarfGnuPubNamesSection()1.40k
1873
1.74k
                 : 
Asm->getObjFileLowering().getDwarfPubNamesSection()343
);
1874
1.74k
    emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
1875
1.74k
1876
1.74k
    Asm->OutStreamer->SwitchSection(
1877
1.74k
        GnuStyle ? 
Asm->getObjFileLowering().getDwarfGnuPubTypesSection()1.40k
1878
1.74k
                 : 
Asm->getObjFileLowering().getDwarfPubTypesSection()343
);
1879
1.74k
    emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
1880
1.74k
  }
1881
3.21k
}
1882
1883
3.49k
void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
1884
3.49k
  if (useSectionsAsReferences())
1885
2
    Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(),
1886
2
                         CU.getDebugSectionOffset());
1887
3.49k
  else
1888
3.49k
    Asm->emitDwarfSymbolReference(CU.getLabelBegin());
1889
3.49k
}
1890
1891
void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
1892
                                     DwarfCompileUnit *TheU,
1893
3.48k
                                     const StringMap<const DIE *> &Globals) {
1894
3.48k
  if (auto *Skeleton = TheU->getSkeleton())
1895
66
    TheU = Skeleton;
1896
3.48k
1897
3.48k
  // Emit the header.
1898
3.48k
  Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1899
3.48k
  MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1900
3.48k
  MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1901
3.48k
  Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1902
3.48k
1903
3.48k
  Asm->OutStreamer->EmitLabel(BeginLabel);
1904
3.48k
1905
3.48k
  Asm->OutStreamer->AddComment("DWARF Version");
1906
3.48k
  Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
1907
3.48k
1908
3.48k
  Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1909
3.48k
  emitSectionReference(*TheU);
1910
3.48k
1911
3.48k
  Asm->OutStreamer->AddComment("Compilation Unit Length");
1912
3.48k
  Asm->emitInt32(TheU->getLength());
1913
3.48k
1914
3.48k
  // Emit the pubnames for this compilation unit.
1915
70.3k
  for (const auto &GI : Globals) {
1916
70.3k
    const char *Name = GI.getKeyData();
1917
70.3k
    const DIE *Entity = GI.second;
1918
70.3k
1919
70.3k
    Asm->OutStreamer->AddComment("DIE offset");
1920
70.3k
    Asm->emitInt32(Entity->getOffset());
1921
70.3k
1922
70.3k
    if (GnuStyle) {
1923
69.0k
      dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1924
69.0k
      Asm->OutStreamer->AddComment(
1925
69.0k
          Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
1926
69.0k
          ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1927
69.0k
      Asm->emitInt8(Desc.toBits());
1928
69.0k
    }
1929
70.3k
1930
70.3k
    Asm->OutStreamer->AddComment("External Name");
1931
70.3k
    Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1932
70.3k
  }
1933
3.48k
1934
3.48k
  Asm->OutStreamer->AddComment("End Mark");
1935
3.48k
  Asm->emitInt32(0);
1936
3.48k
  Asm->OutStreamer->EmitLabel(EndLabel);
1937
3.48k
}
1938
1939
/// Emit null-terminated strings into a debug str section.
1940
3.21k
void DwarfDebug::emitDebugStr() {
1941
3.21k
  MCSection *StringOffsetsSection = nullptr;
1942
3.21k
  if (useSegmentedStringOffsetsTable()) {
1943
55
    emitStringOffsetsTableHeader();
1944
55
    StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
1945
55
  }
1946
3.21k
  DwarfFile &Holder = useSplitDwarf() ? 
SkeletonHolder49
:
InfoHolder3.16k
;
1947
3.21k
  Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
1948
3.21k
                     StringOffsetsSection, /* UseRelativeOffsets = */ true);
1949
3.21k
}
1950
1951
void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1952
                                   const DebugLocStream::Entry &Entry,
1953
646
                                   const DwarfCompileUnit *CU) {
1954
646
  auto &&Comments = DebugLocs.getComments(Entry);
1955
646
  auto Comment = Comments.begin();
1956
646
  auto End = Comments.end();
1957
646
1958
646
  // The expressions are inserted into a byte stream rather early (see
1959
646
  // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
1960
646
  // need to reference a base_type DIE the offset of that DIE is not yet known.
1961
646
  // To deal with this we instead insert a placeholder early and then extract
1962
646
  // it here and replace it with the real reference.
1963
646
  unsigned PtrSize = Asm->MAI->getCodePointerSize();
1964
646
  DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
1965
646
                                    DebugLocs.getBytes(Entry).size()),
1966
646
                          Asm->getDataLayout().isLittleEndian(), PtrSize);
1967
646
  DWARFExpression Expr(Data, getDwarfVersion(), PtrSize);
1968
646
1969
646
  using Encoding = DWARFExpression::Operation::Encoding;
1970
646
  uint32_t Offset = 0;
1971
1.05k
  for (auto &Op : Expr) {
1972
1.05k
    assert(Op.getCode() != dwarf::DW_OP_const_type &&
1973
1.05k
           "3 operand ops not yet supported");
1974
1.05k
    Streamer.EmitInt8(Op.getCode(), Comment != End ? 
*(Comment++)584
:
""466
);
1975
1.05k
    Offset++;
1976
3.15k
    for (unsigned I = 0; I < 2; 
++I2.10k
) {
1977
2.10k
      if (Op.getDescription().Op[I] == Encoding::SizeNA)
1978
1.70k
        continue;
1979
397
      if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
1980
0
          if (CU) {
1981
0
            uint64_t Offset = CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset();
1982
0
            assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit");
1983
0
            Asm->EmitULEB128(Offset, nullptr, ULEB128PadSize);
1984
0
          } else {
1985
0
            // Emit a reference to the 'generic type'.
1986
0
            Asm->EmitULEB128(0, nullptr, ULEB128PadSize);
1987
0
          }
1988
0
          // Make sure comments stay aligned.
1989
0
          for (unsigned J = 0; J < ULEB128PadSize; ++J)
1990
0
            if (Comment != End)
1991
0
              Comment++;
1992
397
      } else {
1993
900
        for (uint32_t J = Offset; J < Op.getOperandEndOffset(I); 
++J503
)
1994
503
          Streamer.EmitInt8(Data.getData()[J], Comment != End ? 
*(Comment++)251
:
""252
);
1995
397
      }
1996
397
      Offset = Op.getOperandEndOffset(I);
1997
397
    }
1998
1.05k
    assert(Offset == Op.getEndOffset());
1999
1.05k
  }
2000
646
}
2001
2002
void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
2003
                                   const DbgValueLoc &Value,
2004
4.71k
                                   DwarfExpression &DwarfExpr) {
2005
4.71k
  auto *DIExpr = Value.getExpression();
2006
4.71k
  DIExpressionCursor ExprCursor(DIExpr);
2007
4.71k
  DwarfExpr.addFragmentOffset(DIExpr);
2008
4.71k
  // Regular entry.
2009
4.71k
  if (Value.isInt()) {
2010
4.06k
    if (BT && 
(40
BT->getEncoding() == dwarf::DW_ATE_signed40
||
2011
40
               
BT->getEncoding() == dwarf::DW_ATE_signed_char5
))
2012
35
      DwarfExpr.addSignedConstant(Value.getInt());
2013
4.03k
    else
2014
4.03k
      DwarfExpr.addUnsignedConstant(Value.getInt());
2015
4.06k
  } else 
if (645
Value.isLocation()645
) {
2016
639
    MachineLocation Location = Value.getLoc();
2017
639
    if (Location.isIndirect())
2018
106
      DwarfExpr.setMemoryLocationKind();
2019
639
    DIExpressionCursor Cursor(DIExpr);
2020
639
2021
639
    if (DIExpr->isEntryValue()) {
2022
0
      DwarfExpr.setEntryValueFlag();
2023
0
      DwarfExpr.addEntryValueExpression(Cursor);
2024
0
    }
2025
639
2026
639
    const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
2027
639
    if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2028
28
      return;
2029
611
    return DwarfExpr.addExpression(std::move(Cursor));
2030
611
  } else 
if (6
Value.isConstantFP()6
) {
2031
6
    APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
2032
6
    DwarfExpr.addUnsignedConstant(RawBytes);
2033
6
  }
2034
4.71k
  DwarfExpr.addExpression(std::move(ExprCursor));
2035
4.07k
}
2036
2037
void DebugLocEntry::finalize(const AsmPrinter &AP,
2038
                             DebugLocStream::ListBuilder &List,
2039
                             const DIBasicType *BT,
2040
667
                             DwarfCompileUnit &TheCU) {
2041
667
  assert(!Values.empty() &&
2042
667
         "location list entries without values are redundant");
2043
667
  assert(Begin != End && "unexpected location list entry with empty range");
2044
667
  DebugLocStream::EntryBuilder Entry(List, Begin, End);
2045
667
  BufferByteStreamer Streamer = Entry.getStreamer();
2046
667
  DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
2047
667
  const DbgValueLoc &Value = Values[0];
2048
667
  if (Value.isFragment()) {
2049
50
    // Emit all fragments that belong to the same variable and range.
2050
50
    assert(llvm::all_of(Values, [](DbgValueLoc P) {
2051
50
          return P.isFragment();
2052
50
        }) && "all values are expected to be fragments");
2053
50
    assert(std::is_sorted(Values.begin(), Values.end()) &&
2054
50
           "fragments are expected to be sorted");
2055
50
2056
50
    for (auto Fragment : Values)
2057
4.09k
      DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
2058
50
2059
617
  } else {
2060
617
    assert(Values.size() == 1 && "only fragments may have >1 value");
2061
617
    DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
2062
617
  }
2063
667
  DwarfExpr.finalize();
2064
667
}
2065
2066
void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
2067
643
                                           const DwarfCompileUnit *CU) {
2068
643
  // Emit the size.
2069
643
  Asm->OutStreamer->AddComment("Loc expr size");
2070
643
  if (getDwarfVersion() >= 5)
2071
28
    Asm->EmitULEB128(DebugLocs.getBytes(Entry).size());
2072
615
  else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2073
614
    Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2074
1
  else {
2075
1
    // The entry is too big to fit into 16 bit, drop it as there is nothing we
2076
1
    // can do.
2077
1
    Asm->emitInt16(0);
2078
1
    return;
2079
1
  }
2080
642
  // Emit the entry.
2081
642
  APByteStreamer Streamer(*Asm);
2082
642
  emitDebugLocEntry(Streamer, Entry, CU);
2083
642
}
2084
2085
// Emit the common part of the DWARF 5 range/locations list tables header.
2086
static void emitListsTableHeaderStart(AsmPrinter *Asm, const DwarfFile &Holder,
2087
                                      MCSymbol *TableStart,
2088
13
                                      MCSymbol *TableEnd) {
2089
13
  // Build the table header, which starts with the length field.
2090
13
  Asm->OutStreamer->AddComment("Length");
2091
13
  Asm->EmitLabelDifference(TableEnd, TableStart, 4);
2092
13
  Asm->OutStreamer->EmitLabel(TableStart);
2093
13
  // Version number (DWARF v5 and later).
2094
13
  Asm->OutStreamer->AddComment("Version");
2095
13
  Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion());
2096
13
  // Address size.
2097
13
  Asm->OutStreamer->AddComment("Address size");
2098
13
  Asm->emitInt8(Asm->MAI->getCodePointerSize());
2099
13
  // Segment selector size.
2100
13
  Asm->OutStreamer->AddComment("Segment selector size");
2101
13
  Asm->emitInt8(0);
2102
13
}
2103
2104
// Emit the header of a DWARF 5 range list table list table. Returns the symbol
2105
// that designates the end of the table for the caller to emit when the table is
2106
// complete.
2107
static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
2108
7
                                         const DwarfFile &Holder) {
2109
7
  MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start");
2110
7
  MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end");
2111
7
  emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd);
2112
7
2113
7
  Asm->OutStreamer->AddComment("Offset entry count");
2114
7
  Asm->emitInt32(Holder.getRangeLists().size());
2115
7
  Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym());
2116
7
2117
7
  for (const RangeSpanList &List : Holder.getRangeLists())
2118
9
    Asm->EmitLabelDifference(List.getSym(), Holder.getRnglistsTableBaseSym(),
2119
9
                             4);
2120
7
2121
7
  return TableEnd;
2122
7
}
2123
2124
// Emit the header of a DWARF 5 locations list table. Returns the symbol that
2125
// designates the end of the table for the caller to emit when the table is
2126
// complete.
2127
static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
2128
6
                                         const DwarfFile &Holder) {
2129
6
  MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start");
2130
6
  MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end");
2131
6
  emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd);
2132
6
2133
6
  // FIXME: Generate the offsets table and use DW_FORM_loclistx with the
2134
6
  // DW_AT_loclists_base attribute. Until then set the number of offsets to 0.
2135
6
  Asm->OutStreamer->AddComment("Offset entry count");
2136
6
  Asm->emitInt32(0);
2137
6
  Asm->OutStreamer->EmitLabel(Holder.getLoclistsTableBaseSym());
2138
6
2139
6
  return TableEnd;
2140
6
}
2141
2142
// Emit locations into the .debug_loc/.debug_rnglists section.
2143
3.16k
void DwarfDebug::emitDebugLoc() {
2144
3.16k
  if (DebugLocs.getLists().empty())
2145
2.97k
    return;
2146
189
2147
189
  bool IsLocLists = getDwarfVersion() >= 5;
2148
189
  MCSymbol *TableEnd = nullptr;
2149
189
  if (IsLocLists) {
2150
6
    Asm->OutStreamer->SwitchSection(
2151
6
        Asm->getObjFileLowering().getDwarfLoclistsSection());
2152
6
    TableEnd = emitLoclistsTableHeader(Asm, useSplitDwarf() ? 
SkeletonHolder0
2153
6
                                                            : InfoHolder);
2154
183
  } else {
2155
183
    Asm->OutStreamer->SwitchSection(
2156
183
        Asm->getObjFileLowering().getDwarfLocSection());
2157
183
  }
2158
189
2159
189
  unsigned char Size = Asm->MAI->getCodePointerSize();
2160
410
  for (const auto &List : DebugLocs.getLists()) {
2161
410
    Asm->OutStreamer->EmitLabel(List.Label);
2162
410
2163
410
    const DwarfCompileUnit *CU = List.CU;
2164
410
    const MCSymbol *Base = CU->getBaseAddress();
2165
628
    for (const auto &Entry : DebugLocs.getEntries(List)) {
2166
628
      if (Base) {
2167
624
        // Set up the range. This range is relative to the entry point of the
2168
624
        // compile unit. This is a hard coded 0 for low_pc when we're emitting
2169
624
        // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2170
624
        if (IsLocLists) {
2171
28
          Asm->OutStreamer->AddComment("DW_LLE_offset_pair");
2172
28
          Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_offset_pair, 1);
2173
28
          Asm->OutStreamer->AddComment("  starting offset");
2174
28
          Asm->EmitLabelDifferenceAsULEB128(Entry.BeginSym, Base);
2175
28
          Asm->OutStreamer->AddComment("  ending offset");
2176
28
          Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Base);
2177
596
        } else {
2178
596
          Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
2179
596
          Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
2180
596
        }
2181
624
2182
624
        emitDebugLocEntryLocation(Entry, CU);
2183
624
        continue;
2184
624
      }
2185
4
2186
4
      // We have no base address.
2187
4
      if (IsLocLists) {
2188
0
        // TODO: Use DW_LLE_base_addressx + DW_LLE_offset_pair, or
2189
0
        // DW_LLE_startx_length in case if there is only a single range.
2190
0
        // That should reduce the size of the debug data emited.
2191
0
        // For now just use the DW_LLE_startx_length for all cases.
2192
0
        Asm->OutStreamer->AddComment("DW_LLE_startx_length");
2193
0
        Asm->emitInt8(dwarf::DW_LLE_startx_length);
2194
0
        Asm->OutStreamer->AddComment("  start idx");
2195
0
        Asm->EmitULEB128(AddrPool.getIndex(Entry.BeginSym));
2196
0
        Asm->OutStreamer->AddComment("  length");
2197
0
        Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Entry.BeginSym);
2198
4
      } else {
2199
4
        Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
2200
4
        Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
2201
4
      }
2202
4
2203
4
      emitDebugLocEntryLocation(Entry, CU);
2204
4
    }
2205
410
2206
410
    if (IsLocLists) {
2207
16
      // .debug_loclists section ends with DW_LLE_end_of_list.
2208
16
      Asm->OutStreamer->AddComment("DW_LLE_end_of_list");
2209
16
      Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_end_of_list, 1);
2210
394
    } else {
2211
394
      // Terminate the .debug_loc list with two 0 values.
2212
394
      Asm->OutStreamer->EmitIntValue(0, Size);
2213
394
      Asm->OutStreamer->EmitIntValue(0, Size);
2214
394
    }
2215
410
  }
2216
189
2217
189
  if (TableEnd)
2218
6
    Asm->OutStreamer->EmitLabel(TableEnd);
2219
189
}
2220
2221
49
void DwarfDebug::emitDebugLocDWO() {
2222
49
  for (const auto &List : DebugLocs.getLists()) {
2223
9
    Asm->OutStreamer->SwitchSection(
2224
9
        Asm->getObjFileLowering().getDwarfLocDWOSection());
2225
9
    Asm->OutStreamer->EmitLabel(List.Label);
2226
15
    for (const auto &Entry : DebugLocs.getEntries(List)) {
2227
15
      // GDB only supports startx_length in pre-standard split-DWARF.
2228
15
      // (in v5 standard loclists, it currently* /only/ supports base_address +
2229
15
      // offset_pair, so the implementations can't really share much since they
2230
15
      // need to use different representations)
2231
15
      // * as of October 2018, at least
2232
15
      // Ideally/in v5, this could use SectionLabels to reuse existing addresses
2233
15
      // in the address pool to minimize object size/relocations.
2234
15
      Asm->emitInt8(dwarf::DW_LLE_startx_length);
2235
15
      unsigned idx = AddrPool.getIndex(Entry.BeginSym);
2236
15
      Asm->EmitULEB128(idx);
2237
15
      Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
2238
15
2239
15
      emitDebugLocEntryLocation(Entry, List.CU);
2240
15
    }
2241
9
    Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2242
9
  }
2243
49
}
2244
2245
struct ArangeSpan {
2246
  const MCSymbol *Start, *End;
2247
};
2248
2249
// Emit a debug aranges section, containing a CU lookup for any
2250
// address we can tie back to a CU.
2251
6
void DwarfDebug::emitDebugARanges() {
2252
6
  // Provides a unique id per text section.
2253
6
  MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
2254
6
2255
6
  // Filter labels by section.
2256
18
  for (const SymbolCU &SCU : ArangeLabels) {
2257
18
    if (SCU.Sym->isInSection()) {
2258
17
      // Make a note of this symbol and it's section.
2259
17
      MCSection *Section = &SCU.Sym->getSection();
2260
17
      if (!Section->getKind().isMetadata())
2261
17
        SectionMap[Section].push_back(SCU);
2262
17
    } else {
2263
1
      // Some symbols (e.g. common/bss on mach-o) can have no section but still
2264
1
      // appear in the output. This sucks as we rely on sections to build
2265
1
      // arange spans. We can do it without, but it's icky.
2266
1
      SectionMap[nullptr].push_back(SCU);
2267
1
    }
2268
18
  }
2269
6
2270
6
  DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
2271
6
2272
11
  for (auto &I : SectionMap) {
2273
11
    MCSection *Section = I.first;
2274
11
    SmallVector<SymbolCU, 8> &List = I.second;
2275
11
    if (List.size() < 1)
2276
0
      continue;
2277
11
2278
11
    // If we have no section (e.g. common), just write out
2279
11
    // individual spans for each symbol.
2280
11
    if (!Section) {
2281
1
      for (const SymbolCU &Cur : List) {
2282
1
        ArangeSpan Span;
2283
1
        Span.Start = Cur.Sym;
2284
1
        Span.End = nullptr;
2285
1
        assert(Cur.CU);
2286
1
        Spans[Cur.CU].push_back(Span);
2287
1
      }
2288
1
      continue;
2289
1
    }
2290
10
2291
10
    // Sort the symbols by offset within the section.
2292
10
    llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
2293
7
      unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 
00
;
2294
7
      unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 
00
;
2295
7
2296
7
      // Symbols with no order assigned should be placed at the end.
2297
7
      // (e.g. section end labels)
2298
7
      if (IA == 0)
2299
7
        return false;
2300
0
      if (IB == 0)
2301
0
        return true;
2302
0
      return IA < IB;
2303
0
    });
2304
10
2305
10
    // Insert a final terminator.
2306
10
    List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
2307
10
2308
10
    // Build spans between each label.
2309
10
    const MCSymbol *StartSym = List[0].Sym;
2310
27
    for (size_t n = 1, e = List.size(); n < e; 
n++17
) {
2311
17
      const SymbolCU &Prev = List[n - 1];
2312
17
      const SymbolCU &Cur = List[n];
2313
17
2314
17
      // Try and build the longest span we can within the same CU.
2315
17
      if (Cur.CU != Prev.CU) {
2316
11
        ArangeSpan Span;
2317
11
        Span.Start = StartSym;
2318
11
        Span.End = Cur.Sym;
2319
11
        assert(Prev.CU);
2320
11
        Spans[Prev.CU].push_back(Span);
2321
11
        StartSym = Cur.Sym;
2322
11
      }
2323
17
    }
2324
10
  }
2325
6
2326
6
  // Start the dwarf aranges section.
2327
6
  Asm->OutStreamer->SwitchSection(
2328
6
      Asm->getObjFileLowering().getDwarfARangesSection());
2329
6
2330
6
  unsigned PtrSize = Asm->MAI->getCodePointerSize();
2331
6
2332
6
  // Build a list of CUs used.
2333
6
  std::vector<DwarfCompileUnit *> CUs;
2334
7
  for (const auto &it : Spans) {
2335
7
    DwarfCompileUnit *CU = it.first;
2336
7
    CUs.push_back(CU);
2337
7
  }
2338
6
2339
6
  // Sort the CU list (again, to ensure consistent output order).
2340
6
  llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
2341
1
    return A->getUniqueID() < B->getUniqueID();
2342
1
  });
2343
6
2344
6
  // Emit an arange table for each CU we used.
2345
7
  for (DwarfCompileUnit *CU : CUs) {
2346
7
    std::vector<ArangeSpan> &List = Spans[CU];
2347
7
2348
7
    // Describe the skeleton CU's offset and length, not the dwo file's.
2349
7
    if (auto *Skel = CU->getSkeleton())
2350
0
      CU = Skel;
2351
7
2352
7
    // Emit size of content not including length itself.
2353
7
    unsigned ContentSize =
2354
7
        sizeof(int16_t) + // DWARF ARange version number
2355
7
        sizeof(int32_t) + // Offset of CU in the .debug_info section
2356
7
        sizeof(int8_t) +  // Pointer Size (in bytes)
2357
7
        sizeof(int8_t);   // Segment Size (in bytes)
2358
7
2359
7
    unsigned TupleSize = PtrSize * 2;
2360
7
2361
7
    // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2362
7
    unsigned Padding =
2363
7
        OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2364
7
2365
7
    ContentSize += Padding;
2366
7
    ContentSize += (List.size() + 1) * TupleSize;
2367
7
2368
7
    // For each compile unit, write the list of spans it covers.
2369
7
    Asm->OutStreamer->AddComment("Length of ARange Set");
2370
7
    Asm->emitInt32(ContentSize);
2371
7
    Asm->OutStreamer->AddComment("DWARF Arange version number");
2372
7
    Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
2373
7
    Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
2374
7
    emitSectionReference(*CU);
2375
7
    Asm->OutStreamer->AddComment("Address Size (in bytes)");
2376
7
    Asm->emitInt8(PtrSize);
2377
7
    Asm->OutStreamer->AddComment("Segment Size (in bytes)");
2378
7
    Asm->emitInt8(0);
2379
7
2380
7
    Asm->OutStreamer->emitFill(Padding, 0xff);
2381
7
2382
12
    for (const ArangeSpan &Span : List) {
2383
12
      Asm->EmitLabelReference(Span.Start, PtrSize);
2384
12
2385
12
      // Calculate the size as being from the span start to it's end.
2386
12
      if (Span.End) {
2387
11
        Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2388
11
      } else {
2389
1
        // For symbols without an end marker (e.g. common), we
2390
1
        // write a single arange entry containing just that one symbol.
2391
1
        uint64_t Size = SymSize[Span.Start];
2392
1
        if (Size == 0)
2393
0
          Size = 1;
2394
1
2395
1
        Asm->OutStreamer->EmitIntValue(Size, PtrSize);
2396
1
      }
2397
12
    }
2398
7
2399
7
    Asm->OutStreamer->AddComment("ARange terminator");
2400
7
    Asm->OutStreamer->EmitIntValue(0, PtrSize);
2401
7
    Asm->OutStreamer->EmitIntValue(0, PtrSize);
2402
7
  }
2403
6
}
2404
2405
/// Emit a single range list. We handle both DWARF v5 and earlier.
2406
static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
2407
56.9k
                          const RangeSpanList &List) {
2408
56.9k
2409
56.9k
  auto DwarfVersion = DD.getDwarfVersion();
2410
56.9k
  // Emit our symbol so we can find the beginning of the range.
2411
56.9k
  Asm->OutStreamer->EmitLabel(List.getSym());
2412
56.9k
  // Gather all the ranges that apply to the same section so they can share
2413
56.9k
  // a base address entry.
2414
56.9k
  MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges;
2415
56.9k
  // Size for our labels.
2416
56.9k
  auto Size = Asm->MAI->getCodePointerSize();
2417
56.9k
2418
56.9k
  for (const RangeSpan &Range : List.getRanges())
2419
138k
    SectionRanges[&Range.getStart()->getSection()].push_back(&Range);
2420
56.9k
2421
56.9k
  const DwarfCompileUnit &CU = List.getCU();
2422
56.9k
  const MCSymbol *CUBase = CU.getBaseAddress();
2423
56.9k
  bool BaseIsSet = false;
2424
57.0k
  for (const auto &P : SectionRanges) {
2425
57.0k
    // Don't bother with a base address entry if there's only one range in
2426
57.0k
    // this section in this range list - for example ranges for a CU will
2427
57.0k
    // usually consist of single regions from each of many sections
2428
57.0k
    // (-ffunction-sections, or just C++ inline functions) except under LTO
2429
57.0k
    // or optnone where there may be holes in a single CU's section
2430
57.0k
    // contributions.
2431
57.0k
    auto *Base = CUBase;
2432
57.0k
    if (!Base && 
(8.87k
P.second.size() > 18.87k
||
DwarfVersion < 5151
) &&
2433
57.0k
        
(8.86k
CU.getCUNode()->getRangesBaseAddress()8.86k
||
DwarfVersion >= 58.86k
)) {
2434
7
      BaseIsSet = true;
2435
7
      // FIXME/use care: This may not be a useful base address if it's not
2436
7
      // the lowest address/range in this object.
2437
7
      Base = P.second.front()->getStart();
2438
7
      if (DwarfVersion >= 5) {
2439
3
        Base = DD.getSectionLabel(&Base->getSection());
2440
3
        Asm->OutStreamer->AddComment("DW_RLE_base_addressx");
2441
3
        Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_addressx, 1);
2442
3
        Asm->OutStreamer->AddComment("  base address index");
2443
3
        Asm->EmitULEB128(DD.getAddressPool().getIndex(Base));
2444
4
      } else {
2445
4
        Asm->OutStreamer->EmitIntValue(-1, Size);
2446
4
        Asm->OutStreamer->AddComment("  base address");
2447
4
        Asm->OutStreamer->EmitSymbolValue(Base, Size);
2448
4
      }
2449
56.9k
    } else if (BaseIsSet && 
DwarfVersion < 52
) {
2450
0
      BaseIsSet = false;
2451
0
      assert(!Base);
2452
0
      Asm->OutStreamer->EmitIntValue(-1, Size);
2453
0
      Asm->OutStreamer->EmitIntValue(0, Size);
2454
0
    }
2455
57.0k
2456
138k
    for (const auto *RS : P.second) {
2457
138k
      const MCSymbol *Begin = RS->getStart();
2458
138k
      const MCSymbol *End = RS->getEnd();
2459
138k
      assert(Begin && "Range without a begin symbol?");
2460
138k
      assert(End && "Range without an end symbol?");
2461
138k
      if (Base) {
2462
115k
        if (DwarfVersion >= 5) {
2463
11
          // Emit DW_RLE_offset_pair when we have a base.
2464
11
          Asm->OutStreamer->AddComment("DW_RLE_offset_pair");
2465
11
          Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1);
2466
11
          Asm->OutStreamer->AddComment("  starting offset");
2467
11
          Asm->EmitLabelDifferenceAsULEB128(Begin, Base);
2468
11
          Asm->OutStreamer->AddComment("  ending offset");
2469
11
          Asm->EmitLabelDifferenceAsULEB128(End, Base);
2470
115k
        } else {
2471
115k
          Asm->EmitLabelDifference(Begin, Base, Size);
2472
115k
          Asm->EmitLabelDifference(End, Base, Size);
2473
115k
        }
2474
115k
      } else 
if (22.7k
DwarfVersion >= 522.7k
) {
2475
11
        Asm->OutStreamer->AddComment("DW_RLE_startx_length");
2476
11
        Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_startx_length, 1);
2477
11
        Asm->OutStreamer->AddComment("  start index");
2478
11
        Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin));
2479
11
        Asm->OutStreamer->AddComment("  length");
2480
11
        Asm->EmitLabelDifferenceAsULEB128(End, Begin);
2481
22.7k
      } else {
2482
22.7k
        Asm->OutStreamer->EmitSymbolValue(Begin, Size);
2483
22.7k
        Asm->OutStreamer->EmitSymbolValue(End, Size);
2484
22.7k
      }
2485
138k
    }
2486
57.0k
  }
2487
56.9k
  if (DwarfVersion >= 5) {
2488
9
    Asm->OutStreamer->AddComment("DW_RLE_end_of_list");
2489
9
    Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1);
2490
56.9k
  } else {
2491
56.9k
    // Terminate the list with two 0 values.
2492
56.9k
    Asm->OutStreamer->EmitIntValue(0, Size);
2493
56.9k
    Asm->OutStreamer->EmitIntValue(0, Size);
2494
56.9k
  }
2495
56.9k
}
2496
2497
static void emitDebugRangesImpl(DwarfDebug &DD, AsmPrinter *Asm,
2498
1.11k
                                const DwarfFile &Holder, MCSymbol *TableEnd) {
2499
1.11k
  for (const RangeSpanList &List : Holder.getRangeLists())
2500
56.9k
    emitRangeList(DD, Asm, List);
2501
1.11k
2502
1.11k
  if (TableEnd)
2503
7
    Asm->OutStreamer->EmitLabel(TableEnd);
2504
1.11k
}
2505
2506
/// Emit address ranges into the .debug_ranges section or into the DWARF v5
2507
/// .debug_rnglists section.
2508
3.21k
void DwarfDebug::emitDebugRanges() {
2509
3.21k
  if (CUMap.empty())
2510
865
    return;
2511
2.35k
2512
2.35k
  const auto &Holder = useSplitDwarf() ? 
SkeletonHolder49
:
InfoHolder2.30k
;
2513
2.35k
2514
2.35k
  if (Holder.getRangeLists().empty())
2515
1.23k
    return;
2516
1.11k
2517
1.11k
  assert(useRangesSection());
2518
1.11k
  assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2519
1.11k
    return Pair.second->getCUNode()->isDebugDirectivesOnly();
2520
1.11k
  }));
2521
1.11k
2522
1.11k
  // Start the dwarf ranges section.
2523
1.11k
  MCSymbol *TableEnd = nullptr;
2524
1.11k
  if (getDwarfVersion() >= 5) {
2525
6
    Asm->OutStreamer->SwitchSection(
2526
6
        Asm->getObjFileLowering().getDwarfRnglistsSection());
2527
6
    TableEnd = emitRnglistsTableHeader(Asm, Holder);
2528
6
  } else
2529
1.10k
    Asm->OutStreamer->SwitchSection(
2530
1.10k
        Asm->getObjFileLowering().getDwarfRangesSection());
2531
1.11k
2532
1.11k
  emitDebugRangesImpl(*this, Asm, Holder, TableEnd);
2533
1.11k
}
2534
2535
49
void DwarfDebug::emitDebugRangesDWO() {
2536
49
  assert(useSplitDwarf());
2537
49
2538
49
  if (CUMap.empty())
2539
0
    return;
2540
49
2541
49
  const auto &Holder = InfoHolder;
2542
49
2543
49
  if (Holder.getRangeLists().empty())
2544
48
    return;
2545
1
2546
1
  assert(getDwarfVersion() >= 5);
2547
1
  assert(useRangesSection());
2548
1
  assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2549
1
    return Pair.second->getCUNode()->isDebugDirectivesOnly();
2550
1
  }));
2551
1
2552
1
  // Start the dwarf ranges section.
2553
1
  Asm->OutStreamer->SwitchSection(
2554
1
      Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
2555
1
  MCSymbol *TableEnd = emitRnglistsTableHeader(Asm, Holder);
2556
1
2557
1
  emitDebugRangesImpl(*this, Asm, Holder, TableEnd);
2558
1
}
2559
2560
5
void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
2561
7
  for (auto *MN : Nodes) {
2562
7
    if (auto *M = dyn_cast<DIMacro>(MN))
2563
4
      emitMacro(*M);
2564
3
    else if (auto *F = dyn_cast<DIMacroFile>(MN))
2565
3
      emitMacroFile(*F, U);
2566
3
    else
2567
3
      
llvm_unreachable0
("Unexpected DI type!");
2568
7
  }
2569
5
}
2570
2571
4
void DwarfDebug::emitMacro(DIMacro &M) {
2572
4
  Asm->EmitULEB128(M.getMacinfoType());
2573
4
  Asm->EmitULEB128(M.getLine());
2574
4
  StringRef Name = M.getName();
2575
4
  StringRef Value = M.getValue();
2576
4
  Asm->OutStreamer->EmitBytes(Name);
2577
4
  if (!Value.empty()) {
2578
2
    // There should be one space between macro name and macro value.
2579
2
    Asm->emitInt8(' ');
2580
2
    Asm->OutStreamer->EmitBytes(Value);
2581
2
  }
2582
4
  Asm->emitInt8('\0');
2583
4
}
2584
2585
3
void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
2586
3
  assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
2587
3
  Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
2588
3
  Asm->EmitULEB128(F.getLine());
2589
3
  Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
2590
3
  handleMacroNodes(F.getElements(), U);
2591
3
  Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
2592
3
}
2593
2594
/// Emit macros into a debug macinfo section.
2595
3.21k
void DwarfDebug::emitDebugMacinfo() {
2596
3.21k
  if (CUMap.empty())
2597
865
    return;
2598
2.35k
2599
2.35k
  if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2600
2.35k
        return Pair.second->getCUNode()->isDebugDirectivesOnly();
2601
2.35k
      }))
2602
3
    return;
2603
2.34k
2604
2.34k
  // Start the dwarf macinfo section.
2605
2.34k
  Asm->OutStreamer->SwitchSection(
2606
2.34k
      Asm->getObjFileLowering().getDwarfMacinfoSection());
2607
2.34k
2608
2.66k
  for (const auto &P : CUMap) {
2609
2.66k
    auto &TheCU = *P.second;
2610
2.66k
    if (TheCU.getCUNode()->isDebugDirectivesOnly())
2611
0
      continue;
2612
2.66k
    auto *SkCU = TheCU.getSkeleton();
2613
2.66k
    DwarfCompileUnit &U = SkCU ? 
*SkCU55
:
TheCU2.61k
;
2614
2.66k
    auto *CUNode = cast<DICompileUnit>(P.first);
2615
2.66k
    DIMacroNodeArray Macros = CUNode->getMacros();
2616
2.66k
    if (!Macros.empty()) {
2617
2
      Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2618
2
      handleMacroNodes(Macros, U);
2619
2
    }
2620
2.66k
  }
2621
2.34k
  Asm->OutStreamer->AddComment("End Of Macro List Mark");
2622
2.34k
  Asm->emitInt8(0);
2623
2.34k
}
2624
2625
// DWARF5 Experimental Separate Dwarf emitters.
2626
2627
void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2628
55
                                  std::unique_ptr<DwarfCompileUnit> NewU) {
2629
55
2630
55
  if (!CompilationDir.empty())
2631
55
    NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2632
55
2633
55
  addGnuPubAttributes(*NewU, Die);
2634
55
2635
55
  SkeletonHolder.addUnit(std::move(NewU));
2636
55
}
2637
2638
55
DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2639
55
2640
55
  auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
2641
55
      CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2642
55
  DwarfCompileUnit &NewCU = *OwnedUnit;
2643
55
  NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
2644
55
2645
55
  NewCU.initStmtList();
2646
55
2647
55
  if (useSegmentedStringOffsetsTable())
2648
9
    NewCU.addStringOffsetsStart();
2649
55
2650
55
  initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2651
55
2652
55
  return NewCU;
2653
55
}
2654
2655
// Emit the .debug_info.dwo section for separated dwarf. This contains the
2656
// compile units that would normally be in debug_info.
2657
49
void DwarfDebug::emitDebugInfoDWO() {
2658
49
  assert(useSplitDwarf() && "No split dwarf debug info?");
2659
49
  // Don't emit relocations into the dwo file.
2660
49
  InfoHolder.emitUnits(/* UseOffsets */ true);
2661
49
}
2662
2663
// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2664
// abbreviations for the .debug_info.dwo section.
2665
49
void DwarfDebug::emitDebugAbbrevDWO() {
2666
49
  assert(useSplitDwarf() && "No split dwarf?");
2667
49
  InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2668
49
}
2669
2670
49
void DwarfDebug::emitDebugLineDWO() {
2671
49
  assert(useSplitDwarf() && "No split dwarf?");
2672
49
  SplitTypeUnitFileTable.Emit(
2673
49
      *Asm->OutStreamer, MCDwarfLineTableParams(),
2674
49
      Asm->getObjFileLowering().getDwarfLineDWOSection());
2675
49
}
2676
2677
7
void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2678
7
  assert(useSplitDwarf() && "No split dwarf?");
2679
7
  InfoHolder.getStringPool().emitStringOffsetsTableHeader(
2680
7
      *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
2681
7
      InfoHolder.getStringOffsetsStartSym());
2682
7
}
2683
2684
// Emit the .debug_str.dwo section for separated dwarf. This contains the
2685
// string section and is identical in format to traditional .debug_str
2686
// sections.
2687
49
void DwarfDebug::emitDebugStrDWO() {
2688
49
  if (useSegmentedStringOffsetsTable())
2689
7
    emitStringOffsetsTableHeaderDWO();
2690
49
  assert(useSplitDwarf() && "No split dwarf?");
2691
49
  MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2692
49
  InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2693
49
                         OffSec, /* UseRelativeOffsets = */ false);
2694
49
}
2695
2696
// Emit address pool.
2697
3.21k
void DwarfDebug::emitDebugAddr() {
2698
3.21k
  AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
2699
3.21k
}
2700
2701
47
MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2702
47
  if (!useSplitDwarf())
2703
23
    return nullptr;
2704
24
  const DICompileUnit *DIUnit = CU.getCUNode();
2705
24
  SplitTypeUnitFileTable.maybeSetRootFile(
2706
24
      DIUnit->getDirectory(), DIUnit->getFilename(),
2707
24
      CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
2708
24
  return &SplitTypeUnitFileTable;
2709
24
}
2710
2711
47
uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2712
47
  MD5 Hash;
2713
47
  Hash.update(Identifier);
2714
47
  // ... take the least significant 8 bytes and return those. Our MD5
2715
47
  // implementation always returns its results in little endian, so we actually
2716
47
  // need the "high" word.
2717
47
  MD5::MD5Result Result;
2718
47
  Hash.final(Result);
2719
47
  return Result.high();
2720
47
}
2721
2722
void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2723
                                      StringRef Identifier, DIE &RefDie,
2724
57
                                      const DICompositeType *CTy) {
2725
57
  // Fast path if we're building some type units and one has already used the
2726
57
  // address pool we know we're going to throw away all this work anyway, so
2727
57
  // don't bother building dependent types.
2728
57
  if (!TypeUnitsUnderConstruction.empty() && 
AddrPool.hasBeenUsed()15
)
2729
1
    return;
2730
56
2731
56
  auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2732
56
  if (!Ins.second) {
2733
9
    CU.addDIETypeSignature(RefDie, Ins.first->second);
2734
9
    return;
2735
9
  }
2736
47
2737
47
  bool TopLevelType = TypeUnitsUnderConstruction.empty();
2738
47
  AddrPool.resetUsedFlag();
2739
47
2740
47
  auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2741
47
                                                    getDwoLineTable(CU));
2742
47
  DwarfTypeUnit &NewTU = *OwnedUnit;
2743
47
  DIE &UnitDie = NewTU.getUnitDie();
2744
47
  TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
2745
47
2746
47
  NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2747
47
                CU.getLanguage());
2748
47
2749
47
  uint64_t Signature = makeTypeSignature(Identifier);
2750
47
  NewTU.setTypeSignature(Signature);
2751
47
  Ins.first->second = Signature;
2752
47
2753
47
  if (useSplitDwarf()) {
2754
24
    MCSection *Section =
2755
24
        getDwarfVersion() <= 4
2756
24
            ? 
Asm->getObjFileLowering().getDwarfTypesDWOSection()20
2757
24
            : 
Asm->getObjFileLowering().getDwarfInfoDWOSection()4
;
2758
24
    NewTU.setSection(Section);
2759
24
  } else {
2760
23
    MCSection *Section =
2761
23
        getDwarfVersion() <= 4
2762
23
            ? 
Asm->getObjFileLowering().getDwarfTypesSection(Signature)18
2763
23
            : 
Asm->getObjFileLowering().getDwarfInfoSection(Signature)5
;
2764
23
    NewTU.setSection(Section);
2765
23
    // Non-split type units reuse the compile unit's line table.
2766
23
    CU.applyStmtList(UnitDie);
2767
23
  }
2768
47
2769
47
  // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2770
47
  // units.
2771
47
  if (useSegmentedStringOffsetsTable() && 
!useSplitDwarf()9
)
2772
5
    NewTU.addStringOffsetsStart();
2773
47
2774
47
  NewTU.setType(NewTU.createTypeDIE(CTy));
2775
47
2776
47
  if (TopLevelType) {
2777
35
    auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2778
35
    TypeUnitsUnderConstruction.clear();
2779
35
2780
35
    // Types referencing entries in the address table cannot be placed in type
2781
35
    // units.
2782
35
    if (AddrPool.hasBeenUsed()) {
2783
7
2784
7
      // Remove all the types built while building this type.
2785
7
      // This is pessimistic as some of these types might not be dependent on
2786
7
      // the type that used an address.
2787
7
      for (const auto &TU : TypeUnitsToAdd)
2788
11
        TypeSignatures.erase(TU.second);
2789
7
2790
7
      // Construct this type in the CU directly.
2791
7
      // This is inefficient because all the dependent types will be rebuilt
2792
7
      // from scratch, including building them in type units, discovering that
2793
7
      // they depend on addresses, throwing them out and rebuilding them.
2794
7
      CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2795
7
      return;
2796
7
    }
2797
28
2798
28
    // If the type wasn't dependent on fission addresses, finish adding the type
2799
28
    // and all its dependent types.
2800
36
    
for (auto &TU : TypeUnitsToAdd)28
{
2801
36
      InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2802
36
      InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2803
36
    }
2804
28
  }
2805
47
  CU.addDIETypeSignature(RefDie, Signature);
2806
40
}
2807
2808
DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD)
2809
    : DD(DD),
2810
6
      TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)) {
2811
6
  DD->TypeUnitsUnderConstruction.clear();
2812
6
  assert(TypeUnitsUnderConstruction.empty() || !DD->AddrPool.hasBeenUsed());
2813
6
}
2814
2815
6
DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() {
2816
6
  DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction);
2817
6
  DD->AddrPool.resetUsedFlag();
2818
6
}
2819
2820
6
DwarfDebug::NonTypeUnitContext DwarfDebug::enterNonTypeUnitContext() {
2821
6
  return NonTypeUnitContext(this);
2822
6
}
2823
2824
// Add the Name along with its companion DIE to the appropriate accelerator
2825
// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
2826
// AccelTableKind::Apple, we use the table we got as an argument). If
2827
// accelerator tables are disabled, this function does nothing.
2828
template <typename DataT>
2829
void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
2830
                                  AccelTable<DataT> &AppleAccel, StringRef Name,
2831
317k
                                  const DIE &Die) {
2832
317k
  if (getAccelTableKind() == AccelTableKind::None)
2833
1.66k
    return;
2834
316k
2835
316k
  if (getAccelTableKind() != AccelTableKind::Apple &&
2836
316k
      
CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default839
)
2837
383
    return;
2838
315k
2839
315k
  DwarfFile &Holder = useSplitDwarf() ? 
SkeletonHolder19
:
InfoHolder315k
;
2840
315k
  DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
2841
315k
2842
315k
  switch (getAccelTableKind()) {
2843
315k
  case AccelTableKind::Apple:
2844
315k
    AppleAccel.addName(Ref, Die);
2845
315k
    break;
2846
315k
  case AccelTableKind::Dwarf:
2847
456
    AccelDebugNames.addName(Ref, Die);
2848
456
    break;
2849
315k
  case AccelTableKind::Default:
2850
0
    llvm_unreachable("Default should have already been resolved.");
2851
315k
  case AccelTableKind::None:
2852
0
    llvm_unreachable("None handled above");
2853
315k
  }
2854
315k
}
void llvm::DwarfDebug::addAccelNameImpl<llvm::AppleAccelTableOffsetData>(llvm::DICompileUnit const&, llvm::AccelTable<llvm::AppleAccelTableOffsetData>&, llvm::StringRef, llvm::DIE const&)
Line
Count
Source
2831
316k
                                  const DIE &Die) {
2832
316k
  if (getAccelTableKind() == AccelTableKind::None)
2833
927
    return;
2834
315k
2835
315k
  if (getAccelTableKind() != AccelTableKind::Apple &&
2836
315k
      
CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default510
)
2837
125
    return;
2838
314k
2839
314k
  DwarfFile &Holder = useSplitDwarf() ? 
SkeletonHolder11
:
InfoHolder314k
;
2840
314k
  DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
2841
314k
2842
314k
  switch (getAccelTableKind()) {
2843
314k
  case AccelTableKind::Apple:
2844
314k
    AppleAccel.addName(Ref, Die);
2845
314k
    break;
2846
314k
  case AccelTableKind::Dwarf:
2847
385
    AccelDebugNames.addName(Ref, Die);
2848
385
    break;
2849
314k
  case AccelTableKind::Default:
2850
0
    llvm_unreachable("Default should have already been resolved.");
2851
314k
  case AccelTableKind::None:
2852
0
    llvm_unreachable("None handled above");
2853
314k
  }
2854
314k
}
void llvm::DwarfDebug::addAccelNameImpl<llvm::AppleAccelTableTypeData>(llvm::DICompileUnit const&, llvm::AccelTable<llvm::AppleAccelTableTypeData>&, llvm::StringRef, llvm::DIE const&)
Line
Count
Source
2831
1.89k
                                  const DIE &Die) {
2832
1.89k
  if (getAccelTableKind() == AccelTableKind::None)
2833
742
    return;
2834
1.14k
2835
1.14k
  if (getAccelTableKind() != AccelTableKind::Apple &&
2836
1.14k
      
CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default329
)
2837
258
    return;
2838
891
2839
891
  DwarfFile &Holder = useSplitDwarf() ? 
SkeletonHolder8
:
InfoHolder883
;
2840
891
  DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
2841
891
2842
891
  switch (getAccelTableKind()) {
2843
891
  case AccelTableKind::Apple:
2844
820
    AppleAccel.addName(Ref, Die);
2845
820
    break;
2846
891
  case AccelTableKind::Dwarf:
2847
71
    AccelDebugNames.addName(Ref, Die);
2848
71
    break;
2849
891
  case AccelTableKind::Default:
2850
0
    llvm_unreachable("Default should have already been resolved.");
2851
891
  case AccelTableKind::None:
2852
0
    llvm_unreachable("None handled above");
2853
891
  }
2854
891
}
2855
2856
void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
2857
315k
                              const DIE &Die) {
2858
315k
  addAccelNameImpl(CU, AccelNames, Name, Die);
2859
315k
}
2860
2861
void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
2862
23
                              const DIE &Die) {
2863
23
  // ObjC names go only into the Apple accelerator tables.
2864
23
  if (getAccelTableKind() == AccelTableKind::Apple)
2865
23
    addAccelNameImpl(CU, AccelObjC, Name, Die);
2866
23
}
2867
2868
void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
2869
75
                                   const DIE &Die) {
2870
75
  addAccelNameImpl(CU, AccelNamespace, Name, Die);
2871
75
}
2872
2873
void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
2874
1.89k
                              const DIE &Die, char Flags) {
2875
1.89k
  addAccelNameImpl(CU, AccelTypes, Name, Die);
2876
1.89k
}
2877
2878
3.36M
uint16_t DwarfDebug::getDwarfVersion() const {
2879
3.36M
  return Asm->OutStreamer->getContext().getDwarfVersion();
2880
3.36M
}
2881
2882
2.26k
void DwarfDebug::addSectionLabel(const MCSymbol *Sym) {
2883
2.26k
  SectionLabels.insert(std::make_pair(&Sym->getSection(), Sym));
2884
2.26k
}
2885
2886
3
const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
2887
3
  return SectionLabels.find(S)->second;
2888
3
}