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