1//===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains support for writing dwarf debug info into asm files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "DwarfDebug.h"
14#include "ByteStreamer.h"
15#include "DIEHash.h"
16#include "DwarfCompileUnit.h"
17#include "DwarfExpression.h"
18#include "DwarfUnit.h"
19#include "llvm/ADT/APInt.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/CodeGen/AsmPrinter.h"
24#include "llvm/CodeGen/DIE.h"
25#include "llvm/CodeGen/LexicalScopes.h"
26#include "llvm/CodeGen/MachineBasicBlock.h"
27#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineModuleInfo.h"
29#include "llvm/CodeGen/MachineOperand.h"
30#include "llvm/CodeGen/TargetInstrInfo.h"
31#include "llvm/CodeGen/TargetLowering.h"
32#include "llvm/CodeGen/TargetRegisterInfo.h"
33#include "llvm/CodeGen/TargetSubtargetInfo.h"
34#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
35#include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"
36#include "llvm/IR/Constants.h"
37#include "llvm/IR/DebugInfoMetadata.h"
38#include "llvm/IR/Function.h"
39#include "llvm/IR/GlobalVariable.h"
40#include "llvm/IR/Module.h"
41#include "llvm/MC/MCAsmInfo.h"
42#include "llvm/MC/MCContext.h"
43#include "llvm/MC/MCSection.h"
44#include "llvm/MC/MCStreamer.h"
45#include "llvm/MC/MCSymbol.h"
46#include "llvm/MC/MCTargetOptions.h"
47#include "llvm/MC/MachineLocation.h"
48#include "llvm/Support/Casting.h"
49#include "llvm/Support/CommandLine.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/MD5.h"
53#include "llvm/Support/MathExtras.h"
54#include "llvm/Support/raw_ostream.h"
55#include "llvm/Target/TargetLoweringObjectFile.h"
56#include "llvm/Target/TargetMachine.h"
57#include "llvm/TargetParser/Triple.h"
58#include <cstddef>
59#include <iterator>
60#include <optional>
61#include <string>
62
63using namespace llvm;
64
65#define DEBUG_TYPE "dwarfdebug"
66
67STATISTIC(NumCSParams, "Number of dbg call site params created");
68
69static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
70 "use-dwarf-ranges-base-address-specifier", cl::Hidden,
71 cl::desc("Use base address specifiers in debug_ranges"), cl::init(Val: false));
72
73static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74 cl::Hidden,
75 cl::desc("Generate dwarf aranges"),
76 cl::init(Val: false));
77
78static cl::opt<bool>
79 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
80 cl::desc("Generate DWARF4 type units."),
81 cl::init(Val: false));
82
83static cl::opt<bool> SplitDwarfCrossCuReferences(
84 "split-dwarf-cross-cu-references", cl::Hidden,
85 cl::desc("Enable cross-cu references in DWO files"), cl::init(Val: false));
86
87enum DefaultOnOff { Default, Enable, Disable };
88
89static cl::opt<DefaultOnOff> UnknownLocations(
90 "use-unknown-locations", cl::Hidden,
91 cl::desc("Make an absence of debug location information explicit."),
92 cl::values(clEnumVal(Default, "At top of block or after label"),
93 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
94 cl::init(Val: Default));
95
96static cl::opt<AccelTableKind> AccelTables(
97 "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
98 cl::values(clEnumValN(AccelTableKind::Default, "Default",
99 "Default for platform"),
100 clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
101 clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
102 clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
103 cl::init(Val: AccelTableKind::Default));
104
105static cl::opt<DefaultOnOff>
106DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
107 cl::desc("Use inlined strings rather than string section."),
108 cl::values(clEnumVal(Default, "Default for platform"),
109 clEnumVal(Enable, "Enabled"),
110 clEnumVal(Disable, "Disabled")),
111 cl::init(Val: Default));
112
113static cl::opt<bool>
114 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
115 cl::desc("Disable emission .debug_ranges section."),
116 cl::init(Val: false));
117
118static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
119 "dwarf-sections-as-references", cl::Hidden,
120 cl::desc("Use sections+offset as references rather than labels."),
121 cl::values(clEnumVal(Default, "Default for platform"),
122 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
123 cl::init(Val: Default));
124
125static cl::opt<bool>
126 UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden,
127 cl::desc("Emit the GNU .debug_macro format with DWARF <5"),
128 cl::init(Val: false));
129
130static cl::opt<DefaultOnOff> DwarfOpConvert(
131 "dwarf-op-convert", cl::Hidden,
132 cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"),
133 cl::values(clEnumVal(Default, "Default for platform"),
134 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
135 cl::init(Val: Default));
136
137enum LinkageNameOption {
138 DefaultLinkageNames,
139 AllLinkageNames,
140 AbstractLinkageNames
141};
142
143static cl::opt<LinkageNameOption>
144 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
145 cl::desc("Which DWARF linkage-name attributes to emit."),
146 cl::values(clEnumValN(DefaultLinkageNames, "Default",
147 "Default for platform"),
148 clEnumValN(AllLinkageNames, "All", "All"),
149 clEnumValN(AbstractLinkageNames, "Abstract",
150 "Abstract subprograms")),
151 cl::init(Val: DefaultLinkageNames));
152
153static cl::opt<DwarfDebug::MinimizeAddrInV5> MinimizeAddrInV5Option(
154 "minimize-addr-in-v5", cl::Hidden,
155 cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more "
156 "address pool entry sharing to reduce relocations/object size"),
157 cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default, "Default",
158 "Default address minimization strategy"),
159 clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges, "Ranges",
160 "Use rnglists for contiguous ranges if that allows "
161 "using a pre-existing base address"),
162 clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions,
163 "Expressions",
164 "Use exprloc addrx+offset expressions for any "
165 "address with a prior base address"),
166 clEnumValN(DwarfDebug::MinimizeAddrInV5::Form, "Form",
167 "Use addrx+offset extension form for any address "
168 "with a prior base address"),
169 clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled, "Disabled",
170 "Stuff")),
171 cl::init(Val: DwarfDebug::MinimizeAddrInV5::Default));
172
173/// Set to false to ignore Key Instructions metadata.
174static cl::opt<bool> KeyInstructionsAreStmts(
175 "dwarf-use-key-instructions", cl::Hidden, cl::init(Val: true),
176 cl::desc("Set to false to ignore Key Instructions metadata"));
177
178static constexpr unsigned ULEB128PadSize = 4;
179
180void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
181 getActiveStreamer().emitInt8(
182 Byte: Op, Comment: Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Encoding: Op)
183 : dwarf::OperationEncodingString(Encoding: Op));
184}
185
186void DebugLocDwarfExpression::emitSigned(int64_t Value) {
187 getActiveStreamer().emitSLEB128(DWord: Value, Comment: Twine(Value));
188}
189
190void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
191 getActiveStreamer().emitULEB128(DWord: Value, Comment: Twine(Value));
192}
193
194void DebugLocDwarfExpression::emitData1(uint8_t Value) {
195 getActiveStreamer().emitInt8(Byte: Value, Comment: Twine(Value));
196}
197
198void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
199 assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
200 getActiveStreamer().emitULEB128(DWord: Idx, Comment: Twine(Idx), PadTo: ULEB128PadSize);
201}
202
203bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
204 llvm::Register MachineReg) {
205 // This information is not available while emitting .debug_loc entries.
206 return false;
207}
208
209void DebugLocDwarfExpression::enableTemporaryBuffer() {
210 assert(!IsBuffering && "Already buffering?");
211 if (!TmpBuf)
212 TmpBuf = std::make_unique<TempBuffer>(args: OutBS.GenerateComments);
213 IsBuffering = true;
214}
215
216void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
217
218unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
219 return TmpBuf ? TmpBuf->Bytes.size() : 0;
220}
221
222void DebugLocDwarfExpression::commitTemporaryBuffer() {
223 if (!TmpBuf)
224 return;
225 for (auto Byte : enumerate(First&: TmpBuf->Bytes)) {
226 const char *Comment = (Byte.index() < TmpBuf->Comments.size())
227 ? TmpBuf->Comments[Byte.index()].c_str()
228 : "";
229 OutBS.emitInt8(Byte: Byte.value(), Comment);
230 }
231 TmpBuf->Bytes.clear();
232 TmpBuf->Comments.clear();
233}
234
235const DIType *DbgVariable::getType() const {
236 return getVariable()->getType();
237}
238
239/// Get .debug_loc entry for the instruction range starting at MI.
240static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
241 const DIExpression *Expr = MI->getDebugExpression();
242 auto SingleLocExprOpt = DIExpression::convertToNonVariadicExpression(Expr);
243 const bool IsVariadic = !SingleLocExprOpt;
244 // If we have a variadic debug value instruction that is equivalent to a
245 // non-variadic instruction, then convert it to non-variadic form here.
246 if (!IsVariadic && !MI->isNonListDebugValue()) {
247 assert(MI->getNumDebugOperands() == 1 &&
248 "Mismatched DIExpression and debug operands for debug instruction.");
249 Expr = *SingleLocExprOpt;
250 }
251 assert(MI->getNumOperands() >= 3);
252 SmallVector<DbgValueLocEntry, 4> DbgValueLocEntries;
253 for (const MachineOperand &Op : MI->debug_operands()) {
254 if (Op.isReg()) {
255 MachineLocation MLoc(Op.getReg(),
256 MI->isNonListDebugValue() && MI->isDebugOffsetImm());
257 DbgValueLocEntries.push_back(Elt: DbgValueLocEntry(MLoc));
258 } else if (Op.isTargetIndex()) {
259 DbgValueLocEntries.push_back(
260 Elt: DbgValueLocEntry(TargetIndexLocation(Op.getIndex(), Op.getOffset())));
261 } else if (Op.isImm())
262 DbgValueLocEntries.push_back(Elt: DbgValueLocEntry(Op.getImm()));
263 else if (Op.isFPImm())
264 DbgValueLocEntries.push_back(Elt: DbgValueLocEntry(Op.getFPImm()));
265 else if (Op.isCImm())
266 DbgValueLocEntries.push_back(Elt: DbgValueLocEntry(Op.getCImm()));
267 else
268 llvm_unreachable("Unexpected debug operand in DBG_VALUE* instruction!");
269 }
270 return DbgValueLoc(Expr, DbgValueLocEntries, IsVariadic);
271}
272
273static uint64_t getFragmentOffsetInBits(const DIExpression &Expr) {
274 std::optional<DIExpression::FragmentInfo> Fragment = Expr.getFragmentInfo();
275 return Fragment ? Fragment->OffsetInBits : 0;
276}
277
278bool llvm::operator<(const FrameIndexExpr &LHS, const FrameIndexExpr &RHS) {
279 return getFragmentOffsetInBits(Expr: *LHS.Expr) <
280 getFragmentOffsetInBits(Expr: *RHS.Expr);
281}
282
283bool llvm::operator<(const EntryValueInfo &LHS, const EntryValueInfo &RHS) {
284 return getFragmentOffsetInBits(Expr: LHS.Expr) < getFragmentOffsetInBits(Expr: RHS.Expr);
285}
286
287Loc::Single::Single(DbgValueLoc ValueLoc)
288 : ValueLoc(std::make_unique<DbgValueLoc>(args&: ValueLoc)),
289 Expr(ValueLoc.getExpression()) {
290 if (!Expr->getNumElements())
291 Expr = nullptr;
292}
293
294Loc::Single::Single(const MachineInstr *DbgValue)
295 : Single(getDebugLocValue(MI: DbgValue)) {}
296
297const std::set<FrameIndexExpr> &Loc::MMI::getFrameIndexExprs() const {
298 return FrameIndexExprs;
299}
300
301void Loc::MMI::addFrameIndexExpr(const DIExpression *Expr, int FI) {
302 FrameIndexExprs.insert(x: {.FI: FI, .Expr: Expr});
303 assert((FrameIndexExprs.size() == 1 ||
304 llvm::all_of(FrameIndexExprs,
305 [](const FrameIndexExpr &FIE) {
306 return FIE.Expr && FIE.Expr->isFragment();
307 })) &&
308 "conflicting locations for variable");
309}
310
311static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
312 bool GenerateTypeUnits,
313 DebuggerKind Tuning,
314 const Triple &TT) {
315 // Honor an explicit request.
316 if (AccelTables != AccelTableKind::Default)
317 return AccelTables;
318
319 // Generating DWARF5 acceleration table.
320 // Currently Split dwarf and non ELF format is not supported.
321 if (GenerateTypeUnits && (DwarfVersion < 5 || !TT.isOSBinFormatELF()))
322 return AccelTableKind::None;
323
324 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
325 // always implies debug_names. For lower standard versions we use apple
326 // accelerator tables on apple platforms and debug_names elsewhere.
327 if (DwarfVersion >= 5)
328 return AccelTableKind::Dwarf;
329 if (Tuning == DebuggerKind::LLDB)
330 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
331 : AccelTableKind::Dwarf;
332 return AccelTableKind::None;
333}
334
335DwarfDebug::DwarfDebug(AsmPrinter *A)
336 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
337 SkeletonHolder(A, "skel_string", DIEValueAllocator),
338 IsDarwin(A->TM.getTargetTriple().isOSDarwin()),
339 InfoHolder(A, "info_string", DIEValueAllocator) {
340 const Triple &TT = Asm->TM.getTargetTriple();
341
342 // Make sure we know our "debugger tuning". The target option takes
343 // precedence; fall back to triple-based defaults.
344 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
345 DebuggerTuning = Asm->TM.Options.DebuggerTuning;
346 else if (IsDarwin)
347 DebuggerTuning = DebuggerKind::LLDB;
348 else if (TT.isPS())
349 DebuggerTuning = DebuggerKind::SCE;
350 else if (TT.isOSAIX())
351 DebuggerTuning = DebuggerKind::DBX;
352 else
353 DebuggerTuning = DebuggerKind::GDB;
354
355 if (DwarfInlinedStrings == Default)
356 UseInlineStrings = tuneForDBX();
357 else
358 UseInlineStrings = DwarfInlinedStrings == Enable;
359
360 // Always emit .debug_aranges for SCE tuning.
361 UseARangesSection = GenerateARangeSection || tuneForSCE();
362
363 HasAppleExtensionAttributes = tuneForLLDB();
364
365 // Handle split DWARF.
366 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
367
368 // SCE defaults to linkage names only for abstract subprograms.
369 if (DwarfLinkageNames == DefaultLinkageNames)
370 UseAllLinkageNames = !tuneForSCE();
371 else
372 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
373
374 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
375 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
376 : MMI->getModule()->getDwarfVersion();
377 if (!DwarfVersion)
378 DwarfVersion = dwarf::DWARF_VERSION;
379
380 bool Dwarf64 = DwarfVersion >= 3 && // DWARF64 was introduced in DWARFv3.
381 TT.isArch64Bit(); // DWARF64 requires 64-bit relocations.
382
383 // Support DWARF64
384 // 1: For ELF when requested.
385 // 2: For XCOFF64: the AIX assembler will fill in debug section lengths
386 // according to the DWARF64 format for 64-bit assembly, so we must use
387 // DWARF64 in the compiler too for 64-bit mode.
388 Dwarf64 &=
389 ((Asm->TM.Options.MCOptions.Dwarf64 || MMI->getModule()->isDwarf64()) &&
390 TT.isOSBinFormatELF()) ||
391 TT.isOSBinFormatXCOFF();
392
393 if (!Dwarf64 && TT.isArch64Bit() && TT.isOSBinFormatXCOFF())
394 report_fatal_error(reason: "XCOFF requires DWARF64 for 64-bit mode!");
395
396 UseRangesSection = !NoDwarfRangesSection;
397
398 if (DwarfSectionsAsReferences != Default)
399 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
400
401 // Don't generate type units for unsupported object file formats.
402 GenerateTypeUnits = (A->TM.getTargetTriple().isOSBinFormatELF() ||
403 A->TM.getTargetTriple().isOSBinFormatWasm()) &&
404 GenerateDwarfTypeUnits;
405
406 TheAccelTableKind = computeAccelTableKind(
407 DwarfVersion, GenerateTypeUnits, Tuning: DebuggerTuning, TT: A->TM.getTargetTriple());
408
409 // Work around a GDB bug. GDB doesn't support the standard opcode;
410 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
411 // is defined as of DWARF 3.
412 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
413 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
414 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
415
416 UseDWARF2Bitfields = DwarfVersion < 4;
417
418 // The DWARF v5 string offsets table has - possibly shared - contributions
419 // from each compile and type unit each preceded by a header. The string
420 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
421 // a monolithic string offsets table without any header.
422 UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
423
424 // Emit call-site-param debug info for GDB and LLDB, if the target supports
425 // the debug entry values feature. It can also be enabled explicitly.
426 EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues();
427
428 // It is unclear if the GCC .debug_macro extension is well-specified
429 // for split DWARF. For now, do not allow LLVM to emit it.
430 UseDebugMacroSection =
431 DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf());
432 if (DwarfOpConvert == Default)
433 EnableOpConvert = !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT.isOSBinFormatMachO()));
434 else
435 EnableOpConvert = (DwarfOpConvert == Enable);
436
437 // Split DWARF would benefit object size significantly by trading reductions
438 // in address pool usage for slightly increased range list encodings.
439 if (DwarfVersion >= 5)
440 MinimizeAddr = MinimizeAddrInV5Option;
441
442 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
443 Asm->OutStreamer->getContext().setDwarfFormat(Dwarf64 ? dwarf::DWARF64
444 : dwarf::DWARF32);
445}
446
447// Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
448DwarfDebug::~DwarfDebug() = default;
449
450static bool isObjCClass(StringRef Name) {
451 return Name.starts_with(Prefix: "+") || Name.starts_with(Prefix: "-");
452}
453
454static bool hasObjCCategory(StringRef Name) {
455 if (!isObjCClass(Name))
456 return false;
457
458 return Name.contains(Other: ") ");
459}
460
461static void getObjCClassCategory(StringRef In, StringRef &Class,
462 StringRef &Category) {
463 if (!hasObjCCategory(Name: In)) {
464 Class = In.slice(Start: In.find(C: '[') + 1, End: In.find(C: ' '));
465 Category = "";
466 return;
467 }
468
469 Class = In.slice(Start: In.find(C: '[') + 1, End: In.find(C: '('));
470 Category = In.slice(Start: In.find(C: '[') + 1, End: In.find(C: ' '));
471}
472
473static StringRef getObjCMethodName(StringRef In) {
474 return In.slice(Start: In.find(C: ' ') + 1, End: In.find(C: ']'));
475}
476
477// Add the various names to the Dwarf accelerator table names.
478void DwarfDebug::addSubprogramNames(
479 const DwarfUnit &Unit,
480 const DICompileUnit::DebugNameTableKind NameTableKind,
481 const DISubprogram *SP, DIE &Die) {
482 if (getAccelTableKind() != AccelTableKind::Apple &&
483 NameTableKind != DICompileUnit::DebugNameTableKind::Apple &&
484 NameTableKind == DICompileUnit::DebugNameTableKind::None)
485 return;
486
487 if (!SP->isDefinition())
488 return;
489
490 if (SP->getName() != "")
491 addAccelName(Unit, NameTableKind, Name: SP->getName(), Die);
492
493 // We drop the mangling escape prefix when emitting the DW_AT_linkage_name. So
494 // ensure we don't include it when inserting into the accelerator tables.
495 llvm::StringRef LinkageName =
496 GlobalValue::dropLLVMManglingEscape(Name: SP->getLinkageName());
497
498 // If the linkage name is different than the name, go ahead and output that as
499 // well into the name table. Only do that if we are going to actually emit
500 // that name.
501 if (LinkageName != "" && SP->getName() != LinkageName &&
502 (useAllLinkageNames() || InfoHolder.getAbstractScopeDIEs().lookup(Val: SP)))
503 addAccelName(Unit, NameTableKind, Name: LinkageName, Die);
504
505 // If this is an Objective-C selector name add it to the ObjC accelerator
506 // too.
507 if (isObjCClass(Name: SP->getName())) {
508 StringRef Class, Category;
509 getObjCClassCategory(In: SP->getName(), Class, Category);
510 addAccelObjC(Unit, NameTableKind, Name: Class, Die);
511 if (Category != "")
512 addAccelObjC(Unit, NameTableKind, Name: Category, Die);
513 // Also add the base method name to the name table.
514 addAccelName(Unit, NameTableKind, Name: getObjCMethodName(In: SP->getName()), Die);
515 }
516}
517
518/// Check whether we should create a DIE for the given Scope, return true
519/// if we don't create a DIE (the corresponding DIE is null).
520bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
521 if (Scope->isAbstractScope())
522 return false;
523
524 // We don't create a DIE if there is no Range.
525 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
526 if (Ranges.empty())
527 return true;
528
529 if (Ranges.size() > 1)
530 return false;
531
532 // We don't create a DIE if we have a single Range and the end label
533 // is null.
534 return !getLabelAfterInsn(MI: Ranges.front().second);
535}
536
537template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
538 F(CU);
539 if (auto *SkelCU = CU.getSkeleton())
540 if (CU.getCUNode()->getSplitDebugInlining())
541 F(*SkelCU);
542}
543
544bool DwarfDebug::shareAcrossDWOCUs() const {
545 return SplitDwarfCrossCuReferences;
546}
547
548DwarfCompileUnit &
549DwarfDebug::getOrCreateAbstractSubprogramCU(const DISubprogram *SP,
550 DwarfCompileUnit &SrcCU) {
551 auto &CU = getOrCreateDwarfCompileUnit(DIUnit: SP->getUnit());
552 if (CU.getSkeleton())
553 return shareAcrossDWOCUs() ? CU : SrcCU;
554
555 return CU;
556}
557
558void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
559 LexicalScope *Scope) {
560 assert(Scope && Scope->getScopeNode());
561 assert(Scope->isAbstractScope());
562 assert(!Scope->getInlinedAt());
563
564 auto *SP = cast<DISubprogram>(Val: Scope->getScopeNode());
565
566 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
567 // was inlined from another compile unit.
568 auto &CU = getOrCreateDwarfCompileUnit(DIUnit: SP->getUnit());
569 auto &TargetCU = getOrCreateAbstractSubprogramCU(SP, SrcCU);
570 TargetCU.constructAbstractSubprogramScopeDIE(Scope);
571 if (auto *SkelCU = CU.getSkeleton())
572 if (CU.getCUNode()->getSplitDebugInlining())
573 SkelCU->constructAbstractSubprogramScopeDIE(Scope);
574}
575
576/// Represents a parameter whose call site value can be described by applying a
577/// debug expression to a register in the forwarded register worklist.
578struct FwdRegParamInfo {
579 /// The described parameter register.
580 uint64_t ParamReg;
581
582 /// Debug expression that has been built up when walking through the
583 /// instruction chain that produces the parameter's value.
584 const DIExpression *Expr;
585};
586
587/// Register worklist for finding call site values.
588using FwdRegWorklist = MapVector<Register, SmallVector<FwdRegParamInfo, 2>>;
589/// Container for the set of register units known to be clobbered on the path
590/// to a call site.
591using ClobberedRegUnitSet = SmallSet<MCRegUnit, 16>;
592
593/// Append the expression \p Addition to \p Original and return the result.
594static const DIExpression *combineDIExpressions(const DIExpression *Original,
595 const DIExpression *Addition) {
596 std::vector<uint64_t> Elts = Addition->getElements().vec();
597 // Avoid multiple DW_OP_stack_values.
598 if (Original->isImplicit() && Addition->isImplicit())
599 llvm::erase(C&: Elts, V: dwarf::DW_OP_stack_value);
600 const DIExpression *CombinedExpr =
601 (Elts.size() > 0) ? DIExpression::append(Expr: Original, Ops: Elts) : Original;
602 return CombinedExpr;
603}
604
605/// Emit call site parameter entries that are described by the given value and
606/// debug expression.
607template <typename ValT>
608static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
609 ArrayRef<FwdRegParamInfo> DescribedParams,
610 ParamSet &Params) {
611 for (auto Param : DescribedParams) {
612 bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
613
614 // If a parameter's call site value is produced by a chain of
615 // instructions we may have already created an expression for the
616 // parameter when walking through the instructions. Append that to the
617 // base expression.
618 const DIExpression *CombinedExpr =
619 ShouldCombineExpressions ? combineDIExpressions(Original: Expr, Addition: Param.Expr)
620 : Expr;
621 assert((!CombinedExpr || CombinedExpr->isValid()) &&
622 "Combined debug expression is invalid");
623
624 DbgValueLoc DbgLocVal(CombinedExpr, DbgValueLocEntry(Val));
625 DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
626 Params.push_back(Elt: CSParm);
627 ++NumCSParams;
628 }
629}
630
631/// Add \p Reg to the worklist, if it's not already present, and mark that the
632/// given parameter registers' values can (potentially) be described using
633/// that register and an debug expression.
634static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
635 const DIExpression *Expr,
636 ArrayRef<FwdRegParamInfo> ParamsToAdd) {
637 auto &ParamsForFwdReg = Worklist[Reg];
638 for (auto Param : ParamsToAdd) {
639 assert(none_of(ParamsForFwdReg,
640 [Param](const FwdRegParamInfo &D) {
641 return D.ParamReg == Param.ParamReg;
642 }) &&
643 "Same parameter described twice by forwarding reg");
644
645 // If a parameter's call site value is produced by a chain of
646 // instructions we may have already created an expression for the
647 // parameter when walking through the instructions. Append that to the
648 // new expression.
649 const DIExpression *CombinedExpr = combineDIExpressions(Original: Expr, Addition: Param.Expr);
650 ParamsForFwdReg.push_back(Elt: {.ParamReg: Param.ParamReg, .Expr: CombinedExpr});
651 }
652}
653
654/// Interpret values loaded into registers by \p CurMI.
655static void interpretValues(const MachineInstr *CurMI,
656 FwdRegWorklist &ForwardedRegWorklist,
657 ParamSet &Params,
658 ClobberedRegUnitSet &ClobberedRegUnits) {
659
660 const MachineFunction *MF = CurMI->getMF();
661 const DIExpression *EmptyExpr =
662 DIExpression::get(Context&: MF->getFunction().getContext(), Elements: {});
663 const auto &TRI = *MF->getSubtarget().getRegisterInfo();
664 const auto &TII = *MF->getSubtarget().getInstrInfo();
665 const auto &TLI = *MF->getSubtarget().getTargetLowering();
666
667 // It's possible that we find a copy from a non-volatile register to the param
668 // register, which is clobbered in the meantime. Test for clobbered reg unit
669 // overlaps before completing.
670 auto IsRegClobberedInMeantime = [&](Register Reg) -> bool {
671 for (auto &RegUnit : ClobberedRegUnits)
672 if (TRI.hasRegUnit(Reg, RegUnit))
673 return true;
674 return false;
675 };
676
677 auto DescribeFwdRegsByCalleeSavedCopy = [&](const DestSourcePair &CopyInst) {
678 Register CopyDestReg = CopyInst.Destination->getReg();
679 Register CopySrcReg = CopyInst.Source->getReg();
680 if (IsRegClobberedInMeantime(CopyDestReg))
681 return;
682 // FIXME: This may be incorrect in cases where the caller and callee use
683 // different calling conventions.
684 if (!TRI.isCalleeSavedPhysReg(PhysReg: CopyDestReg, MF: *MF))
685 return;
686 // Describe any forward registers matching the source register. If the
687 // forward register is a sub-register of the source, we describe it using
688 // the corresponding sub-register in the destination, if such a
689 // sub-register exists. The end iterator in the MapVector is invalidated at
690 // erase(), so it needs to be evaluated at each iteration.
691 for (auto FwdRegIt = ForwardedRegWorklist.begin();
692 FwdRegIt != ForwardedRegWorklist.end();) {
693 Register CalleeSavedReg = MCRegister::NoRegister;
694 if (FwdRegIt->first == CopySrcReg)
695 CalleeSavedReg = CopyDestReg;
696 else if (unsigned SubRegIdx =
697 TRI.getSubRegIndex(RegNo: CopySrcReg, SubRegNo: FwdRegIt->first))
698 if (Register CopyDestSubReg = TRI.getSubReg(Reg: CopyDestReg, Idx: SubRegIdx))
699 CalleeSavedReg = CopyDestSubReg;
700
701 if (CalleeSavedReg == MCRegister::NoRegister) {
702 ++FwdRegIt;
703 continue;
704 }
705
706 MachineLocation MLoc(CalleeSavedReg, /*Indirect=*/false);
707 finishCallSiteParams(Val: MLoc, Expr: EmptyExpr, DescribedParams: FwdRegIt->second, Params);
708 FwdRegIt = ForwardedRegWorklist.erase(Iterator: FwdRegIt);
709 }
710 };
711
712 // Detect if this is a copy instruction. If this saves any of the forward
713 // registers in callee-saved registers, we can finalize those parameters
714 // directly.
715 // TODO: Can we do something similar for stack saves?
716 if (auto CopyInst = TII.isCopyInstr(MI: *CurMI))
717 DescribeFwdRegsByCalleeSavedCopy(*CopyInst);
718
719 // If an instruction defines more than one item in the worklist, we may run
720 // into situations where a worklist register's value is (potentially)
721 // described by the previous value of another register that is also defined
722 // by that instruction.
723 //
724 // This can for example occur in cases like this:
725 //
726 // $r1 = mov 123
727 // $r0, $r1 = mvrr $r1, 456
728 // call @foo, $r0, $r1
729 //
730 // When describing $r1's value for the mvrr instruction, we need to make sure
731 // that we don't finalize an entry value for $r0, as that is dependent on the
732 // previous value of $r1 (123 rather than 456).
733 //
734 // In order to not have to distinguish between those cases when finalizing
735 // entry values, we simply postpone adding new parameter registers to the
736 // worklist, by first keeping them in this temporary container until the
737 // instruction has been handled.
738 FwdRegWorklist TmpWorklistItems;
739
740 // If the MI is an instruction defining one or more parameters' forwarding
741 // registers, add those defines.
742 ClobberedRegUnitSet NewClobberedRegUnits;
743 auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
744 SmallSetVector<unsigned, 4> &Defs) {
745 if (MI.isDebugInstr())
746 return;
747
748 for (const MachineOperand &MO : MI.all_defs()) {
749 if (MO.getReg().isPhysical()) {
750 for (auto &FwdReg : ForwardedRegWorklist)
751 if (TRI.regsOverlap(RegA: FwdReg.first, RegB: MO.getReg()))
752 Defs.insert(X: FwdReg.first);
753 NewClobberedRegUnits.insert_range(R: TRI.regunits(Reg: MO.getReg()));
754 }
755 }
756 };
757
758 // Set of worklist registers that are defined by this instruction.
759 SmallSetVector<unsigned, 4> FwdRegDefs;
760
761 getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
762 if (FwdRegDefs.empty()) {
763 // Any definitions by this instruction will clobber earlier reg movements.
764 ClobberedRegUnits.insert_range(R&: NewClobberedRegUnits);
765 return;
766 }
767
768 for (auto ParamFwdReg : FwdRegDefs) {
769 if (auto ParamValue = TII.describeLoadedValue(MI: *CurMI, Reg: ParamFwdReg)) {
770 if (ParamValue->first.isImm()) {
771 int64_t Val = ParamValue->first.getImm();
772 finishCallSiteParams(Val, Expr: ParamValue->second,
773 DescribedParams: ForwardedRegWorklist[ParamFwdReg], Params);
774 } else if (ParamValue->first.isReg()) {
775 Register RegLoc = ParamValue->first.getReg();
776 Register SP = TLI.getStackPointerRegisterToSaveRestore();
777 Register FP = TRI.getFrameRegister(MF: *MF);
778 bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
779 // FIXME: This may be incorrect in cases where the caller and callee use
780 // different calling conventions.
781 if (!IsRegClobberedInMeantime(RegLoc) &&
782 (TRI.isCalleeSavedPhysReg(PhysReg: RegLoc, MF: *MF) || IsSPorFP)) {
783 MachineLocation MLoc(RegLoc, /*Indirect=*/IsSPorFP);
784 finishCallSiteParams(Val: MLoc, Expr: ParamValue->second,
785 DescribedParams: ForwardedRegWorklist[ParamFwdReg], Params);
786 } else {
787 // ParamFwdReg was described by the non-callee saved register
788 // RegLoc. Mark that the call site values for the parameters are
789 // dependent on that register instead of ParamFwdReg. Since RegLoc
790 // may be a register that will be handled in this iteration, we
791 // postpone adding the items to the worklist, and instead keep them
792 // in a temporary container.
793 addToFwdRegWorklist(Worklist&: TmpWorklistItems, Reg: RegLoc, Expr: ParamValue->second,
794 ParamsToAdd: ForwardedRegWorklist[ParamFwdReg]);
795 }
796 }
797 }
798 }
799
800 // Remove all registers that this instruction defines from the worklist.
801 for (auto ParamFwdReg : FwdRegDefs)
802 ForwardedRegWorklist.erase(Key: ParamFwdReg);
803
804 // Any definitions by this instruction will clobber earlier reg movements.
805 ClobberedRegUnits.insert_range(R&: NewClobberedRegUnits);
806
807 // Now that we are done handling this instruction, add items from the
808 // temporary worklist to the real one.
809 for (auto &New : TmpWorklistItems)
810 addToFwdRegWorklist(Worklist&: ForwardedRegWorklist, Reg: New.first, Expr: EmptyExpr, ParamsToAdd: New.second);
811 TmpWorklistItems.clear();
812}
813
814static bool interpretNextInstr(const MachineInstr *CurMI,
815 FwdRegWorklist &ForwardedRegWorklist,
816 ParamSet &Params,
817 ClobberedRegUnitSet &ClobberedRegUnits) {
818 // Skip bundle headers.
819 if (CurMI->isBundle())
820 return true;
821
822 // If the next instruction is a call we can not interpret parameter's
823 // forwarding registers or we finished the interpretation of all
824 // parameters.
825 if (CurMI->isCall())
826 return false;
827
828 if (ForwardedRegWorklist.empty())
829 return false;
830
831 // Avoid NOP description.
832 if (CurMI->getNumOperands() == 0)
833 return true;
834
835 interpretValues(CurMI, ForwardedRegWorklist, Params, ClobberedRegUnits);
836
837 return true;
838}
839
840/// Try to interpret values loaded into registers that forward parameters
841/// for \p CallMI. Store parameters with interpreted value into \p Params.
842static void collectCallSiteParameters(const MachineInstr *CallMI,
843 ParamSet &Params) {
844 const MachineFunction *MF = CallMI->getMF();
845 const auto &CalleesMap = MF->getCallSitesInfo();
846 auto CSInfo = CalleesMap.find(Val: CallMI);
847
848 // There is no information for the call instruction.
849 if (CSInfo == CalleesMap.end())
850 return;
851
852 const MachineBasicBlock *MBB = CallMI->getParent();
853
854 // Skip the call instruction.
855 auto I = std::next(x: CallMI->getReverseIterator());
856
857 FwdRegWorklist ForwardedRegWorklist;
858
859 const DIExpression *EmptyExpr =
860 DIExpression::get(Context&: MF->getFunction().getContext(), Elements: {});
861
862 // Add all the forwarding registers into the ForwardedRegWorklist.
863 for (const auto &ArgReg : CSInfo->second.ArgRegPairs) {
864 bool InsertedReg =
865 ForwardedRegWorklist.insert(KV: {ArgReg.Reg, {{.ParamReg: ArgReg.Reg, .Expr: EmptyExpr}}})
866 .second;
867 assert(InsertedReg && "Single register used to forward two arguments?");
868 (void)InsertedReg;
869 }
870
871 // Do not emit CSInfo for undef forwarding registers.
872 for (const auto &MO : CallMI->uses())
873 if (MO.isReg() && MO.isUndef())
874 ForwardedRegWorklist.erase(Key: MO.getReg());
875
876 // We erase, from the ForwardedRegWorklist, those forwarding registers for
877 // which we successfully describe a loaded value (by using
878 // the describeLoadedValue()). For those remaining arguments in the working
879 // list, for which we do not describe a loaded value by
880 // the describeLoadedValue(), we try to generate an entry value expression
881 // for their call site value description, if the call is within the entry MBB.
882 // TODO: Handle situations when call site parameter value can be described
883 // as the entry value within basic blocks other than the first one.
884 bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
885
886 // Search for a loading value in forwarding registers inside call delay slot.
887 ClobberedRegUnitSet ClobberedRegUnits;
888 if (CallMI->hasDelaySlot()) {
889 auto Suc = std::next(x: CallMI->getIterator());
890 // Only one-instruction delay slot is supported.
891 auto BundleEnd = llvm::getBundleEnd(I: CallMI->getIterator());
892 (void)BundleEnd;
893 assert(std::next(Suc) == BundleEnd &&
894 "More than one instruction in call delay slot");
895 // Try to interpret value loaded by instruction.
896 if (!interpretNextInstr(CurMI: &*Suc, ForwardedRegWorklist, Params, ClobberedRegUnits))
897 return;
898 }
899
900 // Search for a loading value in forwarding registers.
901 for (; I != MBB->rend(); ++I) {
902 // Try to interpret values loaded by instruction.
903 if (!interpretNextInstr(CurMI: &*I, ForwardedRegWorklist, Params, ClobberedRegUnits))
904 return;
905 }
906
907 // Emit the call site parameter's value as an entry value.
908 if (ShouldTryEmitEntryVals) {
909 // Create an expression where the register's entry value is used.
910 DIExpression *EntryExpr = DIExpression::get(
911 Context&: MF->getFunction().getContext(), Elements: {dwarf::DW_OP_LLVM_entry_value, 1});
912 for (auto &RegEntry : ForwardedRegWorklist) {
913 MachineLocation MLoc(RegEntry.first);
914 finishCallSiteParams(Val: MLoc, Expr: EntryExpr, DescribedParams: RegEntry.second, Params);
915 }
916 }
917}
918
919void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
920 DwarfCompileUnit &CU, DIE &ScopeDIE,
921 const MachineFunction &MF) {
922 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
923 // the subprogram is required to have one.
924 if (!SP.areAllCallsDescribed() || !SP.isDefinition())
925 return;
926
927 // Use DW_AT_call_all_calls to express that call site entries are present
928 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
929 // because one of its requirements is not met: call site entries for
930 // optimized-out calls are elided.
931 CU.addFlag(Die&: ScopeDIE, Attribute: CU.getDwarf5OrGNUAttr(Attr: dwarf::DW_AT_call_all_calls));
932
933 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
934 assert(TII && "TargetInstrInfo not found: cannot label tail calls");
935
936 // Delay slot support check.
937 auto delaySlotSupported = [&](const MachineInstr &MI) {
938 if (!MI.isBundledWithSucc())
939 return false;
940 auto Suc = std::next(x: MI.getIterator());
941 auto CallInstrBundle = getBundleStart(I: MI.getIterator());
942 (void)CallInstrBundle;
943 auto DelaySlotBundle = getBundleStart(I: Suc);
944 (void)DelaySlotBundle;
945 // Ensure that label after call is following delay slot instruction.
946 // Ex. CALL_INSTRUCTION {
947 // DELAY_SLOT_INSTRUCTION }
948 // LABEL_AFTER_CALL
949 assert(getLabelAfterInsn(&*CallInstrBundle) ==
950 getLabelAfterInsn(&*DelaySlotBundle) &&
951 "Call and its successor instruction don't have same label after.");
952 return true;
953 };
954
955 // Create call_target connections for indirect calls.
956 auto addCallSiteTargetForIndirectCalls = [&](const MachineInstr *MI,
957 DIE &CallSiteDIE) {
958 const MachineFunction *MF = MI->getMF();
959 const auto &CalleesMap = MF->getCallSitesInfo();
960 auto CSInfo = CalleesMap.find(Val: MI);
961 // Get the information for the call instruction.
962 if (CSInfo == CalleesMap.end() || !CSInfo->second.CallTarget)
963 return;
964
965 MDNode *CallTarget = CSInfo->second.CallTarget;
966 // Add DW_AT_LLVM_virtual_call_origin with the 'call_target' metadata.
967 assert(!CallSiteDIE.findAttribute(dwarf::DW_AT_LLVM_virtual_call_origin) &&
968 "DW_AT_LLVM_virtual_call_origin already exists");
969 const DISubprogram *CalleeSP = dyn_cast<DISubprogram>(Val: CallTarget);
970 DIE *CalleeDIE = CU.getOrCreateSubprogramDIE(SP: CalleeSP, F: nullptr);
971 assert(CalleeDIE && "Could not create DIE for call site entry origin");
972 CU.addDIEEntry(Die&: CallSiteDIE,
973 Attribute: CU.getDwarf5OrGNUAttr(Attr: dwarf::DW_AT_LLVM_virtual_call_origin),
974 Entry&: *CalleeDIE);
975 // Add DW_AT_linkage_name to the method declaration if needed.
976 CU.addLinkageNamesToDeclarations(DD: *this, CalleeSP: *CalleeSP, CalleeDIE&: *CalleeDIE);
977 };
978
979 // Emit call site entries for each call or tail call in the function.
980 for (const MachineBasicBlock &MBB : MF) {
981 for (const MachineInstr &MI : MBB.instrs()) {
982 // Bundles with call in them will pass the isCall() test below but do not
983 // have callee operand information so skip them here. Iterator will
984 // eventually reach the call MI.
985 if (MI.isBundle())
986 continue;
987
988 // Skip instructions which aren't calls. Both calls and tail-calling jump
989 // instructions (e.g TAILJMPd64) are classified correctly here.
990 if (!MI.isCandidateForAdditionalCallInfo())
991 continue;
992
993 // Skip instructions marked as frame setup, as they are not interesting to
994 // the user.
995 if (MI.getFlag(Flag: MachineInstr::FrameSetup))
996 continue;
997
998 // Check if delay slot support is enabled.
999 if (MI.hasDelaySlot() && !delaySlotSupported(*&MI))
1000 return;
1001
1002 DIType *AllocSiteTy = dyn_cast_or_null<DIType>(Val: MI.getHeapAllocMarker());
1003
1004 // If this is a direct call, find the callee's subprogram.
1005 // In the case of an indirect call find the register or memory location
1006 // that holds the callee address.
1007 const MachineOperand &CalleeOp = TII->getCalleeOperand(MI);
1008 bool PhysRegCalleeOperand =
1009 CalleeOp.isReg() && CalleeOp.getReg().isPhysical();
1010 MachineLocation CallTarget{0};
1011 int64_t Offset = 0;
1012 const DISubprogram *CalleeSP = nullptr;
1013 const Function *CalleeDecl = nullptr;
1014 if (PhysRegCalleeOperand) {
1015 bool Scalable = false;
1016 const MachineOperand *BaseOp = nullptr;
1017 const TargetRegisterInfo &TRI =
1018 *Asm->MF->getSubtarget().getRegisterInfo();
1019 if (TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable&: Scalable, TRI: &TRI)) {
1020 if (BaseOp && BaseOp->isReg() && !Scalable)
1021 CallTarget = MachineLocation(BaseOp->getReg(), /*Indirect*/ true);
1022 }
1023
1024 if (!CallTarget.isIndirect())
1025 CallTarget = MachineLocation(CalleeOp.getReg()); // Might be zero.
1026 } else if (CalleeOp.isGlobal()) {
1027 CalleeDecl = dyn_cast<Function>(Val: CalleeOp.getGlobal());
1028 if (CalleeDecl)
1029 CalleeSP = CalleeDecl->getSubprogram(); // might be nullptr
1030 }
1031
1032 // Omit DIE if we can't tell where the call goes *and* we don't want to
1033 // add metadata to it.
1034 if (CalleeSP == nullptr && CallTarget.getReg() == 0 &&
1035 AllocSiteTy == nullptr)
1036 continue;
1037
1038 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
1039
1040 bool IsTail = TII->isTailCall(Inst: MI);
1041
1042 // If MI is in a bundle, the label was created after the bundle since
1043 // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
1044 // to search for that label below.
1045 const MachineInstr *TopLevelCallMI =
1046 MI.isInsideBundle() ? &*getBundleStart(I: MI.getIterator()) : &MI;
1047
1048 // For non-tail calls, the return PC is needed to disambiguate paths in
1049 // the call graph which could lead to some target function. For tail
1050 // calls, no return PC information is needed, unless tuning for GDB in
1051 // DWARF4 mode in which case we fake a return PC for compatibility.
1052 const MCSymbol *PCAddr = (!IsTail || CU.useGNUAnalogForDwarf5Feature())
1053 ? getLabelAfterInsn(MI: TopLevelCallMI)
1054 : nullptr;
1055
1056 // For tail calls, it's necessary to record the address of the branch
1057 // instruction so that the debugger can show where the tail call occurred.
1058 const MCSymbol *CallAddr =
1059 IsTail ? getLabelBeforeInsn(MI: TopLevelCallMI) : nullptr;
1060
1061 assert((IsTail || PCAddr) && "Non-tail call without return PC");
1062
1063 LLVM_DEBUG(
1064 dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
1065 << (CalleeDecl
1066 ? CalleeDecl->getName()
1067 : StringRef(
1068 MF.getSubtarget().getRegisterInfo()->getName(
1069 CallTarget.getReg())))
1070 << (IsTail ? " [IsTail]" : "") << "\n");
1071
1072 DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(
1073 ScopeDIE, CalleeSP, CalleeF: CalleeDecl, IsTail, PCAddr, CallAddr, CallTarget,
1074 Offset, AllocSiteTy);
1075
1076 if (CallTarget.getReg())
1077 addCallSiteTargetForIndirectCalls(TopLevelCallMI, CallSiteDIE);
1078
1079 // Optionally emit call-site-param debug info.
1080 if (emitDebugEntryValues()) {
1081 ParamSet Params;
1082 // Try to interpret values of call site parameters.
1083 collectCallSiteParameters(CallMI: &MI, Params);
1084 CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
1085 }
1086 }
1087 }
1088}
1089
1090void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
1091 if (!U.hasDwarfPubSections())
1092 return;
1093
1094 U.addFlag(Die&: D, Attribute: dwarf::DW_AT_GNU_pubnames);
1095}
1096
1097static bool isLangCaseSensitive(const DISourceLanguageName &Lang) {
1098 if (Lang.hasVersionedName()) {
1099 switch (Lang.getName()) {
1100 case dwarf::DW_LNAME_Fortran:
1101 case dwarf::DW_LNAME_Cobol:
1102 case dwarf::DW_LNAME_Pascal:
1103 return false;
1104 default:
1105 return true;
1106 }
1107 }
1108 switch (Lang.getName()) {
1109 case dwarf::DW_LANG_Cobol74:
1110 case dwarf::DW_LANG_Cobol85:
1111 case dwarf::DW_LANG_Fortran77:
1112 case dwarf::DW_LANG_Fortran90:
1113 case dwarf::DW_LANG_Fortran95:
1114 case dwarf::DW_LANG_Fortran03:
1115 case dwarf::DW_LANG_Fortran08:
1116 case dwarf::DW_LANG_Fortran18:
1117 case dwarf::DW_LANG_Fortran23:
1118 case dwarf::DW_LANG_Pascal83:
1119 return false;
1120 default:
1121 return true;
1122 }
1123}
1124
1125void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
1126 DwarfCompileUnit &NewCU) {
1127 DIE &Die = NewCU.getUnitDie();
1128 StringRef FN = DIUnit->getFilename();
1129
1130 StringRef Producer = DIUnit->getProducer();
1131 StringRef Flags = DIUnit->getFlags();
1132 if (!Flags.empty() && !useAppleExtensionAttributes()) {
1133 std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
1134 NewCU.addString(Die, Attribute: dwarf::DW_AT_producer, Str: ProducerWithFlags);
1135 } else
1136 NewCU.addString(Die, Attribute: dwarf::DW_AT_producer, Str: Producer);
1137
1138 if (auto Lang = DIUnit->getSourceLanguage(); Lang.hasVersionedName()) {
1139 NewCU.addUInt(Die, Attribute: dwarf::DW_AT_language_name, Form: dwarf::DW_FORM_data2,
1140 Integer: Lang.getName());
1141
1142 if (uint32_t LangVersion = Lang.getVersion(); LangVersion != 0)
1143 NewCU.addUInt(Die, Attribute: dwarf::DW_AT_language_version, /*Form=*/std::nullopt,
1144 Integer: LangVersion);
1145 } else {
1146 NewCU.addUInt(Die, Attribute: dwarf::DW_AT_language, Form: dwarf::DW_FORM_data2,
1147 Integer: Lang.getName());
1148 }
1149
1150 if (!isLangCaseSensitive(Lang: DIUnit->getSourceLanguage()))
1151 NewCU.addUInt(Die, Attribute: dwarf::DW_AT_identifier_case, Form: dwarf::DW_FORM_data1,
1152 Integer: dwarf::DW_ID_case_insensitive);
1153 NewCU.addString(Die, Attribute: dwarf::DW_AT_name, Str: FN);
1154
1155 finishTargetUnitAttributes(DIUnit: *DIUnit, NewCU);
1156
1157 StringRef SysRoot = DIUnit->getSysRoot();
1158 if (!SysRoot.empty())
1159 NewCU.addString(Die, Attribute: dwarf::DW_AT_LLVM_sysroot, Str: SysRoot);
1160 StringRef SDK = DIUnit->getSDK();
1161 if (!SDK.empty())
1162 NewCU.addString(Die, Attribute: dwarf::DW_AT_APPLE_sdk, Str: SDK);
1163
1164 if (!useSplitDwarf()) {
1165 // Add DW_str_offsets_base to the unit DIE, except for split units.
1166 if (useSegmentedStringOffsetsTable())
1167 NewCU.addStringOffsetsStart();
1168
1169 NewCU.initStmtList();
1170
1171 // If we're using split dwarf the compilation dir is going to be in the
1172 // skeleton CU and so we don't need to duplicate it here.
1173 if (!CompilationDir.empty())
1174 NewCU.addString(Die, Attribute: dwarf::DW_AT_comp_dir, Str: CompilationDir);
1175 addGnuPubAttributes(U&: NewCU, D&: Die);
1176 }
1177
1178 if (DIUnit->isOptimized())
1179 NewCU.addFlag(Die, Attribute: dwarf::DW_AT_APPLE_optimized);
1180
1181 if (useAppleExtensionAttributes()) {
1182 StringRef Flags = DIUnit->getFlags();
1183 if (!Flags.empty())
1184 NewCU.addString(Die, Attribute: dwarf::DW_AT_APPLE_flags, Str: Flags);
1185
1186 if (unsigned RVer = DIUnit->getRuntimeVersion())
1187 NewCU.addUInt(Die, Attribute: dwarf::DW_AT_APPLE_major_runtime_vers,
1188 Form: dwarf::DW_FORM_data1, Integer: RVer);
1189 }
1190
1191 if (DIUnit->getDWOId()) {
1192 // This CU is either a clang module DWO or a skeleton CU.
1193 NewCU.addUInt(Die, Attribute: dwarf::DW_AT_GNU_dwo_id, Form: dwarf::DW_FORM_data8,
1194 Integer: DIUnit->getDWOId());
1195 if (!DIUnit->getSplitDebugFilename().empty()) {
1196 // This is a prefabricated skeleton CU.
1197 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1198 ? dwarf::DW_AT_dwo_name
1199 : dwarf::DW_AT_GNU_dwo_name;
1200 NewCU.addString(Die, Attribute: attrDWOName, Str: DIUnit->getSplitDebugFilename());
1201 }
1202 }
1203}
1204
1205DwarfCompileUnit *DwarfDebug::getDwarfCompileUnit(const DICompileUnit *DIUnit) {
1206 if (auto *CU = CUMap.lookup(Key: DIUnit))
1207 return CU;
1208
1209 if (useSplitDwarf() && !shareAcrossDWOCUs() &&
1210 (!DIUnit->getSplitDebugInlining() ||
1211 DIUnit->getEmissionKind() == DICompileUnit::FullDebug) &&
1212 !CUMap.empty())
1213 return CUMap.begin()->second;
1214
1215 return nullptr;
1216}
1217
1218// Create new DwarfCompileUnit for the given metadata node with tag
1219// DW_TAG_compile_unit.
1220DwarfCompileUnit &
1221DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
1222 if (auto *CU = getDwarfCompileUnit(DIUnit))
1223 return *CU;
1224
1225 CompilationDir = DIUnit->getDirectory();
1226
1227 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
1228 args: InfoHolder.getUnits().size(), args&: DIUnit, args&: Asm, args: this, args: &InfoHolder);
1229 DwarfCompileUnit &NewCU = *OwnedUnit;
1230 InfoHolder.addUnit(U: std::move(OwnedUnit));
1231
1232 // LTO with assembly output shares a single line table amongst multiple CUs.
1233 // To avoid the compilation directory being ambiguous, let the line table
1234 // explicitly describe the directory of all files, never relying on the
1235 // compilation directory.
1236 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
1237 Asm->OutStreamer->emitDwarfFile0Directive(
1238 Directory: CompilationDir, Filename: DIUnit->getFilename(), Checksum: getMD5AsBytes(File: DIUnit->getFile()),
1239 Source: DIUnit->getSource(), CUID: NewCU.getUniqueID());
1240
1241 if (useSplitDwarf()) {
1242 NewCU.setSkeleton(constructSkeletonCU(CU: NewCU));
1243 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
1244 } else {
1245 finishUnitAttributes(DIUnit, NewCU);
1246 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
1247 }
1248
1249 CUMap.insert(KV: {DIUnit, &NewCU});
1250 CUDieMap.insert(KV: {&NewCU.getUnitDie(), &NewCU});
1251 return NewCU;
1252}
1253
1254/// Sort and unique GVEs by comparing their fragment offset.
1255static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
1256sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
1257 llvm::sort(
1258 C&: GVEs, Comp: [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
1259 // Sort order: first null exprs, then exprs without fragment
1260 // info, then sort by fragment offset in bits.
1261 // FIXME: Come up with a more comprehensive comparator so
1262 // the sorting isn't non-deterministic, and so the following
1263 // std::unique call works correctly.
1264 if (!A.Expr || !B.Expr)
1265 return !!B.Expr;
1266 auto FragmentA = A.Expr->getFragmentInfo();
1267 auto FragmentB = B.Expr->getFragmentInfo();
1268 if (!FragmentA || !FragmentB)
1269 return !!FragmentB;
1270 return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
1271 });
1272 GVEs.erase(CS: llvm::unique(R&: GVEs,
1273 P: [](DwarfCompileUnit::GlobalExpr A,
1274 DwarfCompileUnit::GlobalExpr B) {
1275 return A.Expr == B.Expr;
1276 }),
1277 CE: GVEs.end());
1278 return GVEs;
1279}
1280
1281// Emit all Dwarf sections that should come prior to the content. Create
1282// global DIEs and emit initial debug info sections. This is invoked by
1283// the target AsmPrinter.
1284void DwarfDebug::beginModule(Module *M) {
1285 DebugHandlerBase::beginModule(M);
1286
1287 if (!Asm)
1288 return;
1289
1290 unsigned NumDebugCUs = std::distance(first: M->debug_compile_units_begin(),
1291 last: M->debug_compile_units_end());
1292 if (NumDebugCUs == 0)
1293 return;
1294
1295 assert(NumDebugCUs > 0 && "Asm unexpectedly initialized");
1296 SingleCU = NumDebugCUs == 1;
1297
1298 // Create the symbol that designates the start of the unit's contribution
1299 // to the string offsets table. In a split DWARF scenario, only the skeleton
1300 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
1301 if (useSegmentedStringOffsetsTable())
1302 (useSplitDwarf() ? SkeletonHolder : InfoHolder)
1303 .setStringOffsetsStartSym(Asm->createTempSymbol(Name: "str_offsets_base"));
1304
1305
1306 // Create the symbols that designates the start of the DWARF v5 range list
1307 // and locations list tables. They are located past the table headers.
1308 if (getDwarfVersion() >= 5) {
1309 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1310 Holder.setRnglistsTableBaseSym(
1311 Asm->createTempSymbol(Name: "rnglists_table_base"));
1312
1313 if (useSplitDwarf())
1314 InfoHolder.setRnglistsTableBaseSym(
1315 Asm->createTempSymbol(Name: "rnglists_dwo_table_base"));
1316 }
1317
1318 // Create the symbol that points to the first entry following the debug
1319 // address table (.debug_addr) header.
1320 AddrPool.setLabel(Asm->createTempSymbol(Name: "addr_table_base"));
1321 DebugLocs.setSym(Asm->createTempSymbol(Name: "loclists_table_base"));
1322
1323 for (DICompileUnit *CUNode : M->debug_compile_units()) {
1324 if (CUNode->getImportedEntities().empty() &&
1325 CUNode->getEnumTypes().empty() && CUNode->getRetainedTypes().empty() &&
1326 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1327 continue;
1328
1329 getOrCreateDwarfCompileUnit(DIUnit: CUNode);
1330 }
1331}
1332
1333void DwarfDebug::finishEntityDefinitions() {
1334 for (const auto &Entity : ConcreteEntities) {
1335 DIE *Die = Entity->getDIE();
1336 assert(Die);
1337 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1338 // in the ConcreteEntities list, rather than looking it up again here.
1339 // DIE::getUnit isn't simple - it walks parent pointers, etc.
1340 DwarfCompileUnit *Unit = CUDieMap.lookup(Val: Die->getUnitDie());
1341 assert(Unit);
1342 Unit->finishEntityDefinition(Entity: Entity.get());
1343 }
1344}
1345
1346void DwarfDebug::finishSubprogramDefinitions() {
1347 for (const DISubprogram *SP : ProcessedSPNodes) {
1348 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
1349 forBothCUs(
1350 CU&: getOrCreateDwarfCompileUnit(DIUnit: SP->getUnit()),
1351 F: [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1352 }
1353}
1354
1355void DwarfDebug::finalizeModuleInfo() {
1356 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1357
1358 finishSubprogramDefinitions();
1359
1360 finishEntityDefinitions();
1361
1362 bool HasEmittedSplitCU = false;
1363
1364 // Handle anything that needs to be done on a per-unit basis after
1365 // all other generation.
1366 for (const auto &P : CUMap) {
1367 auto &TheCU = *P.second;
1368 if (TheCU.getCUNode()->isDebugDirectivesOnly())
1369 continue;
1370 TheCU.attachLexicalScopesAbstractOrigins();
1371 // Emit DW_AT_containing_type attribute to connect types with their
1372 // vtable holding type.
1373 TheCU.constructContainingTypeDIEs();
1374 TheCU.constructPropertyForwardDIEs();
1375
1376 // Add CU specific attributes if we need to add any.
1377 // If we're splitting the dwarf out now that we've got the entire
1378 // CU then add the dwo id to it.
1379 auto *SkCU = TheCU.getSkeleton();
1380
1381 bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1382
1383 if (HasSplitUnit) {
1384 (void)HasEmittedSplitCU;
1385 assert((shareAcrossDWOCUs() || !HasEmittedSplitCU) &&
1386 "Multiple CUs emitted into a single dwo file");
1387 HasEmittedSplitCU = true;
1388 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1389 ? dwarf::DW_AT_dwo_name
1390 : dwarf::DW_AT_GNU_dwo_name;
1391 finishUnitAttributes(DIUnit: TheCU.getCUNode(), NewCU&: TheCU);
1392 StringRef DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
1393 TheCU.addString(Die&: TheCU.getUnitDie(), Attribute: attrDWOName, Str: DWOName);
1394 SkCU->addString(Die&: SkCU->getUnitDie(), Attribute: attrDWOName, Str: DWOName);
1395 // Emit a unique identifier for this CU. Include the DWO file name in the
1396 // hash to avoid the case where two (almost) empty compile units have the
1397 // same contents. This can happen if link-time optimization removes nearly
1398 // all (unused) code from a CU.
1399 uint64_t ID =
1400 DIEHash(Asm, &TheCU).computeCUSignature(DWOName, Die: TheCU.getUnitDie());
1401 if (getDwarfVersion() >= 5) {
1402 TheCU.setDWOId(ID);
1403 SkCU->setDWOId(ID);
1404 } else {
1405 TheCU.addUInt(Die&: TheCU.getUnitDie(), Attribute: dwarf::DW_AT_GNU_dwo_id,
1406 Form: dwarf::DW_FORM_data8, Integer: ID);
1407 SkCU->addUInt(Die&: SkCU->getUnitDie(), Attribute: dwarf::DW_AT_GNU_dwo_id,
1408 Form: dwarf::DW_FORM_data8, Integer: ID);
1409 }
1410
1411 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1412 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
1413 SkCU->addSectionLabel(Die&: SkCU->getUnitDie(), Attribute: dwarf::DW_AT_GNU_ranges_base,
1414 Label: Sym, Sec: Sym);
1415 }
1416 } else if (SkCU) {
1417 finishUnitAttributes(DIUnit: SkCU->getCUNode(), NewCU&: *SkCU);
1418 }
1419
1420 // If we have code split among multiple sections or non-contiguous
1421 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1422 // remain in the .o file, otherwise add a DW_AT_low_pc.
1423 // FIXME: We should use ranges allow reordering of code ala
1424 // .subsections_via_symbols in mach-o. This would mean turning on
1425 // ranges for all subprogram DIEs for mach-o.
1426 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1427
1428 if (unsigned NumRanges = TheCU.getRanges().size()) {
1429 if (shouldAttachCompileUnitRanges()) {
1430 if (NumRanges > 1 && useRangesSection())
1431 // A DW_AT_low_pc attribute may also be specified in combination with
1432 // DW_AT_ranges to specify the default base address for use in
1433 // location lists (see Section 2.6.2) and range lists (see Section
1434 // 2.17.3).
1435 U.addUInt(Die&: U.getUnitDie(), Attribute: dwarf::DW_AT_low_pc, Form: dwarf::DW_FORM_addr,
1436 Integer: 0);
1437 else
1438 U.setBaseAddress(TheCU.getRanges().front().Begin);
1439 U.attachRangesOrLowHighPC(D&: U.getUnitDie(), Ranges: TheCU.takeRanges());
1440 }
1441 }
1442
1443 // We don't keep track of which addresses are used in which CU so this
1444 // is a bit pessimistic under LTO.
1445 if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
1446 U.addAddrTableBase();
1447
1448 if (getDwarfVersion() >= 5) {
1449 if (U.hasRangeLists())
1450 U.addRnglistsBase();
1451
1452 if (!DebugLocs.getLists().empty() && !useSplitDwarf()) {
1453 U.addSectionLabel(Die&: U.getUnitDie(), Attribute: dwarf::DW_AT_loclists_base,
1454 Label: DebugLocs.getSym(),
1455 Sec: TLOF.getDwarfLoclistsSection()->getBeginSymbol());
1456 }
1457 }
1458
1459 auto *CUNode = cast<DICompileUnit>(Val: P.first);
1460 // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
1461 // attribute.
1462 if (CUNode->getMacros()) {
1463 DwarfCompileUnit &CompileUnit = useSplitDwarf() ? TheCU : U;
1464 if (UseDebugMacroSection) {
1465 const MCSymbol *Section =
1466 useSplitDwarf() ? TLOF.getDwarfMacroDWOSection()->getBeginSymbol()
1467 : TLOF.getDwarfMacroSection()->getBeginSymbol();
1468 dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5 || useSplitDwarf()
1469 ? dwarf::DW_AT_macros
1470 : dwarf::DW_AT_GNU_macros;
1471 CompileUnit.addSectionLabel(Die&: CompileUnit.getUnitDie(), Attribute: MacrosAttr,
1472 Label: U.getMacroLabelBegin(), Sec: Section);
1473 } else {
1474 const MCSymbol *Section =
1475 useSplitDwarf() ? TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol()
1476 : TLOF.getDwarfMacinfoSection()->getBeginSymbol();
1477 CompileUnit.addSectionLabel(Die&: CompileUnit.getUnitDie(),
1478 Attribute: dwarf::DW_AT_macro_info,
1479 Label: U.getMacroLabelBegin(), Sec: Section);
1480 }
1481 }
1482 }
1483
1484 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1485 for (auto *CUNode : MMI->getModule()->debug_compile_units())
1486 if (CUNode->getDWOId())
1487 getOrCreateDwarfCompileUnit(DIUnit: CUNode);
1488
1489 // Compute DIE offsets and sizes.
1490 InfoHolder.computeSizeAndOffsets();
1491 if (useSplitDwarf())
1492 SkeletonHolder.computeSizeAndOffsets();
1493
1494 // Now that offsets are computed, can replace DIEs in debug_names Entry with
1495 // an actual offset.
1496 AccelDebugNames.convertDieToOffset();
1497}
1498
1499// Emit all Dwarf sections that should come after the content.
1500void DwarfDebug::endModule() {
1501 // Terminate the pending line table.
1502 if (PrevCU)
1503 terminateLineTable(CU: PrevCU);
1504 PrevCU = nullptr;
1505 assert(CurFn == nullptr);
1506 assert(CurMI == nullptr);
1507
1508 const Module *M = MMI->getModule();
1509
1510 // Collect global variables info.
1511 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
1512 GVMap;
1513 for (const GlobalVariable &Global : M->globals()) {
1514 SmallVector<DIGlobalVariableExpression *, 1> GVs;
1515 Global.getDebugInfo(GVs);
1516 for (auto *GVE : GVs)
1517 GVMap[GVE->getVariable()].push_back(Elt: {.Var: &Global, .Expr: GVE->getExpression()});
1518 }
1519
1520 for (DICompileUnit *CUNode : M->debug_compile_units()) {
1521 DwarfCompileUnit *CU = getDwarfCompileUnit(DIUnit: CUNode);
1522
1523 // If the CU hasn't been emitted yet, it must be empty. Skip it.
1524 if (!CU)
1525 continue;
1526
1527 // Emit Global Variables.
1528 for (auto *GVE : CUNode->getGlobalVariables()) {
1529 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1530 // already know about the variable and it isn't adding a constant
1531 // expression.
1532 auto &GVMapEntry = GVMap[GVE->getVariable()];
1533 auto *Expr = GVE->getExpression();
1534 if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1535 GVMapEntry.push_back(Elt: {.Var: nullptr, .Expr: Expr});
1536 }
1537 DenseSet<DIGlobalVariable *> Processed;
1538 for (auto *GVE : CUNode->getGlobalVariables()) {
1539 DIGlobalVariable *GV = GVE->getVariable();
1540 assert(!isa_and_nonnull<DILocalScope>(GV->getScope()) &&
1541 "Unexpected function-local entity in 'globals' CU field.");
1542 if (Processed.insert(V: GV).second)
1543 CU->getOrCreateGlobalVariableDIE(GV, GlobalExprs: sortGlobalExprs(GVEs&: GVMap[GV]));
1544 }
1545
1546 // Emit types.
1547 for (auto *Ty : CUNode->getEnumTypes()) {
1548 assert(!isa_and_nonnull<DILocalScope>(Ty->getScope()) &&
1549 "Unexpected function-local entity in 'enums' CU field.");
1550 CU->getOrCreateTypeDIE(TyNode: cast<DIType>(Val: Ty));
1551 }
1552
1553 for (auto *Ty : CUNode->getRetainedTypes()) {
1554 if (DIType *RT = dyn_cast<DIType>(Val: Ty)) {
1555 // There is no point in force-emitting a forward declaration.
1556 CU->getOrCreateTypeDIE(TyNode: RT);
1557 }
1558 }
1559
1560 // Emit imported entities.
1561 for (auto *IE : CUNode->getImportedEntities()) {
1562 assert(!isa_and_nonnull<DILocalScope>(IE->getScope()) &&
1563 "Unexpected function-local entity in 'imports' CU field.");
1564 CU->getOrCreateImportedEntityDIE(IE);
1565 }
1566
1567 // Emit function-local entities.
1568 const auto Unexpected = [](const Metadata *N) {
1569 llvm_unreachable("Unexpected local retained node!");
1570 };
1571 for (const auto *D : CU->getDeferredLocalDecls())
1572 DISubprogram::visitRetainedNode<void>(
1573 N: D, FuncLV: Unexpected, FuncLabel: Unexpected,
1574 FuncIE: [CU](const auto *IE) { CU->getOrCreateImportedEntityDIE(IE); },
1575 FuncType: [CU](const auto *Ty) { CU->getOrCreateTypeDIE(TyNode: Ty); },
1576 FuncGVE: [&](const auto *GVE) {
1577 DIGlobalVariable *GV = GVE->getVariable();
1578 if (Processed.insert(V: GV).second)
1579 CU->getOrCreateGlobalVariableDIE(GV, GlobalExprs: sortGlobalExprs(GVEs&: GVMap[GV]));
1580 },
1581 FuncUnknown: Unexpected);
1582
1583 // Emit base types.
1584 CU->createBaseTypeDIEs();
1585 }
1586
1587 // If we aren't actually generating debug info (check beginModule -
1588 // conditionalized on the presence of the llvm.dbg.cu metadata node)
1589 if (!Asm || !Asm->hasDebugInfo())
1590 return;
1591
1592 // Finalize the debug info for the module.
1593 finalizeModuleInfo();
1594
1595 if (useSplitDwarf())
1596 // Emit debug_loc.dwo/debug_loclists.dwo section.
1597 emitDebugLocDWO();
1598 else
1599 // Emit debug_loc/debug_loclists section.
1600 emitDebugLoc();
1601
1602 // Corresponding abbreviations into a abbrev section.
1603 emitAbbreviations();
1604
1605 // Emit all the DIEs into a debug info section.
1606 emitDebugInfo();
1607
1608 // Emit info into a debug aranges section.
1609 if (UseARangesSection)
1610 emitDebugARanges();
1611
1612 // Emit info into a debug ranges section.
1613 emitDebugRanges();
1614
1615 if (useSplitDwarf())
1616 // Emit info into a debug macinfo.dwo section.
1617 emitDebugMacinfoDWO();
1618 else
1619 // Emit info into a debug macinfo/macro section.
1620 emitDebugMacinfo();
1621
1622 emitDebugStr();
1623
1624 if (useSplitDwarf()) {
1625 emitDebugStrDWO();
1626 emitDebugInfoDWO();
1627 emitDebugAbbrevDWO();
1628 emitDebugLineDWO();
1629 emitDebugRangesDWO();
1630 }
1631
1632 emitDebugAddr();
1633
1634 // Emit info into the dwarf accelerator table sections.
1635 switch (getAccelTableKind()) {
1636 case AccelTableKind::Apple:
1637 emitAccelNames();
1638 emitAccelObjC();
1639 emitAccelNamespaces();
1640 emitAccelTypes();
1641 break;
1642 case AccelTableKind::Dwarf:
1643 emitAccelDebugNames();
1644 break;
1645 case AccelTableKind::None:
1646 break;
1647 case AccelTableKind::Default:
1648 llvm_unreachable("Default should have already been resolved.");
1649 }
1650
1651 // Emit the pubnames and pubtypes sections if requested.
1652 emitDebugPubSections();
1653
1654 // clean up.
1655 // FIXME: AbstractVariables.clear();
1656}
1657
1658void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1659 const DINode *Node, const MDNode *ScopeNode) {
1660 if (CU.getExistingAbstractEntity(Node))
1661 return;
1662
1663 if (LexicalScope *Scope =
1664 LScopes.findAbstractScope(N: cast_or_null<DILocalScope>(Val: ScopeNode)))
1665 CU.createAbstractEntity(Node, Scope);
1666}
1667
1668static const DILocalScope *getRetainedNodeScope(const MDNode *N) {
1669 // Ensure the scope is not a DILexicalBlockFile.
1670 return DISubprogram::getRetainedNodeScope(N)->getNonLexicalBlockFileScope();
1671}
1672
1673// Collect variable information from side table maintained by MF.
1674void DwarfDebug::collectVariableInfoFromMFTable(
1675 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1676 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1677 LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
1678 for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1679 if (!VI.Var)
1680 continue;
1681 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1682 "Expected inlined-at fields to agree");
1683
1684 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1685 Processed.insert(V: Var);
1686 LexicalScope *Scope = LScopes.findLexicalScope(DL: VI.Loc);
1687
1688 // If variable scope is not found then skip this variable.
1689 if (!Scope) {
1690 LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1691 << ", no variable scope found\n");
1692 continue;
1693 }
1694
1695 ensureAbstractEntityIsCreatedIfScoped(CU&: TheCU, Node: Var.first, ScopeNode: Scope->getScopeNode());
1696
1697 // If we have already seen information for this variable, add to what we
1698 // already know.
1699 if (DbgVariable *PreviousLoc = MFVars.lookup(Val: Var)) {
1700 auto *PreviousMMI = std::get_if<Loc::MMI>(ptr: PreviousLoc);
1701 auto *PreviousEntryValue = std::get_if<Loc::EntryValue>(ptr: PreviousLoc);
1702 // Previous and new locations are both stack slots (MMI).
1703 if (PreviousMMI && VI.inStackSlot())
1704 PreviousMMI->addFrameIndexExpr(Expr: VI.Expr, FI: VI.getStackSlot());
1705 // Previous and new locations are both entry values.
1706 else if (PreviousEntryValue && VI.inEntryValueRegister())
1707 PreviousEntryValue->addExpr(Reg: VI.getEntryValueRegister(), Expr: *VI.Expr);
1708 else {
1709 // Locations differ, this should (rarely) happen in optimized async
1710 // coroutines.
1711 // Prefer whichever location has an EntryValue.
1712 if (PreviousLoc->holds<Loc::MMI>())
1713 PreviousLoc->emplace<Loc::EntryValue>(args: VI.getEntryValueRegister(),
1714 args: *VI.Expr);
1715 LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1716 << ", conflicting fragment location types\n");
1717 }
1718 continue;
1719 }
1720
1721 auto RegVar = std::make_unique<DbgVariable>(
1722 args: cast<DILocalVariable>(Val: Var.first), args&: Var.second);
1723 if (VI.inStackSlot())
1724 RegVar->emplace<Loc::MMI>(args: VI.Expr, args: VI.getStackSlot());
1725 else
1726 RegVar->emplace<Loc::EntryValue>(args: VI.getEntryValueRegister(), args: *VI.Expr);
1727 LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
1728 << "\n");
1729 InfoHolder.addScopeVariable(LS: Scope, Var: RegVar.get());
1730 MFVars.insert(KV: {Var, RegVar.get()});
1731 ConcreteEntities.push_back(Elt: std::move(RegVar));
1732 }
1733}
1734
1735/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1736/// enclosing lexical scope. The check ensures there are no other instructions
1737/// in the same lexical scope preceding the DBG_VALUE and that its range is
1738/// either open or otherwise rolls off the end of the scope.
1739static bool validThroughout(LexicalScopes &LScopes,
1740 const MachineInstr *DbgValue,
1741 const MachineInstr *RangeEnd,
1742 const InstructionOrdering &Ordering) {
1743 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1744 auto MBB = DbgValue->getParent();
1745 auto DL = DbgValue->getDebugLoc();
1746 auto *LScope = LScopes.findLexicalScope(DL);
1747 // Scope doesn't exist; this is a dead DBG_VALUE.
1748 if (!LScope)
1749 return false;
1750 auto &LSRange = LScope->getRanges();
1751 if (LSRange.size() == 0)
1752 return false;
1753
1754 const MachineInstr *LScopeBegin = LSRange.front().first;
1755 // If the scope starts before the DBG_VALUE then we may have a negative
1756 // result. Otherwise the location is live coming into the scope and we
1757 // can skip the following checks.
1758 if (!Ordering.isBefore(A: DbgValue, B: LScopeBegin)) {
1759 // Exit if the lexical scope begins outside of the current block.
1760 if (LScopeBegin->getParent() != MBB)
1761 return false;
1762
1763 MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1764 for (++Pred; Pred != MBB->rend(); ++Pred) {
1765 if (Pred->getFlag(Flag: MachineInstr::FrameSetup))
1766 break;
1767 auto PredDL = Pred->getDebugLoc();
1768 if (!PredDL || Pred->isMetaInstruction())
1769 continue;
1770 // Check whether the instruction preceding the DBG_VALUE is in the same
1771 // (sub)scope as the DBG_VALUE.
1772 if (DL->getScope() == PredDL->getScope())
1773 return false;
1774 auto *PredScope = LScopes.findLexicalScope(DL: PredDL);
1775 if (!PredScope || LScope->dominates(S: PredScope))
1776 return false;
1777 }
1778 }
1779
1780 // If the range of the DBG_VALUE is open-ended, report success.
1781 if (!RangeEnd)
1782 return true;
1783
1784 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1785 // throughout the function. This is a hack, presumably for DWARF v2 and not
1786 // necessarily correct. It would be much better to use a dbg.declare instead
1787 // if we know the constant is live throughout the scope.
1788 if (MBB->pred_empty() &&
1789 all_of(Range: DbgValue->debug_operands(),
1790 P: [](const MachineOperand &Op) { return Op.isImm(); }))
1791 return true;
1792
1793 // Test if the location terminates before the end of the scope.
1794 const MachineInstr *LScopeEnd = LSRange.back().second;
1795 if (Ordering.isBefore(A: RangeEnd, B: LScopeEnd))
1796 return false;
1797
1798 // There's a single location which starts at the scope start, and ends at or
1799 // after the scope end.
1800 return true;
1801}
1802
1803/// Build the location list for all DBG_VALUEs in the function that
1804/// describe the same variable. The resulting DebugLocEntries will have
1805/// strict monotonically increasing begin addresses and will never
1806/// overlap. If the resulting list has only one entry that is valid
1807/// throughout variable's scope return true.
1808//
1809// See the definition of DbgValueHistoryMap::Entry for an explanation of the
1810// different kinds of history map entries. One thing to be aware of is that if
1811// a debug value is ended by another entry (rather than being valid until the
1812// end of the function), that entry's instruction may or may not be included in
1813// the range, depending on if the entry is a clobbering entry (it has an
1814// instruction that clobbers one or more preceding locations), or if it is an
1815// (overlapping) debug value entry. This distinction can be seen in the example
1816// below. The first debug value is ended by the clobbering entry 2, and the
1817// second and third debug values are ended by the overlapping debug value entry
1818// 4.
1819//
1820// Input:
1821//
1822// History map entries [type, end index, mi]
1823//
1824// 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1825// 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1826// 2 | | [Clobber, $reg0 = [...], -, -]
1827// 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1828// 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1829//
1830// Output [start, end) [Value...]:
1831//
1832// [0-1) [(reg0, fragment 0, 32)]
1833// [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1834// [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1835// [4-) [(@g, fragment 0, 96)]
1836bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1837 const DbgValueHistoryMap::Entries &Entries) {
1838 using OpenRange =
1839 std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1840 SmallVector<OpenRange, 4> OpenRanges;
1841 bool isSafeForSingleLocation = true;
1842 const MachineInstr *StartDebugMI = nullptr;
1843 const MachineInstr *EndMI = nullptr;
1844
1845 for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1846 const MachineInstr *Instr = EI->getInstr();
1847
1848 // Remove all values that are no longer live.
1849 size_t Index = std::distance(first: EB, last: EI);
1850 erase_if(C&: OpenRanges, P: [&](OpenRange &R) { return R.first <= Index; });
1851
1852 // If we are dealing with a clobbering entry, this iteration will result in
1853 // a location list entry starting after the clobbering instruction.
1854 const MCSymbol *StartLabel =
1855 EI->isClobber() ? getLabelAfterInsn(MI: Instr) : getLabelBeforeInsn(MI: Instr);
1856 assert(StartLabel &&
1857 "Forgot label before/after instruction starting a range!");
1858
1859 const MCSymbol *EndLabel;
1860 if (std::next(x: EI) == Entries.end()) {
1861 const MachineBasicBlock &EndMBB = Asm->MF->back();
1862 EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionID()].EndLabel;
1863 if (EI->isClobber())
1864 EndMI = EI->getInstr();
1865 }
1866 else if (std::next(x: EI)->isClobber())
1867 EndLabel = getLabelAfterInsn(MI: std::next(x: EI)->getInstr());
1868 else
1869 EndLabel = getLabelBeforeInsn(MI: std::next(x: EI)->getInstr());
1870 assert(EndLabel && "Forgot label after instruction ending a range!");
1871
1872 if (EI->isDbgValue())
1873 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1874
1875 // If this history map entry has a debug value, add that to the list of
1876 // open ranges and check if its location is valid for a single value
1877 // location.
1878 if (EI->isDbgValue()) {
1879 // Do not add undef debug values, as they are redundant information in
1880 // the location list entries. An undef debug results in an empty location
1881 // description. If there are any non-undef fragments then padding pieces
1882 // with empty location descriptions will automatically be inserted, and if
1883 // all fragments are undef then the whole location list entry is
1884 // redundant.
1885 if (!Instr->isUndefDebugValue()) {
1886 auto Value = getDebugLocValue(MI: Instr);
1887 OpenRanges.emplace_back(Args: EI->getEndIndex(), Args&: Value);
1888
1889 // TODO: Add support for single value fragment locations.
1890 if (Instr->getDebugExpression()->isFragment())
1891 isSafeForSingleLocation = false;
1892
1893 if (!StartDebugMI)
1894 StartDebugMI = Instr;
1895 } else {
1896 isSafeForSingleLocation = false;
1897 }
1898 }
1899
1900 // Location list entries with empty location descriptions are redundant
1901 // information in DWARF, so do not emit those.
1902 if (OpenRanges.empty())
1903 continue;
1904
1905 // Omit entries with empty ranges as they do not have any effect in DWARF.
1906 if (StartLabel == EndLabel) {
1907 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1908 continue;
1909 }
1910
1911 SmallVector<DbgValueLoc, 4> Values;
1912 for (auto &R : OpenRanges)
1913 Values.push_back(Elt: R.second);
1914
1915 // With Basic block sections, it is posssible that the StartLabel and the
1916 // Instr are not in the same section. This happens when the StartLabel is
1917 // the function begin label and the dbg value appears in a basic block
1918 // that is not the entry. In this case, the range needs to be split to
1919 // span each individual section in the range from StartLabel to EndLabel.
1920 if (Asm->MF->hasBBSections() && StartLabel == Asm->getFunctionBegin() &&
1921 !Instr->getParent()->sameSection(MBB: &Asm->MF->front())) {
1922 for (const auto &[MBBSectionId, MBBSectionRange] :
1923 Asm->MBBSectionRanges) {
1924 if (Instr->getParent()->getSectionID() == MBBSectionId) {
1925 DebugLoc.emplace_back(Args: MBBSectionRange.BeginLabel, Args&: EndLabel, Args&: Values);
1926 break;
1927 }
1928 DebugLoc.emplace_back(Args: MBBSectionRange.BeginLabel,
1929 Args: MBBSectionRange.EndLabel, Args&: Values);
1930 }
1931 } else {
1932 DebugLoc.emplace_back(Args&: StartLabel, Args&: EndLabel, Args&: Values);
1933 }
1934
1935 // Attempt to coalesce the ranges of two otherwise identical
1936 // DebugLocEntries.
1937 auto CurEntry = DebugLoc.rbegin();
1938 LLVM_DEBUG({
1939 dbgs() << CurEntry->getValues().size() << " Values:\n";
1940 for (auto &Value : CurEntry->getValues())
1941 Value.dump();
1942 dbgs() << "-----\n";
1943 });
1944
1945 auto PrevEntry = std::next(x: CurEntry);
1946 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(Next: *CurEntry))
1947 DebugLoc.pop_back();
1948 }
1949
1950 if (!isSafeForSingleLocation ||
1951 !validThroughout(LScopes, DbgValue: StartDebugMI, RangeEnd: EndMI, Ordering: getInstOrdering()))
1952 return false;
1953
1954 if (DebugLoc.size() == 1)
1955 return true;
1956
1957 if (!Asm->MF->hasBBSections())
1958 return false;
1959
1960 // Check here to see if loclist can be merged into a single range. If not,
1961 // we must keep the split loclists per section. This does exactly what
1962 // MergeRanges does without sections. We don't actually merge the ranges
1963 // as the split ranges must be kept intact if this cannot be collapsed
1964 // into a single range.
1965 const MachineBasicBlock *RangeMBB = nullptr;
1966 if (DebugLoc[0].getBeginSym() == Asm->getFunctionBegin())
1967 RangeMBB = &Asm->MF->front();
1968 else
1969 RangeMBB = Entries.begin()->getInstr()->getParent();
1970 auto RangeIt = Asm->MBBSectionRanges.find(Key: RangeMBB->getSectionID());
1971 assert(RangeIt != Asm->MBBSectionRanges.end() &&
1972 "Range MBB not found in MBBSectionRanges!");
1973 auto *CurEntry = DebugLoc.begin();
1974 auto *NextEntry = std::next(x: CurEntry);
1975 auto NextRangeIt = std::next(x: RangeIt);
1976 while (NextEntry != DebugLoc.end()) {
1977 if (NextRangeIt == Asm->MBBSectionRanges.end())
1978 return false;
1979 // CurEntry should end the current section and NextEntry should start
1980 // the next section and the Values must match for these two ranges to be
1981 // merged. Do not match the section label end if it is the entry block
1982 // section. This is because the end label for the Debug Loc and the
1983 // Function end label could be different.
1984 if ((RangeIt->second.EndLabel != Asm->getFunctionEnd() &&
1985 CurEntry->getEndSym() != RangeIt->second.EndLabel) ||
1986 NextEntry->getBeginSym() != NextRangeIt->second.BeginLabel ||
1987 CurEntry->getValues() != NextEntry->getValues())
1988 return false;
1989 RangeIt = NextRangeIt;
1990 NextRangeIt = std::next(x: RangeIt);
1991 CurEntry = NextEntry;
1992 NextEntry = std::next(x: CurEntry);
1993 }
1994 return true;
1995}
1996
1997DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1998 LexicalScope &Scope,
1999 const DINode *Node,
2000 const DILocation *Location,
2001 const MCSymbol *Sym) {
2002 ensureAbstractEntityIsCreatedIfScoped(CU&: TheCU, Node, ScopeNode: Scope.getScopeNode());
2003 if (isa<const DILocalVariable>(Val: Node)) {
2004 ConcreteEntities.push_back(
2005 Elt: std::make_unique<DbgVariable>(args: cast<const DILocalVariable>(Val: Node),
2006 args&: Location));
2007 InfoHolder.addScopeVariable(LS: &Scope,
2008 Var: cast<DbgVariable>(Val: ConcreteEntities.back().get()));
2009 } else if (isa<const DILabel>(Val: Node)) {
2010 ConcreteEntities.push_back(
2011 Elt: std::make_unique<DbgLabel>(args: cast<const DILabel>(Val: Node),
2012 args&: Location, args&: Sym));
2013 InfoHolder.addScopeLabel(LS: &Scope,
2014 Label: cast<DbgLabel>(Val: ConcreteEntities.back().get()));
2015 }
2016 return ConcreteEntities.back().get();
2017}
2018
2019// Find variables for each lexical scope.
2020void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
2021 const DISubprogram *SP,
2022 DenseSet<InlinedEntity> &Processed) {
2023 // Grab the variable info that was squirreled away in the MMI side-table.
2024 collectVariableInfoFromMFTable(TheCU, Processed);
2025
2026 for (const auto &I : DbgValues) {
2027 InlinedEntity IV = I.first;
2028 if (Processed.count(V: IV))
2029 continue;
2030
2031 // Instruction ranges, specifying where IV is accessible.
2032 const auto &HistoryMapEntries = I.second;
2033
2034 // Try to find any non-empty variable location. Do not create a concrete
2035 // entity if there are no locations.
2036 if (!DbgValues.hasNonEmptyLocation(Entries: HistoryMapEntries))
2037 continue;
2038
2039 LexicalScope *Scope = nullptr;
2040 const DILocalVariable *LocalVar = cast<DILocalVariable>(Val: IV.first);
2041 if (const DILocation *IA = IV.second)
2042 Scope = LScopes.findInlinedScope(N: LocalVar->getScope(), IA);
2043 else
2044 Scope = LScopes.findLexicalScope(N: LocalVar->getScope());
2045 // If variable scope is not found then skip this variable.
2046 if (!Scope)
2047 continue;
2048
2049 Processed.insert(V: IV);
2050 DbgVariable *RegVar = cast<DbgVariable>(Val: createConcreteEntity(TheCU,
2051 Scope&: *Scope, Node: LocalVar, Location: IV.second));
2052
2053 const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
2054 assert(MInsn->isDebugValue() && "History must begin with debug value");
2055
2056 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
2057 // If the history map contains a single debug value, there may be an
2058 // additional entry which clobbers the debug value.
2059 size_t HistSize = HistoryMapEntries.size();
2060 bool SingleValueWithClobber =
2061 HistSize == 2 && HistoryMapEntries[1].isClobber();
2062 if (HistSize == 1 || SingleValueWithClobber) {
2063 const auto *End =
2064 SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
2065 if (validThroughout(LScopes, DbgValue: MInsn, RangeEnd: End, Ordering: getInstOrdering())) {
2066 RegVar->emplace<Loc::Single>(args&: MInsn);
2067 continue;
2068 }
2069 }
2070
2071 // Handle multiple DBG_VALUE instructions describing one variable.
2072 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar);
2073
2074 // Build the location list for this variable.
2075 SmallVector<DebugLocEntry, 8> Entries;
2076 bool isValidSingleLocation = buildLocationList(DebugLoc&: Entries, Entries: HistoryMapEntries);
2077
2078 // Check whether buildLocationList managed to merge all locations to one
2079 // that is valid throughout the variable's scope. If so, produce single
2080 // value location.
2081 if (isValidSingleLocation) {
2082 RegVar->emplace<Loc::Single>(args: Entries[0].getValues()[0]);
2083 continue;
2084 }
2085
2086 // If the variable has a DIBasicType, extract it. Basic types cannot have
2087 // unique identifiers, so don't bother resolving the type with the
2088 // identifier map.
2089 const DIBasicType *BT = dyn_cast<DIBasicType>(
2090 Val: static_cast<const Metadata *>(LocalVar->getType()));
2091
2092 // Finalize the entry by lowering it into a DWARF bytestream.
2093 for (auto &Entry : Entries)
2094 Entry.finalize(AP: *Asm, List, BT, TheCU);
2095 }
2096
2097 // For each InlinedEntity collected from DBG_LABEL instructions, convert to
2098 // DWARF-related DbgLabel.
2099 for (const auto &I : DbgLabels) {
2100 InlinedEntity IL = I.first;
2101 const MachineInstr *MI = I.second;
2102 if (MI == nullptr)
2103 continue;
2104
2105 LexicalScope *Scope = nullptr;
2106 const DILabel *Label = cast<DILabel>(Val: IL.first);
2107 // The scope could have an extra lexical block file.
2108 const DILocalScope *LocalScope =
2109 Label->getScope()->getNonLexicalBlockFileScope();
2110 // Get inlined DILocation if it is inlined label.
2111 if (const DILocation *IA = IL.second)
2112 Scope = LScopes.findInlinedScope(N: LocalScope, IA);
2113 else
2114 Scope = LScopes.findLexicalScope(N: LocalScope);
2115 // If label scope is not found then skip this label.
2116 if (!Scope)
2117 continue;
2118
2119 Processed.insert(V: IL);
2120 /// At this point, the temporary label is created.
2121 /// Save the temporary label to DbgLabel entity to get the
2122 /// actually address when generating Dwarf DIE.
2123 MCSymbol *Sym = getLabelBeforeInsn(MI);
2124 createConcreteEntity(TheCU, Scope&: *Scope, Node: Label, Location: IL.second, Sym);
2125 }
2126
2127 // Collect info for retained nodes.
2128 for (const MDNode *N : SP->getRetainedNodes()) {
2129 const auto *LS = getRetainedNodeScope(N);
2130 if (isa<DILocalVariable>(Val: N) || isa<DILabel>(Val: N)) {
2131 auto *DN = cast<DINode>(Val: N);
2132 if (!Processed.insert(V: InlinedEntity(DN, nullptr)).second)
2133 continue;
2134 LexicalScope *LexS = LScopes.findLexicalScope(N: LS);
2135 if (LexS)
2136 createConcreteEntity(TheCU, Scope&: *LexS, Node: DN, Location: nullptr);
2137 } else {
2138 LocalDeclsPerLS[LS].insert(X: N);
2139 }
2140 }
2141}
2142
2143// Process beginning of an instruction.
2144void DwarfDebug::beginInstruction(const MachineInstr *MI) {
2145 const MachineFunction &MF = *MI->getMF();
2146 const auto *SP = MF.getFunction().getSubprogram();
2147 bool NoDebug =
2148 !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
2149
2150 // Delay slot support check.
2151 auto delaySlotSupported = [](const MachineInstr &MI) {
2152 if (!MI.isBundledWithSucc())
2153 return false;
2154 auto Suc = std::next(x: MI.getIterator());
2155 (void)Suc;
2156 // Ensure that delay slot instruction is successor of the call instruction.
2157 // Ex. CALL_INSTRUCTION {
2158 // DELAY_SLOT_INSTRUCTION }
2159 assert(Suc->isBundledWithPred() &&
2160 "Call bundle instructions are out of order");
2161 return true;
2162 };
2163
2164 // When describing calls, we need a label for the call instruction.
2165 if (!NoDebug && SP->areAllCallsDescribed() &&
2166 MI->isCandidateForAdditionalCallInfo(Type: MachineInstr::AnyInBundle) &&
2167 (!MI->hasDelaySlot() || delaySlotSupported(*MI))) {
2168 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
2169 bool IsTail = TII->isTailCall(Inst: *MI);
2170 // For tail calls, we need the address of the branch instruction for
2171 // DW_AT_call_pc.
2172 if (IsTail)
2173 requestLabelBeforeInsn(MI);
2174 // For non-tail calls, we need the return address for the call for
2175 // DW_AT_call_return_pc. Under GDB tuning, this information is needed for
2176 // tail calls as well.
2177 requestLabelAfterInsn(MI);
2178 }
2179
2180 DebugHandlerBase::beginInstruction(MI);
2181 if (!CurMI)
2182 return;
2183
2184 if (NoDebug)
2185 return;
2186
2187 auto RecordLineZero = [&]() {
2188 // Preserve the file and column numbers, if we can, to save space in
2189 // the encoded line table.
2190 // Do not update PrevInstLoc, it remembers the last non-0 line.
2191 const MDNode *Scope = nullptr;
2192 unsigned Column = 0;
2193 if (PrevInstLoc) {
2194 Scope = PrevInstLoc.getScope();
2195 Column = PrevInstLoc.getCol();
2196 }
2197 recordSourceLine(/*Line=*/0, Col: Column, Scope, /*Flags=*/0);
2198 };
2199
2200 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
2201 // the last line number actually emitted, to see if it was line 0.
2202 unsigned LastAsmLine =
2203 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
2204
2205 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
2206 // If the instruction is part of the function frame setup code, do not emit
2207 // any line record, as there is no correspondence with any user code.
2208 if (MI->isMetaInstruction())
2209 return;
2210 if (MI->getFlag(Flag: MachineInstr::FrameSetup)) {
2211 // Prevent a loc from the previous block leaking into frame setup instrs.
2212 if (LastAsmLine && PrevInstBB && PrevInstBB != MI->getParent())
2213 RecordLineZero();
2214 return;
2215 }
2216
2217 const DebugLoc &DL = MI->getDebugLoc();
2218 unsigned Flags = 0;
2219
2220 if (MI->getFlag(Flag: MachineInstr::FrameDestroy) && DL) {
2221 const MachineBasicBlock *MBB = MI->getParent();
2222 if (MBB && (MBB != EpilogBeginBlock)) {
2223 // First time FrameDestroy has been seen in this basic block
2224 EpilogBeginBlock = MBB;
2225 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2226 }
2227 }
2228
2229 auto RecordSourceLine = [this](auto &DL, auto Flags) {
2230 SmallString<128> LocationString;
2231 if (Asm->OutStreamer->isVerboseAsm()) {
2232 raw_svector_ostream OS(LocationString);
2233 DL.print(OS);
2234 }
2235 recordSourceLine(Line: DL.getLine(), Col: DL.getCol(), Scope: DL.getScope(), Flags,
2236 Location: LocationString);
2237 };
2238
2239 // There may be a mixture of scopes using and not using Key Instructions.
2240 // Not-Key-Instructions functions inlined into Key Instructions functions
2241 // should use not-key is_stmt handling. Key Instructions functions inlined
2242 // into Not-Key-Instructions functions should use Key Instructions is_stmt
2243 // handling.
2244 bool ScopeUsesKeyInstructions =
2245 KeyInstructionsAreStmts && DL &&
2246 DL->getScope()->getSubprogram()->getKeyInstructionsEnabled();
2247
2248 bool IsKey = false;
2249 if (ScopeUsesKeyInstructions && DL && DL.getLine())
2250 IsKey = KeyInstructions.contains(V: MI);
2251
2252 if (!DL && MI == PrologEndLoc) {
2253 // In rare situations, we might want to place the end of the prologue
2254 // somewhere that doesn't have a source location already. It should be in
2255 // the entry block.
2256 assert(MI->getParent() == &*MI->getMF()->begin());
2257 recordSourceLine(Line: SP->getScopeLine(), Col: 0, Scope: SP,
2258 DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT);
2259 return;
2260 }
2261
2262 bool PrevInstInSameSection =
2263 (!PrevInstBB ||
2264 PrevInstBB->getSectionID() == MI->getParent()->getSectionID());
2265 bool ForceIsStmt = ForceIsStmtInstrs.contains(V: MI);
2266 if (PrevInstInSameSection && !ForceIsStmt && DL.isSameSourceLocation(Other: PrevInstLoc)) {
2267 // If we have an ongoing unspecified location, nothing to do here.
2268 if (!DL)
2269 return;
2270
2271 // Skip this if the instruction is Key, else we might accidentally miss an
2272 // is_stmt.
2273 if (!IsKey) {
2274 // We have an explicit location, same as the previous location.
2275 // But we might be coming back to it after a line 0 record.
2276 if ((LastAsmLine == 0 && DL.getLine() != 0) || Flags) {
2277 // Reinstate the source location but not marked as a statement.
2278 RecordSourceLine(DL, Flags);
2279 }
2280 return;
2281 }
2282 }
2283
2284 if (!DL) {
2285 // FIXME: We could assert that `DL.getKind() != DebugLocKind::Temporary`
2286 // here, or otherwise record any temporary DebugLocs seen to ensure that
2287 // transient compiler-generated instructions aren't leaking their DLs to
2288 // other instructions.
2289 // We have an unspecified location, which might want to be line 0.
2290 // If we have already emitted a line-0 record, don't repeat it.
2291 if (LastAsmLine == 0)
2292 return;
2293 // If user said Don't Do That, don't do that.
2294 if (UnknownLocations == Disable)
2295 return;
2296 // See if we have a reason to emit a line-0 record now.
2297 // Reasons to emit a line-0 record include:
2298 // - User asked for it (UnknownLocations).
2299 // - Instruction has a label, so it's referenced from somewhere else,
2300 // possibly debug information; we want it to have a source location.
2301 // - Instruction is at the top of a block; we don't want to inherit the
2302 // location from the physically previous (maybe unrelated) block.
2303 if (UnknownLocations == Enable || PrevLabel ||
2304 (PrevInstBB && PrevInstBB != MI->getParent()))
2305 RecordLineZero();
2306 return;
2307 }
2308
2309 // We have an explicit location, different from the previous location.
2310 // Don't repeat a line-0 record, but otherwise emit the new location.
2311 // (The new location might be an explicit line 0, which we do emit.)
2312 if (DL.getLine() == 0 && LastAsmLine == 0)
2313 return;
2314 if (MI == PrologEndLoc) {
2315 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
2316 PrologEndLoc = nullptr;
2317 }
2318
2319 if (ScopeUsesKeyInstructions) {
2320 if (IsKey)
2321 Flags |= DWARF2_FLAG_IS_STMT;
2322 } else {
2323 // If the line changed, we call that a new statement; unless we went to
2324 // line 0 and came back, in which case it is not a new statement.
2325 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
2326 if (DL.getLine() && (DL.getLine() != OldLine || ForceIsStmt))
2327 Flags |= DWARF2_FLAG_IS_STMT;
2328 }
2329
2330 // Call target-specific source line recording.
2331 recordTargetSourceLine(DL, Flags);
2332
2333 // If we're not at line 0, remember this location.
2334 if (DL.getLine())
2335 PrevInstLoc = DL;
2336}
2337
2338/// Default implementation of target-specific source line recording.
2339void DwarfDebug::recordTargetSourceLine(const DebugLoc &DL, unsigned Flags) {
2340 SmallString<128> LocationString;
2341 if (Asm->OutStreamer->isVerboseAsm()) {
2342 raw_svector_ostream OS(LocationString);
2343 DL.print(OS);
2344 }
2345 recordSourceLine(Line: DL.getLine(), Col: DL.getCol(), Scope: DL.getScope(), Flags,
2346 Location: LocationString);
2347}
2348
2349// Returns the position where we should place prologue_end, potentially nullptr,
2350// which means "no good place to put prologue_end". Returns true in the second
2351// return value if there are no setup instructions in this function at all,
2352// meaning we should not emit a start-of-function linetable entry, because it
2353// would be zero-lengthed.
2354static std::pair<const MachineInstr *, bool>
2355findPrologueEndLoc(const MachineFunction *MF) {
2356 // First known non-DBG_VALUE and non-frame setup location marks
2357 // the beginning of the function body.
2358 const auto &TII = *MF->getSubtarget().getInstrInfo();
2359 const MachineInstr *NonTrivialInst = nullptr;
2360 const Function &F = MF->getFunction();
2361 DISubprogram *SP = const_cast<DISubprogram *>(F.getSubprogram());
2362
2363 // Some instructions may be inserted into prologue after this function. Must
2364 // keep prologue for these cases.
2365 bool IsEmptyPrologue =
2366 !(F.hasPrologueData() || F.getMetadata(KindID: LLVMContext::MD_func_sanitize));
2367
2368 // Helper lambda to examine each instruction and potentially return it
2369 // as the prologue_end point.
2370 auto ExamineInst = [&](const MachineInstr &MI)
2371 -> std::optional<std::pair<const MachineInstr *, bool>> {
2372 // Is this instruction trivial data shuffling or frame-setup?
2373 bool isCopy = (TII.isCopyInstr(MI) ? true : false);
2374 bool isTrivRemat = TII.isTriviallyReMaterializable(MI);
2375 bool isFrameSetup = MI.getFlag(Flag: MachineInstr::FrameSetup);
2376
2377 if (!isFrameSetup && MI.getDebugLoc()) {
2378 // Scan forward to try to find a non-zero line number. The
2379 // prologue_end marks the first breakpoint in the function after the
2380 // frame setup, and a compiler-generated line 0 location is not a
2381 // meaningful breakpoint. If none is found, return the first
2382 // location after the frame setup.
2383 if (MI.getDebugLoc().getLine())
2384 return std::make_pair(x: &MI, y&: IsEmptyPrologue);
2385 }
2386
2387 // Keep track of the first "non-trivial" instruction seen, i.e. anything
2388 // that doesn't involve shuffling data around or is a frame-setup.
2389 if (!isCopy && !isTrivRemat && !isFrameSetup && !NonTrivialInst)
2390 NonTrivialInst = &MI;
2391
2392 IsEmptyPrologue = false;
2393 return std::nullopt;
2394 };
2395
2396 // Examine all the instructions at the start of the function. This doesn't
2397 // necessarily mean just the entry block: unoptimised code can fall-through
2398 // into an initial loop, and it makes sense to put the initial breakpoint on
2399 // the first instruction of such a loop. However, if we pass branches, we're
2400 // better off synthesising an early prologue_end.
2401 auto CurBlock = MF->begin();
2402 auto CurInst = CurBlock->begin();
2403
2404 // Find the initial instruction, we're guaranteed one by the caller, but not
2405 // which block it's in.
2406 while (CurBlock->empty())
2407 CurInst = (++CurBlock)->begin();
2408 assert(CurInst != CurBlock->end());
2409
2410 // Helper function for stepping through the initial sequence of
2411 // unconditionally executed instructions.
2412 auto getNextInst = [&CurBlock, &CurInst, MF]() -> bool {
2413 // We've reached the end of the block. Did we just look at a terminator?
2414 if (CurInst->isTerminator()) {
2415 // Some kind of "real" control flow is occurring. At the very least
2416 // we would have to start exploring the CFG, a good signal that the
2417 // prologue is over.
2418 return false;
2419 }
2420
2421 // If we've already fallen through into a loop, don't fall through
2422 // further, use a backup-location.
2423 if (CurBlock->pred_size() > 1)
2424 return false;
2425
2426 // Fall-through from entry to the next block. This is common at -O0 when
2427 // there's no initialisation in the function. Bail if we're also at the
2428 // end of the function, or the remaining blocks have no instructions.
2429 // Skip empty blocks, in rare cases the entry can be empty, and
2430 // other optimisations may add empty blocks that the control flow falls
2431 // through.
2432 do {
2433 ++CurBlock;
2434 if (CurBlock == MF->end())
2435 return false;
2436 } while (CurBlock->empty());
2437 CurInst = CurBlock->begin();
2438 return true;
2439 };
2440
2441 while (true) {
2442 // Check whether this non-meta instruction a good position for prologue_end.
2443 if (!CurInst->isMetaInstruction()) {
2444 auto FoundInst = ExamineInst(*CurInst);
2445 if (FoundInst)
2446 return *FoundInst;
2447 }
2448
2449 // In very rare scenarios function calls can have line zero, and we
2450 // shouldn't step over such a call while trying to reach prologue_end. In
2451 // these extraordinary conditions, force the call to have the scope line
2452 // and put prologue_end there. This isn't ideal, but signals that the call
2453 // is where execution in the function starts, and is less catastrophic than
2454 // stepping over the call.
2455 if (CurInst->isCall()) {
2456 if (const DILocation *Loc = CurInst->getDebugLoc().get();
2457 Loc && Loc->getLine() == 0) {
2458 // Create and assign the scope-line position.
2459 unsigned ScopeLine = SP->getScopeLine();
2460 DILocation *ScopeLineDILoc =
2461 DILocation::get(Context&: SP->getContext(), Line: ScopeLine, Column: 0, Scope: SP);
2462 const_cast<MachineInstr *>(&*CurInst)->setDebugLoc(ScopeLineDILoc);
2463
2464 // Consider this position to be where prologue_end is placed.
2465 return std::make_pair(x: &*CurInst, y: false);
2466 }
2467 }
2468
2469 // Try to continue searching, but use a backup-location if substantive
2470 // computation is happening.
2471 auto NextInst = std::next(x: CurInst);
2472 if (NextInst != CurInst->getParent()->end()) {
2473 // Continue examining the current block.
2474 CurInst = NextInst;
2475 continue;
2476 }
2477
2478 if (!getNextInst())
2479 break;
2480 }
2481
2482 // We couldn't find any source-location, suggesting all meaningful information
2483 // got optimised away. Set the prologue_end to be the first non-trivial
2484 // instruction, which will get the scope line number. This is better than
2485 // nothing.
2486 // Only do this in the entry block, as we'll be giving it the scope line for
2487 // the function. Return IsEmptyPrologue==true if we've picked the first
2488 // instruction.
2489 if (NonTrivialInst && NonTrivialInst->getParent() == &*MF->begin()) {
2490 IsEmptyPrologue = NonTrivialInst == &*MF->begin()->begin();
2491 return std::make_pair(x&: NonTrivialInst, y&: IsEmptyPrologue);
2492 }
2493
2494 // If the entry path is empty, just don't have a prologue_end at all.
2495 return std::make_pair(x: nullptr, y&: IsEmptyPrologue);
2496}
2497
2498/// Register a source line with debug info. Returns the unique label that was
2499/// emitted and which provides correspondence to the source line list.
2500static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
2501 const MDNode *S, unsigned Flags, unsigned CUID,
2502 uint16_t DwarfVersion,
2503 ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs,
2504 StringRef Comment = {}) {
2505 StringRef Fn;
2506 unsigned FileNo = 1;
2507 unsigned Discriminator = 0;
2508 if (auto *Scope = cast_or_null<DIScope>(Val: S)) {
2509 Fn = Scope->getFilename();
2510 if (Line != 0 && DwarfVersion >= 4)
2511 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Val: Scope))
2512 Discriminator = LBF->getDiscriminator();
2513
2514 FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
2515 .getOrCreateSourceID(File: Scope->getFile());
2516 }
2517 Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Column: Col, Flags, Isa: 0,
2518 Discriminator, FileName: Fn, Comment);
2519}
2520
2521const MachineInstr *
2522DwarfDebug::emitInitialLocDirective(const MachineFunction &MF, unsigned CUID) {
2523 // Don't deal with functions that have no instructions.
2524 if (llvm::all_of(Range: MF, P: [](const MachineBasicBlock &MBB) { return MBB.empty(); }))
2525 return nullptr;
2526
2527 std::pair<const MachineInstr *, bool> PrologEnd = findPrologueEndLoc(MF: &MF);
2528 const MachineInstr *PrologEndLoc = PrologEnd.first;
2529 bool IsEmptyPrologue = PrologEnd.second;
2530
2531 // If the prolog is empty, no need to generate scope line for the proc.
2532 if (IsEmptyPrologue) {
2533 // If there's nowhere to put a prologue_end flag, emit a scope line in case
2534 // there are simply no source locations anywhere in the function.
2535 if (PrologEndLoc) {
2536 // Avoid trying to assign prologue_end to a line-zero location.
2537 // Instructions with no DebugLoc at all are fine, they'll be given the
2538 // scope line nuumber.
2539 const DebugLoc &DL = PrologEndLoc->getDebugLoc();
2540 if (!DL || DL->getLine() != 0)
2541 return PrologEndLoc;
2542
2543 // Later, don't place the prologue_end flag on this line-zero location.
2544 PrologEndLoc = nullptr;
2545 }
2546 }
2547
2548 // Ensure the compile unit is created if the function is called before
2549 // beginFunction().
2550 DISubprogram *SP = MF.getFunction().getSubprogram();
2551 (void)getOrCreateDwarfCompileUnit(DIUnit: SP->getUnit());
2552 // We'd like to list the prologue as "not statements" but GDB behaves
2553 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
2554 ::recordSourceLine(Asm&: *Asm, Line: SP->getScopeLine(), Col: 0, S: SP, DWARF2_FLAG_IS_STMT,
2555 CUID, DwarfVersion: getDwarfVersion(), DCUs: getUnits());
2556 return PrologEndLoc;
2557}
2558
2559void DwarfDebug::computeKeyInstructions(const MachineFunction *MF) {
2560 // New function - reset KeyInstructions.
2561 KeyInstructions.clear();
2562
2563 // The current candidate is_stmt instructions for each source atom.
2564 // Map {(InlinedAt, Group): (Rank, Instructions)}.
2565 // NOTE: Anecdotally, for a large C++ blob, 99% of the instruction
2566 // SmallVectors contain 2 or fewer elements; use 2 inline elements.
2567 DenseMap<std::pair<DILocation *, uint64_t>,
2568 std::pair<uint8_t, SmallVector<const MachineInstr *, 2>>>
2569 GroupCandidates;
2570
2571 const auto &TII = *MF->getSubtarget().getInstrInfo();
2572
2573 // For each instruction:
2574 // * Skip insts without DebugLoc, AtomGroup or AtomRank, and line zeros.
2575 // * Check if insts in this group have been seen already in GroupCandidates.
2576 // * If this instr rank is equal, add this instruction to GroupCandidates.
2577 // Remove existing instructions from GroupCandidates if they have the
2578 // same parent.
2579 // * If this instr rank is higher (lower precedence), ignore it.
2580 // * If this instr rank is lower (higher precedence), erase existing
2581 // instructions from GroupCandidates and add this one.
2582 //
2583 // Then insert each GroupCandidates instruction into KeyInstructions.
2584
2585 for (auto &MBB : *MF) {
2586 // Rather than apply is_stmt directly to Key Instructions, we "float"
2587 // is_stmt up to the 1st instruction with the same line number in a
2588 // contiguous block. That instruction is called the "buoy". The
2589 // buoy gets reset if we encouner an instruction with an atom
2590 // group.
2591 const MachineInstr *Buoy = nullptr;
2592 // The atom group number associated with Buoy which may be 0 if we haven't
2593 // encountered an atom group yet in this blob of instructions with the same
2594 // line number.
2595 uint64_t BuoyAtom = 0;
2596
2597 for (auto &MI : MBB) {
2598 if (MI.isMetaInstruction())
2599 continue;
2600
2601 const DILocation *Loc = MI.getDebugLoc().get();
2602 if (!Loc || !Loc->getLine())
2603 continue;
2604
2605 // Reset the Buoy to this instruction if it has a different line number.
2606 if (!Buoy || Buoy->getDebugLoc().getLine() != Loc->getLine()) {
2607 Buoy = &MI;
2608 BuoyAtom = 0; // Set later when we know which atom the buoy is used by.
2609 }
2610
2611 // Call instructions are handled specially - we always mark them as key
2612 // regardless of atom info.
2613 bool IsCallLike = MI.isCall() || TII.isTailCall(Inst: MI);
2614 if (IsCallLike) {
2615 // Calls are always key. Put the buoy (may not be the call) into
2616 // KeyInstructions directly rather than the candidate map to avoid it
2617 // being erased (and we may not have a group number for the call).
2618 KeyInstructions.insert(V: Buoy);
2619
2620 // Avoid floating any future is_stmts up to the call.
2621 Buoy = nullptr;
2622 BuoyAtom = 0;
2623
2624 if (!Loc->getAtomGroup() || !Loc->getAtomRank())
2625 continue;
2626 }
2627
2628 auto *InlinedAt = Loc->getInlinedAt();
2629 uint64_t Group = Loc->getAtomGroup();
2630 uint8_t Rank = Loc->getAtomRank();
2631 if (!Group || !Rank)
2632 continue;
2633
2634 // Don't let is_stmts float past instructions from different source atoms.
2635 if (BuoyAtom && BuoyAtom != Group) {
2636 Buoy = &MI;
2637 BuoyAtom = Group;
2638 }
2639
2640 auto &[CandidateRank, CandidateInsts] =
2641 GroupCandidates[{InlinedAt, Group}];
2642
2643 // If CandidateRank is zero then CandidateInsts should be empty: there
2644 // are no other candidates for this group yet. If CandidateRank is nonzero
2645 // then CandidateInsts shouldn't be empty: we've got existing candidate
2646 // instructions.
2647 assert((CandidateRank == 0 && CandidateInsts.empty()) ||
2648 (CandidateRank != 0 && !CandidateInsts.empty()));
2649
2650 assert(Rank && "expected nonzero rank");
2651 // If we've seen other instructions in this group with higher precedence
2652 // (lower nonzero rank), don't add this one as a candidate.
2653 if (CandidateRank && CandidateRank < Rank)
2654 continue;
2655
2656 // If we've seen other instructions in this group of the same rank,
2657 // discard any from this block (keeping the others). Else if we've
2658 // seen other instructions in this group of lower precedence (higher
2659 // rank), discard them all.
2660 if (CandidateRank == Rank)
2661 llvm::remove_if(Range&: CandidateInsts, P: [&MI](const MachineInstr *Candidate) {
2662 return MI.getParent() == Candidate->getParent();
2663 });
2664 else if (CandidateRank > Rank)
2665 CandidateInsts.clear();
2666
2667 if (Buoy) {
2668 // Add this candidate.
2669 CandidateInsts.push_back(Elt: Buoy);
2670 CandidateRank = Rank;
2671
2672 assert(!BuoyAtom || BuoyAtom == Loc->getAtomGroup());
2673 BuoyAtom = Loc->getAtomGroup();
2674 } else {
2675 // Don't add calls, because they've been dealt with already. This means
2676 // CandidateInsts might now be empty - handle that.
2677 assert(IsCallLike);
2678 if (CandidateInsts.empty())
2679 CandidateRank = 0;
2680 }
2681 }
2682 }
2683
2684 for (const auto &[_, Insts] : GroupCandidates.values())
2685 for (auto *I : Insts)
2686 KeyInstructions.insert(V: I);
2687}
2688
2689/// For the function \p MF, finds the set of instructions which may represent a
2690/// change in line number from one or more of the preceding MBBs. Stores the
2691/// resulting set of instructions, which should have is_stmt set, in
2692/// ForceIsStmtInstrs.
2693void DwarfDebug::findForceIsStmtInstrs(const MachineFunction *MF) {
2694 ForceIsStmtInstrs.clear();
2695
2696 // For this function, we try to find MBBs where the last source line in every
2697 // block predecessor matches the first line seen in the block itself; for
2698 // every such MBB, we set is_stmt=false on the first line in the block, and
2699 // for every other block we set is_stmt=true on the first line.
2700 // For example, if we have the block %bb.3, which has 2 predecesors %bb.1 and
2701 // %bb.2:
2702 // bb.1:
2703 // $r3 = MOV64ri 12, debug-location !DILocation(line: 4)
2704 // JMP %bb.3, debug-location !DILocation(line: 5)
2705 // bb.2:
2706 // $r3 = MOV64ri 24, debug-location !DILocation(line: 5)
2707 // JMP %bb.3
2708 // bb.3:
2709 // $r2 = MOV64ri 1
2710 // $r1 = ADD $r2, $r3, debug-location !DILocation(line: 5)
2711 // When we examine %bb.3, we first check to see if it contains any
2712 // instructions with debug locations, and select the first such instruction;
2713 // in this case, the ADD, with line=5. We then examine both of its
2714 // predecessors to see what the last debug-location in them is. For each
2715 // predecessor, if they do not contain any debug-locations, or if the last
2716 // debug-location before jumping to %bb.3 does not have line=5, then the ADD
2717 // in %bb.3 must use IsStmt. In this case, all predecessors have a
2718 // debug-location with line=5 as the last debug-location before jumping to
2719 // %bb.3, so we do not set is_stmt for the ADD instruction - we know that
2720 // whichever MBB we have arrived from, the line has not changed.
2721
2722 const auto *TII = MF->getSubtarget().getInstrInfo();
2723
2724 // We only need to the predecessors of MBBs that could have is_stmt set by
2725 // this logic.
2726 SmallDenseSet<MachineBasicBlock *, 4> PredMBBsToExamine;
2727 SmallDenseMap<MachineBasicBlock *, MachineInstr *> PotentialIsStmtMBBInstrs;
2728 // We use const_cast even though we won't actually modify MF, because some
2729 // methods we need take a non-const MBB.
2730 for (auto &MBB : *const_cast<MachineFunction *>(MF)) {
2731 if (MBB.empty() || MBB.pred_empty())
2732 continue;
2733 for (auto &MI : MBB) {
2734 if (MI.getDebugLoc() && MI.getDebugLoc()->getLine()) {
2735 PredMBBsToExamine.insert_range(R: MBB.predecessors());
2736 PotentialIsStmtMBBInstrs.insert(KV: {&MBB, &MI});
2737 break;
2738 }
2739 }
2740 }
2741
2742 // For each predecessor MBB, we examine the last line seen before each branch
2743 // or logical fallthrough. We use analyzeBranch to handle cases where
2744 // different branches have different outgoing lines (i.e. if there are
2745 // multiple branches that each have their own source location); otherwise we
2746 // just use the last line in the block.
2747 for (auto *MBB : PredMBBsToExamine) {
2748 auto CheckMBBEdge = [&](MachineBasicBlock *Succ, unsigned OutgoingLine) {
2749 auto MBBInstrIt = PotentialIsStmtMBBInstrs.find(Val: Succ);
2750 if (MBBInstrIt == PotentialIsStmtMBBInstrs.end())
2751 return;
2752 MachineInstr *MI = MBBInstrIt->second;
2753 if (MI->getDebugLoc()->getLine() == OutgoingLine)
2754 return;
2755 PotentialIsStmtMBBInstrs.erase(I: MBBInstrIt);
2756 ForceIsStmtInstrs.insert(V: MI);
2757 };
2758 // If this block is empty, we conservatively assume that its fallthrough
2759 // successor needs is_stmt; we could check MBB's predecessors to see if it
2760 // has a consistent entry line, but this seems unlikely to be worthwhile.
2761 if (MBB->empty()) {
2762 for (auto *Succ : MBB->successors())
2763 CheckMBBEdge(Succ, 0);
2764 continue;
2765 }
2766 // If MBB has no successors that are in the "potential" set, due to one or
2767 // more of them having confirmed is_stmt, we can skip this check early.
2768 if (none_of(Range: MBB->successors(), P: [&](auto *SuccMBB) {
2769 return PotentialIsStmtMBBInstrs.contains(Val: SuccMBB);
2770 }))
2771 continue;
2772 // If we can't determine what DLs this branch's successors use, just treat
2773 // all the successors as coming from the last DebugLoc.
2774 SmallVector<MachineBasicBlock *, 2> SuccessorBBs;
2775 auto MIIt = MBB->rbegin();
2776 {
2777 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2778 SmallVector<MachineOperand, 4> Cond;
2779 bool AnalyzeFailed = TII->analyzeBranch(MBB&: *MBB, TBB, FBB, Cond);
2780 // For a conditional branch followed by unconditional branch where the
2781 // unconditional branch has a DebugLoc, that loc is the outgoing loc to
2782 // the the false destination only; otherwise, both destinations share an
2783 // outgoing loc.
2784 if (!AnalyzeFailed && !Cond.empty() && FBB != nullptr &&
2785 MBB->back().getDebugLoc() && MBB->back().getDebugLoc()->getLine()) {
2786 unsigned FBBLine = MBB->back().getDebugLoc()->getLine();
2787 assert(MIIt->isBranch() && "Bad result from analyzeBranch?");
2788 CheckMBBEdge(FBB, FBBLine);
2789 ++MIIt;
2790 SuccessorBBs.push_back(Elt: TBB);
2791 } else {
2792 // For all other cases, all successors share the last outgoing DebugLoc.
2793 SuccessorBBs.assign(in_start: MBB->succ_begin(), in_end: MBB->succ_end());
2794 }
2795 }
2796
2797 // If we don't find an outgoing loc, this block will start with a line 0.
2798 // It is possible that we have a block that has no DebugLoc, but acts as a
2799 // simple passthrough between two blocks that end and start with the same
2800 // line, e.g.:
2801 // bb.1:
2802 // JMP %bb.2, debug-location !10
2803 // bb.2:
2804 // JMP %bb.3
2805 // bb.3:
2806 // $r1 = ADD $r2, $r3, debug-location !10
2807 // If these blocks were merged into a single block, we would not attach
2808 // is_stmt to the ADD, but with this logic that only checks the immediate
2809 // predecessor, we will; we make this tradeoff because doing a full dataflow
2810 // analysis would be expensive, and these situations are probably not common
2811 // enough for this to be worthwhile.
2812 unsigned LastLine = 0;
2813 while (MIIt != MBB->rend()) {
2814 if (auto DL = MIIt->getDebugLoc(); DL && DL->getLine()) {
2815 LastLine = DL->getLine();
2816 break;
2817 }
2818 ++MIIt;
2819 }
2820 for (auto *Succ : SuccessorBBs)
2821 CheckMBBEdge(Succ, LastLine);
2822 }
2823}
2824
2825// Gather pre-function debug information. Assumes being called immediately
2826// after the function entry point has been emitted.
2827void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
2828 CurFn = MF;
2829
2830 auto *SP = MF->getFunction().getSubprogram();
2831 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
2832 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
2833 return;
2834
2835 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(DIUnit: SP->getUnit());
2836 FunctionLineTableLabel = CU.emitFuncLineTableOffsets()
2837 ? Asm->OutStreamer->emitLineTableLabel()
2838 : nullptr;
2839
2840 Asm->OutStreamer->getContext().setDwarfCompileUnitID(
2841 getDwarfCompileUnitIDForLineTable(CU));
2842
2843 // Call target-specific debug info initialization.
2844 initializeTargetDebugInfo(MF: *MF);
2845
2846 // Record beginning of function.
2847 PrologEndLoc = emitInitialLocDirective(
2848 MF: *MF, CUID: Asm->OutStreamer->getContext().getDwarfCompileUnitID());
2849
2850 // Run both `findForceIsStmtInstrs` and `computeKeyInstructions` because
2851 // Not-Key-Instructions functions may be inlined into Key Instructions
2852 // functions and vice versa.
2853 if (KeyInstructionsAreStmts)
2854 computeKeyInstructions(MF);
2855 findForceIsStmtInstrs(MF);
2856}
2857
2858unsigned
2859DwarfDebug::getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU) {
2860 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
2861 // belongs to so that we add to the correct per-cu line table in the
2862 // non-asm case.
2863 if (Asm->OutStreamer->hasRawTextSupport())
2864 // Use a single line table if we are generating assembly.
2865 return 0;
2866 else
2867 return CU.getUniqueID();
2868}
2869
2870void DwarfDebug::terminateLineTable(const DwarfCompileUnit *CU) {
2871 const auto &CURanges = CU->getRanges();
2872 auto &LineTable = Asm->OutStreamer->getContext().getMCDwarfLineTable(
2873 CUID: getDwarfCompileUnitIDForLineTable(CU: *CU));
2874 // Add the last range label for the given CU.
2875 LineTable.getMCLineSections().addEndEntry(
2876 EndLabel: const_cast<MCSymbol *>(CURanges.back().End));
2877}
2878
2879void DwarfDebug::skippedNonDebugFunction() {
2880 // If we don't have a subprogram for this function then there will be a hole
2881 // in the range information. Keep note of this by setting the previously used
2882 // section to nullptr.
2883 // Terminate the pending line table.
2884 if (PrevCU)
2885 terminateLineTable(CU: PrevCU);
2886 PrevCU = nullptr;
2887 CurFn = nullptr;
2888}
2889
2890// Gather and emit post-function debug information.
2891void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
2892 const Function &F = MF->getFunction();
2893 const DISubprogram *SP = F.getSubprogram();
2894
2895 assert(CurFn == MF &&
2896 "endFunction should be called with the same function as beginFunction");
2897
2898 // Set DwarfDwarfCompileUnitID in MCContext to default value.
2899 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
2900
2901 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
2902 assert(!FnScope || SP == FnScope->getScopeNode());
2903 DwarfCompileUnit &TheCU = getOrCreateDwarfCompileUnit(DIUnit: SP->getUnit());
2904 if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
2905 PrevLabel = nullptr;
2906 CurFn = nullptr;
2907 return;
2908 }
2909
2910 DenseSet<InlinedEntity> Processed;
2911 collectEntityInfo(TheCU, SP, Processed);
2912
2913 // Add the range of this function to the list of ranges for the CU.
2914 // With basic block sections, add ranges for all basic block sections.
2915 for (const auto &R : Asm->MBBSectionRanges)
2916 TheCU.addRange(Range: {.Begin: R.second.BeginLabel, .End: R.second.EndLabel});
2917
2918 // Under -gmlt, skip building the subprogram if there are no inlined
2919 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
2920 // is still needed as we need its source location.
2921 if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
2922 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
2923 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
2924 for (const auto &R : Asm->MBBSectionRanges)
2925 addArangeLabel(SCU: SymbolCU(&TheCU, R.second.BeginLabel));
2926
2927 assert(InfoHolder.getScopeVariables().empty());
2928 PrevLabel = nullptr;
2929 CurFn = nullptr;
2930 return;
2931 }
2932
2933#ifndef NDEBUG
2934 size_t NumAbstractSubprograms = LScopes.getAbstractScopesList().size();
2935#endif
2936 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
2937 const auto *SP = cast<DISubprogram>(Val: AScope->getScopeNode());
2938 for (const MDNode *N : SP->getRetainedNodes()) {
2939 const auto *LS = getRetainedNodeScope(N);
2940 // Ensure LexicalScope is created for the scope of this node.
2941 auto *LexS = LScopes.getOrCreateAbstractScope(Scope: LS);
2942 assert(LexS && "Expected the LexicalScope to be created.");
2943 if (isa<DILocalVariable>(Val: N) || isa<DILabel>(Val: N)) {
2944 auto *DN = cast<DINode>(Val: N);
2945 // Collect info for variables/labels that were optimized out.
2946 if (!Processed.insert(V: InlinedEntity(DN, nullptr)).second ||
2947 TheCU.getExistingAbstractEntity(Node: DN))
2948 continue;
2949 TheCU.createAbstractEntity(Node: DN, Scope: LexS);
2950 } else {
2951 // Remember the node if this is a local declarations.
2952 LocalDeclsPerLS[LS].insert(X: N);
2953 }
2954 assert(
2955 LScopes.getAbstractScopesList().size() == NumAbstractSubprograms &&
2956 "getOrCreateAbstractScope() inserted an abstract subprogram scope");
2957 }
2958 constructAbstractSubprogramScopeDIE(SrcCU&: TheCU, Scope: AScope);
2959 }
2960
2961 ProcessedSPNodes.insert(X: SP);
2962 DIE &ScopeDIE =
2963 TheCU.constructSubprogramScopeDIE(Sub: SP, F, Scope: FnScope, LineTableSym: FunctionLineTableLabel);
2964 if (auto *SkelCU = TheCU.getSkeleton())
2965 if (!LScopes.getAbstractScopesList().empty() &&
2966 TheCU.getCUNode()->getSplitDebugInlining())
2967 SkelCU->constructSubprogramScopeDIE(Sub: SP, F, Scope: FnScope,
2968 LineTableSym: FunctionLineTableLabel);
2969
2970 FunctionLineTableLabel = nullptr;
2971
2972 // Construct call site entries.
2973 constructCallSiteEntryDIEs(SP: *SP, CU&: TheCU, ScopeDIE, MF: *MF);
2974
2975 // Clear debug info
2976 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
2977 // DbgVariables except those that are also in AbstractVariables (since they
2978 // can be used cross-function)
2979 InfoHolder.getScopeVariables().clear();
2980 InfoHolder.getScopeLabels().clear();
2981 LocalDeclsPerLS.clear();
2982 PrevLabel = nullptr;
2983 CurFn = nullptr;
2984}
2985
2986// Register a source line with debug info. Returns the unique label that was
2987// emitted and which provides correspondence to the source line list.
2988void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
2989 unsigned Flags, StringRef Location) {
2990 ::recordSourceLine(Asm&: *Asm, Line, Col, S, Flags,
2991 CUID: Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
2992 DwarfVersion: getDwarfVersion(), DCUs: getUnits(), Comment: Location);
2993}
2994
2995//===----------------------------------------------------------------------===//
2996// Emit Methods
2997//===----------------------------------------------------------------------===//
2998
2999// Emit the debug info section.
3000void DwarfDebug::emitDebugInfo() {
3001 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3002 Holder.emitUnits(/* UseOffsets */ false);
3003}
3004
3005// Emit the abbreviation section.
3006void DwarfDebug::emitAbbreviations() {
3007 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3008
3009 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
3010}
3011
3012void DwarfDebug::emitStringOffsetsTableHeader() {
3013 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3014 Holder.getStringPool().emitStringOffsetsTableHeader(
3015 Asm&: *Asm, OffsetSection: Asm->getObjFileLowering().getDwarfStrOffSection(),
3016 StartSym: Holder.getStringOffsetsStartSym());
3017}
3018
3019template <typename AccelTableT>
3020void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
3021 StringRef TableName) {
3022 Asm->OutStreamer->switchSection(Section);
3023
3024 // Emit the full data.
3025 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
3026}
3027
3028void DwarfDebug::emitAccelDebugNames() {
3029 // Don't emit anything if we have no compilation units to index.
3030 if (getUnits().empty())
3031 return;
3032
3033 emitDWARF5AccelTable(Asm, Contents&: AccelDebugNames, DD: *this, CUs: getUnits());
3034}
3035
3036// Emit visible names into a hashed accelerator table section.
3037void DwarfDebug::emitAccelNames() {
3038 emitAccel(Accel&: AccelNames, Section: Asm->getObjFileLowering().getDwarfAccelNamesSection(),
3039 TableName: "Names");
3040}
3041
3042// Emit objective C classes and categories into a hashed accelerator table
3043// section.
3044void DwarfDebug::emitAccelObjC() {
3045 emitAccel(Accel&: AccelObjC, Section: Asm->getObjFileLowering().getDwarfAccelObjCSection(),
3046 TableName: "ObjC");
3047}
3048
3049// Emit namespace dies into a hashed accelerator table.
3050void DwarfDebug::emitAccelNamespaces() {
3051 emitAccel(Accel&: AccelNamespace,
3052 Section: Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
3053 TableName: "namespac");
3054}
3055
3056// Emit type dies into a hashed accelerator table.
3057void DwarfDebug::emitAccelTypes() {
3058 emitAccel(Accel&: AccelTypes, Section: Asm->getObjFileLowering().getDwarfAccelTypesSection(),
3059 TableName: "types");
3060}
3061
3062// Public name handling.
3063// The format for the various pubnames:
3064//
3065// dwarf pubnames - offset/name pairs where the offset is the offset into the CU
3066// for the DIE that is named.
3067//
3068// gnu pubnames - offset/index value/name tuples where the offset is the offset
3069// into the CU and the index value is computed according to the type of value
3070// for the DIE that is named.
3071//
3072// For type units the offset is the offset of the skeleton DIE. For split dwarf
3073// it's the offset within the debug_info/debug_types dwo section, however, the
3074// reference in the pubname header doesn't change.
3075
3076/// computeIndexValue - Compute the gdb index value for the DIE and CU.
3077static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
3078 const DIE *Die) {
3079 // Entities that ended up only in a Type Unit reference the CU instead (since
3080 // the pub entry has offsets within the CU there's no real offset that can be
3081 // provided anyway). As it happens all such entities (namespaces and types,
3082 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
3083 // not to be true it would be necessary to persist this information from the
3084 // point at which the entry is added to the index data structure - since by
3085 // the time the index is built from that, the original type/namespace DIE in a
3086 // type unit has already been destroyed so it can't be queried for properties
3087 // like tag, etc.
3088 if (Die->getTag() == dwarf::DW_TAG_compile_unit)
3089 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
3090 dwarf::GIEL_EXTERNAL);
3091 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
3092
3093 // We could have a specification DIE that has our most of our knowledge,
3094 // look for that now.
3095 if (DIEValue SpecVal = Die->findAttribute(Attribute: dwarf::DW_AT_specification)) {
3096 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
3097 if (SpecDIE.findAttribute(Attribute: dwarf::DW_AT_external))
3098 Linkage = dwarf::GIEL_EXTERNAL;
3099 } else if (Die->findAttribute(Attribute: dwarf::DW_AT_external))
3100 Linkage = dwarf::GIEL_EXTERNAL;
3101
3102 switch (Die->getTag()) {
3103 case dwarf::DW_TAG_class_type:
3104 case dwarf::DW_TAG_structure_type:
3105 case dwarf::DW_TAG_union_type:
3106 case dwarf::DW_TAG_enumeration_type:
3107 return dwarf::PubIndexEntryDescriptor(
3108 dwarf::GIEK_TYPE, dwarf::isCPlusPlus(S: CU->getSourceLanguage())
3109 ? dwarf::GIEL_EXTERNAL
3110 : dwarf::GIEL_STATIC);
3111 case dwarf::DW_TAG_typedef:
3112 case dwarf::DW_TAG_base_type:
3113 case dwarf::DW_TAG_subrange_type:
3114 case dwarf::DW_TAG_template_alias:
3115 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
3116 case dwarf::DW_TAG_namespace:
3117 return dwarf::GIEK_TYPE;
3118 case dwarf::DW_TAG_subprogram:
3119 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
3120 case dwarf::DW_TAG_variable:
3121 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
3122 case dwarf::DW_TAG_enumerator:
3123 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
3124 dwarf::GIEL_STATIC);
3125 default:
3126 return dwarf::GIEK_NONE;
3127 }
3128}
3129
3130/// emitDebugPubSections - Emit visible names and types into debug pubnames and
3131/// pubtypes sections.
3132void DwarfDebug::emitDebugPubSections() {
3133 for (const auto &NU : CUMap) {
3134 DwarfCompileUnit *TheU = NU.second;
3135 if (!TheU->hasDwarfPubSections())
3136 continue;
3137
3138 bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
3139 DICompileUnit::DebugNameTableKind::GNU;
3140
3141 Asm->OutStreamer->switchSection(
3142 Section: GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
3143 : Asm->getObjFileLowering().getDwarfPubNamesSection());
3144 emitDebugPubSection(GnuStyle, Name: "Names", TheU, Globals: TheU->getGlobalNames());
3145
3146 Asm->OutStreamer->switchSection(
3147 Section: GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
3148 : Asm->getObjFileLowering().getDwarfPubTypesSection());
3149 emitDebugPubSection(GnuStyle, Name: "Types", TheU, Globals: TheU->getGlobalTypes());
3150 }
3151}
3152
3153void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
3154 if (useSectionsAsReferences())
3155 Asm->emitDwarfOffset(Label: CU.getSection()->getBeginSymbol(),
3156 Offset: CU.getDebugSectionOffset());
3157 else
3158 Asm->emitDwarfSymbolReference(Label: CU.getLabelBegin());
3159}
3160
3161void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
3162 DwarfCompileUnit *TheU,
3163 const StringMap<const DIE *> &Globals) {
3164 if (auto *Skeleton = TheU->getSkeleton())
3165 TheU = Skeleton;
3166
3167 // Emit the header.
3168 MCSymbol *EndLabel = Asm->emitDwarfUnitLength(
3169 Prefix: "pub" + Name, Comment: "Length of Public " + Name + " Info");
3170
3171 Asm->OutStreamer->AddComment(T: "DWARF Version");
3172 Asm->emitInt16(Value: dwarf::DW_PUBNAMES_VERSION);
3173
3174 Asm->OutStreamer->AddComment(T: "Offset of Compilation Unit Info");
3175 emitSectionReference(CU: *TheU);
3176
3177 Asm->OutStreamer->AddComment(T: "Compilation Unit Length");
3178 Asm->emitDwarfLengthOrOffset(Value: TheU->getLength());
3179
3180 // Emit the pubnames for this compilation unit.
3181 SmallVector<std::pair<StringRef, const DIE *>, 0> Vec;
3182 for (const auto &GI : Globals)
3183 Vec.emplace_back(Args: GI.first(), Args: GI.second);
3184 llvm::sort(C&: Vec, Comp: [](auto &A, auto &B) {
3185 return A.second->getOffset() < B.second->getOffset();
3186 });
3187 for (const auto &[Name, Entity] : Vec) {
3188 Asm->OutStreamer->AddComment(T: "DIE offset");
3189 Asm->emitDwarfLengthOrOffset(Value: Entity->getOffset());
3190
3191 if (GnuStyle) {
3192 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(CU: TheU, Die: Entity);
3193 Asm->OutStreamer->AddComment(
3194 T: Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Kind: Desc.Kind) +
3195 ", " + dwarf::GDBIndexEntryLinkageString(Linkage: Desc.Linkage));
3196 Asm->emitInt8(Value: Desc.toBits());
3197 }
3198
3199 Asm->OutStreamer->AddComment(T: "External Name");
3200 Asm->OutStreamer->emitBytes(Data: StringRef(Name.data(), Name.size() + 1));
3201 }
3202
3203 Asm->OutStreamer->AddComment(T: "End Mark");
3204 Asm->emitDwarfLengthOrOffset(Value: 0);
3205 Asm->OutStreamer->emitLabel(Symbol: EndLabel);
3206}
3207
3208/// Emit null-terminated strings into a debug str section.
3209void DwarfDebug::emitDebugStr() {
3210 MCSection *StringOffsetsSection = nullptr;
3211 if (useSegmentedStringOffsetsTable()) {
3212 emitStringOffsetsTableHeader();
3213 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
3214 }
3215 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3216 Holder.emitStrings(StrSection: Asm->getObjFileLowering().getDwarfStrSection(),
3217 OffsetSection: StringOffsetsSection, /* UseRelativeOffsets = */ true);
3218}
3219
3220void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
3221 const DebugLocStream::Entry &Entry,
3222 const DwarfCompileUnit *CU) {
3223 auto &&Comments = DebugLocs.getComments(E: Entry);
3224 auto Comment = Comments.begin();
3225 auto End = Comments.end();
3226
3227 // The expressions are inserted into a byte stream rather early (see
3228 // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
3229 // need to reference a base_type DIE the offset of that DIE is not yet known.
3230 // To deal with this we instead insert a placeholder early and then extract
3231 // it here and replace it with the real reference.
3232 unsigned PtrSize = Asm->MAI.getCodePointerSize();
3233 DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(E: Entry).data(),
3234 DebugLocs.getBytes(E: Entry).size()),
3235 Asm->getDataLayout().isLittleEndian(), PtrSize);
3236 DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat());
3237
3238 using Encoding = DWARFExpression::Operation::Encoding;
3239 uint64_t Offset = 0;
3240 for (const auto &Op : Expr) {
3241 assert(Op.getCode() != dwarf::DW_OP_const_type &&
3242 "3 operand ops not yet supported");
3243 assert(!Op.getSubCode() && "SubOps not yet supported");
3244 Streamer.emitInt8(Byte: Op.getCode(), Comment: Comment != End ? *(Comment++) : "");
3245 Offset++;
3246 for (unsigned I = 0; I < Op.getDescription().Op.size(); ++I) {
3247 if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
3248 unsigned Length =
3249 Streamer.emitDIERef(D: *CU->ExprRefedBaseTypes[Op.getRawOperand(Idx: I)].Die);
3250 // Make sure comments stay aligned.
3251 for (unsigned J = 0; J < Length; ++J)
3252 if (Comment != End)
3253 Comment++;
3254 } else {
3255 for (uint64_t J = Offset; J < Op.getOperandEndOffset(Idx: I); ++J)
3256 Streamer.emitInt8(Byte: Data.getData()[J], Comment: Comment != End ? *(Comment++) : "");
3257 }
3258 Offset = Op.getOperandEndOffset(Idx: I);
3259 }
3260 assert(Offset == Op.getEndOffset());
3261 }
3262}
3263
3264void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
3265 const DbgValueLoc &Value,
3266 DwarfExpression &DwarfExpr) {
3267 auto *DIExpr = Value.getExpression();
3268 DIExpressionCursor ExprCursor(DIExpr);
3269 DwarfExpr.addFragmentOffset(Expr: DIExpr);
3270
3271 // If the DIExpr is an Entry Value, we want to follow the same code path
3272 // regardless of whether the DBG_VALUE is variadic or not.
3273 if (DIExpr && DIExpr->isEntryValue()) {
3274 // Entry values can only be a single register with no additional DIExpr,
3275 // so just add it directly.
3276 assert(Value.getLocEntries().size() == 1);
3277 assert(Value.getLocEntries()[0].isLocation());
3278 MachineLocation Location = Value.getLocEntries()[0].getLoc();
3279 DwarfExpr.setLocation(Loc: Location, DIExpr);
3280
3281 DwarfExpr.beginEntryValueExpression(ExprCursor);
3282
3283 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
3284 if (!DwarfExpr.addMachineRegExpression(TRI, Expr&: ExprCursor, MachineReg: Location.getReg()))
3285 return;
3286 return DwarfExpr.addExpression(Expr: std::move(ExprCursor));
3287 }
3288
3289 // Regular entry.
3290 auto EmitValueLocEntry = [&DwarfExpr, &BT,
3291 &AP](const DbgValueLocEntry &Entry,
3292 DIExpressionCursor &Cursor) -> bool {
3293 if (Entry.isInt()) {
3294 if (BT && (BT->getEncoding() == dwarf::DW_ATE_boolean)) {
3295 DwarfExpr.addBooleanConstant(Value: Entry.getInt());
3296 return true;
3297 }
3298
3299 bool IsSigned = BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
3300 BT->getEncoding() == dwarf::DW_ATE_signed_char);
3301 if (BT && AP.getDwarfVersion() >= 4 &&
3302 !AP.getDwarfDebug()->tuneForSCE() && !Cursor) {
3303 // DW_OP_const* pushes a generic, address-sized value. For a wider
3304 // source integer value that cannot fit in the generic type, use
3305 // DW_OP_implicit_value to preserve the source bytes instead. Keep this
3306 // limited to complete constant values: SCE tuning already avoids
3307 // DW_OP_implicit_value for compatibility, and expressions with
3308 // remaining operations may need a scalar stack value rather than an
3309 // implicit value block.
3310 unsigned GenericBitSize = AP.MAI.getCodePointerSize() * 8;
3311 uint64_t TypeBitSize = BT->getSizeInBits();
3312 bool IsByteSized = TypeBitSize % 8 == 0;
3313 bool IsOutOfRange =
3314 IsSigned ? !isIntN(N: GenericBitSize, x: Entry.getInt())
3315 : !isUIntN(N: GenericBitSize,
3316 x: static_cast<uint64_t>(Entry.getInt()));
3317 if (TypeBitSize > GenericBitSize && IsByteSized && IsOutOfRange) {
3318 DwarfExpr.addImplicitValue(
3319 Value: APInt(static_cast<unsigned>(TypeBitSize),
3320 static_cast<uint64_t>(Entry.getInt()), IsSigned,
3321 /*implicitTrunc=*/true),
3322 AP);
3323 return true;
3324 }
3325 }
3326
3327 if (IsSigned)
3328 DwarfExpr.addSignedConstant(Value: Entry.getInt());
3329 else
3330 DwarfExpr.addUnsignedConstant(Value: Entry.getInt());
3331 } else if (Entry.isLocation()) {
3332 MachineLocation Location = Entry.getLoc();
3333 if (Location.isIndirect())
3334 DwarfExpr.setMemoryLocationKind();
3335
3336 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
3337 if (!DwarfExpr.addMachineRegExpression(TRI, Expr&: Cursor, MachineReg: Location.getReg()))
3338 return false;
3339 } else if (Entry.isTargetIndexLocation()) {
3340 TargetIndexLocation Loc = Entry.getTargetIndexLocation();
3341 // TODO TargetIndexLocation is a target-independent. Currently only the
3342 // WebAssembly-specific encoding is supported.
3343 assert(AP.TM.getTargetTriple().isWasm());
3344 DwarfExpr.addWasmLocation(Index: Loc.Index, Offset: static_cast<uint64_t>(Loc.Offset));
3345 } else if (Entry.isConstantFP()) {
3346 if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() &&
3347 !Cursor) {
3348 DwarfExpr.addConstantFP(Value: Entry.getConstantFP()->getValueAPF(), AP);
3349 } else if (Entry.getConstantFP()
3350 ->getValueAPF()
3351 .bitcastToAPInt()
3352 .getBitWidth() <= 64 /*bits*/) {
3353 DwarfExpr.addUnsignedConstant(
3354 Value: Entry.getConstantFP()->getValueAPF().bitcastToAPInt());
3355 } else {
3356 LLVM_DEBUG(
3357 dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
3358 << Entry.getConstantFP()
3359 ->getValueAPF()
3360 .bitcastToAPInt()
3361 .getBitWidth()
3362 << " bits\n");
3363 return false;
3364 }
3365 }
3366 return true;
3367 };
3368
3369 if (!Value.isVariadic()) {
3370 if (!EmitValueLocEntry(Value.getLocEntries()[0], ExprCursor))
3371 return;
3372 DwarfExpr.addExpression(Expr: std::move(ExprCursor));
3373 return;
3374 }
3375
3376 // If any of the location entries are registers with the value 0, then the
3377 // location is undefined.
3378 if (any_of(Range: Value.getLocEntries(), P: [](const DbgValueLocEntry &Entry) {
3379 return Entry.isLocation() && !Entry.getLoc().getReg();
3380 }))
3381 return;
3382
3383 DwarfExpr.addExpression(
3384 Expr: std::move(ExprCursor),
3385 InsertArg: [EmitValueLocEntry, &Value](unsigned Idx,
3386 DIExpressionCursor &Cursor) -> bool {
3387 return EmitValueLocEntry(Value.getLocEntries()[Idx], Cursor);
3388 });
3389}
3390
3391void DebugLocEntry::finalize(const AsmPrinter &AP,
3392 DebugLocStream::ListBuilder &List,
3393 const DIBasicType *BT,
3394 DwarfCompileUnit &TheCU) {
3395 assert(!Values.empty() &&
3396 "location list entries without values are redundant");
3397 assert(Begin != End && "unexpected location list entry with empty range");
3398 DebugLocStream::EntryBuilder Entry(List, Begin, End);
3399 BufferByteStreamer Streamer = Entry.getStreamer();
3400 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
3401 const DbgValueLoc &Value = Values[0];
3402 if (Value.isFragment()) {
3403 // Emit all fragments that belong to the same variable and range.
3404 assert(llvm::all_of(Values, [](DbgValueLoc P) {
3405 return P.isFragment();
3406 }) && "all values are expected to be fragments");
3407 assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");
3408
3409 for (const auto &Fragment : Values)
3410 DwarfDebug::emitDebugLocValue(AP, BT, Value: Fragment, DwarfExpr);
3411
3412 } else {
3413 assert(Values.size() == 1 && "only fragments may have >1 value");
3414 DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
3415 }
3416 DwarfExpr.finalize();
3417 if (DwarfExpr.TagOffset)
3418 List.setTagOffset(*DwarfExpr.TagOffset);
3419}
3420
3421void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
3422 const DwarfCompileUnit *CU) {
3423 // Emit the size.
3424 Asm->OutStreamer->AddComment(T: "Loc expr size");
3425 if (getDwarfVersion() >= 5)
3426 Asm->emitULEB128(Value: DebugLocs.getBytes(E: Entry).size());
3427 else if (DebugLocs.getBytes(E: Entry).size() <= std::numeric_limits<uint16_t>::max())
3428 Asm->emitInt16(Value: DebugLocs.getBytes(E: Entry).size());
3429 else {
3430 // The entry is too big to fit into 16 bit, drop it as there is nothing we
3431 // can do.
3432 Asm->emitInt16(Value: 0);
3433 return;
3434 }
3435 // Emit the entry.
3436 APByteStreamer Streamer(*Asm);
3437 emitDebugLocEntry(Streamer, Entry, CU);
3438}
3439
3440// Emit the header of a DWARF 5 range list table list table. Returns the symbol
3441// that designates the end of the table for the caller to emit when the table is
3442// complete.
3443static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
3444 const DwarfFile &Holder) {
3445 MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(S&: *Asm->OutStreamer);
3446
3447 Asm->OutStreamer->AddComment(T: "Offset entry count");
3448 Asm->emitInt32(Value: Holder.getRangeLists().size());
3449 Asm->OutStreamer->emitLabel(Symbol: Holder.getRnglistsTableBaseSym());
3450
3451 for (const RangeSpanList &List : Holder.getRangeLists())
3452 Asm->emitLabelDifference(Hi: List.Label, Lo: Holder.getRnglistsTableBaseSym(),
3453 Size: Asm->getDwarfOffsetByteSize());
3454
3455 return TableEnd;
3456}
3457
3458// Emit the header of a DWARF 5 locations list table. Returns the symbol that
3459// designates the end of the table for the caller to emit when the table is
3460// complete.
3461static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
3462 const DwarfDebug &DD) {
3463 MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(S&: *Asm->OutStreamer);
3464
3465 const auto &DebugLocs = DD.getDebugLocs();
3466
3467 Asm->OutStreamer->AddComment(T: "Offset entry count");
3468 Asm->emitInt32(Value: DebugLocs.getLists().size());
3469 Asm->OutStreamer->emitLabel(Symbol: DebugLocs.getSym());
3470
3471 for (const auto &List : DebugLocs.getLists())
3472 Asm->emitLabelDifference(Hi: List.Label, Lo: DebugLocs.getSym(),
3473 Size: Asm->getDwarfOffsetByteSize());
3474
3475 return TableEnd;
3476}
3477
3478template <typename Ranges, typename PayloadEmitter>
3479static void
3480emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
3481 const DwarfCompileUnit &CU, unsigned BaseAddressx,
3482 unsigned OffsetPair, unsigned StartxLength, unsigned StartxEndx,
3483 unsigned EndOfList, StringRef (*StringifyEnum)(unsigned),
3484 bool ShouldUseBaseAddress, PayloadEmitter EmitPayload) {
3485 auto Size = Asm->MAI.getCodePointerSize();
3486 bool UseDwarf5 = DD.getDwarfVersion() >= 5;
3487
3488 // Emit our symbol so we can find the beginning of the range.
3489 Asm->OutStreamer->emitLabel(Symbol: Sym);
3490
3491 // Gather all the ranges that apply to the same section so they can share
3492 // a base address entry.
3493 SmallMapVector<const MCSection *, std::vector<decltype(&*R.begin())>, 16>
3494 SectionRanges;
3495
3496 for (const auto &Range : R)
3497 SectionRanges[&Range.Begin->getSection()].push_back(&Range);
3498
3499 const MCSymbol *CUBase = CU.getBaseAddress();
3500 bool BaseIsSet = false;
3501 for (const auto &P : SectionRanges) {
3502 auto *Base = CUBase;
3503 if (DD.shouldResetBaseAddress(Section: *P.first) ||
3504 (DD.useSplitDwarf() && UseDwarf5 && P.first->isLinkerRelaxable())) {
3505 BaseIsSet = false;
3506 Base = nullptr;
3507 } else if (!Base && ShouldUseBaseAddress) {
3508 const MCSymbol *Begin = P.second.front()->Begin;
3509 const MCSymbol *NewBase = DD.getSectionLabel(S: &Begin->getSection());
3510 if (!UseDwarf5) {
3511 Base = NewBase;
3512 BaseIsSet = true;
3513 Asm->OutStreamer->emitIntValue(Value: -1, Size);
3514 Asm->OutStreamer->AddComment(T: " base address");
3515 Asm->OutStreamer->emitSymbolValue(Sym: Base, Size);
3516 } else if (NewBase != Begin || P.second.size() > 1) {
3517 // Only use a base address if
3518 // * the existing pool address doesn't match (NewBase != Begin)
3519 // * or, there's more than one entry to share the base address
3520 Base = NewBase;
3521 BaseIsSet = true;
3522 Asm->OutStreamer->AddComment(T: StringifyEnum(BaseAddressx));
3523 Asm->emitInt8(Value: BaseAddressx);
3524 Asm->OutStreamer->AddComment(T: " base address index");
3525 Asm->emitULEB128(Value: DD.getAddressPool().getIndex(Sym: Base));
3526 }
3527 } else if (BaseIsSet && !UseDwarf5) {
3528 BaseIsSet = false;
3529 assert(!Base);
3530 Asm->OutStreamer->emitIntValue(Value: -1, Size);
3531 Asm->OutStreamer->emitIntValue(Value: 0, Size);
3532 }
3533
3534 for (const auto *RS : P.second) {
3535 const MCSymbol *Begin = RS->Begin;
3536 const MCSymbol *End = RS->End;
3537 assert(Begin && "Range without a begin symbol?");
3538 assert(End && "Range without an end symbol?");
3539 if (Base) {
3540 if (UseDwarf5) {
3541 // Emit offset_pair when we have a base.
3542 Asm->OutStreamer->AddComment(T: StringifyEnum(OffsetPair));
3543 Asm->emitInt8(Value: OffsetPair);
3544 Asm->OutStreamer->AddComment(T: " starting offset");
3545 Asm->emitLabelDifferenceAsULEB128(Hi: Begin, Lo: Base);
3546 Asm->OutStreamer->AddComment(T: " ending offset");
3547 Asm->emitLabelDifferenceAsULEB128(Hi: End, Lo: Base);
3548 } else {
3549 Asm->emitLabelDifference(Hi: Begin, Lo: Base, Size);
3550 Asm->emitLabelDifference(Hi: End, Lo: Base, Size);
3551 }
3552 } else if (UseDwarf5) {
3553 // NOTE: We can't use absoluteSymbolDiff here instead of
3554 // isRangeRelaxable. While isRangeRelaxable only checks that the offset
3555 // between labels won't change at link time (which is exactly what we
3556 // need), absoluteSymbolDiff also requires that the offset remain
3557 // unchanged at assembly time, imposing a much stricter condition.
3558 // Consequently, this would lead to less optimal debug info emission.
3559 if (DD.useSplitDwarf() && llvm::isRangeRelaxable(Begin, End)) {
3560 Asm->OutStreamer->AddComment(T: StringifyEnum(StartxEndx));
3561 Asm->emitInt8(Value: StartxEndx);
3562 Asm->OutStreamer->AddComment(T: " start index");
3563 Asm->emitULEB128(Value: DD.getAddressPool().getIndex(Sym: Begin));
3564 Asm->OutStreamer->AddComment(T: " end index");
3565 Asm->emitULEB128(Value: DD.getAddressPool().getIndex(Sym: End));
3566 } else {
3567 Asm->OutStreamer->AddComment(T: StringifyEnum(StartxLength));
3568 Asm->emitInt8(Value: StartxLength);
3569 Asm->OutStreamer->AddComment(T: " start index");
3570 Asm->emitULEB128(Value: DD.getAddressPool().getIndex(Sym: Begin));
3571 Asm->OutStreamer->AddComment(T: " length");
3572 Asm->emitLabelDifferenceAsULEB128(Hi: End, Lo: Begin);
3573 }
3574 } else {
3575 Asm->OutStreamer->emitSymbolValue(Sym: Begin, Size);
3576 Asm->OutStreamer->emitSymbolValue(Sym: End, Size);
3577 }
3578 EmitPayload(*RS);
3579 }
3580 }
3581
3582 if (UseDwarf5) {
3583 Asm->OutStreamer->AddComment(T: StringifyEnum(EndOfList));
3584 Asm->emitInt8(Value: EndOfList);
3585 } else {
3586 // Terminate the list with two 0 values.
3587 Asm->OutStreamer->emitIntValue(Value: 0, Size);
3588 Asm->OutStreamer->emitIntValue(Value: 0, Size);
3589 }
3590}
3591
3592// Handles emission of both debug_loclist / debug_loclist.dwo
3593static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
3594 emitRangeList(
3595 DD, Asm, Sym: List.Label, R: DD.getDebugLocs().getEntries(L: List), CU: *List.CU,
3596 BaseAddressx: dwarf::DW_LLE_base_addressx, OffsetPair: dwarf::DW_LLE_offset_pair,
3597 StartxLength: dwarf::DW_LLE_startx_length, StartxEndx: dwarf::DW_LLE_startx_endx,
3598 EndOfList: dwarf::DW_LLE_end_of_list, StringifyEnum: llvm::dwarf::LocListEncodingString,
3599 /* ShouldUseBaseAddress */ true, EmitPayload: [&](const DebugLocStream::Entry &E) {
3600 DD.emitDebugLocEntryLocation(Entry: E, CU: List.CU);
3601 });
3602}
3603
3604void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
3605 if (DebugLocs.getLists().empty())
3606 return;
3607
3608 Asm->OutStreamer->switchSection(Section: Sec);
3609
3610 MCSymbol *TableEnd = nullptr;
3611 if (getDwarfVersion() >= 5)
3612 TableEnd = emitLoclistsTableHeader(Asm, DD: *this);
3613
3614 for (const auto &List : DebugLocs.getLists())
3615 emitLocList(DD&: *this, Asm, List);
3616
3617 if (TableEnd)
3618 Asm->OutStreamer->emitLabel(Symbol: TableEnd);
3619}
3620
3621// Emit locations into the .debug_loc/.debug_loclists section.
3622void DwarfDebug::emitDebugLoc() {
3623 emitDebugLocImpl(
3624 Sec: getDwarfVersion() >= 5
3625 ? Asm->getObjFileLowering().getDwarfLoclistsSection()
3626 : Asm->getObjFileLowering().getDwarfLocSection());
3627}
3628
3629// Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
3630void DwarfDebug::emitDebugLocDWO() {
3631 if (getDwarfVersion() >= 5) {
3632 emitDebugLocImpl(
3633 Sec: Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
3634
3635 return;
3636 }
3637
3638 for (const auto &List : DebugLocs.getLists()) {
3639 Asm->OutStreamer->switchSection(
3640 Section: Asm->getObjFileLowering().getDwarfLocDWOSection());
3641 Asm->OutStreamer->emitLabel(Symbol: List.Label);
3642
3643 for (const auto &Entry : DebugLocs.getEntries(L: List)) {
3644 // GDB only supports startx_length in pre-standard split-DWARF.
3645 // (in v5 standard loclists, it currently* /only/ supports base_address +
3646 // offset_pair, so the implementations can't really share much since they
3647 // need to use different representations)
3648 // * as of October 2018, at least
3649 //
3650 // In v5 (see emitLocList), this uses SectionLabels to reuse existing
3651 // addresses in the address pool to minimize object size/relocations.
3652 Asm->emitInt8(Value: dwarf::DW_LLE_startx_length);
3653 unsigned idx = AddrPool.getIndex(Sym: Entry.Begin);
3654 Asm->emitULEB128(Value: idx);
3655 // Also the pre-standard encoding is slightly different, emitting this as
3656 // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
3657 Asm->emitLabelDifference(Hi: Entry.End, Lo: Entry.Begin, Size: 4);
3658 emitDebugLocEntryLocation(Entry, CU: List.CU);
3659 }
3660 Asm->emitInt8(Value: dwarf::DW_LLE_end_of_list);
3661 }
3662}
3663
3664struct ArangeSpan {
3665 const MCSymbol *Start, *End;
3666};
3667
3668// Emit a debug aranges section, containing a CU lookup for any
3669// address we can tie back to a CU.
3670void DwarfDebug::emitDebugARanges() {
3671 if (ArangeLabels.empty())
3672 return;
3673
3674 // Provides a unique id per text section.
3675 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
3676
3677 // Filter labels by section.
3678 for (const SymbolCU &SCU : ArangeLabels) {
3679 if (SCU.Sym->isInSection()) {
3680 // Make a note of this symbol and it's section.
3681 MCSection *Section = &SCU.Sym->getSection();
3682 SectionMap[Section].push_back(Elt: SCU);
3683 } else {
3684 // Some symbols (e.g. common/bss on mach-o) can have no section but still
3685 // appear in the output. This sucks as we rely on sections to build
3686 // arange spans. We can do it without, but it's icky.
3687 SectionMap[nullptr].push_back(Elt: SCU);
3688 }
3689 }
3690
3691 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
3692
3693 for (auto &I : SectionMap) {
3694 MCSection *Section = I.first;
3695 SmallVector<SymbolCU, 8> &List = I.second;
3696 assert(!List.empty());
3697
3698 // If we have no section (e.g. common), just write out
3699 // individual spans for each symbol.
3700 if (!Section) {
3701 for (const SymbolCU &Cur : List) {
3702 ArangeSpan Span;
3703 Span.Start = Cur.Sym;
3704 Span.End = nullptr;
3705 assert(Cur.CU);
3706 Spans[Cur.CU].push_back(x: Span);
3707 }
3708 continue;
3709 }
3710
3711 // Insert a final terminator.
3712 List.push_back(Elt: SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
3713
3714 // Build spans between each label.
3715 const MCSymbol *StartSym = List[0].Sym;
3716 for (size_t n = 1, e = List.size(); n < e; n++) {
3717 const SymbolCU &Prev = List[n - 1];
3718 const SymbolCU &Cur = List[n];
3719
3720 // Try and build the longest span we can within the same CU.
3721 if (Cur.CU != Prev.CU) {
3722 ArangeSpan Span;
3723 Span.Start = StartSym;
3724 Span.End = Cur.Sym;
3725 assert(Prev.CU);
3726 Spans[Prev.CU].push_back(x: Span);
3727 StartSym = Cur.Sym;
3728 }
3729 }
3730 }
3731
3732 // Start the dwarf aranges section.
3733 Asm->OutStreamer->switchSection(
3734 Section: Asm->getObjFileLowering().getDwarfARangesSection());
3735
3736 unsigned PtrSize = Asm->MAI.getCodePointerSize();
3737
3738 // Build a list of CUs used.
3739 std::vector<DwarfCompileUnit *> CUs;
3740 for (const auto &it : Spans) {
3741 DwarfCompileUnit *CU = it.first;
3742 CUs.push_back(x: CU);
3743 }
3744
3745 // Sort the CU list (again, to ensure consistent output order).
3746 llvm::sort(C&: CUs, Comp: [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
3747 return A->getUniqueID() < B->getUniqueID();
3748 });
3749
3750 // Emit an arange table for each CU we used.
3751 for (DwarfCompileUnit *CU : CUs) {
3752 std::vector<ArangeSpan> &List = Spans[CU];
3753
3754 // Describe the skeleton CU's offset and length, not the dwo file's.
3755 if (auto *Skel = CU->getSkeleton())
3756 CU = Skel;
3757
3758 // Emit size of content not including length itself.
3759 unsigned ContentSize =
3760 sizeof(int16_t) + // DWARF ARange version number
3761 Asm->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info
3762 // section
3763 sizeof(int8_t) + // Pointer Size (in bytes)
3764 sizeof(int8_t); // Segment Size (in bytes)
3765
3766 unsigned TupleSize = PtrSize * 2;
3767
3768 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
3769 unsigned Padding = offsetToAlignment(
3770 Value: Asm->getUnitLengthFieldByteSize() + ContentSize, Alignment: Align(TupleSize));
3771
3772 ContentSize += Padding;
3773 ContentSize += (List.size() + 1) * TupleSize;
3774
3775 // For each compile unit, write the list of spans it covers.
3776 Asm->emitDwarfUnitLength(Length: ContentSize, Comment: "Length of ARange Set");
3777 Asm->OutStreamer->AddComment(T: "DWARF Arange version number");
3778 Asm->emitInt16(Value: dwarf::DW_ARANGES_VERSION);
3779 Asm->OutStreamer->AddComment(T: "Offset Into Debug Info Section");
3780 emitSectionReference(CU: *CU);
3781 Asm->OutStreamer->AddComment(T: "Address Size (in bytes)");
3782 Asm->emitInt8(Value: PtrSize);
3783 Asm->OutStreamer->AddComment(T: "Segment Size (in bytes)");
3784 Asm->emitInt8(Value: 0);
3785
3786 Asm->OutStreamer->emitFill(NumBytes: Padding, FillValue: 0xff);
3787
3788 for (const ArangeSpan &Span : List) {
3789 Asm->emitLabelReference(Label: Span.Start, Size: PtrSize);
3790
3791 // Calculate the size as being from the span start to its end.
3792 //
3793 // If the size is zero, then round it up to one byte. The DWARF
3794 // specification requires that entries in this table have nonzero
3795 // lengths.
3796 auto SizeRef = SymSize.find(Val: Span.Start);
3797 if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {
3798 Asm->emitLabelDifference(Hi: Span.End, Lo: Span.Start, Size: PtrSize);
3799 } else {
3800 // For symbols without an end marker (e.g. common), we
3801 // write a single arange entry containing just that one symbol.
3802 uint64_t Size;
3803 if (SizeRef == SymSize.end() || SizeRef->second == 0)
3804 Size = 1;
3805 else
3806 Size = SizeRef->second;
3807
3808 Asm->OutStreamer->emitIntValue(Value: Size, Size: PtrSize);
3809 }
3810 }
3811
3812 Asm->OutStreamer->AddComment(T: "ARange terminator");
3813 Asm->OutStreamer->emitIntValue(Value: 0, Size: PtrSize);
3814 Asm->OutStreamer->emitIntValue(Value: 0, Size: PtrSize);
3815 }
3816}
3817
3818/// Emit a single range list. We handle both DWARF v5 and earlier.
3819static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
3820 const RangeSpanList &List) {
3821 emitRangeList(DD, Asm, Sym: List.Label, R: List.Ranges, CU: *List.CU,
3822 BaseAddressx: dwarf::DW_RLE_base_addressx, OffsetPair: dwarf::DW_RLE_offset_pair,
3823 StartxLength: dwarf::DW_RLE_startx_length, StartxEndx: dwarf::DW_RLE_startx_endx,
3824 EndOfList: dwarf::DW_RLE_end_of_list, StringifyEnum: llvm::dwarf::RangeListEncodingString,
3825 ShouldUseBaseAddress: List.CU->getCUNode()->getRangesBaseAddress() ||
3826 DD.getDwarfVersion() >= 5,
3827 EmitPayload: [](auto) {});
3828}
3829
3830void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
3831 if (Holder.getRangeLists().empty())
3832 return;
3833
3834 assert(useRangesSection());
3835 assert(!CUMap.empty());
3836 assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
3837 return !Pair.second->getCUNode()->isDebugDirectivesOnly();
3838 }));
3839
3840 Asm->OutStreamer->switchSection(Section);
3841
3842 MCSymbol *TableEnd = nullptr;
3843 if (getDwarfVersion() >= 5)
3844 TableEnd = emitRnglistsTableHeader(Asm, Holder);
3845
3846 for (const RangeSpanList &List : Holder.getRangeLists())
3847 emitRangeList(DD&: *this, Asm, List);
3848
3849 if (TableEnd)
3850 Asm->OutStreamer->emitLabel(Symbol: TableEnd);
3851}
3852
3853/// Emit address ranges into the .debug_ranges section or into the DWARF v5
3854/// .debug_rnglists section.
3855void DwarfDebug::emitDebugRanges() {
3856 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3857
3858 emitDebugRangesImpl(Holder,
3859 Section: getDwarfVersion() >= 5
3860 ? Asm->getObjFileLowering().getDwarfRnglistsSection()
3861 : Asm->getObjFileLowering().getDwarfRangesSection());
3862}
3863
3864void DwarfDebug::emitDebugRangesDWO() {
3865 emitDebugRangesImpl(Holder: InfoHolder,
3866 Section: Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
3867}
3868
3869/// Emit the header of a DWARF 5 macro section, or the GNU extension for
3870/// DWARF 4.
3871static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
3872 const DwarfCompileUnit &CU, uint16_t DwarfVersion) {
3873 enum HeaderFlagMask {
3874#define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
3875#include "llvm/BinaryFormat/Dwarf.def"
3876 };
3877 Asm->OutStreamer->AddComment(T: "Macro information version");
3878 Asm->emitInt16(Value: DwarfVersion >= 5 ? DwarfVersion : 4);
3879 // We emit the line offset flag unconditionally here, since line offset should
3880 // be mostly present.
3881 if (Asm->isDwarf64()) {
3882 Asm->OutStreamer->AddComment(T: "Flags: 64 bit, debug_line_offset present");
3883 Asm->emitInt8(Value: MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
3884 } else {
3885 Asm->OutStreamer->AddComment(T: "Flags: 32 bit, debug_line_offset present");
3886 Asm->emitInt8(Value: MACRO_FLAG_DEBUG_LINE_OFFSET);
3887 }
3888 Asm->OutStreamer->AddComment(T: "debug_line_offset");
3889 if (DD.useSplitDwarf())
3890 Asm->emitDwarfLengthOrOffset(Value: 0);
3891 else
3892 Asm->emitDwarfSymbolReference(Label: CU.getLineTableStartSym());
3893}
3894
3895void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
3896 for (auto *MN : Nodes) {
3897 if (auto *M = dyn_cast<DIMacro>(Val: MN))
3898 emitMacro(M&: *M);
3899 else if (auto *F = dyn_cast<DIMacroFile>(Val: MN))
3900 emitMacroFile(F&: *F, U);
3901 else
3902 llvm_unreachable("Unexpected DI type!");
3903 }
3904}
3905
3906void DwarfDebug::emitMacro(DIMacro &M) {
3907 StringRef Name = M.getName();
3908 StringRef Value = M.getValue();
3909
3910 // There should be one space between the macro name and the macro value in
3911 // define entries. In undef entries, only the macro name is emitted.
3912 std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();
3913
3914 if (UseDebugMacroSection) {
3915 if (getDwarfVersion() >= 5) {
3916 unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3917 ? dwarf::DW_MACRO_define_strx
3918 : dwarf::DW_MACRO_undef_strx;
3919 Asm->OutStreamer->AddComment(T: dwarf::MacroString(Encoding: Type));
3920 Asm->emitULEB128(Value: Type);
3921 Asm->OutStreamer->AddComment(T: "Line Number");
3922 Asm->emitULEB128(Value: M.getLine());
3923 Asm->OutStreamer->AddComment(T: "Macro String");
3924 Asm->emitULEB128(
3925 Value: InfoHolder.getStringPool().getIndexedEntry(Asm&: *Asm, Str).getIndex());
3926 } else {
3927 unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3928 ? dwarf::DW_MACRO_GNU_define_indirect
3929 : dwarf::DW_MACRO_GNU_undef_indirect;
3930 Asm->OutStreamer->AddComment(T: dwarf::GnuMacroString(Encoding: Type));
3931 Asm->emitULEB128(Value: Type);
3932 Asm->OutStreamer->AddComment(T: "Line Number");
3933 Asm->emitULEB128(Value: M.getLine());
3934 Asm->OutStreamer->AddComment(T: "Macro String");
3935 Asm->emitDwarfSymbolReference(
3936 Label: InfoHolder.getStringPool().getEntry(Asm&: *Asm, Str).getSymbol());
3937 }
3938 } else {
3939 Asm->OutStreamer->AddComment(T: dwarf::MacinfoString(Encoding: M.getMacinfoType()));
3940 Asm->emitULEB128(Value: M.getMacinfoType());
3941 Asm->OutStreamer->AddComment(T: "Line Number");
3942 Asm->emitULEB128(Value: M.getLine());
3943 Asm->OutStreamer->AddComment(T: "Macro String");
3944 Asm->OutStreamer->emitBytes(Data: Str);
3945 Asm->emitInt8(Value: '\0');
3946 }
3947}
3948
3949void DwarfDebug::emitMacroFileImpl(
3950 DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
3951 StringRef (*MacroFormToString)(unsigned Form)) {
3952
3953 Asm->OutStreamer->AddComment(T: MacroFormToString(StartFile));
3954 Asm->emitULEB128(Value: StartFile);
3955 Asm->OutStreamer->AddComment(T: "Line Number");
3956 Asm->emitULEB128(Value: MF.getLine());
3957 Asm->OutStreamer->AddComment(T: "File Number");
3958 DIFile &F = *MF.getFile();
3959 if (useSplitDwarf())
3960 Asm->emitULEB128(Value: getDwoLineTable(U)->getFile(
3961 Directory: F.getDirectory(), FileName: F.getFilename(), Checksum: getMD5AsBytes(File: &F),
3962 DwarfVersion: Asm->OutContext.getDwarfVersion(), Source: F.getSource()));
3963 else
3964 Asm->emitULEB128(Value: U.getOrCreateSourceID(File: &F));
3965 handleMacroNodes(Nodes: MF.getElements(), U);
3966 Asm->OutStreamer->AddComment(T: MacroFormToString(EndFile));
3967 Asm->emitULEB128(Value: EndFile);
3968}
3969
3970void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
3971 // DWARFv5 macro and DWARFv4 macinfo share some common encodings,
3972 // so for readibility/uniformity, We are explicitly emitting those.
3973 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
3974 if (UseDebugMacroSection)
3975 emitMacroFileImpl(
3976 MF&: F, U, StartFile: dwarf::DW_MACRO_start_file, EndFile: dwarf::DW_MACRO_end_file,
3977 MacroFormToString: (getDwarfVersion() >= 5) ? dwarf::MacroString : dwarf::GnuMacroString);
3978 else
3979 emitMacroFileImpl(MF&: F, U, StartFile: dwarf::DW_MACINFO_start_file,
3980 EndFile: dwarf::DW_MACINFO_end_file, MacroFormToString: dwarf::MacinfoString);
3981}
3982
3983void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
3984 for (const auto &P : CUMap) {
3985 auto &TheCU = *P.second;
3986 auto *SkCU = TheCU.getSkeleton();
3987 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
3988 auto *CUNode = cast<DICompileUnit>(Val: P.first);
3989 DIMacroNodeArray Macros = CUNode->getMacros();
3990 if (Macros.empty())
3991 continue;
3992 Asm->OutStreamer->switchSection(Section);
3993 Asm->OutStreamer->emitLabel(Symbol: U.getMacroLabelBegin());
3994 if (UseDebugMacroSection)
3995 emitMacroHeader(Asm, DD: *this, CU: U, DwarfVersion: getDwarfVersion());
3996 handleMacroNodes(Nodes: Macros, U);
3997 Asm->OutStreamer->AddComment(T: "End Of Macro List Mark");
3998 Asm->emitInt8(Value: 0);
3999 }
4000}
4001
4002/// Emit macros into a debug macinfo/macro section.
4003void DwarfDebug::emitDebugMacinfo() {
4004 auto &ObjLower = Asm->getObjFileLowering();
4005 emitDebugMacinfoImpl(Section: UseDebugMacroSection
4006 ? ObjLower.getDwarfMacroSection()
4007 : ObjLower.getDwarfMacinfoSection());
4008}
4009
4010void DwarfDebug::emitDebugMacinfoDWO() {
4011 auto &ObjLower = Asm->getObjFileLowering();
4012 emitDebugMacinfoImpl(Section: UseDebugMacroSection
4013 ? ObjLower.getDwarfMacroDWOSection()
4014 : ObjLower.getDwarfMacinfoDWOSection());
4015}
4016
4017// DWARF5 Experimental Separate Dwarf emitters.
4018
4019void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
4020 std::unique_ptr<DwarfCompileUnit> NewU) {
4021
4022 if (!CompilationDir.empty())
4023 NewU->addString(Die, Attribute: dwarf::DW_AT_comp_dir, Str: CompilationDir);
4024 addGnuPubAttributes(U&: *NewU, D&: Die);
4025
4026 SkeletonHolder.addUnit(U: std::move(NewU));
4027}
4028
4029DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
4030
4031 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
4032 args: CU.getUniqueID(), args: CU.getCUNode(), args&: Asm, args: this, args: &SkeletonHolder,
4033 args: UnitKind::Skeleton);
4034 DwarfCompileUnit &NewCU = *OwnedUnit;
4035 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
4036
4037 NewCU.initStmtList();
4038
4039 if (useSegmentedStringOffsetsTable())
4040 NewCU.addStringOffsetsStart();
4041
4042 initSkeletonUnit(U: CU, Die&: NewCU.getUnitDie(), NewU: std::move(OwnedUnit));
4043
4044 return NewCU;
4045}
4046
4047// Emit the .debug_info.dwo section for separated dwarf. This contains the
4048// compile units that would normally be in debug_info.
4049void DwarfDebug::emitDebugInfoDWO() {
4050 assert(useSplitDwarf() && "No split dwarf debug info?");
4051 // Don't emit relocations into the dwo file.
4052 InfoHolder.emitUnits(/* UseOffsets */ true);
4053}
4054
4055// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
4056// abbreviations for the .debug_info.dwo section.
4057void DwarfDebug::emitDebugAbbrevDWO() {
4058 assert(useSplitDwarf() && "No split dwarf?");
4059 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
4060}
4061
4062void DwarfDebug::emitDebugLineDWO() {
4063 assert(useSplitDwarf() && "No split dwarf?");
4064 SplitTypeUnitFileTable.Emit(
4065 MCOS&: *Asm->OutStreamer, Params: MCDwarfLineTableParams(),
4066 Section: Asm->getObjFileLowering().getDwarfLineDWOSection());
4067}
4068
4069void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
4070 assert(useSplitDwarf() && "No split dwarf?");
4071 InfoHolder.getStringPool().emitStringOffsetsTableHeader(
4072 Asm&: *Asm, OffsetSection: Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
4073 StartSym: InfoHolder.getStringOffsetsStartSym());
4074}
4075
4076// Emit the .debug_str.dwo section for separated dwarf. This contains the
4077// string section and is identical in format to traditional .debug_str
4078// sections.
4079void DwarfDebug::emitDebugStrDWO() {
4080 if (useSegmentedStringOffsetsTable())
4081 emitStringOffsetsTableHeaderDWO();
4082 assert(useSplitDwarf() && "No split dwarf?");
4083 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
4084 InfoHolder.emitStrings(StrSection: Asm->getObjFileLowering().getDwarfStrDWOSection(),
4085 OffsetSection: OffSec, /* UseRelativeOffsets = */ false);
4086}
4087
4088// Emit address pool.
4089void DwarfDebug::emitDebugAddr() {
4090 AddrPool.emit(Asm&: *Asm, AddrSection: Asm->getObjFileLowering().getDwarfAddrSection());
4091}
4092
4093MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
4094 if (!useSplitDwarf())
4095 return nullptr;
4096 const DICompileUnit *DIUnit = CU.getCUNode();
4097 SplitTypeUnitFileTable.maybeSetRootFile(
4098 Directory: DIUnit->getDirectory(), FileName: DIUnit->getFilename(),
4099 Checksum: getMD5AsBytes(File: DIUnit->getFile()), Source: DIUnit->getSource());
4100 return &SplitTypeUnitFileTable;
4101}
4102
4103uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
4104 MD5 Hash;
4105 Hash.update(Str: Identifier);
4106 // ... take the least significant 8 bytes and return those. Our MD5
4107 // implementation always returns its results in little endian, so we actually
4108 // need the "high" word.
4109 MD5::MD5Result Result;
4110 Hash.final(Result);
4111 return Result.high();
4112}
4113
4114void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
4115 StringRef Identifier, DIE &RefDie,
4116 const DICompositeType *CTy) {
4117 // Fast path if we're building some type units and one has already used the
4118 // address pool we know we're going to throw away all this work anyway, so
4119 // don't bother building dependent types.
4120 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
4121 return;
4122
4123 auto Ins = TypeSignatures.try_emplace(Key: CTy);
4124 if (!Ins.second) {
4125 CU.addDIETypeSignature(Die&: RefDie, Signature: Ins.first->second);
4126 return;
4127 }
4128
4129 setCurrentDWARF5AccelTable(DWARF5AccelTableKind::TU);
4130 bool TopLevelType = TypeUnitsUnderConstruction.empty();
4131 AddrPool.resetUsedFlag();
4132
4133 auto OwnedUnit = std::make_unique<DwarfTypeUnit>(
4134 args&: CU, args&: Asm, args: this, args: &InfoHolder, args: NumTypeUnitsCreated++, args: getDwoLineTable(CU));
4135 DwarfTypeUnit &NewTU = *OwnedUnit;
4136 DIE &UnitDie = NewTU.getUnitDie();
4137 TypeUnitsUnderConstruction.emplace_back(Args: std::move(OwnedUnit), Args&: CTy);
4138
4139 NewTU.addUInt(Die&: UnitDie, Attribute: dwarf::DW_AT_language, Form: dwarf::DW_FORM_data2,
4140 Integer: CU.getSourceLanguage());
4141
4142 uint64_t Signature = makeTypeSignature(Identifier);
4143 NewTU.setTypeSignature(Signature);
4144 Ins.first->second = Signature;
4145
4146 if (useSplitDwarf()) {
4147 // Although multiple type units can have the same signature, they are not
4148 // guranteed to be bit identical. When LLDB uses .debug_names it needs to
4149 // know from which CU a type unit came from. These two attrbutes help it to
4150 // figure that out.
4151 if (getDwarfVersion() >= 5) {
4152 if (!CompilationDir.empty())
4153 NewTU.addString(Die&: UnitDie, Attribute: dwarf::DW_AT_comp_dir, Str: CompilationDir);
4154 NewTU.addString(Die&: UnitDie, Attribute: dwarf::DW_AT_dwo_name,
4155 Str: Asm->TM.Options.MCOptions.SplitDwarfFile);
4156 }
4157 MCSection *Section =
4158 getDwarfVersion() <= 4
4159 ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
4160 : Asm->getObjFileLowering().getDwarfInfoDWOSection();
4161 NewTU.setSection(Section);
4162 } else {
4163 MCSection *Section =
4164 getDwarfVersion() <= 4
4165 ? Asm->getObjFileLowering().getDwarfTypesSection(Hash: Signature)
4166 : Asm->getObjFileLowering().getDwarfInfoSection(Hash: Signature);
4167 NewTU.setSection(Section);
4168 // Non-split type units reuse the compile unit's line table.
4169 CU.applyStmtList(D&: UnitDie);
4170 }
4171
4172 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
4173 // units.
4174 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
4175 NewTU.addStringOffsetsStart();
4176
4177 NewTU.setType(NewTU.createTypeDIE(Ty: CTy));
4178
4179 if (TopLevelType) {
4180 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
4181 TypeUnitsUnderConstruction.clear();
4182
4183 // Types referencing entries in the address table cannot be placed in type
4184 // units.
4185 if (AddrPool.hasBeenUsed()) {
4186 AccelTypeUnitsDebugNames.clear();
4187 // Remove all the types built while building this type.
4188 // This is pessimistic as some of these types might not be dependent on
4189 // the type that used an address.
4190 for (const auto &TU : TypeUnitsToAdd)
4191 TypeSignatures.erase(Val: TU.second);
4192
4193 // Construct this type in the CU directly.
4194 // This is inefficient because all the dependent types will be rebuilt
4195 // from scratch, including building them in type units, discovering that
4196 // they depend on addresses, throwing them out and rebuilding them.
4197 setCurrentDWARF5AccelTable(DWARF5AccelTableKind::CU);
4198 CU.constructTypeDIE(Buffer&: RefDie, CTy: cast<DICompositeType>(Val: CTy));
4199 CU.updateAcceleratorTables(Context: CTy->getScope(), Ty: CTy, TyDIE: RefDie);
4200 return;
4201 }
4202
4203 // If the type wasn't dependent on fission addresses, finish adding the type
4204 // and all its dependent types.
4205 for (auto &TU : TypeUnitsToAdd) {
4206 InfoHolder.computeSizeAndOffsetsForUnit(TheU: TU.first.get());
4207 InfoHolder.emitUnit(TheU: TU.first.get(), UseOffsets: useSplitDwarf());
4208 if (getDwarfVersion() >= 5 &&
4209 getAccelTableKind() == AccelTableKind::Dwarf) {
4210 if (useSplitDwarf())
4211 AccelDebugNames.addTypeUnitSignature(U&: *TU.first);
4212 else
4213 AccelDebugNames.addTypeUnitSymbol(U&: *TU.first);
4214 }
4215 }
4216 AccelTypeUnitsDebugNames.convertDieToOffset();
4217 AccelDebugNames.addTypeEntries(Table&: AccelTypeUnitsDebugNames);
4218 AccelTypeUnitsDebugNames.clear();
4219 setCurrentDWARF5AccelTable(DWARF5AccelTableKind::CU);
4220 }
4221 CU.addDIETypeSignature(Die&: RefDie, Signature);
4222}
4223
4224// Add the Name along with its companion DIE to the appropriate accelerator
4225// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
4226// AccelTableKind::Apple, we use the table we got as an argument). If
4227// accelerator tables are disabled, this function does nothing.
4228template <typename DataT>
4229void DwarfDebug::addAccelNameImpl(
4230 const DwarfUnit &Unit,
4231 const DICompileUnit::DebugNameTableKind NameTableKind,
4232 AccelTable<DataT> &AppleAccel, StringRef Name, const DIE &Die) {
4233 if (getAccelTableKind() == AccelTableKind::None ||
4234 Unit.getUnitDie().getTag() == dwarf::DW_TAG_skeleton_unit || Name.empty())
4235 return;
4236
4237 if (getAccelTableKind() != AccelTableKind::Apple &&
4238 NameTableKind != DICompileUnit::DebugNameTableKind::Apple &&
4239 NameTableKind != DICompileUnit::DebugNameTableKind::Default)
4240 return;
4241
4242 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
4243 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(Asm&: *Asm, Str: Name);
4244
4245 switch (getAccelTableKind()) {
4246 case AccelTableKind::Apple:
4247 AppleAccel.addName(Ref, Die);
4248 break;
4249 case AccelTableKind::Dwarf: {
4250 DWARF5AccelTable &Current = getCurrentDWARF5AccelTable();
4251 assert(((&Current == &AccelTypeUnitsDebugNames) ||
4252 ((&Current == &AccelDebugNames) &&
4253 (Unit.getUnitDie().getTag() != dwarf::DW_TAG_type_unit))) &&
4254 "Kind is CU but TU is being processed.");
4255 assert(((&Current == &AccelDebugNames) ||
4256 ((&Current == &AccelTypeUnitsDebugNames) &&
4257 (Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit))) &&
4258 "Kind is TU but CU is being processed.");
4259 // The type unit can be discarded, so need to add references to final
4260 // acceleration table once we know it's complete and we emit it.
4261 Current.addName(Name: Ref, Args: Die, Args: Unit.getUniqueID(),
4262 Args: Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit);
4263 break;
4264 }
4265 case AccelTableKind::Default:
4266 llvm_unreachable("Default should have already been resolved.");
4267 case AccelTableKind::None:
4268 llvm_unreachable("None handled above");
4269 }
4270}
4271
4272void DwarfDebug::addAccelName(
4273 const DwarfUnit &Unit,
4274 const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
4275 const DIE &Die) {
4276 addAccelNameImpl(Unit, NameTableKind, AppleAccel&: AccelNames, Name, Die);
4277}
4278
4279void DwarfDebug::addAccelObjC(
4280 const DwarfUnit &Unit,
4281 const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
4282 const DIE &Die) {
4283 // ObjC names go only into the Apple accelerator tables.
4284 if (getAccelTableKind() == AccelTableKind::Apple)
4285 addAccelNameImpl(Unit, NameTableKind, AppleAccel&: AccelObjC, Name, Die);
4286}
4287
4288void DwarfDebug::addAccelNamespace(
4289 const DwarfUnit &Unit,
4290 const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
4291 const DIE &Die) {
4292 addAccelNameImpl(Unit, NameTableKind, AppleAccel&: AccelNamespace, Name, Die);
4293}
4294
4295void DwarfDebug::addAccelType(
4296 const DwarfUnit &Unit,
4297 const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
4298 const DIE &Die, char Flags) {
4299 addAccelNameImpl(Unit, NameTableKind, AppleAccel&: AccelTypes, Name, Die);
4300}
4301
4302uint16_t DwarfDebug::getDwarfVersion() const {
4303 return Asm->OutStreamer->getContext().getDwarfVersion();
4304}
4305
4306dwarf::Form DwarfDebug::getDwarfSectionOffsetForm() const {
4307 if (Asm->getDwarfVersion() >= 4)
4308 return dwarf::Form::DW_FORM_sec_offset;
4309 assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) &&
4310 "DWARF64 is not defined prior DWARFv3");
4311 return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8
4312 : dwarf::Form::DW_FORM_data4;
4313}
4314
4315const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
4316 return SectionLabels.lookup(Val: S);
4317}
4318
4319void DwarfDebug::insertSectionLabel(const MCSymbol *S) {
4320 if (SectionLabels.insert(KV: std::make_pair(x: &S->getSection(), y&: S)).second)
4321 if (useSplitDwarf() || getDwarfVersion() >= 5)
4322 AddrPool.getIndex(Sym: S);
4323}
4324
4325std::optional<MD5::MD5Result>
4326DwarfDebug::getMD5AsBytes(const DIFile *File) const {
4327 assert(File);
4328 if (getDwarfVersion() < 5)
4329 return std::nullopt;
4330 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
4331 if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
4332 return std::nullopt;
4333
4334 // Convert the string checksum to an MD5Result for the streamer.
4335 // The verifier validates the checksum so we assume it's okay.
4336 // An MD5 checksum is 16 bytes.
4337 std::string ChecksumString = fromHex(Input: Checksum->Value);
4338 MD5::MD5Result CKMem;
4339 llvm::copy(Range&: ChecksumString, Out: CKMem.data());
4340 return CKMem;
4341}
4342
4343bool DwarfDebug::alwaysUseRanges(const DwarfCompileUnit &CU) const {
4344 if (MinimizeAddr == MinimizeAddrInV5::Ranges)
4345 return true;
4346 if (MinimizeAddr != MinimizeAddrInV5::Default)
4347 return false;
4348 if (useSplitDwarf())
4349 return true;
4350 return false;
4351}
4352
4353void DwarfDebug::beginCodeAlignment(const MachineBasicBlock &MBB) {
4354 if (MBB.getAlignment() == Align(1))
4355 return;
4356
4357 auto *SP = MBB.getParent()->getFunction().getSubprogram();
4358 bool NoDebug =
4359 !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
4360
4361 if (NoDebug)
4362 return;
4363
4364 auto PrevLoc = Asm->OutStreamer->getContext().getCurrentDwarfLoc();
4365 if (PrevLoc.getLine()) {
4366 Asm->OutStreamer->emitDwarfLocDirective(
4367 FileNo: PrevLoc.getFileNum(), Line: 0, Column: PrevLoc.getColumn(), Flags: 0, Isa: 0, Discriminator: 0, FileName: StringRef());
4368 MCDwarfLineEntry::make(MCOS: Asm->OutStreamer.get(),
4369 Section: Asm->OutStreamer->getCurrentSectionOnly());
4370 }
4371}
4372