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