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