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