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