LLVM 19.0.0git
DwarfDebug.cpp
Go to the documentation of this file.
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"
22#include "llvm/ADT/Twine.h"
24#include "llvm/CodeGen/DIE.h"
36#include "llvm/IR/Constants.h"
37#include "llvm/IR/Function.h"
39#include "llvm/IR/Module.h"
40#include "llvm/MC/MCAsmInfo.h"
41#include "llvm/MC/MCContext.h"
42#include "llvm/MC/MCSection.h"
43#include "llvm/MC/MCStreamer.h"
44#include "llvm/MC/MCSymbol.h"
47#include "llvm/MC/SectionKind.h"
50#include "llvm/Support/Debug.h"
52#include "llvm/Support/MD5.h"
57#include <algorithm>
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
70 "use-dwarf-ranges-base-address-specifier", cl::Hidden,
71 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
72
73static cl::opt<bool> GenerateARangeSection("generate-arange-section",
75 cl::desc("Generate dwarf aranges"),
76 cl::init(false));
77
78static cl::opt<bool>
79 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
80 cl::desc("Generate DWARF4 type units."),
81 cl::init(false));
82
84 "split-dwarf-cross-cu-references", cl::Hidden,
85 cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
86
88
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")),
95
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(AccelTableKind::Default));
104
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")),
112
113static cl::opt<bool>
114 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
115 cl::desc("Disable emission .debug_ranges section."),
116 cl::init(false));
117
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")),
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(false));
129
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")),
136
142
144 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
145 cl::desc("Which DWARF linkage-name attributes to emit."),
147 "Default for platform"),
148 clEnumValN(AllLinkageNames, "All", "All"),
150 "Abstract subprograms")),
152
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(DwarfDebug::MinimizeAddrInV5::Default));
172
173static constexpr unsigned ULEB128PadSize = 4;
174
175void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
176 getActiveStreamer().emitInt8(
177 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
179}
180
181void DebugLocDwarfExpression::emitSigned(int64_t Value) {
182 getActiveStreamer().emitSLEB128(Value, Twine(Value));
183}
184
185void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
186 getActiveStreamer().emitULEB128(Value, Twine(Value));
187}
188
189void DebugLocDwarfExpression::emitData1(uint8_t Value) {
190 getActiveStreamer().emitInt8(Value, Twine(Value));
191}
192
193void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
194 assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
195 getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);
196}
197
198bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
199 llvm::Register MachineReg) {
200 // This information is not available while emitting .debug_loc entries.
201 return false;
202}
203
204void DebugLocDwarfExpression::enableTemporaryBuffer() {
205 assert(!IsBuffering && "Already buffering?");
206 if (!TmpBuf)
207 TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
208 IsBuffering = true;
209}
210
211void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
212
213unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
214 return TmpBuf ? TmpBuf->Bytes.size() : 0;
215}
216
217void DebugLocDwarfExpression::commitTemporaryBuffer() {
218 if (!TmpBuf)
219 return;
220 for (auto Byte : enumerate(TmpBuf->Bytes)) {
221 const char *Comment = (Byte.index() < TmpBuf->Comments.size())
222 ? TmpBuf->Comments[Byte.index()].c_str()
223 : "";
224 OutBS.emitInt8(Byte.value(), Comment);
225 }
226 TmpBuf->Bytes.clear();
227 TmpBuf->Comments.clear();
228}
229
231 return getVariable()->getType();
232}
233
234/// Get .debug_loc entry for the instruction range starting at MI.
236 const DIExpression *Expr = MI->getDebugExpression();
237 auto SingleLocExprOpt = DIExpression::convertToNonVariadicExpression(Expr);
238 const bool IsVariadic = !SingleLocExprOpt;
239 // If we have a variadic debug value instruction that is equivalent to a
240 // non-variadic instruction, then convert it to non-variadic form here.
241 if (!IsVariadic && !MI->isNonListDebugValue()) {
242 assert(MI->getNumDebugOperands() == 1 &&
243 "Mismatched DIExpression and debug operands for debug instruction.");
244 Expr = *SingleLocExprOpt;
245 }
246 assert(MI->getNumOperands() >= 3);
247 SmallVector<DbgValueLocEntry, 4> DbgValueLocEntries;
248 for (const MachineOperand &Op : MI->debug_operands()) {
249 if (Op.isReg()) {
250 MachineLocation MLoc(Op.getReg(),
251 MI->isNonListDebugValue() && MI->isDebugOffsetImm());
252 DbgValueLocEntries.push_back(DbgValueLocEntry(MLoc));
253 } else if (Op.isTargetIndex()) {
254 DbgValueLocEntries.push_back(
255 DbgValueLocEntry(TargetIndexLocation(Op.getIndex(), Op.getOffset())));
256 } else if (Op.isImm())
257 DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getImm()));
258 else if (Op.isFPImm())
259 DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getFPImm()));
260 else if (Op.isCImm())
261 DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getCImm()));
262 else
263 llvm_unreachable("Unexpected debug operand in DBG_VALUE* instruction!");
264 }
265 return DbgValueLoc(Expr, DbgValueLocEntries, IsVariadic);
266}
267
269 std::optional<DIExpression::FragmentInfo> Fragment = Expr.getFragmentInfo();
270 return Fragment ? Fragment->OffsetInBits : 0;
271}
272
273bool llvm::operator<(const FrameIndexExpr &LHS, const FrameIndexExpr &RHS) {
274 return getFragmentOffsetInBits(*LHS.Expr) <
276}
277
278bool llvm::operator<(const EntryValueInfo &LHS, const EntryValueInfo &RHS) {
280}
281
283 : ValueLoc(std::make_unique<DbgValueLoc>(ValueLoc)),
284 Expr(ValueLoc.getExpression()) {
285 if (!Expr->getNumElements())
286 Expr = nullptr;
287}
288
291
292const std::set<FrameIndexExpr> &Loc::MMI::getFrameIndexExprs() const {
293 return FrameIndexExprs;
294}
295
296void Loc::MMI::addFrameIndexExpr(const DIExpression *Expr, int FI) {
297 FrameIndexExprs.insert({FI, Expr});
298 assert((FrameIndexExprs.size() == 1 ||
299 llvm::all_of(FrameIndexExprs,
300 [](const FrameIndexExpr &FIE) {
301 return FIE.Expr && FIE.Expr->isFragment();
302 })) &&
303 "conflicting locations for variable");
304}
305
306static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
307 bool GenerateTypeUnits,
308 DebuggerKind Tuning,
309 const Triple &TT) {
310 // Honor an explicit request.
312 return AccelTables;
313
314 // Generating DWARF5 acceleration table.
315 // Currently Split dwarf and non ELF format is not supported.
316 if (GenerateTypeUnits && (DwarfVersion < 5 || !TT.isOSBinFormatELF()))
318
319 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
320 // always implies debug_names. For lower standard versions we use apple
321 // accelerator tables on apple platforms and debug_names elsewhere.
322 if (DwarfVersion >= 5)
324 if (Tuning == DebuggerKind::LLDB)
325 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
328}
329
331 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
332 InfoHolder(A, "info_string", DIEValueAllocator),
333 SkeletonHolder(A, "skel_string", DIEValueAllocator),
334 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
335 const Triple &TT = Asm->TM.getTargetTriple();
336
337 // Make sure we know our "debugger tuning". The target option takes
338 // precedence; fall back to triple-based defaults.
340 DebuggerTuning = Asm->TM.Options.DebuggerTuning;
341 else if (IsDarwin)
342 DebuggerTuning = DebuggerKind::LLDB;
343 else if (TT.isPS())
344 DebuggerTuning = DebuggerKind::SCE;
345 else if (TT.isOSAIX())
346 DebuggerTuning = DebuggerKind::DBX;
347 else
348 DebuggerTuning = DebuggerKind::GDB;
349
351 UseInlineStrings = TT.isNVPTX() || tuneForDBX();
352 else
353 UseInlineStrings = DwarfInlinedStrings == Enable;
354
355 UseLocSection = !TT.isNVPTX();
356
357 HasAppleExtensionAttributes = tuneForLLDB();
358
359 // Handle split DWARF.
360 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
361
362 // SCE defaults to linkage names only for abstract subprograms.
364 UseAllLinkageNames = !tuneForSCE();
365 else
366 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
367
368 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
369 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
371 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
372 DwarfVersion =
373 TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
374
375 bool Dwarf64 = DwarfVersion >= 3 && // DWARF64 was introduced in DWARFv3.
376 TT.isArch64Bit(); // DWARF64 requires 64-bit relocations.
377
378 // Support DWARF64
379 // 1: For ELF when requested.
380 // 2: For XCOFF64: the AIX assembler will fill in debug section lengths
381 // according to the DWARF64 format for 64-bit assembly, so we must use
382 // DWARF64 in the compiler too for 64-bit mode.
383 Dwarf64 &=
385 TT.isOSBinFormatELF()) ||
386 TT.isOSBinFormatXCOFF();
387
388 if (!Dwarf64 && TT.isArch64Bit() && TT.isOSBinFormatXCOFF())
389 report_fatal_error("XCOFF requires DWARF64 for 64-bit mode!");
390
391 UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
392
393 // Use sections as references. Force for NVPTX.
395 UseSectionsAsReferences = TT.isNVPTX();
396 else
397 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
398
399 // Don't generate type units for unsupported object file formats.
400 GenerateTypeUnits = (A->TM.getTargetTriple().isOSBinFormatELF() ||
401 A->TM.getTargetTriple().isOSBinFormatWasm()) &&
403
404 TheAccelTableKind = computeAccelTableKind(
405 DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
406
407 // Work around a GDB bug. GDB doesn't support the standard opcode;
408 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
409 // is defined as of DWARF 3.
410 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
411 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
412 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
413
414 UseDWARF2Bitfields = DwarfVersion < 4;
415
416 // The DWARF v5 string offsets table has - possibly shared - contributions
417 // from each compile and type unit each preceded by a header. The string
418 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
419 // a monolithic string offsets table without any header.
420 UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
421
422 // Emit call-site-param debug info for GDB and LLDB, if the target supports
423 // the debug entry values feature. It can also be enabled explicitly.
424 EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues();
425
426 // It is unclear if the GCC .debug_macro extension is well-specified
427 // for split DWARF. For now, do not allow LLVM to emit it.
428 UseDebugMacroSection =
429 DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf());
430 if (DwarfOpConvert == Default)
431 EnableOpConvert = !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT.isOSBinFormatMachO()));
432 else
433 EnableOpConvert = (DwarfOpConvert == Enable);
434
435 // Split DWARF would benefit object size significantly by trading reductions
436 // in address pool usage for slightly increased range list encodings.
437 if (DwarfVersion >= 5)
438 MinimizeAddr = MinimizeAddrInV5Option;
439
440 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
441 Asm->OutStreamer->getContext().setDwarfFormat(Dwarf64 ? dwarf::DWARF64
443}
444
445// Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
446DwarfDebug::~DwarfDebug() = default;
447
449 return Name.starts_with("+") || Name.starts_with("-");
450}
451
453 if (!isObjCClass(Name))
454 return false;
455
456 return Name.contains(") ");
457}
458
460 StringRef &Category) {
461 if (!hasObjCCategory(In)) {
462 Class = In.slice(In.find('[') + 1, In.find(' '));
463 Category = "";
464 return;
465 }
466
467 Class = In.slice(In.find('[') + 1, In.find('('));
468 Category = In.slice(In.find('[') + 1, In.find(' '));
469}
470
472 return In.slice(In.find(' ') + 1, In.find(']'));
473}
474
475// Add the various names to the Dwarf accelerator table names.
477 const DwarfUnit &Unit,
478 const DICompileUnit::DebugNameTableKind NameTableKind,
479 const DISubprogram *SP, DIE &Die) {
483 return;
484
485 if (!SP->isDefinition())
486 return;
487
488 if (SP->getName() != "")
489 addAccelName(Unit, NameTableKind, SP->getName(), Die);
490
491 // If the linkage name is different than the name, go ahead and output that as
492 // well into the name table. Only do that if we are going to actually emit
493 // that name.
494 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
495 (useAllLinkageNames() || InfoHolder.getAbstractScopeDIEs().lookup(SP)))
496 addAccelName(Unit, NameTableKind, SP->getLinkageName(), Die);
497
498 // If this is an Objective-C selector name add it to the ObjC accelerator
499 // too.
500 if (isObjCClass(SP->getName())) {
501 StringRef Class, Category;
502 getObjCClassCategory(SP->getName(), Class, Category);
503 addAccelObjC(Unit, NameTableKind, Class, Die);
504 if (Category != "")
505 addAccelObjC(Unit, NameTableKind, Category, Die);
506 // Also add the base method name to the name table.
507 addAccelName(Unit, NameTableKind, getObjCMethodName(SP->getName()), Die);
508 }
509}
510
511/// Check whether we should create a DIE for the given Scope, return true
512/// if we don't create a DIE (the corresponding DIE is null).
514 if (Scope->isAbstractScope())
515 return false;
516
517 // We don't create a DIE if there is no Range.
518 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
519 if (Ranges.empty())
520 return true;
521
522 if (Ranges.size() > 1)
523 return false;
524
525 // We don't create a DIE if we have a single Range and the end label
526 // is null.
527 return !getLabelAfterInsn(Ranges.front().second);
528}
529
530template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
531 F(CU);
532 if (auto *SkelCU = CU.getSkeleton())
533 if (CU.getCUNode()->getSplitDebugInlining())
534 F(*SkelCU);
535}
536
539}
540
541void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
542 LexicalScope *Scope) {
543 assert(Scope && Scope->getScopeNode());
544 assert(Scope->isAbstractScope());
545 assert(!Scope->getInlinedAt());
546
547 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
548
549 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
550 // was inlined from another compile unit.
551 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
552 // Avoid building the original CU if it won't be used
554 else {
555 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
556 if (auto *SkelCU = CU.getSkeleton()) {
557 (shareAcrossDWOCUs() ? CU : SrcCU)
558 .constructAbstractSubprogramScopeDIE(Scope);
559 if (CU.getCUNode()->getSplitDebugInlining())
560 SkelCU->constructAbstractSubprogramScopeDIE(Scope);
561 } else
562 CU.constructAbstractSubprogramScopeDIE(Scope);
563 }
564}
565
566/// Represents a parameter whose call site value can be described by applying a
567/// debug expression to a register in the forwarded register worklist.
569 /// The described parameter register.
570 unsigned ParamReg;
571
572 /// Debug expression that has been built up when walking through the
573 /// instruction chain that produces the parameter's value.
575};
576
577/// Register worklist for finding call site values.
579/// Container for the set of registers known to be clobbered on the path to a
580/// call site.
582
583/// Append the expression \p Addition to \p Original and return the result.
584static const DIExpression *combineDIExpressions(const DIExpression *Original,
585 const DIExpression *Addition) {
586 std::vector<uint64_t> Elts = Addition->getElements().vec();
587 // Avoid multiple DW_OP_stack_values.
588 if (Original->isImplicit() && Addition->isImplicit())
589 llvm::erase(Elts, dwarf::DW_OP_stack_value);
590 const DIExpression *CombinedExpr =
591 (Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original;
592 return CombinedExpr;
593}
594
595/// Emit call site parameter entries that are described by the given value and
596/// debug expression.
597template <typename ValT>
598static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
599 ArrayRef<FwdRegParamInfo> DescribedParams,
600 ParamSet &Params) {
601 for (auto Param : DescribedParams) {
602 bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
603
604 // TODO: Entry value operations can currently not be combined with any
605 // other expressions, so we can't emit call site entries in those cases.
606 if (ShouldCombineExpressions && Expr->isEntryValue())
607 continue;
608
609 // If a parameter's call site value is produced by a chain of
610 // instructions we may have already created an expression for the
611 // parameter when walking through the instructions. Append that to the
612 // base expression.
613 const DIExpression *CombinedExpr =
614 ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr)
615 : Expr;
616 assert((!CombinedExpr || CombinedExpr->isValid()) &&
617 "Combined debug expression is invalid");
618
619 DbgValueLoc DbgLocVal(CombinedExpr, DbgValueLocEntry(Val));
620 DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
621 Params.push_back(CSParm);
622 ++NumCSParams;
623 }
624}
625
626/// Add \p Reg to the worklist, if it's not already present, and mark that the
627/// given parameter registers' values can (potentially) be described using
628/// that register and an debug expression.
629static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
630 const DIExpression *Expr,
631 ArrayRef<FwdRegParamInfo> ParamsToAdd) {
632 auto I = Worklist.insert({Reg, {}});
633 auto &ParamsForFwdReg = I.first->second;
634 for (auto Param : ParamsToAdd) {
635 assert(none_of(ParamsForFwdReg,
636 [Param](const FwdRegParamInfo &D) {
637 return D.ParamReg == Param.ParamReg;
638 }) &&
639 "Same parameter described twice by forwarding reg");
640
641 // If a parameter's call site value is produced by a chain of
642 // instructions we may have already created an expression for the
643 // parameter when walking through the instructions. Append that to the
644 // new expression.
645 const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr);
646 ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
647 }
648}
649
650/// Interpret values loaded into registers by \p CurMI.
651static void interpretValues(const MachineInstr *CurMI,
652 FwdRegWorklist &ForwardedRegWorklist,
653 ParamSet &Params,
654 ClobberedRegSet &ClobberedRegUnits) {
655
656 const MachineFunction *MF = CurMI->getMF();
657 const DIExpression *EmptyExpr =
659 const auto &TRI = *MF->getSubtarget().getRegisterInfo();
660 const auto &TII = *MF->getSubtarget().getInstrInfo();
661 const auto &TLI = *MF->getSubtarget().getTargetLowering();
662
663 // If an instruction defines more than one item in the worklist, we may run
664 // into situations where a worklist register's value is (potentially)
665 // described by the previous value of another register that is also defined
666 // by that instruction.
667 //
668 // This can for example occur in cases like this:
669 //
670 // $r1 = mov 123
671 // $r0, $r1 = mvrr $r1, 456
672 // call @foo, $r0, $r1
673 //
674 // When describing $r1's value for the mvrr instruction, we need to make sure
675 // that we don't finalize an entry value for $r0, as that is dependent on the
676 // previous value of $r1 (123 rather than 456).
677 //
678 // In order to not have to distinguish between those cases when finalizing
679 // entry values, we simply postpone adding new parameter registers to the
680 // worklist, by first keeping them in this temporary container until the
681 // instruction has been handled.
682 FwdRegWorklist TmpWorklistItems;
683
684 // If the MI is an instruction defining one or more parameters' forwarding
685 // registers, add those defines.
686 ClobberedRegSet NewClobberedRegUnits;
687 auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
689 if (MI.isDebugInstr())
690 return;
691
692 for (const MachineOperand &MO : MI.all_defs()) {
693 if (MO.getReg().isPhysical()) {
694 for (auto &FwdReg : ForwardedRegWorklist)
695 if (TRI.regsOverlap(FwdReg.first, MO.getReg()))
696 Defs.insert(FwdReg.first);
697 for (MCRegUnit Unit : TRI.regunits(MO.getReg()))
698 NewClobberedRegUnits.insert(Unit);
699 }
700 }
701 };
702
703 // Set of worklist registers that are defined by this instruction.
705
706 getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
707 if (FwdRegDefs.empty()) {
708 // Any definitions by this instruction will clobber earlier reg movements.
709 ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),
710 NewClobberedRegUnits.end());
711 return;
712 }
713
714 // It's possible that we find a copy from a non-volatile register to the param
715 // register, which is clobbered in the meantime. Test for clobbered reg unit
716 // overlaps before completing.
717 auto IsRegClobberedInMeantime = [&](Register Reg) -> bool {
718 for (auto &RegUnit : ClobberedRegUnits)
719 if (TRI.hasRegUnit(Reg, RegUnit))
720 return true;
721 return false;
722 };
723
724 for (auto ParamFwdReg : FwdRegDefs) {
725 if (auto ParamValue = TII.describeLoadedValue(*CurMI, ParamFwdReg)) {
726 if (ParamValue->first.isImm()) {
727 int64_t Val = ParamValue->first.getImm();
728 finishCallSiteParams(Val, ParamValue->second,
729 ForwardedRegWorklist[ParamFwdReg], Params);
730 } else if (ParamValue->first.isReg()) {
731 Register RegLoc = ParamValue->first.getReg();
732 Register SP = TLI.getStackPointerRegisterToSaveRestore();
733 Register FP = TRI.getFrameRegister(*MF);
734 bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
735 if (!IsRegClobberedInMeantime(RegLoc) &&
736 (TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP)) {
737 MachineLocation MLoc(RegLoc, /*Indirect=*/IsSPorFP);
738 finishCallSiteParams(MLoc, ParamValue->second,
739 ForwardedRegWorklist[ParamFwdReg], Params);
740 } else {
741 // ParamFwdReg was described by the non-callee saved register
742 // RegLoc. Mark that the call site values for the parameters are
743 // dependent on that register instead of ParamFwdReg. Since RegLoc
744 // may be a register that will be handled in this iteration, we
745 // postpone adding the items to the worklist, and instead keep them
746 // in a temporary container.
747 addToFwdRegWorklist(TmpWorklistItems, RegLoc, ParamValue->second,
748 ForwardedRegWorklist[ParamFwdReg]);
749 }
750 }
751 }
752 }
753
754 // Remove all registers that this instruction defines from the worklist.
755 for (auto ParamFwdReg : FwdRegDefs)
756 ForwardedRegWorklist.erase(ParamFwdReg);
757
758 // Any definitions by this instruction will clobber earlier reg movements.
759 ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),
760 NewClobberedRegUnits.end());
761
762 // Now that we are done handling this instruction, add items from the
763 // temporary worklist to the real one.
764 for (auto &New : TmpWorklistItems)
765 addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr, New.second);
766 TmpWorklistItems.clear();
767}
768
769static bool interpretNextInstr(const MachineInstr *CurMI,
770 FwdRegWorklist &ForwardedRegWorklist,
771 ParamSet &Params,
772 ClobberedRegSet &ClobberedRegUnits) {
773 // Skip bundle headers.
774 if (CurMI->isBundle())
775 return true;
776
777 // If the next instruction is a call we can not interpret parameter's
778 // forwarding registers or we finished the interpretation of all
779 // parameters.
780 if (CurMI->isCall())
781 return false;
782
783 if (ForwardedRegWorklist.empty())
784 return false;
785
786 // Avoid NOP description.
787 if (CurMI->getNumOperands() == 0)
788 return true;
789
790 interpretValues(CurMI, ForwardedRegWorklist, Params, ClobberedRegUnits);
791
792 return true;
793}
794
795/// Try to interpret values loaded into registers that forward parameters
796/// for \p CallMI. Store parameters with interpreted value into \p Params.
797static void collectCallSiteParameters(const MachineInstr *CallMI,
798 ParamSet &Params) {
799 const MachineFunction *MF = CallMI->getMF();
800 const auto &CalleesMap = MF->getCallSitesInfo();
801 auto CSInfo = CalleesMap.find(CallMI);
802
803 // There is no information for the call instruction.
804 if (CSInfo == CalleesMap.end())
805 return;
806
807 const MachineBasicBlock *MBB = CallMI->getParent();
808
809 // Skip the call instruction.
810 auto I = std::next(CallMI->getReverseIterator());
811
812 FwdRegWorklist ForwardedRegWorklist;
813
814 const DIExpression *EmptyExpr =
816
817 // Add all the forwarding registers into the ForwardedRegWorklist.
818 for (const auto &ArgReg : CSInfo->second.ArgRegPairs) {
819 bool InsertedReg =
820 ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
821 .second;
822 assert(InsertedReg && "Single register used to forward two arguments?");
823 (void)InsertedReg;
824 }
825
826 // Do not emit CSInfo for undef forwarding registers.
827 for (const auto &MO : CallMI->uses())
828 if (MO.isReg() && MO.isUndef())
829 ForwardedRegWorklist.erase(MO.getReg());
830
831 // We erase, from the ForwardedRegWorklist, those forwarding registers for
832 // which we successfully describe a loaded value (by using
833 // the describeLoadedValue()). For those remaining arguments in the working
834 // list, for which we do not describe a loaded value by
835 // the describeLoadedValue(), we try to generate an entry value expression
836 // for their call site value description, if the call is within the entry MBB.
837 // TODO: Handle situations when call site parameter value can be described
838 // as the entry value within basic blocks other than the first one.
839 bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
840
841 // Search for a loading value in forwarding registers inside call delay slot.
842 ClobberedRegSet ClobberedRegUnits;
843 if (CallMI->hasDelaySlot()) {
844 auto Suc = std::next(CallMI->getIterator());
845 // Only one-instruction delay slot is supported.
846 auto BundleEnd = llvm::getBundleEnd(CallMI->getIterator());
847 (void)BundleEnd;
848 assert(std::next(Suc) == BundleEnd &&
849 "More than one instruction in call delay slot");
850 // Try to interpret value loaded by instruction.
851 if (!interpretNextInstr(&*Suc, ForwardedRegWorklist, Params, ClobberedRegUnits))
852 return;
853 }
854
855 // Search for a loading value in forwarding registers.
856 for (; I != MBB->rend(); ++I) {
857 // Try to interpret values loaded by instruction.
858 if (!interpretNextInstr(&*I, ForwardedRegWorklist, Params, ClobberedRegUnits))
859 return;
860 }
861
862 // Emit the call site parameter's value as an entry value.
863 if (ShouldTryEmitEntryVals) {
864 // Create an expression where the register's entry value is used.
865 DIExpression *EntryExpr = DIExpression::get(
866 MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
867 for (auto &RegEntry : ForwardedRegWorklist) {
868 MachineLocation MLoc(RegEntry.first);
869 finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);
870 }
871 }
872}
873
874void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
875 DwarfCompileUnit &CU, DIE &ScopeDIE,
876 const MachineFunction &MF) {
877 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
878 // the subprogram is required to have one.
879 if (!SP.areAllCallsDescribed() || !SP.isDefinition())
880 return;
881
882 // Use DW_AT_call_all_calls to express that call site entries are present
883 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
884 // because one of its requirements is not met: call site entries for
885 // optimized-out calls are elided.
886 CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
887
889 assert(TII && "TargetInstrInfo not found: cannot label tail calls");
890
891 // Delay slot support check.
892 auto delaySlotSupported = [&](const MachineInstr &MI) {
893 if (!MI.isBundledWithSucc())
894 return false;
895 auto Suc = std::next(MI.getIterator());
896 auto CallInstrBundle = getBundleStart(MI.getIterator());
897 (void)CallInstrBundle;
898 auto DelaySlotBundle = getBundleStart(Suc);
899 (void)DelaySlotBundle;
900 // Ensure that label after call is following delay slot instruction.
901 // Ex. CALL_INSTRUCTION {
902 // DELAY_SLOT_INSTRUCTION }
903 // LABEL_AFTER_CALL
904 assert(getLabelAfterInsn(&*CallInstrBundle) ==
905 getLabelAfterInsn(&*DelaySlotBundle) &&
906 "Call and its successor instruction don't have same label after.");
907 return true;
908 };
909
910 // Emit call site entries for each call or tail call in the function.
911 for (const MachineBasicBlock &MBB : MF) {
912 for (const MachineInstr &MI : MBB.instrs()) {
913 // Bundles with call in them will pass the isCall() test below but do not
914 // have callee operand information so skip them here. Iterator will
915 // eventually reach the call MI.
916 if (MI.isBundle())
917 continue;
918
919 // Skip instructions which aren't calls. Both calls and tail-calling jump
920 // instructions (e.g TAILJMPd64) are classified correctly here.
921 if (!MI.isCandidateForCallSiteEntry())
922 continue;
923
924 // Skip instructions marked as frame setup, as they are not interesting to
925 // the user.
926 if (MI.getFlag(MachineInstr::FrameSetup))
927 continue;
928
929 // Check if delay slot support is enabled.
930 if (MI.hasDelaySlot() && !delaySlotSupported(*&MI))
931 return;
932
933 // If this is a direct call, find the callee's subprogram.
934 // In the case of an indirect call find the register that holds
935 // the callee.
936 const MachineOperand &CalleeOp = TII->getCalleeOperand(MI);
937 if (!CalleeOp.isGlobal() &&
938 (!CalleeOp.isReg() || !CalleeOp.getReg().isPhysical()))
939 continue;
940
941 unsigned CallReg = 0;
942 const DISubprogram *CalleeSP = nullptr;
943 const Function *CalleeDecl = nullptr;
944 if (CalleeOp.isReg()) {
945 CallReg = CalleeOp.getReg();
946 if (!CallReg)
947 continue;
948 } else {
949 CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
950 if (!CalleeDecl || !CalleeDecl->getSubprogram())
951 continue;
952 CalleeSP = CalleeDecl->getSubprogram();
953 }
954
955 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
956
957 bool IsTail = TII->isTailCall(MI);
958
959 // If MI is in a bundle, the label was created after the bundle since
960 // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
961 // to search for that label below.
962 const MachineInstr *TopLevelCallMI =
963 MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
964
965 // For non-tail calls, the return PC is needed to disambiguate paths in
966 // the call graph which could lead to some target function. For tail
967 // calls, no return PC information is needed, unless tuning for GDB in
968 // DWARF4 mode in which case we fake a return PC for compatibility.
969 const MCSymbol *PCAddr =
970 (!IsTail || CU.useGNUAnalogForDwarf5Feature())
971 ? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))
972 : nullptr;
973
974 // For tail calls, it's necessary to record the address of the branch
975 // instruction so that the debugger can show where the tail call occurred.
976 const MCSymbol *CallAddr =
977 IsTail ? getLabelBeforeInsn(TopLevelCallMI) : nullptr;
978
979 assert((IsTail || PCAddr) && "Non-tail call without return PC");
980
981 LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
982 << (CalleeDecl ? CalleeDecl->getName()
983 : StringRef(MF.getSubtarget()
984 .getRegisterInfo()
985 ->getName(CallReg)))
986 << (IsTail ? " [IsTail]" : "") << "\n");
987
988 DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(
989 ScopeDIE, CalleeSP, IsTail, PCAddr, CallAddr, CallReg);
990
991 // Optionally emit call-site-param debug info.
992 if (emitDebugEntryValues()) {
993 ParamSet Params;
994 // Try to interpret values of call site parameters.
996 CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
997 }
998 }
999 }
1000}
1001
1002void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
1003 if (!U.hasDwarfPubSections())
1004 return;
1005
1006 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
1007}
1008
1009void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
1010 DwarfCompileUnit &NewCU) {
1011 DIE &Die = NewCU.getUnitDie();
1012 StringRef FN = DIUnit->getFilename();
1013
1014 StringRef Producer = DIUnit->getProducer();
1015 StringRef Flags = DIUnit->getFlags();
1016 if (!Flags.empty() && !useAppleExtensionAttributes()) {
1017 std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
1018 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
1019 } else
1020 NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
1021
1022 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1023 DIUnit->getSourceLanguage());
1024 NewCU.addString(Die, dwarf::DW_AT_name, FN);
1025 StringRef SysRoot = DIUnit->getSysRoot();
1026 if (!SysRoot.empty())
1027 NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
1028 StringRef SDK = DIUnit->getSDK();
1029 if (!SDK.empty())
1030 NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
1031
1032 if (!useSplitDwarf()) {
1033 // Add DW_str_offsets_base to the unit DIE, except for split units.
1035 NewCU.addStringOffsetsStart();
1036
1037 NewCU.initStmtList();
1038
1039 // If we're using split dwarf the compilation dir is going to be in the
1040 // skeleton CU and so we don't need to duplicate it here.
1041 if (!CompilationDir.empty())
1042 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1043 addGnuPubAttributes(NewCU, Die);
1044 }
1045
1047 if (DIUnit->isOptimized())
1048 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
1049
1050 StringRef Flags = DIUnit->getFlags();
1051 if (!Flags.empty())
1052 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
1053
1054 if (unsigned RVer = DIUnit->getRuntimeVersion())
1055 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1056 dwarf::DW_FORM_data1, RVer);
1057 }
1058
1059 if (DIUnit->getDWOId()) {
1060 // This CU is either a clang module DWO or a skeleton CU.
1061 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
1062 DIUnit->getDWOId());
1063 if (!DIUnit->getSplitDebugFilename().empty()) {
1064 // This is a prefabricated skeleton CU.
1065 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1066 ? dwarf::DW_AT_dwo_name
1067 : dwarf::DW_AT_GNU_dwo_name;
1068 NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
1069 }
1070 }
1071}
1072// Create new DwarfCompileUnit for the given metadata node with tag
1073// DW_TAG_compile_unit.
1075DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
1076 if (auto *CU = CUMap.lookup(DIUnit))
1077 return *CU;
1078
1079 if (useSplitDwarf() &&
1080 !shareAcrossDWOCUs() &&
1081 (!DIUnit->getSplitDebugInlining() ||
1083 !CUMap.empty()) {
1084 return *CUMap.begin()->second;
1085 }
1086 CompilationDir = DIUnit->getDirectory();
1087
1088 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
1089 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
1090 DwarfCompileUnit &NewCU = *OwnedUnit;
1091 InfoHolder.addUnit(std::move(OwnedUnit));
1092
1093 // LTO with assembly output shares a single line table amongst multiple CUs.
1094 // To avoid the compilation directory being ambiguous, let the line table
1095 // explicitly describe the directory of all files, never relying on the
1096 // compilation directory.
1097 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
1098 Asm->OutStreamer->emitDwarfFile0Directive(
1099 CompilationDir, DIUnit->getFilename(), getMD5AsBytes(DIUnit->getFile()),
1100 DIUnit->getSource(), NewCU.getUniqueID());
1101
1102 if (useSplitDwarf()) {
1103 NewCU.setSkeleton(constructSkeletonCU(NewCU));
1105 } else {
1106 finishUnitAttributes(DIUnit, NewCU);
1108 }
1109
1110 CUMap.insert({DIUnit, &NewCU});
1111 CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
1112 return NewCU;
1113}
1114
1115/// Sort and unique GVEs by comparing their fragment offset.
1118 llvm::sort(
1120 // Sort order: first null exprs, then exprs without fragment
1121 // info, then sort by fragment offset in bits.
1122 // FIXME: Come up with a more comprehensive comparator so
1123 // the sorting isn't non-deterministic, and so the following
1124 // std::unique call works correctly.
1125 if (!A.Expr || !B.Expr)
1126 return !!B.Expr;
1127 auto FragmentA = A.Expr->getFragmentInfo();
1128 auto FragmentB = B.Expr->getFragmentInfo();
1129 if (!FragmentA || !FragmentB)
1130 return !!FragmentB;
1131 return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
1132 });
1133 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
1136 return A.Expr == B.Expr;
1137 }),
1138 GVEs.end());
1139 return GVEs;
1140}
1141
1142// Emit all Dwarf sections that should come prior to the content. Create
1143// global DIEs and emit initial debug info sections. This is invoked by
1144// the target AsmPrinter.
1147
1148 if (!Asm || !MMI->hasDebugInfo())
1149 return;
1150
1151 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
1152 M->debug_compile_units_end());
1153 assert(NumDebugCUs > 0 && "Asm unexpectedly initialized");
1154 assert(MMI->hasDebugInfo() &&
1155 "DebugInfoAvailabilty unexpectedly not initialized");
1156 SingleCU = NumDebugCUs == 1;
1158 GVMap;
1159 for (const GlobalVariable &Global : M->globals()) {
1161 Global.getDebugInfo(GVs);
1162 for (auto *GVE : GVs)
1163 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
1164 }
1165
1166 // Create the symbol that designates the start of the unit's contribution
1167 // to the string offsets table. In a split DWARF scenario, only the skeleton
1168 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
1170 (useSplitDwarf() ? SkeletonHolder : InfoHolder)
1171 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
1172
1173
1174 // Create the symbols that designates the start of the DWARF v5 range list
1175 // and locations list tables. They are located past the table headers.
1176 if (getDwarfVersion() >= 5) {
1177 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1179 Asm->createTempSymbol("rnglists_table_base"));
1180
1181 if (useSplitDwarf())
1182 InfoHolder.setRnglistsTableBaseSym(
1183 Asm->createTempSymbol("rnglists_dwo_table_base"));
1184 }
1185
1186 // Create the symbol that points to the first entry following the debug
1187 // address table (.debug_addr) header.
1188 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1189 DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
1190
1191 for (DICompileUnit *CUNode : M->debug_compile_units()) {
1192 if (CUNode->getImportedEntities().empty() &&
1193 CUNode->getEnumTypes().empty() && CUNode->getRetainedTypes().empty() &&
1194 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1195 continue;
1196
1197 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
1198
1199 // Global Variables.
1200 for (auto *GVE : CUNode->getGlobalVariables()) {
1201 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1202 // already know about the variable and it isn't adding a constant
1203 // expression.
1204 auto &GVMapEntry = GVMap[GVE->getVariable()];
1205 auto *Expr = GVE->getExpression();
1206 if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1207 GVMapEntry.push_back({nullptr, Expr});
1208 }
1209
1211 for (auto *GVE : CUNode->getGlobalVariables()) {
1212 DIGlobalVariable *GV = GVE->getVariable();
1213 if (Processed.insert(GV).second)
1214 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
1215 }
1216
1217 for (auto *Ty : CUNode->getEnumTypes())
1218 CU.getOrCreateTypeDIE(cast<DIType>(Ty));
1219
1220 for (auto *Ty : CUNode->getRetainedTypes()) {
1221 // The retained types array by design contains pointers to
1222 // MDNodes rather than DIRefs. Unique them here.
1223 if (DIType *RT = dyn_cast<DIType>(Ty))
1224 // There is no point in force-emitting a forward declaration.
1225 CU.getOrCreateTypeDIE(RT);
1226 }
1227 }
1228}
1229
1230void DwarfDebug::finishEntityDefinitions() {
1231 for (const auto &Entity : ConcreteEntities) {
1232 DIE *Die = Entity->getDIE();
1233 assert(Die);
1234 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1235 // in the ConcreteEntities list, rather than looking it up again here.
1236 // DIE::getUnit isn't simple - it walks parent pointers, etc.
1237 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
1238 assert(Unit);
1239 Unit->finishEntityDefinition(Entity.get());
1240 }
1241}
1242
1243void DwarfDebug::finishSubprogramDefinitions() {
1244 for (const DISubprogram *SP : ProcessedSPNodes) {
1245 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
1246 forBothCUs(
1247 getOrCreateDwarfCompileUnit(SP->getUnit()),
1248 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1249 }
1250}
1251
1252void DwarfDebug::finalizeModuleInfo() {
1254
1255 finishSubprogramDefinitions();
1256
1257 finishEntityDefinitions();
1258
1259 // Include the DWO file name in the hash if there's more than one CU.
1260 // This handles ThinLTO's situation where imported CUs may very easily be
1261 // duplicate with the same CU partially imported into another ThinLTO unit.
1262 StringRef DWOName;
1263 if (CUMap.size() > 1)
1265
1266 bool HasEmittedSplitCU = false;
1267
1268 // Handle anything that needs to be done on a per-unit basis after
1269 // all other generation.
1270 for (const auto &P : CUMap) {
1271 auto &TheCU = *P.second;
1272 if (TheCU.getCUNode()->isDebugDirectivesOnly())
1273 continue;
1274 // Emit DW_AT_containing_type attribute to connect types with their
1275 // vtable holding type.
1276 TheCU.constructContainingTypeDIEs();
1277
1278 // Add CU specific attributes if we need to add any.
1279 // If we're splitting the dwarf out now that we've got the entire
1280 // CU then add the dwo id to it.
1281 auto *SkCU = TheCU.getSkeleton();
1282
1283 bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1284
1285 if (HasSplitUnit) {
1286 (void)HasEmittedSplitCU;
1287 assert((shareAcrossDWOCUs() || !HasEmittedSplitCU) &&
1288 "Multiple CUs emitted into a single dwo file");
1289 HasEmittedSplitCU = true;
1290 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1291 ? dwarf::DW_AT_dwo_name
1292 : dwarf::DW_AT_GNU_dwo_name;
1293 finishUnitAttributes(TheCU.getCUNode(), TheCU);
1294 TheCU.addString(TheCU.getUnitDie(), attrDWOName,
1296 SkCU->addString(SkCU->getUnitDie(), attrDWOName,
1298 // Emit a unique identifier for this CU.
1299 uint64_t ID =
1300 DIEHash(Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie());
1301 if (getDwarfVersion() >= 5) {
1302 TheCU.setDWOId(ID);
1303 SkCU->setDWOId(ID);
1304 } else {
1305 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1306 dwarf::DW_FORM_data8, ID);
1307 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1308 dwarf::DW_FORM_data8, ID);
1309 }
1310
1311 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1313 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1314 Sym, Sym);
1315 }
1316 } else if (SkCU) {
1317 finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1318 }
1319
1320 // If we have code split among multiple sections or non-contiguous
1321 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1322 // remain in the .o file, otherwise add a DW_AT_low_pc.
1323 // FIXME: We should use ranges allow reordering of code ala
1324 // .subsections_via_symbols in mach-o. This would mean turning on
1325 // ranges for all subprogram DIEs for mach-o.
1326 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1327
1328 if (unsigned NumRanges = TheCU.getRanges().size()) {
1329 if (NumRanges > 1 && useRangesSection())
1330 // A DW_AT_low_pc attribute may also be specified in combination with
1331 // DW_AT_ranges to specify the default base address for use in
1332 // location lists (see Section 2.6.2) and range lists (see Section
1333 // 2.17.3).
1334 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
1335 else
1336 U.setBaseAddress(TheCU.getRanges().front().Begin);
1337 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
1338 }
1339
1340 // We don't keep track of which addresses are used in which CU so this
1341 // is a bit pessimistic under LTO.
1342 if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
1343 U.addAddrTableBase();
1344
1345 if (getDwarfVersion() >= 5) {
1346 if (U.hasRangeLists())
1347 U.addRnglistsBase();
1348
1349 if (!DebugLocs.getLists().empty() && !useSplitDwarf()) {
1350 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
1351 DebugLocs.getSym(),
1353 }
1354 }
1355
1356 auto *CUNode = cast<DICompileUnit>(P.first);
1357 // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
1358 // attribute.
1359 if (CUNode->getMacros()) {
1360 if (UseDebugMacroSection) {
1361 if (useSplitDwarf())
1362 TheCU.addSectionDelta(
1363 TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),
1365 else {
1366 dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5
1367 ? dwarf::DW_AT_macros
1368 : dwarf::DW_AT_GNU_macros;
1369 U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(),
1371 }
1372 } else {
1373 if (useSplitDwarf())
1374 TheCU.addSectionDelta(
1375 TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1376 U.getMacroLabelBegin(),
1378 else
1379 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
1380 U.getMacroLabelBegin(),
1382 }
1383 }
1384 }
1385
1386 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1387 for (auto *CUNode : MMI->getModule()->debug_compile_units())
1388 if (CUNode->getDWOId())
1389 getOrCreateDwarfCompileUnit(CUNode);
1390
1391 // Compute DIE offsets and sizes.
1392 InfoHolder.computeSizeAndOffsets();
1393 if (useSplitDwarf())
1394 SkeletonHolder.computeSizeAndOffsets();
1395
1396 // Now that offsets are computed, can replace DIEs in debug_names Entry with
1397 // an actual offset.
1398 AccelDebugNames.convertDieToOffset();
1399}
1400
1401// Emit all Dwarf sections that should come after the content.
1403 // Terminate the pending line table.
1404 if (PrevCU)
1405 terminateLineTable(PrevCU);
1406 PrevCU = nullptr;
1407 assert(CurFn == nullptr);
1408 assert(CurMI == nullptr);
1409
1410 for (const auto &P : CUMap) {
1411 const auto *CUNode = cast<DICompileUnit>(P.first);
1412 DwarfCompileUnit *CU = &*P.second;
1413
1414 // Emit imported entities.
1415 for (auto *IE : CUNode->getImportedEntities()) {
1416 assert(!isa_and_nonnull<DILocalScope>(IE->getScope()) &&
1417 "Unexpected function-local entity in 'imports' CU field.");
1418 CU->getOrCreateImportedEntityDIE(IE);
1419 }
1420 for (const auto *D : CU->getDeferredLocalDecls()) {
1421 if (auto *IE = dyn_cast<DIImportedEntity>(D))
1422 CU->getOrCreateImportedEntityDIE(IE);
1423 else
1424 llvm_unreachable("Unexpected local retained node!");
1425 }
1426
1427 // Emit base types.
1428 CU->createBaseTypeDIEs();
1429 }
1430
1431 // If we aren't actually generating debug info (check beginModule -
1432 // conditionalized on the presence of the llvm.dbg.cu metadata node)
1433 if (!Asm || !MMI->hasDebugInfo())
1434 return;
1435
1436 // Finalize the debug info for the module.
1437 finalizeModuleInfo();
1438
1439 if (useSplitDwarf())
1440 // Emit debug_loc.dwo/debug_loclists.dwo section.
1441 emitDebugLocDWO();
1442 else
1443 // Emit debug_loc/debug_loclists section.
1444 emitDebugLoc();
1445
1446 // Corresponding abbreviations into a abbrev section.
1447 emitAbbreviations();
1448
1449 // Emit all the DIEs into a debug info section.
1450 emitDebugInfo();
1451
1452 // Emit info into a debug aranges section.
1454 emitDebugARanges();
1455
1456 // Emit info into a debug ranges section.
1457 emitDebugRanges();
1458
1459 if (useSplitDwarf())
1460 // Emit info into a debug macinfo.dwo section.
1461 emitDebugMacinfoDWO();
1462 else
1463 // Emit info into a debug macinfo/macro section.
1464 emitDebugMacinfo();
1465
1466 emitDebugStr();
1467
1468 if (useSplitDwarf()) {
1469 emitDebugStrDWO();
1470 emitDebugInfoDWO();
1471 emitDebugAbbrevDWO();
1472 emitDebugLineDWO();
1473 emitDebugRangesDWO();
1474 }
1475
1476 emitDebugAddr();
1477
1478 // Emit info into the dwarf accelerator table sections.
1479 switch (getAccelTableKind()) {
1481 emitAccelNames();
1482 emitAccelObjC();
1483 emitAccelNamespaces();
1484 emitAccelTypes();
1485 break;
1487 emitAccelDebugNames();
1488 break;
1490 break;
1492 llvm_unreachable("Default should have already been resolved.");
1493 }
1494
1495 // Emit the pubnames and pubtypes sections if requested.
1496 emitDebugPubSections();
1497
1498 // clean up.
1499 // FIXME: AbstractVariables.clear();
1500}
1501
1502void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1503 const DINode *Node, const MDNode *ScopeNode) {
1504 if (CU.getExistingAbstractEntity(Node))
1505 return;
1506
1507 if (LexicalScope *Scope =
1508 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1509 CU.createAbstractEntity(Node, Scope);
1510}
1511
1513 const DIScope *S;
1514 if (const auto *LV = dyn_cast<DILocalVariable>(N))
1515 S = LV->getScope();
1516 else if (const auto *L = dyn_cast<DILabel>(N))
1517 S = L->getScope();
1518 else if (const auto *IE = dyn_cast<DIImportedEntity>(N))
1519 S = IE->getScope();
1520 else
1521 llvm_unreachable("Unexpected retained node!");
1522
1523 // Ensure the scope is not a DILexicalBlockFile.
1524 return cast<DILocalScope>(S)->getNonLexicalBlockFileScope();
1525}
1526
1527// Collect variable information from side table maintained by MF.
1528void DwarfDebug::collectVariableInfoFromMFTable(
1529 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1531 LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
1532 for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1533 if (!VI.Var)
1534 continue;
1535 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1536 "Expected inlined-at fields to agree");
1537
1538 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1539 Processed.insert(Var);
1541
1542 // If variable scope is not found then skip this variable.
1543 if (!Scope) {
1544 LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1545 << ", no variable scope found\n");
1546 continue;
1547 }
1548
1549 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1550
1551 // If we have already seen information for this variable, add to what we
1552 // already know.
1553 if (DbgVariable *PreviousLoc = MFVars.lookup(Var)) {
1554 auto *PreviousMMI = std::get_if<Loc::MMI>(PreviousLoc);
1555 auto *PreviousEntryValue = std::get_if<Loc::EntryValue>(PreviousLoc);
1556 // Previous and new locations are both stack slots (MMI).
1557 if (PreviousMMI && VI.inStackSlot())
1558 PreviousMMI->addFrameIndexExpr(VI.Expr, VI.getStackSlot());
1559 // Previous and new locations are both entry values.
1560 else if (PreviousEntryValue && VI.inEntryValueRegister())
1561 PreviousEntryValue->addExpr(VI.getEntryValueRegister(), *VI.Expr);
1562 else {
1563 // Locations differ, this should (rarely) happen in optimized async
1564 // coroutines.
1565 // Prefer whichever location has an EntryValue.
1566 if (PreviousLoc->holds<Loc::MMI>())
1567 PreviousLoc->emplace<Loc::EntryValue>(VI.getEntryValueRegister(),
1568 *VI.Expr);
1569 LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1570 << ", conflicting fragment location types\n");
1571 }
1572 continue;
1573 }
1574
1575 auto RegVar = std::make_unique<DbgVariable>(
1576 cast<DILocalVariable>(Var.first), Var.second);
1577 if (VI.inStackSlot())
1578 RegVar->emplace<Loc::MMI>(VI.Expr, VI.getStackSlot());
1579 else
1580 RegVar->emplace<Loc::EntryValue>(VI.getEntryValueRegister(), *VI.Expr);
1581 LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
1582 << "\n");
1583 InfoHolder.addScopeVariable(Scope, RegVar.get());
1584 MFVars.insert({Var, RegVar.get()});
1585 ConcreteEntities.push_back(std::move(RegVar));
1586 }
1587}
1588
1589/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1590/// enclosing lexical scope. The check ensures there are no other instructions
1591/// in the same lexical scope preceding the DBG_VALUE and that its range is
1592/// either open or otherwise rolls off the end of the scope.
1593static bool validThroughout(LexicalScopes &LScopes,
1594 const MachineInstr *DbgValue,
1595 const MachineInstr *RangeEnd,
1596 const InstructionOrdering &Ordering) {
1597 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1598 auto MBB = DbgValue->getParent();
1599 auto DL = DbgValue->getDebugLoc();
1600 auto *LScope = LScopes.findLexicalScope(DL);
1601 // Scope doesn't exist; this is a dead DBG_VALUE.
1602 if (!LScope)
1603 return false;
1604 auto &LSRange = LScope->getRanges();
1605 if (LSRange.size() == 0)
1606 return false;
1607
1608 const MachineInstr *LScopeBegin = LSRange.front().first;
1609 // If the scope starts before the DBG_VALUE then we may have a negative
1610 // result. Otherwise the location is live coming into the scope and we
1611 // can skip the following checks.
1612 if (!Ordering.isBefore(DbgValue, LScopeBegin)) {
1613 // Exit if the lexical scope begins outside of the current block.
1614 if (LScopeBegin->getParent() != MBB)
1615 return false;
1616
1618 for (++Pred; Pred != MBB->rend(); ++Pred) {
1619 if (Pred->getFlag(MachineInstr::FrameSetup))
1620 break;
1621 auto PredDL = Pred->getDebugLoc();
1622 if (!PredDL || Pred->isMetaInstruction())
1623 continue;
1624 // Check whether the instruction preceding the DBG_VALUE is in the same
1625 // (sub)scope as the DBG_VALUE.
1626 if (DL->getScope() == PredDL->getScope())
1627 return false;
1628 auto *PredScope = LScopes.findLexicalScope(PredDL);
1629 if (!PredScope || LScope->dominates(PredScope))
1630 return false;
1631 }
1632 }
1633
1634 // If the range of the DBG_VALUE is open-ended, report success.
1635 if (!RangeEnd)
1636 return true;
1637
1638 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1639 // throughout the function. This is a hack, presumably for DWARF v2 and not
1640 // necessarily correct. It would be much better to use a dbg.declare instead
1641 // if we know the constant is live throughout the scope.
1642 if (MBB->pred_empty() &&
1643 all_of(DbgValue->debug_operands(),
1644 [](const MachineOperand &Op) { return Op.isImm(); }))
1645 return true;
1646
1647 // Test if the location terminates before the end of the scope.
1648 const MachineInstr *LScopeEnd = LSRange.back().second;
1649 if (Ordering.isBefore(RangeEnd, LScopeEnd))
1650 return false;
1651
1652 // There's a single location which starts at the scope start, and ends at or
1653 // after the scope end.
1654 return true;
1655}
1656
1657/// Build the location list for all DBG_VALUEs in the function that
1658/// describe the same variable. The resulting DebugLocEntries will have
1659/// strict monotonically increasing begin addresses and will never
1660/// overlap. If the resulting list has only one entry that is valid
1661/// throughout variable's scope return true.
1662//
1663// See the definition of DbgValueHistoryMap::Entry for an explanation of the
1664// different kinds of history map entries. One thing to be aware of is that if
1665// a debug value is ended by another entry (rather than being valid until the
1666// end of the function), that entry's instruction may or may not be included in
1667// the range, depending on if the entry is a clobbering entry (it has an
1668// instruction that clobbers one or more preceding locations), or if it is an
1669// (overlapping) debug value entry. This distinction can be seen in the example
1670// below. The first debug value is ended by the clobbering entry 2, and the
1671// second and third debug values are ended by the overlapping debug value entry
1672// 4.
1673//
1674// Input:
1675//
1676// History map entries [type, end index, mi]
1677//
1678// 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1679// 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1680// 2 | | [Clobber, $reg0 = [...], -, -]
1681// 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1682// 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1683//
1684// Output [start, end) [Value...]:
1685//
1686// [0-1) [(reg0, fragment 0, 32)]
1687// [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1688// [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1689// [4-) [(@g, fragment 0, 96)]
1690bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1691 const DbgValueHistoryMap::Entries &Entries) {
1692 using OpenRange =
1693 std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1694 SmallVector<OpenRange, 4> OpenRanges;
1695 bool isSafeForSingleLocation = true;
1696 const MachineInstr *StartDebugMI = nullptr;
1697 const MachineInstr *EndMI = nullptr;
1698
1699 for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1700 const MachineInstr *Instr = EI->getInstr();
1701
1702 // Remove all values that are no longer live.
1703 size_t Index = std::distance(EB, EI);
1704 erase_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1705
1706 // If we are dealing with a clobbering entry, this iteration will result in
1707 // a location list entry starting after the clobbering instruction.
1708 const MCSymbol *StartLabel =
1709 EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1710 assert(StartLabel &&
1711 "Forgot label before/after instruction starting a range!");
1712
1713 const MCSymbol *EndLabel;
1714 if (std::next(EI) == Entries.end()) {
1715 const MachineBasicBlock &EndMBB = Asm->MF->back();
1716 EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionIDNum()].EndLabel;
1717 if (EI->isClobber())
1718 EndMI = EI->getInstr();
1719 }
1720 else if (std::next(EI)->isClobber())
1721 EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1722 else
1723 EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1724 assert(EndLabel && "Forgot label after instruction ending a range!");
1725
1726 if (EI->isDbgValue())
1727 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1728
1729 // If this history map entry has a debug value, add that to the list of
1730 // open ranges and check if its location is valid for a single value
1731 // location.
1732 if (EI->isDbgValue()) {
1733 // Do not add undef debug values, as they are redundant information in
1734 // the location list entries. An undef debug results in an empty location
1735 // description. If there are any non-undef fragments then padding pieces
1736 // with empty location descriptions will automatically be inserted, and if
1737 // all fragments are undef then the whole location list entry is
1738 // redundant.
1739 if (!Instr->isUndefDebugValue()) {
1740 auto Value = getDebugLocValue(Instr);
1741 OpenRanges.emplace_back(EI->getEndIndex(), Value);
1742
1743 // TODO: Add support for single value fragment locations.
1744 if (Instr->getDebugExpression()->isFragment())
1745 isSafeForSingleLocation = false;
1746
1747 if (!StartDebugMI)
1748 StartDebugMI = Instr;
1749 } else {
1750 isSafeForSingleLocation = false;
1751 }
1752 }
1753
1754 // Location list entries with empty location descriptions are redundant
1755 // information in DWARF, so do not emit those.
1756 if (OpenRanges.empty())
1757 continue;
1758
1759 // Omit entries with empty ranges as they do not have any effect in DWARF.
1760 if (StartLabel == EndLabel) {
1761 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1762 continue;
1763 }
1764
1766 for (auto &R : OpenRanges)
1767 Values.push_back(R.second);
1768
1769 // With Basic block sections, it is posssible that the StartLabel and the
1770 // Instr are not in the same section. This happens when the StartLabel is
1771 // the function begin label and the dbg value appears in a basic block
1772 // that is not the entry. In this case, the range needs to be split to
1773 // span each individual section in the range from StartLabel to EndLabel.
1774 if (Asm->MF->hasBBSections() && StartLabel == Asm->getFunctionBegin() &&
1775 !Instr->getParent()->sameSection(&Asm->MF->front())) {
1776 const MCSymbol *BeginSectionLabel = StartLabel;
1777
1778 for (const MachineBasicBlock &MBB : *Asm->MF) {
1779 if (MBB.isBeginSection() && &MBB != &Asm->MF->front())
1780 BeginSectionLabel = MBB.getSymbol();
1781
1782 if (MBB.sameSection(Instr->getParent())) {
1783 DebugLoc.emplace_back(BeginSectionLabel, EndLabel, Values);
1784 break;
1785 }
1786 if (MBB.isEndSection())
1787 DebugLoc.emplace_back(BeginSectionLabel, MBB.getEndSymbol(), Values);
1788 }
1789 } else {
1790 DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1791 }
1792
1793 // Attempt to coalesce the ranges of two otherwise identical
1794 // DebugLocEntries.
1795 auto CurEntry = DebugLoc.rbegin();
1796 LLVM_DEBUG({
1797 dbgs() << CurEntry->getValues().size() << " Values:\n";
1798 for (auto &Value : CurEntry->getValues())
1799 Value.dump();
1800 dbgs() << "-----\n";
1801 });
1802
1803 auto PrevEntry = std::next(CurEntry);
1804 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1805 DebugLoc.pop_back();
1806 }
1807
1808 if (!isSafeForSingleLocation ||
1809 !validThroughout(LScopes, StartDebugMI, EndMI, getInstOrdering()))
1810 return false;
1811
1812 if (DebugLoc.size() == 1)
1813 return true;
1814
1815 if (!Asm->MF->hasBBSections())
1816 return false;
1817
1818 // Check here to see if loclist can be merged into a single range. If not,
1819 // we must keep the split loclists per section. This does exactly what
1820 // MergeRanges does without sections. We don't actually merge the ranges
1821 // as the split ranges must be kept intact if this cannot be collapsed
1822 // into a single range.
1823 const MachineBasicBlock *RangeMBB = nullptr;
1824 if (DebugLoc[0].getBeginSym() == Asm->getFunctionBegin())
1825 RangeMBB = &Asm->MF->front();
1826 else
1827 RangeMBB = Entries.begin()->getInstr()->getParent();
1828 auto *CurEntry = DebugLoc.begin();
1829 auto *NextEntry = std::next(CurEntry);
1830 while (NextEntry != DebugLoc.end()) {
1831 // Get the last machine basic block of this section.
1832 while (!RangeMBB->isEndSection())
1833 RangeMBB = RangeMBB->getNextNode();
1834 if (!RangeMBB->getNextNode())
1835 return false;
1836 // CurEntry should end the current section and NextEntry should start
1837 // the next section and the Values must match for these two ranges to be
1838 // merged.
1839 if (CurEntry->getEndSym() != RangeMBB->getEndSymbol() ||
1840 NextEntry->getBeginSym() != RangeMBB->getNextNode()->getSymbol() ||
1841 CurEntry->getValues() != NextEntry->getValues())
1842 return false;
1843 RangeMBB = RangeMBB->getNextNode();
1844 CurEntry = NextEntry;
1845 NextEntry = std::next(CurEntry);
1846 }
1847 return true;
1848}
1849
1850DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1851 LexicalScope &Scope,
1852 const DINode *Node,
1853 const DILocation *Location,
1854 const MCSymbol *Sym) {
1855 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1856 if (isa<const DILocalVariable>(Node)) {
1857 ConcreteEntities.push_back(
1858 std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1859 Location));
1860 InfoHolder.addScopeVariable(&Scope,
1861 cast<DbgVariable>(ConcreteEntities.back().get()));
1862 } else if (isa<const DILabel>(Node)) {
1863 ConcreteEntities.push_back(
1864 std::make_unique<DbgLabel>(cast<const DILabel>(Node),
1865 Location, Sym));
1866 InfoHolder.addScopeLabel(&Scope,
1867 cast<DbgLabel>(ConcreteEntities.back().get()));
1868 }
1869 return ConcreteEntities.back().get();
1870}
1871
1872// Find variables for each lexical scope.
1873void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1874 const DISubprogram *SP,
1875 DenseSet<InlinedEntity> &Processed) {
1876 // Grab the variable info that was squirreled away in the MMI side-table.
1877 collectVariableInfoFromMFTable(TheCU, Processed);
1878
1879 for (const auto &I : DbgValues) {
1880 InlinedEntity IV = I.first;
1881 if (Processed.count(IV))
1882 continue;
1883
1884 // Instruction ranges, specifying where IV is accessible.
1885 const auto &HistoryMapEntries = I.second;
1886
1887 // Try to find any non-empty variable location. Do not create a concrete
1888 // entity if there are no locations.
1889 if (!DbgValues.hasNonEmptyLocation(HistoryMapEntries))
1890 continue;
1891
1892 LexicalScope *Scope = nullptr;
1893 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1894 if (const DILocation *IA = IV.second)
1895 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1896 else
1897 Scope = LScopes.findLexicalScope(LocalVar->getScope());
1898 // If variable scope is not found then skip this variable.
1899 if (!Scope)
1900 continue;
1901
1902 Processed.insert(IV);
1903 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1904 *Scope, LocalVar, IV.second));
1905
1906 const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1907 assert(MInsn->isDebugValue() && "History must begin with debug value");
1908
1909 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1910 // If the history map contains a single debug value, there may be an
1911 // additional entry which clobbers the debug value.
1912 size_t HistSize = HistoryMapEntries.size();
1913 bool SingleValueWithClobber =
1914 HistSize == 2 && HistoryMapEntries[1].isClobber();
1915 if (HistSize == 1 || SingleValueWithClobber) {
1916 const auto *End =
1917 SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1918 if (validThroughout(LScopes, MInsn, End, getInstOrdering())) {
1919 RegVar->emplace<Loc::Single>(MInsn);
1920 continue;
1921 }
1922 }
1923
1924 // Do not emit location lists if .debug_loc secton is disabled.
1925 if (!useLocSection())
1926 continue;
1927
1928 // Handle multiple DBG_VALUE instructions describing one variable.
1929 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar);
1930
1931 // Build the location list for this variable.
1933 bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
1934
1935 // Check whether buildLocationList managed to merge all locations to one
1936 // that is valid throughout the variable's scope. If so, produce single
1937 // value location.
1938 if (isValidSingleLocation) {
1939 RegVar->emplace<Loc::Single>(Entries[0].getValues()[0]);
1940 continue;
1941 }
1942
1943 // If the variable has a DIBasicType, extract it. Basic types cannot have
1944 // unique identifiers, so don't bother resolving the type with the
1945 // identifier map.
1946 const DIBasicType *BT = dyn_cast<DIBasicType>(
1947 static_cast<const Metadata *>(LocalVar->getType()));
1948
1949 // Finalize the entry by lowering it into a DWARF bytestream.
1950 for (auto &Entry : Entries)
1951 Entry.finalize(*Asm, List, BT, TheCU);
1952 }
1953
1954 // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1955 // DWARF-related DbgLabel.
1956 for (const auto &I : DbgLabels) {
1957 InlinedEntity IL = I.first;
1958 const MachineInstr *MI = I.second;
1959 if (MI == nullptr)
1960 continue;
1961
1962 LexicalScope *Scope = nullptr;
1963 const DILabel *Label = cast<DILabel>(IL.first);
1964 // The scope could have an extra lexical block file.
1965 const DILocalScope *LocalScope =
1966 Label->getScope()->getNonLexicalBlockFileScope();
1967 // Get inlined DILocation if it is inlined label.
1968 if (const DILocation *IA = IL.second)
1969 Scope = LScopes.findInlinedScope(LocalScope, IA);
1970 else
1971 Scope = LScopes.findLexicalScope(LocalScope);
1972 // If label scope is not found then skip this label.
1973 if (!Scope)
1974 continue;
1975
1976 Processed.insert(IL);
1977 /// At this point, the temporary label is created.
1978 /// Save the temporary label to DbgLabel entity to get the
1979 /// actually address when generating Dwarf DIE.
1981 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1982 }
1983
1984 // Collect info for retained nodes.
1985 for (const DINode *DN : SP->getRetainedNodes()) {
1986 const auto *LS = getRetainedNodeScope(DN);
1987 if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
1988 if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1989 continue;
1991 if (LexS)
1992 createConcreteEntity(TheCU, *LexS, DN, nullptr);
1993 } else {
1994 LocalDeclsPerLS[LS].insert(DN);
1995 }
1996 }
1997}
1998
1999// Process beginning of an instruction.
2001 const MachineFunction &MF = *MI->getMF();
2002 const auto *SP = MF.getFunction().getSubprogram();
2003 bool NoDebug =
2004 !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
2005
2006 // Delay slot support check.
2007 auto delaySlotSupported = [](const MachineInstr &MI) {
2008 if (!MI.isBundledWithSucc())
2009 return false;
2010 auto Suc = std::next(MI.getIterator());
2011 (void)Suc;
2012 // Ensure that delay slot instruction is successor of the call instruction.
2013 // Ex. CALL_INSTRUCTION {
2014 // DELAY_SLOT_INSTRUCTION }
2015 assert(Suc->isBundledWithPred() &&
2016 "Call bundle instructions are out of order");
2017 return true;
2018 };
2019
2020 // When describing calls, we need a label for the call instruction.
2021 if (!NoDebug && SP->areAllCallsDescribed() &&
2022 MI->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle) &&
2023 (!MI->hasDelaySlot() || delaySlotSupported(*MI))) {
2025 bool IsTail = TII->isTailCall(*MI);
2026 // For tail calls, we need the address of the branch instruction for
2027 // DW_AT_call_pc.
2028 if (IsTail)
2030 // For non-tail calls, we need the return address for the call for
2031 // DW_AT_call_return_pc. Under GDB tuning, this information is needed for
2032 // tail calls as well.
2034 }
2035
2037 if (!CurMI)
2038 return;
2039
2040 if (NoDebug)
2041 return;
2042
2043 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
2044 // If the instruction is part of the function frame setup code, do not emit
2045 // any line record, as there is no correspondence with any user code.
2046 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
2047 return;
2048 const DebugLoc &DL = MI->getDebugLoc();
2049 unsigned Flags = 0;
2050
2051 if (MI->getFlag(MachineInstr::FrameDestroy) && DL) {
2052 const MachineBasicBlock *MBB = MI->getParent();
2053 if (MBB && (MBB != EpilogBeginBlock)) {
2054 // First time FrameDestroy has been seen in this basic block
2057 }
2058 }
2059
2060 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
2061 // the last line number actually emitted, to see if it was line 0.
2062 unsigned LastAsmLine =
2063 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
2064
2065 bool PrevInstInSameSection =
2066 (!PrevInstBB ||
2067 PrevInstBB->getSectionIDNum() == MI->getParent()->getSectionIDNum());
2068 if (DL == PrevInstLoc && PrevInstInSameSection) {
2069 // If we have an ongoing unspecified location, nothing to do here.
2070 if (!DL)
2071 return;
2072 // We have an explicit location, same as the previous location.
2073 // But we might be coming back to it after a line 0 record.
2074 if ((LastAsmLine == 0 && DL.getLine() != 0) || Flags) {
2075 // Reinstate the source location but not marked as a statement.
2076 const MDNode *Scope = DL.getScope();
2077 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
2078 }
2079 return;
2080 }
2081
2082 if (!DL) {
2083 // We have an unspecified location, which might want to be line 0.
2084 // If we have already emitted a line-0 record, don't repeat it.
2085 if (LastAsmLine == 0)
2086 return;
2087 // If user said Don't Do That, don't do that.
2089 return;
2090 // See if we have a reason to emit a line-0 record now.
2091 // Reasons to emit a line-0 record include:
2092 // - User asked for it (UnknownLocations).
2093 // - Instruction has a label, so it's referenced from somewhere else,
2094 // possibly debug information; we want it to have a source location.
2095 // - Instruction is at the top of a block; we don't want to inherit the
2096 // location from the physically previous (maybe unrelated) block.
2097 if (UnknownLocations == Enable || PrevLabel ||
2098 (PrevInstBB && PrevInstBB != MI->getParent())) {
2099 // Preserve the file and column numbers, if we can, to save space in
2100 // the encoded line table.
2101 // Do not update PrevInstLoc, it remembers the last non-0 line.
2102 const MDNode *Scope = nullptr;
2103 unsigned Column = 0;
2104 if (PrevInstLoc) {
2105 Scope = PrevInstLoc.getScope();
2106 Column = PrevInstLoc.getCol();
2107 }
2108 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
2109 }
2110 return;
2111 }
2112
2113 // We have an explicit location, different from the previous location.
2114 // Don't repeat a line-0 record, but otherwise emit the new location.
2115 // (The new location might be an explicit line 0, which we do emit.)
2116 if (DL.getLine() == 0 && LastAsmLine == 0)
2117 return;
2118 if (DL == PrologEndLoc) {
2121 }
2122 // If the line changed, we call that a new statement; unless we went to
2123 // line 0 and came back, in which case it is not a new statement.
2124 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
2125 if (DL.getLine() && DL.getLine() != OldLine)
2126 Flags |= DWARF2_FLAG_IS_STMT;
2127
2128 const MDNode *Scope = DL.getScope();
2129 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
2130
2131 // If we're not at line 0, remember this location.
2132 if (DL.getLine())
2133 PrevInstLoc = DL;
2134}
2135
2136static std::pair<DebugLoc, bool> findPrologueEndLoc(const MachineFunction *MF) {
2137 // First known non-DBG_VALUE and non-frame setup location marks
2138 // the beginning of the function body.
2139 DebugLoc LineZeroLoc;
2140 const Function &F = MF->getFunction();
2141
2142 // Some instructions may be inserted into prologue after this function. Must
2143 // keep prologue for these cases.
2144 bool IsEmptyPrologue =
2145 !(F.hasPrologueData() || F.getMetadata(LLVMContext::MD_func_sanitize));
2146 for (const auto &MBB : *MF) {
2147 for (const auto &MI : MBB) {
2148 if (!MI.isMetaInstruction()) {
2149 if (!MI.getFlag(MachineInstr::FrameSetup) && MI.getDebugLoc()) {
2150 // Scan forward to try to find a non-zero line number. The
2151 // prologue_end marks the first breakpoint in the function after the
2152 // frame setup, and a compiler-generated line 0 location is not a
2153 // meaningful breakpoint. If none is found, return the first
2154 // location after the frame setup.
2155 if (MI.getDebugLoc().getLine())
2156 return std::make_pair(MI.getDebugLoc(), IsEmptyPrologue);
2157
2158 LineZeroLoc = MI.getDebugLoc();
2159 }
2160 IsEmptyPrologue = false;
2161 }
2162 }
2163 }
2164 return std::make_pair(LineZeroLoc, IsEmptyPrologue);
2165}
2166
2167/// Register a source line with debug info. Returns the unique label that was
2168/// emitted and which provides correspondence to the source line list.
2169static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
2170 const MDNode *S, unsigned Flags, unsigned CUID,
2171 uint16_t DwarfVersion,
2172 ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
2173 StringRef Fn;
2174 unsigned FileNo = 1;
2175 unsigned Discriminator = 0;
2176 if (auto *Scope = cast_or_null<DIScope>(S)) {
2177 Fn = Scope->getFilename();
2178 if (Line != 0 && DwarfVersion >= 4)
2179 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
2180 Discriminator = LBF->getDiscriminator();
2181
2182 FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
2183 .getOrCreateSourceID(Scope->getFile());
2184 }
2185 Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
2186 Discriminator, Fn);
2187}
2188
2190 unsigned CUID) {
2191 std::pair<DebugLoc, bool> PrologEnd = findPrologueEndLoc(&MF);
2192 DebugLoc PrologEndLoc = PrologEnd.first;
2193 bool IsEmptyPrologue = PrologEnd.second;
2194
2195 // Get beginning of function.
2196 if (PrologEndLoc) {
2197 // If the prolog is empty, no need to generate scope line for the proc.
2198 if (IsEmptyPrologue)
2199 return PrologEndLoc;
2200
2201 // Ensure the compile unit is created if the function is called before
2202 // beginFunction().
2203 (void)getOrCreateDwarfCompileUnit(
2204 MF.getFunction().getSubprogram()->getUnit());
2205 // We'd like to list the prologue as "not statements" but GDB behaves
2206 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
2207 const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
2208 ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
2209 CUID, getDwarfVersion(), getUnits());
2210 return PrologEndLoc;
2211 }
2212 return DebugLoc();
2213}
2214
2215// Gather pre-function debug information. Assumes being called immediately
2216// after the function entry point has been emitted.
2218 CurFn = MF;
2219
2220 auto *SP = MF->getFunction().getSubprogram();
2222 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
2223 return;
2224
2225 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
2226
2227 Asm->OutStreamer->getContext().setDwarfCompileUnitID(
2229
2230 // Record beginning of function.
2232 *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
2233}
2234
2235unsigned
2237 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
2238 // belongs to so that we add to the correct per-cu line table in the
2239 // non-asm case.
2240 if (Asm->OutStreamer->hasRawTextSupport())
2241 // Use a single line table if we are generating assembly.
2242 return 0;
2243 else
2244 return CU.getUniqueID();
2245}
2246
2248 const auto &CURanges = CU->getRanges();
2249 auto &LineTable = Asm->OutStreamer->getContext().getMCDwarfLineTable(
2251 // Add the last range label for the given CU.
2252 LineTable.getMCLineSections().addEndEntry(
2253 const_cast<MCSymbol *>(CURanges.back().End));
2254}
2255
2257 // If we don't have a subprogram for this function then there will be a hole
2258 // in the range information. Keep note of this by setting the previously used
2259 // section to nullptr.
2260 // Terminate the pending line table.
2261 if (PrevCU)
2262 terminateLineTable(PrevCU);
2263 PrevCU = nullptr;
2264 CurFn = nullptr;
2265}
2266
2267// Gather and emit post-function debug information.
2269 const DISubprogram *SP = MF->getFunction().getSubprogram();
2270
2271 assert(CurFn == MF &&
2272 "endFunction should be called with the same function as beginFunction");
2273
2274 // Set DwarfDwarfCompileUnitID in MCContext to default value.
2275 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
2276
2278 assert(!FnScope || SP == FnScope->getScopeNode());
2279 DwarfCompileUnit &TheCU = getOrCreateDwarfCompileUnit(SP->getUnit());
2280 if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
2281 PrevLabel = nullptr;
2282 CurFn = nullptr;
2283 return;
2284 }
2285
2286 DenseSet<InlinedEntity> Processed;
2287 collectEntityInfo(TheCU, SP, Processed);
2288
2289 // Add the range of this function to the list of ranges for the CU.
2290 // With basic block sections, add ranges for all basic block sections.
2291 for (const auto &R : Asm->MBBSectionRanges)
2292 TheCU.addRange({R.second.BeginLabel, R.second.EndLabel});
2293
2294 // Under -gmlt, skip building the subprogram if there are no inlined
2295 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
2296 // is still needed as we need its source location.
2297 if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
2299 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
2300 for (const auto &R : Asm->MBBSectionRanges)
2301 addArangeLabel(SymbolCU(&TheCU, R.second.BeginLabel));
2302
2303 assert(InfoHolder.getScopeVariables().empty());
2304 PrevLabel = nullptr;
2305 CurFn = nullptr;
2306 return;
2307 }
2308
2309#ifndef NDEBUG
2310 size_t NumAbstractSubprograms = LScopes.getAbstractScopesList().size();
2311#endif
2312 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
2313 const auto *SP = cast<DISubprogram>(AScope->getScopeNode());
2314 for (const DINode *DN : SP->getRetainedNodes()) {
2315 const auto *LS = getRetainedNodeScope(DN);
2316 // Ensure LexicalScope is created for the scope of this node.
2317 auto *LexS = LScopes.getOrCreateAbstractScope(LS);
2318 assert(LexS && "Expected the LexicalScope to be created.");
2319 if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
2320 // Collect info for variables/labels that were optimized out.
2321 if (!Processed.insert(InlinedEntity(DN, nullptr)).second ||
2322 TheCU.getExistingAbstractEntity(DN))
2323 continue;
2324 TheCU.createAbstractEntity(DN, LexS);
2325 } else {
2326 // Remember the node if this is a local declarations.
2327 LocalDeclsPerLS[LS].insert(DN);
2328 }
2329 assert(
2330 LScopes.getAbstractScopesList().size() == NumAbstractSubprograms &&
2331 "getOrCreateAbstractScope() inserted an abstract subprogram scope");
2332 }
2333 constructAbstractSubprogramScopeDIE(TheCU, AScope);
2334 }
2335
2336 ProcessedSPNodes.insert(SP);
2337 DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
2338 if (auto *SkelCU = TheCU.getSkeleton())
2339 if (!LScopes.getAbstractScopesList().empty() &&
2341 SkelCU->constructSubprogramScopeDIE(SP, FnScope);
2342
2343 // Construct call site entries.
2344 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
2345
2346 // Clear debug info
2347 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
2348 // DbgVariables except those that are also in AbstractVariables (since they
2349 // can be used cross-function)
2350 InfoHolder.getScopeVariables().clear();
2351 InfoHolder.getScopeLabels().clear();
2352 LocalDeclsPerLS.clear();
2353 PrevLabel = nullptr;
2354 CurFn = nullptr;
2355}
2356
2357// Register a source line with debug info. Returns the unique label that was
2358// emitted and which provides correspondence to the source line list.
2359void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
2360 unsigned Flags) {
2361 ::recordSourceLine(*Asm, Line, Col, S, Flags,
2362 Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
2363 getDwarfVersion(), getUnits());
2364}
2365
2366//===----------------------------------------------------------------------===//
2367// Emit Methods
2368//===----------------------------------------------------------------------===//
2369
2370// Emit the debug info section.
2371void DwarfDebug::emitDebugInfo() {
2372 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2373 Holder.emitUnits(/* UseOffsets */ false);
2374}
2375
2376// Emit the abbreviation section.
2377void DwarfDebug::emitAbbreviations() {
2378 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2379
2381}
2382
2383void DwarfDebug::emitStringOffsetsTableHeader() {
2384 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2387 Holder.getStringOffsetsStartSym());
2388}
2389
2390template <typename AccelTableT>
2391void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
2392 StringRef TableName) {
2393 Asm->OutStreamer->switchSection(Section);
2394
2395 // Emit the full data.
2396 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
2397}
2398
2399void DwarfDebug::emitAccelDebugNames() {
2400 // Don't emit anything if we have no compilation units to index.
2401 if (getUnits().empty())
2402 return;
2403
2404 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
2405}
2406
2407// Emit visible names into a hashed accelerator table section.
2408void DwarfDebug::emitAccelNames() {
2409 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
2410 "Names");
2411}
2412
2413// Emit objective C classes and categories into a hashed accelerator table
2414// section.
2415void DwarfDebug::emitAccelObjC() {
2416 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
2417 "ObjC");
2418}
2419
2420// Emit namespace dies into a hashed accelerator table.
2421void DwarfDebug::emitAccelNamespaces() {
2422 emitAccel(AccelNamespace,
2424 "namespac");
2425}
2426
2427// Emit type dies into a hashed accelerator table.
2428void DwarfDebug::emitAccelTypes() {
2429 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
2430 "types");
2431}
2432
2433// Public name handling.
2434// The format for the various pubnames:
2435//
2436// dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2437// for the DIE that is named.
2438//
2439// gnu pubnames - offset/index value/name tuples where the offset is the offset
2440// into the CU and the index value is computed according to the type of value
2441// for the DIE that is named.
2442//
2443// For type units the offset is the offset of the skeleton DIE. For split dwarf
2444// it's the offset within the debug_info/debug_types dwo section, however, the
2445// reference in the pubname header doesn't change.
2446
2447/// computeIndexValue - Compute the gdb index value for the DIE and CU.
2449 const DIE *Die) {
2450 // Entities that ended up only in a Type Unit reference the CU instead (since
2451 // the pub entry has offsets within the CU there's no real offset that can be
2452 // provided anyway). As it happens all such entities (namespaces and types,
2453 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
2454 // not to be true it would be necessary to persist this information from the
2455 // point at which the entry is added to the index data structure - since by
2456 // the time the index is built from that, the original type/namespace DIE in a
2457 // type unit has already been destroyed so it can't be queried for properties
2458 // like tag, etc.
2459 if (Die->getTag() == dwarf::DW_TAG_compile_unit)
2463
2464 // We could have a specification DIE that has our most of our knowledge,
2465 // look for that now.
2466 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
2467 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
2468 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
2469 Linkage = dwarf::GIEL_EXTERNAL;
2470 } else if (Die->findAttribute(dwarf::DW_AT_external))
2471 Linkage = dwarf::GIEL_EXTERNAL;
2472
2473 switch (Die->getTag()) {
2474 case dwarf::DW_TAG_class_type:
2475 case dwarf::DW_TAG_structure_type:
2476 case dwarf::DW_TAG_union_type:
2477 case dwarf::DW_TAG_enumeration_type:
2483 case dwarf::DW_TAG_typedef:
2484 case dwarf::DW_TAG_base_type:
2485 case dwarf::DW_TAG_subrange_type:
2487 case dwarf::DW_TAG_namespace:
2488 return dwarf::GIEK_TYPE;
2489 case dwarf::DW_TAG_subprogram:
2491 case dwarf::DW_TAG_variable:
2493 case dwarf::DW_TAG_enumerator:
2496 default:
2497 return dwarf::GIEK_NONE;
2498 }
2499}
2500
2501/// emitDebugPubSections - Emit visible names and types into debug pubnames and
2502/// pubtypes sections.
2503void DwarfDebug::emitDebugPubSections() {
2504 for (const auto &NU : CUMap) {
2505 DwarfCompileUnit *TheU = NU.second;
2506 if (!TheU->hasDwarfPubSections())
2507 continue;
2508
2509 bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
2511
2512 Asm->OutStreamer->switchSection(
2515 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
2516
2517 Asm->OutStreamer->switchSection(
2520 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
2521 }
2522}
2523
2524void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
2526 Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
2527 CU.getDebugSectionOffset());
2528 else
2529 Asm->emitDwarfSymbolReference(CU.getLabelBegin());
2530}
2531
2532void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
2533 DwarfCompileUnit *TheU,
2534 const StringMap<const DIE *> &Globals) {
2535 if (auto *Skeleton = TheU->getSkeleton())
2536 TheU = Skeleton;
2537
2538 // Emit the header.
2539 MCSymbol *EndLabel = Asm->emitDwarfUnitLength(
2540 "pub" + Name, "Length of Public " + Name + " Info");
2541
2542 Asm->OutStreamer->AddComment("DWARF Version");
2544
2545 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
2546 emitSectionReference(*TheU);
2547
2548 Asm->OutStreamer->AddComment("Compilation Unit Length");
2550
2551 // Emit the pubnames for this compilation unit.
2553 for (const auto &GI : Globals)
2554 Vec.emplace_back(GI.first(), GI.second);
2555 llvm::sort(Vec, [](auto &A, auto &B) {
2556 return A.second->getOffset() < B.second->getOffset();
2557 });
2558 for (const auto &[Name, Entity] : Vec) {
2559 Asm->OutStreamer->AddComment("DIE offset");
2560 Asm->emitDwarfLengthOrOffset(Entity->getOffset());
2561
2562 if (GnuStyle) {
2564 Asm->OutStreamer->AddComment(
2565 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
2566 ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2567 Asm->emitInt8(Desc.toBits());
2568 }
2569
2570 Asm->OutStreamer->AddComment("External Name");
2571 Asm->OutStreamer->emitBytes(StringRef(Name.data(), Name.size() + 1));
2572 }
2573
2574 Asm->OutStreamer->AddComment("End Mark");
2576 Asm->OutStreamer->emitLabel(EndLabel);
2577}
2578
2579/// Emit null-terminated strings into a debug str section.
2580void DwarfDebug::emitDebugStr() {
2581 MCSection *StringOffsetsSection = nullptr;
2583 emitStringOffsetsTableHeader();
2584 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
2585 }
2586 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2588 StringOffsetsSection, /* UseRelativeOffsets = */ true);
2589}
2590
2592 const DebugLocStream::Entry &Entry,
2593 const DwarfCompileUnit *CU) {
2594 auto &&Comments = DebugLocs.getComments(Entry);
2595 auto Comment = Comments.begin();
2596 auto End = Comments.end();
2597
2598 // The expressions are inserted into a byte stream rather early (see
2599 // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2600 // need to reference a base_type DIE the offset of that DIE is not yet known.
2601 // To deal with this we instead insert a placeholder early and then extract
2602 // it here and replace it with the real reference.
2603 unsigned PtrSize = Asm->MAI->getCodePointerSize();
2604 DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
2605 DebugLocs.getBytes(Entry).size()),
2606 Asm->getDataLayout().isLittleEndian(), PtrSize);
2608
2609 using Encoding = DWARFExpression::Operation::Encoding;
2610 uint64_t Offset = 0;
2611 for (const auto &Op : Expr) {
2612 assert(Op.getCode() != dwarf::DW_OP_const_type &&
2613 "3 operand ops not yet supported");
2614 assert(!Op.getSubCode() && "SubOps not yet supported");
2615 Streamer.emitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
2616 Offset++;
2617 for (unsigned I = 0; I < Op.getDescription().Op.size(); ++I) {
2618 if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
2619 unsigned Length =
2620 Streamer.emitDIERef(*CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die);
2621 // Make sure comments stay aligned.
2622 for (unsigned J = 0; J < Length; ++J)
2623 if (Comment != End)
2624 Comment++;
2625 } else {
2626 for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2627 Streamer.emitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
2628 }
2630 }
2632 }
2633}
2634
2636 const DbgValueLoc &Value,
2637 DwarfExpression &DwarfExpr) {
2638 auto *DIExpr = Value.getExpression();
2639 DIExpressionCursor ExprCursor(DIExpr);
2640 DwarfExpr.addFragmentOffset(DIExpr);
2641
2642 // If the DIExpr is an Entry Value, we want to follow the same code path
2643 // regardless of whether the DBG_VALUE is variadic or not.
2644 if (DIExpr && DIExpr->isEntryValue()) {
2645 // Entry values can only be a single register with no additional DIExpr,
2646 // so just add it directly.
2647 assert(Value.getLocEntries().size() == 1);
2648 assert(Value.getLocEntries()[0].isLocation());
2649 MachineLocation Location = Value.getLocEntries()[0].getLoc();
2650 DwarfExpr.setLocation(Location, DIExpr);
2651
2652 DwarfExpr.beginEntryValueExpression(ExprCursor);
2653
2655 if (!DwarfExpr.addMachineRegExpression(TRI, ExprCursor, Location.getReg()))
2656 return;
2657 return DwarfExpr.addExpression(std::move(ExprCursor));
2658 }
2659
2660 // Regular entry.
2661 auto EmitValueLocEntry = [&DwarfExpr, &BT,
2662 &AP](const DbgValueLocEntry &Entry,
2663 DIExpressionCursor &Cursor) -> bool {
2664 if (Entry.isInt()) {
2665 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
2666 BT->getEncoding() == dwarf::DW_ATE_signed_char))
2667 DwarfExpr.addSignedConstant(Entry.getInt());
2668 else
2669 DwarfExpr.addUnsignedConstant(Entry.getInt());
2670 } else if (Entry.isLocation()) {
2671 MachineLocation Location = Entry.getLoc();
2672 if (Location.isIndirect())
2673 DwarfExpr.setMemoryLocationKind();
2674
2676 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2677 return false;
2678 } else if (Entry.isTargetIndexLocation()) {
2679 TargetIndexLocation Loc = Entry.getTargetIndexLocation();
2680 // TODO TargetIndexLocation is a target-independent. Currently only the
2681 // WebAssembly-specific encoding is supported.
2683 DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
2684 } else if (Entry.isConstantFP()) {
2685 if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() &&
2686 !Cursor) {
2687 DwarfExpr.addConstantFP(Entry.getConstantFP()->getValueAPF(), AP);
2688 } else if (Entry.getConstantFP()
2689 ->getValueAPF()
2690 .bitcastToAPInt()
2691 .getBitWidth() <= 64 /*bits*/) {
2692 DwarfExpr.addUnsignedConstant(
2693 Entry.getConstantFP()->getValueAPF().bitcastToAPInt());
2694 } else {
2695 LLVM_DEBUG(
2696 dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
2697 << Entry.getConstantFP()
2698 ->getValueAPF()
2699 .bitcastToAPInt()
2700 .getBitWidth()
2701 << " bits\n");
2702 return false;
2703 }
2704 }
2705 return true;
2706 };
2707
2708 if (!Value.isVariadic()) {
2709 if (!EmitValueLocEntry(Value.getLocEntries()[0], ExprCursor))
2710 return;
2711 DwarfExpr.addExpression(std::move(ExprCursor));
2712 return;
2713 }
2714
2715 // If any of the location entries are registers with the value 0, then the
2716 // location is undefined.
2717 if (any_of(Value.getLocEntries(), [](const DbgValueLocEntry &Entry) {
2718 return Entry.isLocation() && !Entry.getLoc().getReg();
2719 }))
2720 return;
2721
2722 DwarfExpr.addExpression(
2723 std::move(ExprCursor),
2724 [EmitValueLocEntry, &Value](unsigned Idx,
2725 DIExpressionCursor &Cursor) -> bool {
2726 return EmitValueLocEntry(Value.getLocEntries()[Idx], Cursor);
2727 });
2728}
2729
2732 const DIBasicType *BT,
2733 DwarfCompileUnit &TheCU) {
2734 assert(!Values.empty() &&
2735 "location list entries without values are redundant");
2736 assert(Begin != End && "unexpected location list entry with empty range");
2737 DebugLocStream::EntryBuilder Entry(List, Begin, End);
2738 BufferByteStreamer Streamer = Entry.getStreamer();
2739 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
2740 const DbgValueLoc &Value = Values[0];
2741 if (Value.isFragment()) {
2742 // Emit all fragments that belong to the same variable and range.
2743 assert(llvm::all_of(Values, [](DbgValueLoc P) {
2744 return P.isFragment();
2745 }) && "all values are expected to be fragments");
2746 assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");
2747
2748 for (const auto &Fragment : Values)
2749 DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
2750
2751 } else {
2752 assert(Values.size() == 1 && "only fragments may have >1 value");
2753 DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
2754 }
2755 DwarfExpr.finalize();
2756 if (DwarfExpr.TagOffset)
2757 List.setTagOffset(*DwarfExpr.TagOffset);
2758}
2759
2761 const DwarfCompileUnit *CU) {
2762 // Emit the size.
2763 Asm->OutStreamer->AddComment("Loc expr size");
2764 if (getDwarfVersion() >= 5)
2765 Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
2766 else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2767 Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2768 else {
2769 // The entry is too big to fit into 16 bit, drop it as there is nothing we
2770 // can do.
2771 Asm->emitInt16(0);
2772 return;
2773 }
2774 // Emit the entry.
2775 APByteStreamer Streamer(*Asm);
2776 emitDebugLocEntry(Streamer, Entry, CU);
2777}
2778
2779// Emit the header of a DWARF 5 range list table list table. Returns the symbol
2780// that designates the end of the table for the caller to emit when the table is
2781// complete.
2783 const DwarfFile &Holder) {
2784 MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
2785
2786 Asm->OutStreamer->AddComment("Offset entry count");
2787 Asm->emitInt32(Holder.getRangeLists().size());
2788 Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
2789
2790 for (const RangeSpanList &List : Holder.getRangeLists())
2791 Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),
2792 Asm->getDwarfOffsetByteSize());
2793
2794 return TableEnd;
2795}
2796
2797// Emit the header of a DWARF 5 locations list table. Returns the symbol that
2798// designates the end of the table for the caller to emit when the table is
2799// complete.
2801 const DwarfDebug &DD) {
2802 MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
2803
2804 const auto &DebugLocs = DD.getDebugLocs();
2805
2806 Asm->OutStreamer->AddComment("Offset entry count");
2807 Asm->emitInt32(DebugLocs.getLists().size());
2808 Asm->OutStreamer->emitLabel(DebugLocs.getSym());
2809
2810 for (const auto &List : DebugLocs.getLists())
2811 Asm->emitLabelDifference(List.Label, DebugLocs.getSym(),
2812 Asm->getDwarfOffsetByteSize());
2813
2814 return TableEnd;
2815}
2816
2817template <typename Ranges, typename PayloadEmitter>
2818static void emitRangeList(
2819 DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
2820 const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
2821 unsigned StartxLength, unsigned EndOfList,
2822 StringRef (*StringifyEnum)(unsigned),
2823 bool ShouldUseBaseAddress,
2824 PayloadEmitter EmitPayload) {
2825
2826 auto Size = Asm->MAI->getCodePointerSize();
2827 bool UseDwarf5 = DD.getDwarfVersion() >= 5;
2828
2829 // Emit our symbol so we can find the beginning of the range.
2830 Asm->OutStreamer->emitLabel(Sym);
2831
2832 // Gather all the ranges that apply to the same section so they can share
2833 // a base address entry.
2834 MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
2835
2836 for (const auto &Range : R)
2837 SectionRanges[&Range.Begin->getSection()].push_back(&Range);
2838
2839 const MCSymbol *CUBase = CU.getBaseAddress();
2840 bool BaseIsSet = false;
2841 for (const auto &P : SectionRanges) {
2842 auto *Base = CUBase;
2843 if (!Base && ShouldUseBaseAddress) {
2844 const MCSymbol *Begin = P.second.front()->Begin;
2845 const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
2846 if (!UseDwarf5) {
2847 Base = NewBase;
2848 BaseIsSet = true;
2849 Asm->OutStreamer->emitIntValue(-1, Size);
2850 Asm->OutStreamer->AddComment(" base address");
2851 Asm->OutStreamer->emitSymbolValue(Base, Size);
2852 } else if (NewBase != Begin || P.second.size() > 1) {
2853 // Only use a base address if
2854 // * the existing pool address doesn't match (NewBase != Begin)
2855 // * or, there's more than one entry to share the base address
2856 Base = NewBase;
2857 BaseIsSet = true;
2858 Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
2859 Asm->emitInt8(BaseAddressx);
2860 Asm->OutStreamer->AddComment(" base address index");
2861 Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
2862 }
2863 } else if (BaseIsSet && !UseDwarf5) {
2864 BaseIsSet = false;
2865 assert(!Base);
2866 Asm->OutStreamer->emitIntValue(-1, Size);
2867 Asm->OutStreamer->emitIntValue(0, Size);
2868 }
2869
2870 for (const auto *RS : P.second) {
2871 const MCSymbol *Begin = RS->Begin;
2872 const MCSymbol *End = RS->End;
2873 assert(Begin && "Range without a begin symbol?");
2874 assert(End && "Range without an end symbol?");
2875 if (Base) {
2876 if (UseDwarf5) {
2877 // Emit offset_pair when we have a base.
2878 Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
2879 Asm->emitInt8(OffsetPair);
2880 Asm->OutStreamer->AddComment(" starting offset");
2881 Asm->emitLabelDifferenceAsULEB128(Begin, Base);
2882 Asm->OutStreamer->AddComment(" ending offset");
2883 Asm->emitLabelDifferenceAsULEB128(End, Base);
2884 } else {
2885 Asm->emitLabelDifference(Begin, Base, Size);
2886 Asm->emitLabelDifference(End, Base, Size);
2887 }
2888 } else if (UseDwarf5) {
2889 Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
2890 Asm->emitInt8(StartxLength);
2891 Asm->OutStreamer->AddComment(" start index");
2892 Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
2893 Asm->OutStreamer->AddComment(" length");
2894 Asm->emitLabelDifferenceAsULEB128(End, Begin);
2895 } else {
2896 Asm->OutStreamer->emitSymbolValue(Begin, Size);
2897 Asm->OutStreamer->emitSymbolValue(End, Size);
2898 }
2899 EmitPayload(*RS);
2900 }
2901 }
2902
2903 if (UseDwarf5) {
2904 Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
2905 Asm->emitInt8(EndOfList);
2906 } else {
2907 // Terminate the list with two 0 values.
2908 Asm->OutStreamer->emitIntValue(0, Size);
2909 Asm->OutStreamer->emitIntValue(0, Size);
2910 }
2911}
2912
2913// Handles emission of both debug_loclist / debug_loclist.dwo
2915 emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2916 *List.CU, dwarf::DW_LLE_base_addressx,
2917 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2918 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
2919 /* ShouldUseBaseAddress */ true,
2920 [&](const DebugLocStream::Entry &E) {
2921 DD.emitDebugLocEntryLocation(E, List.CU);
2922 });
2923}
2924
2925void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
2926 if (DebugLocs.getLists().empty())
2927 return;
2928
2929 Asm->OutStreamer->switchSection(Sec);
2930
2931 MCSymbol *TableEnd = nullptr;
2932 if (getDwarfVersion() >= 5)
2933 TableEnd = emitLoclistsTableHeader(Asm, *this);
2934
2935 for (const auto &List : DebugLocs.getLists())
2936 emitLocList(*this, Asm, List);
2937
2938 if (TableEnd)
2939 Asm->OutStreamer->emitLabel(TableEnd);
2940}
2941
2942// Emit locations into the .debug_loc/.debug_loclists section.
2943void DwarfDebug::emitDebugLoc() {
2944 emitDebugLocImpl(
2945 getDwarfVersion() >= 5
2948}
2949
2950// Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
2951void DwarfDebug::emitDebugLocDWO() {
2952 if (getDwarfVersion() >= 5) {
2953 emitDebugLocImpl(
2955
2956 return;
2957 }
2958
2959 for (const auto &List : DebugLocs.getLists()) {
2960 Asm->OutStreamer->switchSection(
2962 Asm->OutStreamer->emitLabel(List.Label);
2963
2964 for (const auto &Entry : DebugLocs.getEntries(List)) {
2965 // GDB only supports startx_length in pre-standard split-DWARF.
2966 // (in v5 standard loclists, it currently* /only/ supports base_address +
2967 // offset_pair, so the implementations can't really share much since they
2968 // need to use different representations)
2969 // * as of October 2018, at least
2970 //
2971 // In v5 (see emitLocList), this uses SectionLabels to reuse existing
2972 // addresses in the address pool to minimize object size/relocations.
2973 Asm->emitInt8(dwarf::DW_LLE_startx_length);
2974 unsigned idx = AddrPool.getIndex(Entry.Begin);
2975 Asm->emitULEB128(idx);
2976 // Also the pre-standard encoding is slightly different, emitting this as
2977 // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
2978 Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
2980 }
2981 Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2982 }
2983}
2984
2986 const MCSymbol *Start, *End;
2987};
2988
2989// Emit a debug aranges section, containing a CU lookup for any
2990// address we can tie back to a CU.
2991void DwarfDebug::emitDebugARanges() {
2992 // Provides a unique id per text section.
2994
2995 // Filter labels by section.
2996 for (const SymbolCU &SCU : ArangeLabels) {
2997 if (SCU.Sym->isInSection()) {
2998 // Make a note of this symbol and it's section.
2999 MCSection *Section = &SCU.Sym->getSection();
3000 if (!Section->getKind().isMetadata())
3001 SectionMap[Section].push_back(SCU);
3002 } else {
3003 // Some symbols (e.g. common/bss on mach-o) can have no section but still
3004 // appear in the output. This sucks as we rely on sections to build
3005 // arange spans. We can do it without, but it's icky.
3006 SectionMap[nullptr].push_back(SCU);
3007 }
3008 }
3009
3011
3012 for (auto &I : SectionMap) {
3013 MCSection *Section = I.first;
3015 if (List.size() < 1)
3016 continue;
3017
3018 // If we have no section (e.g. common), just write out
3019 // individual spans for each symbol.
3020 if (!Section) {
3021 for (const SymbolCU &Cur : List) {
3022 ArangeSpan Span;
3023 Span.Start = Cur.Sym;
3024 Span.End = nullptr;
3025 assert(Cur.CU);
3026 Spans[Cur.CU].push_back(Span);
3027 }
3028 continue;
3029 }
3030
3031 // Sort the symbols by offset within the section.
3032 llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
3033 unsigned IA = A.Sym ? Asm->OutStreamer->getSymbolOrder(A.Sym) : 0;
3034 unsigned IB = B.Sym ? Asm->OutStreamer->getSymbolOrder(B.Sym) : 0;
3035
3036 // Symbols with no order assigned should be placed at the end.
3037 // (e.g. section end labels)
3038 if (IA == 0)
3039 return false;
3040 if (IB == 0)
3041 return true;
3042 return IA < IB;
3043 });
3044
3045 // Insert a final terminator.
3046 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
3047
3048 // Build spans between each label.
3049 const MCSymbol *StartSym = List[0].Sym;
3050 for (size_t n = 1, e = List.size(); n < e; n++) {
3051 const SymbolCU &Prev = List[n - 1];
3052 const SymbolCU &Cur = List[n];
3053
3054 // Try and build the longest span we can within the same CU.
3055 if (Cur.CU != Prev.CU) {
3056 ArangeSpan Span;
3057 Span.Start = StartSym;
3058 Span.End = Cur.Sym;
3059 assert(Prev.CU);
3060 Spans[Prev.CU].push_back(Span);
3061 StartSym = Cur.Sym;
3062 }
3063 }
3064 }
3065
3066 // Start the dwarf aranges section.
3067 Asm->OutStreamer->switchSection(
3069
3070 unsigned PtrSize = Asm->MAI->getCodePointerSize();
3071
3072 // Build a list of CUs used.
3073 std::vector<DwarfCompileUnit *> CUs;
3074 for (const auto &it : Spans) {
3075 DwarfCompileUnit *CU = it.first;
3076 CUs.push_back(CU);
3077 }
3078
3079 // Sort the CU list (again, to ensure consistent output order).
3080 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
3081 return A->getUniqueID() < B->getUniqueID();
3082 });
3083
3084 // Emit an arange table for each CU we used.
3085 for (DwarfCompileUnit *CU : CUs) {
3086 std::vector<ArangeSpan> &List = Spans[CU];
3087
3088 // Describe the skeleton CU's offset and length, not the dwo file's.
3089 if (auto *Skel = CU->getSkeleton())
3090 CU = Skel;
3091
3092 // Emit size of content not including length itself.
3093 unsigned ContentSize =
3094 sizeof(int16_t) + // DWARF ARange version number
3095 Asm->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info
3096 // section
3097 sizeof(int8_t) + // Pointer Size (in bytes)
3098 sizeof(int8_t); // Segment Size (in bytes)
3099
3100 unsigned TupleSize = PtrSize * 2;
3101
3102 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
3103 unsigned Padding = offsetToAlignment(
3104 Asm->getUnitLengthFieldByteSize() + ContentSize, Align(TupleSize));
3105
3106 ContentSize += Padding;
3107 ContentSize += (List.size() + 1) * TupleSize;
3108
3109 // For each compile unit, write the list of spans it covers.
3110 Asm->emitDwarfUnitLength(ContentSize, "Length of ARange Set");
3111 Asm->OutStreamer->AddComment("DWARF Arange version number");
3113 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
3114 emitSectionReference(*CU);
3115 Asm->OutStreamer->AddComment("Address Size (in bytes)");
3116 Asm->emitInt8(PtrSize);
3117 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
3118 Asm->emitInt8(0);
3119
3120 Asm->OutStreamer->emitFill(Padding, 0xff);
3121
3122 for (const ArangeSpan &Span : List) {
3123 Asm->emitLabelReference(Span.Start, PtrSize);
3124
3125 // Calculate the size as being from the span start to its end.
3126 //
3127 // If the size is zero, then round it up to one byte. The DWARF
3128 // specification requires that entries in this table have nonzero
3129 // lengths.
3130 auto SizeRef = SymSize.find(Span.Start);
3131 if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {
3132 Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
3133 } else {
3134 // For symbols without an end marker (e.g. common), we
3135 // write a single arange entry containing just that one symbol.
3136 uint64_t Size;
3137 if (SizeRef == SymSize.end() || SizeRef->second == 0)
3138 Size = 1;
3139 else
3140 Size = SizeRef->second;
3141
3142 Asm->OutStreamer->emitIntValue(Size, PtrSize);
3143 }
3144 }
3145
3146 Asm->OutStreamer->AddComment("ARange terminator");
3147 Asm->OutStreamer->emitIntValue(0, PtrSize);
3148 Asm->OutStreamer->emitIntValue(0, PtrSize);
3149 }
3150}
3151
3152/// Emit a single range list. We handle both DWARF v5 and earlier.
3154 const RangeSpanList &List) {
3155 emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
3156 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
3157 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
3159 List.CU->getCUNode()->getRangesBaseAddress() ||
3160 DD.getDwarfVersion() >= 5,
3161 [](auto) {});
3162}
3163
3164void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
3165 if (Holder.getRangeLists().empty())
3166 return;
3167
3169 assert(!CUMap.empty());
3170 assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
3171 return !Pair.second->getCUNode()->isDebugDirectivesOnly();
3172 }));
3173
3174 Asm->OutStreamer->switchSection(Section);
3175
3176 MCSymbol *TableEnd = nullptr;
3177 if (getDwarfVersion() >= 5)
3178 TableEnd = emitRnglistsTableHeader(Asm, Holder);
3179
3180 for (const RangeSpanList &List : Holder.getRangeLists())
3181 emitRangeList(*this, Asm, List);
3182
3183 if (TableEnd)
3184 Asm->OutStreamer->emitLabel(TableEnd);
3185}
3186
3187/// Emit address ranges into the .debug_ranges section or into the DWARF v5
3188/// .debug_rnglists section.
3189void DwarfDebug::emitDebugRanges() {
3190 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3191
3192 emitDebugRangesImpl(Holder,
3193 getDwarfVersion() >= 5
3196}
3197
3198void DwarfDebug::emitDebugRangesDWO() {
3199 emitDebugRangesImpl(InfoHolder,
3201}
3202
3203/// Emit the header of a DWARF 5 macro section, or the GNU extension for
3204/// DWARF 4.
3205static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
3206 const DwarfCompileUnit &CU, uint16_t DwarfVersion) {
3207 enum HeaderFlagMask {
3208#define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
3209#include "llvm/BinaryFormat/Dwarf.def"
3210 };
3211 Asm->OutStreamer->AddComment("Macro information version");
3212 Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
3213 // We emit the line offset flag unconditionally here, since line offset should
3214 // be mostly present.
3215 if (Asm->isDwarf64()) {
3216 Asm->OutStreamer->AddComment("Flags: 64 bit, debug_line_offset present");
3217 Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
3218 } else {
3219 Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");
3220 Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);
3221 }
3222 Asm->OutStreamer->AddComment("debug_line_offset");
3223 if (DD.useSplitDwarf())
3224 Asm->emitDwarfLengthOrOffset(0);
3225 else
3226 Asm->emitDwarfSymbolReference(CU.getLineTableStartSym());
3227}
3228
3229void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
3230 for (auto *MN : Nodes) {
3231 if (auto *M = dyn_cast<DIMacro>(MN))
3232 emitMacro(*M);
3233 else if (auto *F = dyn_cast<DIMacroFile>(MN))
3234 emitMacroFile(*F, U);
3235 else
3236 llvm_unreachable("Unexpected DI type!");
3237 }
3238}
3239
3240void DwarfDebug::emitMacro(DIMacro &M) {
3241 StringRef Name = M.getName();
3242 StringRef Value = M.getValue();
3243
3244 // There should be one space between the macro name and the macro value in
3245 // define entries. In undef entries, only the macro name is emitted.
3246 std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();
3247
3248 if (UseDebugMacroSection) {
3249 if (getDwarfVersion() >= 5) {
3250 unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3251 ? dwarf::DW_MACRO_define_strx
3252 : dwarf::DW_MACRO_undef_strx;
3253 Asm->OutStreamer->AddComment(dwarf::MacroString(Type));
3255 Asm->OutStreamer->AddComment("Line Number");
3256 Asm->emitULEB128(M.getLine());
3257 Asm->OutStreamer->AddComment("Macro String");
3259 InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex());
3260 } else {
3261 unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3262 ? dwarf::DW_MACRO_GNU_define_indirect
3263 : dwarf::DW_MACRO_GNU_undef_indirect;
3266 Asm->OutStreamer->AddComment("Line Number");
3267 Asm->emitULEB128(M.getLine());
3268 Asm->OutStreamer->AddComment("Macro String");
3270 InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol());
3271 }
3272 } else {
3273 Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));
3274 Asm->emitULEB128(M.getMacinfoType());
3275 Asm->OutStreamer->AddComment("Line Number");
3276 Asm->emitULEB128(M.getLine());
3277 Asm->OutStreamer->AddComment("Macro String");
3278 Asm->OutStreamer->emitBytes(Str);
3279 Asm->emitInt8('\0');
3280 }
3281}
3282
3283void DwarfDebug::emitMacroFileImpl(
3284 DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
3285 StringRef (*MacroFormToString)(unsigned Form)) {
3286
3287 Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
3288 Asm->emitULEB128(StartFile);
3289 Asm->OutStreamer->AddComment("Line Number");
3290 Asm->emitULEB128(MF.getLine());
3291 Asm->OutStreamer->AddComment("File Number");
3292 DIFile &F = *MF.getFile();
3293 if (useSplitDwarf())
3294 Asm->emitULEB128(getDwoLineTable(U)->getFile(
3295 F.getDirectory(), F.getFilename(), getMD5AsBytes(&F),
3296 Asm->OutContext.getDwarfVersion(), F.getSource()));
3297 else
3298 Asm->emitULEB128(U.getOrCreateSourceID(&F));
3299 handleMacroNodes(MF.getElements(), U);
3300 Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
3301 Asm->emitULEB128(EndFile);
3302}
3303
3304void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
3305 // DWARFv5 macro and DWARFv4 macinfo share some common encodings,
3306 // so for readibility/uniformity, We are explicitly emitting those.
3307 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
3308 if (UseDebugMacroSection)
3309 emitMacroFileImpl(
3310 F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
3312 else
3313 emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,
3315}
3316
3317void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
3318 for (const auto &P : CUMap) {
3319 auto &TheCU = *P.second;
3320 auto *SkCU = TheCU.getSkeleton();
3321 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
3322 auto *CUNode = cast<DICompileUnit>(P.first);
3323 DIMacroNodeArray Macros = CUNode->getMacros();
3324 if (Macros.empty())
3325 continue;
3326 Asm->OutStreamer->switchSection(Section);
3327 Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
3328 if (UseDebugMacroSection)
3329 emitMacroHeader(Asm, *this, U, getDwarfVersion());
3330 handleMacroNodes(Macros, U);
3331 Asm->OutStreamer->AddComment("End Of Macro List Mark");
3332 Asm->emitInt8(0);
3333 }
3334}
3335
3336/// Emit macros into a debug macinfo/macro section.
3337void DwarfDebug::emitDebugMacinfo() {
3338 auto &ObjLower = Asm->getObjFileLowering();
3339 emitDebugMacinfoImpl(UseDebugMacroSection
3340 ? ObjLower.getDwarfMacroSection()
3341 : ObjLower.getDwarfMacinfoSection());
3342}
3343
3344void DwarfDebug::emitDebugMacinfoDWO() {
3345 auto &ObjLower = Asm->getObjFileLowering();
3346 emitDebugMacinfoImpl(UseDebugMacroSection
3347 ? ObjLower.getDwarfMacroDWOSection()
3348 : ObjLower.getDwarfMacinfoDWOSection());
3349}
3350
3351// DWARF5 Experimental Separate Dwarf emitters.
3352
3353void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
3354 std::unique_ptr<DwarfCompileUnit> NewU) {
3355
3356 if (!CompilationDir.empty())
3357 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
3358 addGnuPubAttributes(*NewU, Die);
3359
3360 SkeletonHolder.addUnit(std::move(NewU));
3361}
3362
3363DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
3364
3365 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
3366 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
3368 DwarfCompileUnit &NewCU = *OwnedUnit;
3370
3371 NewCU.initStmtList();
3372
3374 NewCU.addStringOffsetsStart();
3375
3376 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
3377
3378 return NewCU;
3379}
3380
3381// Emit the .debug_info.dwo section for separated dwarf. This contains the
3382// compile units that would normally be in debug_info.
3383void DwarfDebug::emitDebugInfoDWO() {
3384 assert(useSplitDwarf() && "No split dwarf debug info?");
3385 // Don't emit relocations into the dwo file.
3386 InfoHolder.emitUnits(/* UseOffsets */ true);
3387}
3388
3389// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3390// abbreviations for the .debug_info.dwo section.
3391void DwarfDebug::emitDebugAbbrevDWO() {
3392 assert(useSplitDwarf() && "No split dwarf?");
3394}
3395
3396void DwarfDebug::emitDebugLineDWO() {
3397 assert(useSplitDwarf() && "No split dwarf?");
3398 SplitTypeUnitFileTable.Emit(
3401}
3402
3403void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
3404 assert(useSplitDwarf() && "No split dwarf?");
3407 InfoHolder.getStringOffsetsStartSym());
3408}
3409
3410// Emit the .debug_str.dwo section for separated dwarf. This contains the
3411// string section and is identical in format to traditional .debug_str
3412// sections.
3413void DwarfDebug::emitDebugStrDWO() {
3415 emitStringOffsetsTableHeaderDWO();
3416 assert(useSplitDwarf() && "No split dwarf?");
3419 OffSec, /* UseRelativeOffsets = */ false);
3420}
3421
3422// Emit address pool.
3423void DwarfDebug::emitDebugAddr() {
3425}
3426
3427MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
3428 if (!useSplitDwarf())
3429 return nullptr;
3430 const DICompileUnit *DIUnit = CU.getCUNode();
3431 SplitTypeUnitFileTable.maybeSetRootFile(
3432 DIUnit->getDirectory(), DIUnit->getFilename(),
3433 getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
3434 return &SplitTypeUnitFileTable;
3435}
3436
3438 MD5 Hash;
3439 Hash.update(Identifier);
3440 // ... take the least significant 8 bytes and return those. Our MD5
3441 // implementation always returns its results in little endian, so we actually
3442 // need the "high" word.
3443 MD5::MD5Result Result;
3444 Hash.final(Result);
3445 return Result.high();
3446}
3447
3449 StringRef Identifier, DIE &RefDie,
3450 const DICompositeType *CTy) {
3451 // Fast path if we're building some type units and one has already used the
3452 // address pool we know we're going to throw away all this work anyway, so
3453 // don't bother building dependent types.
3454 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
3455 return;
3456
3457 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
3458 if (!Ins.second) {
3459 CU.addDIETypeSignature(RefDie, Ins.first->second);
3460 return;
3461 }
3462
3464 bool TopLevelType = TypeUnitsUnderConstruction.empty();
3465 AddrPool.resetUsedFlag();
3466
3467 auto OwnedUnit = std::make_unique<DwarfTypeUnit>(
3468 CU, Asm, this, &InfoHolder, NumTypeUnitsCreated++, getDwoLineTable(CU));
3469 DwarfTypeUnit &NewTU = *OwnedUnit;
3470 DIE &UnitDie = NewTU.getUnitDie();
3471 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
3472
3473 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3474 CU.getLanguage());
3475
3476 uint64_t Signature = makeTypeSignature(Identifier);
3477 NewTU.setTypeSignature(Signature);
3478 Ins.first->second = Signature;
3479
3480 if (useSplitDwarf()) {
3481 // Although multiple type units can have the same signature, they are not
3482 // guranteed to be bit identical. When LLDB uses .debug_names it needs to
3483 // know from which CU a type unit came from. These two attrbutes help it to
3484 // figure that out.
3485 if (getDwarfVersion() >= 5) {
3486 if (!CompilationDir.empty())
3487 NewTU.addString(UnitDie, dwarf::DW_AT_comp_dir, CompilationDir);
3488 NewTU.addString(UnitDie, dwarf::DW_AT_dwo_name,
3490 }
3491 MCSection *Section =
3492 getDwarfVersion() <= 4
3495 NewTU.setSection(Section);
3496 } else {
3497 MCSection *Section =
3498 getDwarfVersion() <= 4
3501 NewTU.setSection(Section);
3502 // Non-split type units reuse the compile unit's line table.
3503 CU.applyStmtList(UnitDie);
3504 }
3505
3506 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
3507 // units.
3509 NewTU.addStringOffsetsStart();
3510
3511 NewTU.setType(NewTU.createTypeDIE(CTy));
3512
3513 if (TopLevelType) {
3514 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
3515 TypeUnitsUnderConstruction.clear();
3516
3517 // Types referencing entries in the address table cannot be placed in type
3518 // units.
3519 if (AddrPool.hasBeenUsed()) {
3520 AccelTypeUnitsDebugNames.clear();
3521 // Remove all the types built while building this type.
3522 // This is pessimistic as some of these types might not be dependent on
3523 // the type that used an address.
3524 for (const auto &TU : TypeUnitsToAdd)
3525 TypeSignatures.erase(TU.second);
3526
3527 // Construct this type in the CU directly.
3528 // This is inefficient because all the dependent types will be rebuilt
3529 // from scratch, including building them in type units, discovering that
3530 // they depend on addresses, throwing them out and rebuilding them.
3532 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
3533 return;
3534 }
3535
3536 // If the type wasn't dependent on fission addresses, finish adding the type
3537 // and all its dependent types.
3538 for (auto &TU : TypeUnitsToAdd) {
3539 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
3540 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
3541 if (getDwarfVersion() >= 5 &&
3543 if (useSplitDwarf())
3544 AccelDebugNames.addTypeUnitSignature(*TU.first);
3545 else
3546 AccelDebugNames.addTypeUnitSymbol(*TU.first);
3547 }
3548 }
3549 AccelTypeUnitsDebugNames.convertDieToOffset();
3550 AccelDebugNames.addTypeEntries(AccelTypeUnitsDebugNames);
3551 AccelTypeUnitsDebugNames.clear();
3553 }
3554 CU.addDIETypeSignature(RefDie, Signature);
3555}
3556
3557// Add the Name along with its companion DIE to the appropriate accelerator
3558// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3559// AccelTableKind::Apple, we use the table we got as an argument). If
3560// accelerator tables are disabled, this function does nothing.
3561template <typename DataT>
3562void DwarfDebug::addAccelNameImpl(
3563 const DwarfUnit &Unit,
3564 const DICompileUnit::DebugNameTableKind NameTableKind,
3565 AccelTable<DataT> &AppleAccel, StringRef Name, const DIE &Die) {
3566 if (getAccelTableKind() == AccelTableKind::None || Name.empty())
3567 return;
3568
3572 return;
3573
3574 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3576
3577 switch (getAccelTableKind()) {
3579 AppleAccel.addName(Ref, Die);
3580 break;
3581 case AccelTableKind::Dwarf: {
3583 assert(((&Current == &AccelTypeUnitsDebugNames) ||
3584 ((&Current == &AccelDebugNames) &&
3585 (Unit.getUnitDie().getTag() != dwarf::DW_TAG_type_unit))) &&
3586 "Kind is CU but TU is being processed.");
3587 assert(((&Current == &AccelDebugNames) ||
3588 ((&Current == &AccelTypeUnitsDebugNames) &&
3589 (Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit))) &&
3590 "Kind is TU but CU is being processed.");
3591 // The type unit can be discarded, so need to add references to final
3592 // acceleration table once we know it's complete and we emit it.
3593 Current.addName(Ref, Die, Unit.getUniqueID());
3594 break;
3595 }
3597 llvm_unreachable("Default should have already been resolved.");
3599 llvm_unreachable("None handled above");
3600 }
3601}
3602
3604 const DwarfUnit &Unit,
3606 const DIE &Die) {
3607 addAccelNameImpl(Unit, NameTableKind, AccelNames, Name, Die);
3608}
3609
3611 const DwarfUnit &Unit,
3613 const DIE &Die) {
3614 // ObjC names go only into the Apple accelerator tables.
3616 addAccelNameImpl(Unit, NameTableKind, AccelObjC, Name, Die);
3617}
3618
3620 const DwarfUnit &Unit,
3622 const DIE &Die) {
3623 addAccelNameImpl(Unit, NameTableKind, AccelNamespace, Name, Die);
3624}
3625
3627 const DwarfUnit &Unit,
3629 const DIE &Die, char Flags) {
3630 addAccelNameImpl(Unit, NameTableKind, AccelTypes, Name, Die);
3631}
3632
3634 return Asm->OutStreamer->getContext().getDwarfVersion();
3635}
3636
3638 if (Asm->getDwarfVersion() >= 4)
3639 return dwarf::Form::DW_FORM_sec_offset;
3640 assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) &&
3641 "DWARF64 is not defined prior DWARFv3");
3642 return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8
3643 : dwarf::Form::DW_FORM_data4;
3644}
3645
3647 return SectionLabels.lookup(S);
3648}
3649
3651 if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)
3652 if (useSplitDwarf() || getDwarfVersion() >= 5)
3653 AddrPool.getIndex(S);
3654}
3655
3656std::optional<MD5::MD5Result>
3658 assert(File);
3659 if (getDwarfVersion() < 5)
3660 return std::nullopt;
3661 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
3662 if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
3663 return std::nullopt;
3664
3665 // Convert the string checksum to an MD5Result for the streamer.
3666 // The verifier validates the checksum so we assume it's okay.
3667 // An MD5 checksum is 16 bytes.
3668 std::string ChecksumString = fromHex(Checksum->Value);
3669 MD5::MD5Result CKMem;
3670 std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.data());
3671 return CKMem;
3672}
3673
3675 if (MinimizeAddr == MinimizeAddrInV5::Ranges)
3676 return true;
3677 if (MinimizeAddr != MinimizeAddrInV5::Default)
3678 return false;
3679 if (useSplitDwarf())
3680 return true;
3681 return false;
3682}
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file implements a class to represent arbitrary precision integral constant values and operations...
BitTracker BT
Definition: BitTracker.cpp:73
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:693
#define clEnumVal(ENUMVAL, DESC)
Definition: CommandLine.h:691
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
static bool isObjCClass(StringRef Name)
Definition: DwarfDebug.cpp:448
static cl::opt< bool > NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden, cl::desc("Disable emission .debug_ranges section."), cl::init(false))
static void finishCallSiteParams(ValT Val, const DIExpression *Expr, ArrayRef< FwdRegParamInfo > DescribedParams, ParamSet &Params)
Emit call site parameter entries that are described by the given value and debug expression.
Definition: DwarfDebug.cpp:598
static cl::opt< bool > UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden, cl::desc("Emit the GNU .debug_macro format with DWARF <5"), cl::init(false))
static cl::opt< DefaultOnOff > DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden, cl::desc("Use inlined strings rather than string section."), cl::values(clEnumVal(Default, "Default for platform"), clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), cl::init(Default))
static bool validThroughout(LexicalScopes &LScopes, const MachineInstr *DbgValue, const MachineInstr *RangeEnd, const InstructionOrdering &Ordering)
Determine whether a singular DBG_VALUE is valid for the entirety of its enclosing lexical scope.
static cl::opt< bool > GenerateARangeSection("generate-arange-section", cl::Hidden, cl::desc("Generate dwarf aranges"), cl::init(false))
static cl::opt< LinkageNameOption > DwarfLinkageNames("dwarf-linkage-names", cl::Hidden, cl::desc("Which DWARF linkage-name attributes to emit."), cl::values(clEnumValN(DefaultLinkageNames, "Default", "Default for platform"), clEnumValN(AllLinkageNames, "All", "All"), clEnumValN(AbstractLinkageNames, "Abstract", "Abstract subprograms")), cl::init(DefaultLinkageNames))
static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg, const DIExpression *Expr, ArrayRef< FwdRegParamInfo > ParamsToAdd)
Add Reg to the worklist, if it's not already present, and mark that the given parameter registers' va...
Definition: DwarfDebug.cpp:629
static std::pair< DebugLoc, bool > findPrologueEndLoc(const MachineFunction *MF)
static cl::opt< bool > GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, cl::desc("Generate DWARF4 type units."), cl::init(false))
static SmallVectorImpl< DwarfCompileUnit::GlobalExpr > & sortGlobalExprs(SmallVectorImpl< DwarfCompileUnit::GlobalExpr > &GVEs)
Sort and unique GVEs by comparing their fragment offset.
LinkageNameOption
Definition: DwarfDebug.cpp:137
@ DefaultLinkageNames
Definition: DwarfDebug.cpp:138
@ AbstractLinkageNames
Definition: DwarfDebug.cpp:140
@ AllLinkageNames
Definition: DwarfDebug.cpp:139
static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, const DIE *Die)
computeIndexValue - Compute the gdb index value for the DIE and CU.
static uint64_t getFragmentOffsetInBits(const DIExpression &Expr)
Definition: DwarfDebug.cpp:268
static cl::opt< DefaultOnOff > DwarfOpConvert("dwarf-op-convert", cl::Hidden, cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"), cl::values(clEnumVal(Default, "Default for platform"), clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), cl::init(Default))
static void collectCallSiteParameters(const MachineInstr *CallMI, ParamSet &Params)
Try to interpret values loaded into registers that forward parameters for CallMI.
Definition: DwarfDebug.cpp:797
static MCSymbol * emitRnglistsTableHeader(AsmPrinter *Asm, const DwarfFile &Holder)
static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col, const MDNode *S, unsigned Flags, unsigned CUID, uint16_t DwarfVersion, ArrayRef< std::unique_ptr< DwarfCompileUnit > > DCUs)
Register a source line with debug info.
static cl::opt< bool > SplitDwarfCrossCuReferences("split-dwarf-cross-cu-references", cl::Hidden, cl::desc("Enable cross-cu references in DWO files"), cl::init(false))
static cl::opt< bool > UseDwarfRangesBaseAddressSpecifier("use-dwarf-ranges-base-address-specifier", cl::Hidden, cl::desc("Use base address specifiers in debug_ranges"), cl::init(false))
static void interpretValues(const MachineInstr *CurMI, FwdRegWorklist &ForwardedRegWorklist, ParamSet &Params, ClobberedRegSet &ClobberedRegUnits)
Interpret values loaded into registers by CurMI.
Definition: DwarfDebug.cpp:651
static bool interpretNextInstr(const MachineInstr *CurMI, FwdRegWorklist &ForwardedRegWorklist, ParamSet &Params, ClobberedRegSet &ClobberedRegUnits)
Definition: DwarfDebug.cpp:769
static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List)
static constexpr unsigned ULEB128PadSize
Definition: DwarfDebug.cpp:173
static cl::opt< DefaultOnOff > DwarfSectionsAsReferences("dwarf-sections-as-references", cl::Hidden, cl::desc("Use sections+offset as references rather than labels."), cl::values(clEnumVal(Default, "Default for platform"), clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), cl::init(Default))
DefaultOnOff
Definition: DwarfDebug.cpp:87
@ Default
Definition: DwarfDebug.cpp:87
@ Enable
Definition: DwarfDebug.cpp:87
@ Disable
Definition: DwarfDebug.cpp:87
static AccelTableKind computeAccelTableKind(unsigned DwarfVersion, bool GenerateTypeUnits, DebuggerKind Tuning, const Triple &TT)
Definition: DwarfDebug.cpp:306
static void forBothCUs(DwarfCompileUnit &CU, Func F)
Definition: DwarfDebug.cpp:530
static MCSymbol * emitLoclistsTableHeader(AsmPrinter *Asm, const DwarfDebug &DD)
static const DILocalScope * getRetainedNodeScope(const MDNode *N)
static const DIExpression * combineDIExpressions(const DIExpression *Original, const DIExpression *Addition)
Append the expression Addition to Original and return the result.
Definition: DwarfDebug.cpp:584
static cl::opt< DefaultOnOff > UnknownLocations("use-unknown-locations", cl::Hidden, cl::desc("Make an absence of debug location information explicit."), cl::values(clEnumVal(Default, "At top of block or after label"), clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")), cl::init(Default))
static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD, const DwarfCompileUnit &CU, uint16_t DwarfVersion)
Emit the header of a DWARF 5 macro section, or the GNU extension for DWARF 4.
static cl::opt< AccelTableKind > AccelTables("accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."), cl::values(clEnumValN(AccelTableKind::Default, "Default", "Default for platform"), clEnumValN(AccelTableKind::None, "Disable", "Disabled."), clEnumValN(AccelTableKind::Apple, "Apple", "Apple"), clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")), cl::init(AccelTableKind::Default))
static cl::opt< DwarfDebug::MinimizeAddrInV5 > MinimizeAddrInV5Option("minimize-addr-in-v5", cl::Hidden, cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more " "address pool entry sharing to reduce relocations/object size"), cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default, "Default", "Default address minimization strategy"), clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges, "Ranges", "Use rnglists for contiguous ranges if that allows " "using a pre-existing base address"), clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions, "Expressions", "Use exprloc addrx+offset expressions for any " "address with a prior base address"), clEnumValN(DwarfDebug::MinimizeAddrInV5::Form, "Form", "Use addrx+offset extension form for any address " "with a prior base address"), clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled, "Disabled", "Stuff")), cl::init(DwarfDebug::MinimizeAddrInV5::Default))
static StringRef getObjCMethodName(StringRef In)
Definition: DwarfDebug.cpp:471
static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R, const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair, unsigned StartxLength, unsigned EndOfList, StringRef(*StringifyEnum)(unsigned), bool ShouldUseBaseAddress, PayloadEmitter EmitPayload)
static DbgValueLoc getDebugLocValue(const MachineInstr *MI)
Get .debug_loc entry for the instruction range starting at MI.
Definition: DwarfDebug.cpp:235
static void getObjCClassCategory(StringRef In, StringRef &Class, StringRef &Category)
Definition: DwarfDebug.cpp:459
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
Symbol * Sym
Definition: ELF_riscv.cpp:479
@ EndOfList
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define DWARF2_FLAG_IS_STMT
Definition: MCDwarf.h:117
#define DWARF2_FLAG_PROLOGUE_END
Definition: MCDwarf.h:119
#define DWARF2_FLAG_EPILOGUE_BEGIN
Definition: MCDwarf.h:120
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
Module.h This file contains the declarations for the Module class.
#define P(N)
if(VerifyEach)
const char LLVMTargetMachineRef TM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This file contains some functions that are useful when dealing with strings.
This file describes how to lower LLVM code to machine code.
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition: blake3_impl.h:78
Class recording the (high level) value of a variable.
This class holds an abstract representation of an Accelerator Table, consisting of a sequence of buck...
Definition: AccelTable.h:202
void addName(DwarfStringPoolEntryRef Name, Types &&... Args)
Definition: AccelTable.h:215
unsigned getIndex(const MCSymbol *Sym, bool TLS=false)
Returns the index into the address pool with the given label/symbol.
Definition: AddressPool.cpp:20
void emit(AsmPrinter &Asm, MCSection *AddrSection)
Definition: AddressPool.cpp:43
void setLabel(MCSymbol *Sym)
Definition: AddressPool.h:54
bool hasBeenUsed() const
Definition: AddressPool.h:49
void resetUsedFlag(bool HasBeenUsed=false)
Definition: AddressPool.h:51
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
std::vector< T > vec() const
Definition: ArrayRef.h:280
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
const T * data() const
Definition: ArrayRef.h:162
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:84
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
Definition: AsmPrinter.cpp:398
void emitULEB128(uint64_t Value, const char *Desc=nullptr, unsigned PadTo=0) const
Emit the specified unsigned leb128 value.
void emitDwarfSymbolReference(const MCSymbol *Label, bool ForceOffset=false) const
Emit a reference to a symbol for use in dwarf.
bool isDwarf64() const
DwarfDebug * getDwarfDebug()
Definition: AsmPrinter.h:245
void emitDwarfLengthOrOffset(uint64_t Value) const
Emit 32- or 64-bit value depending on the DWARF format.
unsigned int getUnitLengthFieldByteSize() const
Returns 4 for DWARF32 and 12 for DWARF64.
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:87
MCSymbol * getFunctionBegin() const
Definition: AsmPrinter.h:274
void emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size) const
Emit something like ".long Hi-Lo" where the size in bytes of the directive is specified by Size and H...
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:90
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:102
void emitDwarfOffset(const MCSymbol *Label, uint64_t Offset) const
Emit something like ".long Label + Offset" or ".quad Label + Offset" depending on the DWARF format.
void emitInt8(int Value) const
Emit a byte directive and value.
MapVector< unsigned, MBBSectionRange > MBBSectionRanges
Definition: AsmPrinter.h:138
void emitDwarfUnitLength(uint64_t Length, const Twine &Comment) const
Emit a unit length field.
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:94
MCSymbol * createTempSymbol(const Twine &Name) const
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:99
void emitLabelReference(const MCSymbol *Label, unsigned Size, bool IsSectionRelative=false) const
Emit something like ".long Label" where the size in bytes of the directive is specified by Size and L...
Definition: AsmPrinter.h:691
unsigned int getDwarfOffsetByteSize() const
Returns 4 for DWARF32 and 8 for DWARF64.
void emitInt16(int Value) const
Emit a short directive and value.
const DataLayout & getDataLayout() const
Return information about data layout.
Definition: AsmPrinter.cpp:402
uint16_t getDwarfVersion() const
void emitInt8(uint8_t Byte, const Twine &Comment) override
Definition: ByteStreamer.h:105
const bool GenerateComments
Only verbose textual output needs comments.
Definition: ByteStreamer.h:99
virtual void emitULEB128(uint64_t DWord, const Twine &Comment="", unsigned PadTo=0)=0
virtual void emitSLEB128(uint64_t DWord, const Twine &Comment="")=0
virtual void emitInt8(uint8_t Byte, const Twine &Comment="")=0
virtual unsigned emitDIERef(const DIE &D)=0
Basic type, like 'int' or 'float'.
bool getDebugInfoForProfiling() const
bool isDebugDirectivesOnly() const
StringRef getFlags() const
StringRef getSDK() const
static std::optional< DebugNameTableKind > getNameTableKind(StringRef Str)
unsigned getRuntimeVersion() const
bool getSplitDebugInlining() const
StringRef getSysRoot() const
StringRef getProducer() const
unsigned getSourceLanguage() const
uint64_t getDWOId() const
StringRef getSplitDebugFilename() const
static std::optional< DebugEmissionKind > getEmissionKind(StringRef Str)
An object containing the capability of hashing and adding hash attributes onto a DIE.
Definition: DIEHash.h:26
uint64_t computeCUSignature(StringRef DWOName, const DIE &Die)
Computes the CU signature.
Definition: DIEHash.cpp:399
void setSection(MCSection *Section)
Set the section that this DIEUnit will be emitted into.
Definition: DIE.h:984
DIE & getUnitDie()
Definition: DIE.h:999
A structured debug information entry.
Definition: DIE.h:819
DIEValue findAttribute(dwarf::Attribute Attribute) const
Find a value in the DIE with the attribute given.
Definition: DIE.cpp:214
const DIE * getUnitDie() const
Climb up the parent chain to get the compile unit or type unit DIE that this DIE belongs to.
Definition: DIE.cpp:195
dwarf::Tag getTag() const
Definition: DIE.h:855
Holds a DIExpression and keeps track of how many operands have been consumed so far.
DWARF expression.
bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
unsigned getNumElements() const
bool isImplicit() const
Return whether this is an implicit location description.
static std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
static std::optional< const DIExpression * > convertToNonVariadicExpression(const DIExpression *Expr)
If Expr is a valid single-location expression, i.e.
ArrayRef< uint64_t > getElements() const
A scope for locals.
Debug location.
DIFile * getFile() const
unsigned getLine() const
DIMacroNodeArray getElements() const
Tagged DWARF-like metadata node.
Base class for scope-like contexts.
StringRef getFilename() const
StringRef getName() const
DIFile * getFile() const
StringRef getDirectory() const
std::optional< StringRef > getSource() const
DIScope * getScope() const
Subprogram description.
Base class for types.
DIType * getType() const
void addTypeUnitSignature(DwarfTypeUnit &U)
Add a type unit Signature.
Definition: AccelTable.cpp:709
void convertDieToOffset()
Convert DIE entries to explicit offset.
Definition: AccelTable.h:402
void addTypeUnitSymbol(DwarfTypeUnit &U)
Add a type unit start symbol.
Definition: AccelTable.cpp:705
void addTypeEntries(DWARF5AccelTable &Table)
Definition: AccelTable.h:414
A DataExtractor (typically for an in-memory copy of an object-file section) plus a relocation map for...
This class represents an Operation in the Expression.
std::optional< unsigned > getSubCode() const
Encoding
Size and signedness of expression operations' operands.
const Description & getDescription() const
uint64_t getOperandEndOffset(unsigned Idx) const
uint64_t getRawOperand(unsigned Idx) const
bool isLittleEndian() const
Layout endianness...
Definition: DataLayout.h:238
Used for tracking debug info about call site parameters.
Definition: DwarfDebug.h:316
This class is defined as the common parent of DbgVariable and DbgLabel such that it could levarage po...
Definition: DwarfDebug.h:65
bool hasNonEmptyLocation(const Entries &Entries) const
Test whether a vector of entries features any non-empty locations.
A single location or constant within a variable location description, with either a single entry (wit...
Definition: DebugLocEntry.h:40
The location of a single variable, composed of an expression and 0 or more DbgValueLocEntries.
This class is used to track local variable information.
Definition: DwarfDebug.h:214
const DILocalVariable * getVariable() const
Definition: DwarfDebug.h:246
const DIType * getType() const
Definition: DwarfDebug.cpp:230
Base class for debug information backends.
const MachineInstr * CurMI
If nonnull, stores the current machine instruction we're processing.
AsmPrinter * Asm
Target of debug info emission.
MCSymbol * getLabelBeforeInsn(const MachineInstr *MI)
Return Label preceding the instruction.
MachineModuleInfo * MMI
Collected machine module information.
DebugLoc PrevInstLoc
Previous instruction's location information.
DebugLoc PrologEndLoc
This location indicates end of function prologue and beginning of function body.
MCSymbol * getLabelAfterInsn(const MachineInstr *MI)
Return Label immediately following the instruction.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
const MachineBasicBlock * PrevInstBB
void requestLabelAfterInsn(const MachineInstr *MI)
Ensure that a label will be emitted after MI.
DbgValueHistoryMap DbgValues
History of DBG_VALUE and clobber instructions for each user variable.
DbgLabelInstrMap DbgLabels
Mapping of inlined labels and DBG_LABEL machine instruction.
void beginModule(Module *M) override
const InstructionOrdering & getInstOrdering() const
void requestLabelBeforeInsn(const MachineInstr *MI)
Ensure that a label will be emitted before MI.
const MachineBasicBlock * EpilogBeginBlock
This block includes epilogue instructions.
DwarfExpression implementation for .debug_loc entries.
void finalize(const AsmPrinter &AP, DebugLocStream::ListBuilder &List, const DIBasicType *BT, DwarfCompileUnit &TheCU)
Lower this entry into a DWARF expression.
Builder for DebugLocStream entries.
Builder for DebugLocStream lists.
ArrayRef< std::string > getComments(const Entry &E) const
ArrayRef< Entry > getEntries(const List &L) const
ArrayRef< char > getBytes(const Entry &E) const
MCSymbol * getSym() const
void setSym(MCSymbol *Sym)
ArrayRef< List > getLists() const
A debug info location.
Definition: DebugLoc.h:33
unsigned getLine() const
Definition: DebugLoc.cpp:24
MDNode * getScope() const
Definition: DebugLoc.cpp:34
unsigned getCol() const
Definition: DebugLoc.cpp:29
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:202
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
void constructAbstractSubprogramScopeDIE(LexicalScope *Scope)
void addRange(RangeSpan Range)
addRange - Add an address range to the list of ranges for this unit.
void createAbstractEntity(const DINode *Node, LexicalScope *Scope)
DIE & constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope)
Construct a DIE for this subprogram scope.
DwarfCompileUnit * getSkeleton() const
void setSkeleton(DwarfCompileUnit &Skel)
Set the skeleton unit associated with this unit.
const StringMap< const DIE * > & getGlobalNames() const
DbgEntity * getExistingAbstractEntity(const DINode *Node)
const StringMap< const DIE * > & getGlobalTypes() const
Collects and handles dwarf debug information.
Definition: DwarfDebug.h:351
bool useSegmentedStringOffsetsTable() const
Returns whether to generate a string offsets table with (possibly shared) contributions from each CU ...
Definition: DwarfDebug.h:814
std::optional< MD5::MD5Result > getMD5AsBytes(const DIFile *File) const
If the File has an MD5 checksum, return it as an MD5Result allocated in the MCContext.
bool emitDebugEntryValues() const
Definition: DwarfDebug.h:818
uint16_t getDwarfVersion() const
Returns the Dwarf Version.
void emitDebugLocEntry(ByteStreamer &Streamer, const DebugLocStream::Entry &Entry, const DwarfCompileUnit *CU)
Emit an entry for the debug loc section.
void addAccelNamespace(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die)
void setCurrentDWARF5AccelTable(const DWARF5AccelTableKind Kind)
Sets the current DWARF5AccelTable to use.
Definition: DwarfDebug.h:927
bool alwaysUseRanges(const DwarfCompileUnit &) const
Returns whether range encodings should be used for single entry range lists.
void beginModule(Module *M) override
Emit all Dwarf sections that should come prior to the content.
void addSubprogramNames(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, const DISubprogram *SP, DIE &Die)
Definition: DwarfDebug.cpp:476
bool useAllLinkageNames() const
Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
Definition: DwarfDebug.h:749
void insertSectionLabel(const MCSymbol *S)
void addAccelObjC(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die)
dwarf::Form getDwarfSectionOffsetForm() const
Returns a suitable DWARF form to represent a section offset, i.e.
bool useAppleExtensionAttributes() const
Definition: DwarfDebug.h:800
void skippedNonDebugFunction() override
void addArangeLabel(SymbolCU SCU)
Add a label so that arange data can be generated for it.
Definition: DwarfDebug.h:739
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
AddressPool & getAddressPool()
Definition: DwarfDebug.h:861
DWARF5AccelTable & getCurrentDWARF5AccelTable()
Returns either CU or TU DWARF5AccelTable.
Definition: DwarfDebug.h:937
bool useSectionsAsReferences() const
Returns whether to use sections as labels rather than temp symbols.
Definition: DwarfDebug.h:782
const DebugLocStream & getDebugLocs() const
Returns the entries for the .debug_loc section.
Definition: DwarfDebug.h:845
bool shareAcrossDWOCUs() const
Definition: DwarfDebug.cpp:537
void terminateLineTable(const DwarfCompileUnit *CU)
Terminate the line table by adding the last range label.
~DwarfDebug() override
void endFunctionImpl(const MachineFunction *MF) override
Gather and emit post-function debug information.
void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry, const DwarfCompileUnit *CU)
Emit the location for a debug loc entry, including the size header.
const MCSymbol * getSectionLabel(const MCSection *S)
static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, const DbgValueLoc &Value, DwarfExpression &DwarfExpr)
bool useSplitDwarf() const
Returns whether or not to change the current debug info for the split dwarf proposal support.
Definition: DwarfDebug.h:806
bool useLocSection() const
Returns whether .debug_loc section should be emitted.
Definition: DwarfDebug.h:787
unsigned getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU)
Get Dwarf compile unit ID for line table.
DebugLoc emitInitialLocDirective(const MachineFunction &MF, unsigned CUID)
Emits inital debug location directive.
bool useRangesSection() const
Returns whether ranges section should be emitted.
Definition: DwarfDebug.h:763
void addAccelName(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die)
bool isLexicalScopeDIENull(LexicalScope *Scope)
A helper function to check whether the DIE for a given Scope is going to be null.
Definition: DwarfDebug.cpp:513
void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier, DIE &Die, const DICompositeType *CTy)
Add a DIE to the set of types that we're going to pull into type units.
void endModule() override
Emit all Dwarf sections that should come after the content.
void addAccelType(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die, char Flags)
DwarfDebug(AsmPrinter *A)
Definition: DwarfDebug.cpp:330
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
AccelTableKind getAccelTableKind() const
Returns what kind (if any) of accelerator tables to emit.
Definition: DwarfDebug.h:795
static uint64_t makeTypeSignature(StringRef Identifier)
Perform an MD5 checksum of Identifier and return the lower 64 bits.
Base class containing the logic for constructing DWARF expressions independently of whether they are ...
void setLocation(const MachineLocation &Loc, const DIExpression *DIExpr)
Set the location (Loc) and DIExpression (DIExpr) to describe.
void finalize()
This needs to be called last to commit any pending changes.
void addFragmentOffset(const DIExpression *Expr)
If applicable, emit an empty DW_OP_piece / DW_OP_bit_piece to advance to the fragment described by Ex...
void setMemoryLocationKind()
Lock this down to become a memory location description.
std::optional< uint8_t > TagOffset
void addConstantFP(const APFloat &Value, const AsmPrinter &AP)
Emit an floating point constant.
bool addMachineRegExpression(const TargetRegisterInfo &TRI, DIExpressionCursor &Expr, llvm::Register MachineReg, unsigned FragmentOffsetInBits=0)
Emit a machine register location.
void addUnsignedConstant(uint64_t Value)
Emit an unsigned constant.
void addExpression(DIExpressionCursor &&Expr)
Emit all remaining operations in the DIExpressionCursor.
void addSignedConstant(int64_t Value)
Emit a signed constant.
void addWasmLocation(unsigned Index, uint64_t Offset)
Emit location information expressed via WebAssembly location + offset The Index is an identifier for ...
void beginEntryValueExpression(DIExpressionCursor &ExprCursor)
Begin emission of an entry value dwarf operation.
void addScopeLabel(LexicalScope *LS, DbgLabel *Label)
Definition: DwarfFile.cpp:117
void addUnit(std::unique_ptr< DwarfCompileUnit > U)
Add a unit to the list of CUs.
Definition: DwarfFile.cpp:23
void computeSizeAndOffsets()
Compute the size and offset of all the DIEs.
Definition: DwarfFile.cpp:57
void setRnglistsTableBaseSym(MCSymbol *Sym)
Definition: DwarfFile.h:151
DenseMap< LexicalScope *, ScopeVars > & getScopeVariables()
Definition: DwarfFile.h:157
unsigned computeSizeAndOffsetsForUnit(DwarfUnit *TheU)
Compute the size and offset of all the DIEs in the given unit.
Definition: DwarfFile.cpp:80
void emitUnits(bool UseOffsets)
Emit all of the units to the section listed with the given abbreviation section.
Definition: DwarfFile.cpp:29
void emitUnit(DwarfUnit *TheU, bool UseOffsets)
Emit the given unit to its section.
Definition: DwarfFile.cpp:34
const SmallVectorImpl< RangeSpanList > & getRangeLists() const
getRangeLists - Get the vector of range lists.
Definition: DwarfFile.h:110
MCSymbol * getStringOffsetsStartSym() const
Definition: DwarfFile.h:147
MCSymbol * getRnglistsTableBaseSym() const
Definition: DwarfFile.h:150
DwarfStringPool & getStringPool()
Returns the string pool.
Definition: DwarfFile.h:145
void emitAbbrevs(MCSection *)
Emit a set of abbreviations to the specific section.
Definition: DwarfFile.cpp:97
void emitStrings(MCSection *StrSection, MCSection *OffsetSection=nullptr, bool UseRelativeOffsets=false)
Emit all of the strings to the section given.
Definition: DwarfFile.cpp:100
DenseMap< LexicalScope *, LabelList > & getScopeLabels()
Definition: DwarfFile.h:161
void addScopeVariable(LexicalScope *LS, DbgVariable *Var)
Definition: DwarfFile.cpp:105
DenseMap< const DILocalScope *, DIE * > & getAbstractScopeDIEs()
Definition: DwarfFile.h:165
const SmallVectorImpl< std::unique_ptr< DwarfCompileUnit > > & getUnits()
Definition: DwarfFile.h:102
DwarfStringPoolEntryRef: Dwarf string pool entry reference.
EntryRef getEntry(AsmPrinter &Asm, StringRef Str)
Get a reference to an entry in the string pool.
EntryRef getIndexedEntry(AsmPrinter &Asm, StringRef Str)
Same as getEntry, except that you can use EntryRef::getIndex to obtain a unique ID of this entry (e....
void emitStringOffsetsTableHeader(AsmPrinter &Asm, MCSection *OffsetSection, MCSymbol *StartSym)
void setTypeSignature(uint64_t Signature)
Definition: DwarfUnit.h:387
void setType(const DIE *Ty)
Definition: DwarfUnit.h:390
This dwarf writer support class manages information associated with a source file.
Definition: DwarfUnit.h:35
void addStringOffsetsStart()
Add the DW_AT_str_offsets_base attribute to the unit DIE.
Definition: DwarfUnit.cpp:1847
void addUInt(DIEValueList &Die, dwarf::Attribute Attribute, std::optional< dwarf::Form > Form, uint64_t Integer)
Add an unsigned integer attribute data and value.
Definition: DwarfUnit.cpp:220
void addString(DIE &Die, dwarf::Attribute Attribute, StringRef Str)
Add a string attribute data and value.
Definition: DwarfUnit.cpp:246
DIE * createTypeDIE(const DIScope *Context, DIE &ContextDIE, const DIType *Ty)
Creates type DIE with specific context.
Definition: DwarfUnit.cpp:575
const DICompileUnit * getCUNode() const
Definition: DwarfUnit.h:111
void addFlag(DIE &Die, dwarf::Attribute Attribute)
Add a flag that is true to the DIE.
Definition: DwarfUnit.cpp:213
unsigned getUniqueID() const
Gets Unique ID for this unit.
Definition: DwarfUnit.h:101
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1831
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:356
bool isTailCall(const MachineInstr &MI) const override
Record instruction ordering so we can query their relative positions within a function.
bool isBefore(const MachineInstr *A, const MachineInstr *B) const
Check if instruction A comes before B, where A and B both belong to the MachineFunction passed to ini...
LexicalScope - This class is used to track scope information.
Definition: LexicalScopes.h:44
SmallVectorImpl< InsnRange > & getRanges()
Definition: LexicalScopes.h:66
const DILocalScope * getScopeNode() const
Definition: LexicalScopes.h:63
LexicalScopes - This class provides interface to collect and use lexical scoping information from mac...
LexicalScope * getOrCreateAbstractScope(const DILocalScope *Scope)
getOrCreateAbstractScope - Find or create an abstract lexical scope.
LexicalScope * findLexicalScope(const DILocation *DL)
findLexicalScope - Find lexical scope, either regular or inlined, for the given DebugLoc.
ArrayRef< LexicalScope * > getAbstractScopesList() const
getAbstractScopesList - Return a reference to list of abstract scopes.
LexicalScope * findInlinedScope(const DILocalScope *N, const DILocation *IA)
findInlinedScope - Find an inlined scope for the given scope/inlined-at.
LexicalScope * findAbstractScope(const DILocalScope *N)
findAbstractScope - Find an abstract scope or return null.
bool empty()
empty - Return true if there is any lexical scope information available.
LexicalScope * getCurrentFunctionScope() const
getCurrentFunctionScope - Return lexical scope for the current function.
Single value location description.
Definition: DwarfDebug.h:131
Single(DbgValueLoc ValueLoc)
Definition: DwarfDebug.cpp:282
unsigned getCodePointerSize() const
Get the code pointer size in bytes.
Definition: MCAsmInfo.h:546
uint16_t getDwarfVersion() const
Definition: MCContext.h:844
dwarf::DwarfFormat getDwarfFormat() const
Definition: MCContext.h:841
void maybeSetRootFile(StringRef Directory, StringRef FileName, std::optional< MD5::MD5Result > Checksum, std::optional< StringRef > Source)
Definition: MCDwarf.h:331
void Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params, MCSection *Section) const
Definition: MCDwarf.cpp:286
MCSection * getDwarfLoclistsSection() const
MCSection * getDwarfAccelTypesSection() const
MCSection * getDwarfGnuPubNamesSection() const
MCSection * getDwarfStrOffDWOSection() const
MCSection * getDwarfRangesSection() const
MCSection * getDwarfAccelNamespaceSection() const
MCSection * getDwarfLineDWOSection() const
MCSection * getDwarfStrOffSection() const
MCSection * getDwarfInfoDWOSection() const
MCSection * getDwarfTypesDWOSection() const
MCSection * getDwarfPubNamesSection() const
MCSection * getDwarfMacroSection() const
MCSection * getDwarfStrSection() const
MCSection * getDwarfLoclistsDWOSection() const
MCSection * getDwarfMacinfoDWOSection() const
MCSection * getDwarfRnglistsSection() const
MCSection * getDwarfAddrSection() const
MCSection * getDwarfInfoSection() const
MCSection * getDwarfPubTypesSection() const
MCSection * getDwarfTypesSection(uint64_t Hash) const
MCSection * getDwarfGnuPubTypesSection() const
MCSection * getDwarfStrDWOSection() const
MCSection * getDwarfAccelNamesSection() const
MCSection * getDwarfAbbrevDWOSection() const
MCSection * getDwarfRnglistsDWOSection() const
MCSection * getDwarfAbbrevSection() const
MCSection * getDwarfMacinfoSection() const
MCSection * getDwarfLocDWOSection() const
MCSection * getDwarfARangesSection() const
MCSection * getDwarfAccelObjCSection() const
MCSection * getDwarfLocSection() const
MCSection * getDwarfMacroDWOSection() const
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:39
MCSymbol * getBeginSymbol()
Definition: MCSection.h:129
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:40
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:269
std::string SplitDwarfFile
Definition: MD5.h:41
void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition: MD5.cpp:189
void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition: MD5.cpp:234
Metadata node.
Definition: Metadata.h:1067
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
reverse_iterator rend()
MCSymbol * getEndSymbol() const
Returns the MCSymbol marking the end of this basic block.
bool sameSection(const MachineBasicBlock *MBB) const
Returns true if this and MBB belong to the same section.
unsigned getSectionIDNum() const
Returns the unique section ID number of this basic block.
bool isBeginSection() const
Returns true if this block begins any section.
bool isEndSection() const
Returns true if this block ends any section.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const CallSiteInfoMap & getCallSitesInfo() const
bool hasBBSections() const
Returns true if this function has basic block sections enabled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & back() const
VariableDbgInfoMapTy & getVariableDbgInfo()
const MachineBasicBlock & front() const
MachineBasicBlock iterator that automatically skips over MIs that are inside bundles (i....
Representation of each machine instruction.
Definition: MachineInstr.h:69
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:329
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:918
iterator_range< mop_iterator > uses()
Returns a range that includes all operands that are register uses.
Definition: MachineInstr.h:710
bool isBundle() const
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:549
bool hasDelaySlot(QueryType Type=AnyInBundle) const
Returns true if the specified instruction has a delay slot which must be filled by the code generator...
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
bool isDebugValue() const
const Module * getModule() const
bool hasDebugInfo() const
Returns true if valid debug info is present.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
Register getReg() const
getReg - Returns the register number.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
Definition: MapVector.h:193
bool empty() const
Definition: MapVector.h:79
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: MapVector.h:141
void clear()
Definition: MapVector.h:88
Root of the metadata hierarchy.
Definition: Metadata.h:62
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
iterator_range< debug_compile_units_iterator > debug_compile_units() const
Return an iterator for all DICompileUnits listed in this Module's llvm.dbg.cu named metadata node and...
Definition: Module.h:867
unsigned getDwarfVersion() const
Returns the Dwarf Version by checking module flags.
Definition: Module.cpp:563
bool isDwarf64() const
Returns the DWARF format by checking module flags.
Definition: Module.cpp:570
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:95
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:93
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
const_iterator begin() const
Definition: SmallSet.h:223
const_iterator end() const
Definition: SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:179
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91