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