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