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