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