1//===- llvm/CodeGen/DwarfDebug.h - Dwarf Debug Framework --------*- C++ -*-===//
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#ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
14#define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
15
16#include "AddressPool.h"
17#include "DebugLocEntry.h"
18#include "DebugLocStream.h"
19#include "DwarfFile.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/DenseSet.h"
22#include "llvm/ADT/MapVector.h"
23#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringMap.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/BinaryFormat/Dwarf.h"
29#include "llvm/CodeGen/AccelTable.h"
30#include "llvm/CodeGen/DbgEntityHistoryCalculator.h"
31#include "llvm/CodeGen/DebugHandlerBase.h"
32#include "llvm/IR/DebugInfoMetadata.h"
33#include "llvm/IR/DebugLoc.h"
34#include "llvm/IR/Metadata.h"
35#include "llvm/MC/MCDwarf.h"
36#include "llvm/Support/Allocator.h"
37#include "llvm/Target/TargetOptions.h"
38#include <cassert>
39#include <cstdint>
40#include <limits>
41#include <memory>
42#include <utility>
43#include <variant>
44#include <vector>
45
46namespace llvm {
47
48class AsmPrinter;
49class ByteStreamer;
50class DIE;
51class DwarfCompileUnit;
52class DwarfExpression;
53class DwarfTypeUnit;
54class DwarfUnit;
55class GlobalVariable;
56class LexicalScope;
57class MachineFunction;
58class MCSection;
59class MCSymbol;
60class Module;
61
62//===----------------------------------------------------------------------===//
63/// This class is defined as the common parent of DbgVariable and DbgLabel
64/// such that it could levarage polymorphism to extract common code for
65/// DbgVariable and DbgLabel.
66class DbgEntity {
67public:
68 enum DbgEntityKind {
69 DbgVariableKind,
70 DbgLabelKind
71 };
72
73private:
74 const DINode *Entity;
75 const DILocation *InlinedAt;
76 DIE *TheDIE = nullptr;
77 const DbgEntityKind SubclassID;
78
79public:
80 DbgEntity(const DINode *N, const DILocation *IA, DbgEntityKind ID)
81 : Entity(N), InlinedAt(IA), SubclassID(ID) {}
82 virtual ~DbgEntity() = default;
83
84 /// Accessors.
85 /// @{
86 const DINode *getEntity() const { return Entity; }
87 const DILocation *getInlinedAt() const { return InlinedAt; }
88 DIE *getDIE() const { return TheDIE; }
89 DbgEntityKind getDbgEntityID() const { return SubclassID; }
90 /// @}
91
92 void setDIE(DIE &D) { TheDIE = &D; }
93
94 static bool classof(const DbgEntity *N) {
95 switch (N->getDbgEntityID()) {
96 case DbgVariableKind:
97 case DbgLabelKind:
98 return true;
99 }
100 llvm_unreachable("Invalid DbgEntityKind");
101 }
102};
103
104class DbgVariable;
105
106bool operator<(const struct FrameIndexExpr &LHS,
107 const struct FrameIndexExpr &RHS);
108bool operator<(const struct EntryValueInfo &LHS,
109 const struct EntryValueInfo &RHS);
110
111/// Proxy for one MMI entry.
112struct FrameIndexExpr {
113 int FI;
114 const DIExpression *Expr;
115
116 /// Operator enabling sorting based on fragment offset.
117 friend bool operator<(const FrameIndexExpr &LHS, const FrameIndexExpr &RHS);
118};
119
120/// Represents an entry-value location, or a fragment of one.
121struct EntryValueInfo {
122 MCRegister Reg;
123 const DIExpression &Expr;
124
125 /// Operator enabling sorting based on fragment offset.
126 friend bool operator<(const EntryValueInfo &LHS, const EntryValueInfo &RHS);
127};
128
129// Namespace for alternatives of a DbgVariable.
130namespace Loc {
131/// Single value location description.
132class Single {
133 std::unique_ptr<DbgValueLoc> ValueLoc;
134 const DIExpression *Expr;
135
136public:
137 explicit Single(DbgValueLoc ValueLoc);
138 explicit Single(const MachineInstr *DbgValue);
139 const DbgValueLoc &getValueLoc() const { return *ValueLoc; }
140 const DIExpression *getExpr() const { return Expr; }
141};
142/// Multi-value location description.
143class Multi {
144 /// Index of the entry list in DebugLocs.
145 unsigned DebugLocListIndex;
146 /// DW_OP_LLVM_tag_offset value from DebugLocs.
147 std::optional<uint8_t> DebugLocListTagOffset;
148
149public:
150 explicit Multi(unsigned DebugLocListIndex,
151 std::optional<uint8_t> DebugLocListTagOffset)
152 : DebugLocListIndex(DebugLocListIndex),
153 DebugLocListTagOffset(DebugLocListTagOffset) {}
154 unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
155 std::optional<uint8_t> getDebugLocListTagOffset() const {
156 return DebugLocListTagOffset;
157 }
158};
159/// Single location defined by (potentially multiple) MMI entries.
160struct MMI {
161 std::set<FrameIndexExpr> FrameIndexExprs;
162
163public:
164 explicit MMI(const DIExpression *E, int FI) : FrameIndexExprs({{.FI: FI, .Expr: E}}) {
165 assert((!E || E->isValid()) && "Expected valid expression");
166 assert(FI != std::numeric_limits<int>::max() && "Expected valid index");
167 }
168 void addFrameIndexExpr(const DIExpression *Expr, int FI);
169 /// Get the FI entries, sorted by fragment offset.
170 const std::set<FrameIndexExpr> &getFrameIndexExprs() const;
171};
172/// Single location defined by (potentially multiple) EntryValueInfo.
173struct EntryValue {
174 std::set<EntryValueInfo> EntryValues;
175 explicit EntryValue(MCRegister Reg, const DIExpression &Expr) {
176 addExpr(Reg, Expr);
177 };
178 // Add the pair Reg, Expr to the list of entry values describing the variable.
179 // If multiple expressions are added, it is the callers responsibility to
180 // ensure they are all non-overlapping fragments.
181 void addExpr(MCRegister Reg, const DIExpression &Expr) {
182 std::optional<const DIExpression *> NonVariadicExpr =
183 DIExpression::convertToNonVariadicExpression(Expr: &Expr);
184 assert(NonVariadicExpr && *NonVariadicExpr);
185
186 EntryValues.insert(x: {.Reg: Reg, .Expr: **NonVariadicExpr});
187 }
188};
189/// Alias for the std::variant specialization base class of DbgVariable.
190using Variant = std::variant<std::monostate, Loc::Single, Loc::Multi, Loc::MMI,
191 Loc::EntryValue>;
192} // namespace Loc
193
194//===----------------------------------------------------------------------===//
195/// This class is used to track local variable information.
196///
197/// Variables that have been optimized out hold the \c monostate alternative.
198/// This is not distinguished from the case of a constructed \c DbgVariable
199/// which has not be initialized yet.
200///
201/// Variables can be created from allocas, in which case they're generated from
202/// the MMI table. Such variables hold the \c Loc::MMI alternative which can
203/// have multiple expressions and frame indices.
204///
205/// Variables can be created from the entry value of registers, in which case
206/// they're generated from the MMI table. Such variables hold the \c
207/// EntryValueLoc alternative which can either have a single expression or
208/// multiple *fragment* expressions.
209///
210/// Variables can be created from \c DBG_VALUE instructions. Those whose
211/// location changes over time hold a \c Loc::Multi alternative which uses \c
212/// DebugLocListIndex and (optionally) \c DebugLocListTagOffset, while those
213/// with a single location hold a \c Loc::Single alternative which use \c
214/// ValueLoc and (optionally) a single \c Expr.
215class DbgVariable : public DbgEntity, public Loc::Variant {
216
217public:
218 /// To workaround P2162R0 https://github.com/cplusplus/papers/issues/873 the
219 /// base class subobject needs to be passed directly to std::visit, so expose
220 /// it directly here.
221 Loc::Variant &asVariant() { return *static_cast<Loc::Variant *>(this); }
222 const Loc::Variant &asVariant() const {
223 return *static_cast<const Loc::Variant *>(this);
224 }
225 /// Member shorthand for std::holds_alternative
226 template <typename T> bool holds() const {
227 return std::holds_alternative<T>(*this);
228 }
229 /// Asserting, noexcept member alternative to std::get
230 template <typename T> auto &get() noexcept {
231 assert(holds<T>());
232 return *std::get_if<T>(this);
233 }
234 /// Asserting, noexcept member alternative to std::get
235 template <typename T> const auto &get() const noexcept {
236 assert(holds<T>());
237 return *std::get_if<T>(this);
238 }
239
240 /// Construct a DbgVariable.
241 ///
242 /// Creates a variable without any DW_AT_location.
243 DbgVariable(const DILocalVariable *V, const DILocation *IA)
244 : DbgEntity(V, IA, DbgVariableKind) {}
245
246 // Accessors.
247 const DILocalVariable *getVariable() const {
248 return cast<DILocalVariable>(Val: getEntity());
249 }
250
251 StringRef getName() const { return getVariable()->getName(); }
252
253 // Translate tag to proper Dwarf tag.
254 dwarf::Tag getTag() const {
255 // FIXME: Why don't we just infer this tag and store it all along?
256 if (getVariable()->isParameter())
257 return dwarf::DW_TAG_formal_parameter;
258
259 return dwarf::DW_TAG_variable;
260 }
261
262 /// Return true if DbgVariable is artificial.
263 bool isArtificial() const {
264 if (getVariable()->isArtificial())
265 return true;
266 if (getType()->isArtificial())
267 return true;
268 return false;
269 }
270
271 bool isObjectPointer() const {
272 if (getVariable()->isObjectPointer())
273 return true;
274 if (getType()->isObjectPointer())
275 return true;
276 return false;
277 }
278
279 const DIType *getType() const;
280
281 static bool classof(const DbgEntity *N) {
282 return N->getDbgEntityID() == DbgVariableKind;
283 }
284};
285
286//===----------------------------------------------------------------------===//
287/// This class is used to track label information.
288///
289/// Labels are collected from \c DBG_LABEL instructions.
290class DbgLabel : public DbgEntity {
291 const MCSymbol *Sym; /// Symbol before DBG_LABEL instruction.
292
293public:
294 /// We need MCSymbol information to generate DW_AT_low_pc.
295 DbgLabel(const DILabel *L, const DILocation *IA, const MCSymbol *Sym = nullptr)
296 : DbgEntity(L, IA, DbgLabelKind), Sym(Sym) {}
297
298 /// Accessors.
299 /// @{
300 const DILabel *getLabel() const { return cast<DILabel>(Val: getEntity()); }
301 const MCSymbol *getSymbol() const { return Sym; }
302
303 StringRef getName() const { return getLabel()->getName(); }
304 /// @}
305
306 /// Translate tag to proper Dwarf tag.
307 dwarf::Tag getTag() const {
308 return dwarf::DW_TAG_label;
309 }
310
311 static bool classof(const DbgEntity *N) {
312 return N->getDbgEntityID() == DbgLabelKind;
313 }
314};
315
316/// Used for tracking debug info about call site parameters.
317class DbgCallSiteParam {
318private:
319 unsigned Register; ///< Parameter register at the callee entry point.
320 DbgValueLoc Value; ///< Corresponding location for the parameter value at
321 ///< the call site.
322public:
323 DbgCallSiteParam(unsigned Reg, DbgValueLoc Val)
324 : Register(Reg), Value(Val) {
325 assert(Reg && "Parameter register cannot be undef");
326 }
327
328 unsigned getRegister() const { return Register; }
329 DbgValueLoc getValue() const { return Value; }
330};
331
332/// Collection used for storing debug call site parameters.
333using ParamSet = SmallVector<DbgCallSiteParam, 4>;
334
335/// Helper used to pair up a symbol and its DWARF compile unit.
336struct SymbolCU {
337 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
338
339 const MCSymbol *Sym;
340 DwarfCompileUnit *CU;
341};
342
343/// The kind of accelerator tables we should emit.
344enum class AccelTableKind {
345 Default, ///< Platform default.
346 None, ///< None.
347 Apple, ///< .apple_names, .apple_namespaces, .apple_types, .apple_objc.
348 Dwarf, ///< DWARF v5 .debug_names.
349};
350
351/// Collects and handles dwarf debug information.
352class DwarfDebug : public DebugHandlerBase {
353 /// All DIEValues are allocated through this allocator.
354 BumpPtrAllocator DIEValueAllocator;
355
356 /// Maps MDNode with its corresponding DwarfCompileUnit.
357 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
358
359 /// Maps a CU DIE with its corresponding DwarfCompileUnit.
360 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
361
362 /// List of all labels used in aranges generation.
363 std::vector<SymbolCU> ArangeLabels;
364
365 /// Size of each symbol emitted (for those symbols that have a specific size).
366 DenseMap<const MCSymbol *, uint64_t> SymSize;
367
368 /// Collection of abstract variables/labels.
369 SmallVector<std::unique_ptr<DbgEntity>, 64> ConcreteEntities;
370
371 /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
372 /// can refer to them in spite of insertions into this list.
373 DebugLocStream DebugLocs;
374
375 /// This is a collection of subprogram MDNodes that are processed to
376 /// create DIEs.
377 SmallSetVector<const DISubprogram *, 16> ProcessedSPNodes;
378
379 /// Map function-local imported entities to their parent local scope
380 /// (either DILexicalBlock or DISubprogram) for a processed function
381 /// (including inlined subprograms).
382 using MDNodeSet = SetVector<const MDNode *, SmallVector<const MDNode *, 2>,
383 SmallPtrSet<const MDNode *, 2>>;
384 DenseMap<const DILocalScope *, MDNodeSet> LocalDeclsPerLS;
385
386 SmallDenseSet<const MachineInstr *> ForceIsStmtInstrs;
387
388 /// If nonnull, stores the current machine function we're processing.
389 const MachineFunction *CurFn = nullptr;
390
391 /// If nonnull, stores the CU in which the previous subprogram was contained.
392 const DwarfCompileUnit *PrevCU = nullptr;
393
394 /// As an optimization, there is no need to emit an entry in the directory
395 /// table for the same directory as DW_AT_comp_dir.
396 StringRef CompilationDir;
397
398 /// Holders for the various debug information flags that we might need to
399 /// have exposed. See accessor functions below for description.
400
401 /// Map from MDNodes for user-defined types to their type signatures. Also
402 /// used to keep track of which types we have emitted type units for.
403 DenseMap<const MDNode *, uint64_t> TypeSignatures;
404
405 DenseMap<const MCSection *, const MCSymbol *> SectionLabels;
406
407 SmallVector<
408 std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
409 TypeUnitsUnderConstruction;
410
411 /// Symbol pointing to the current function's DWARF line table entries.
412 MCSymbol *FunctionLineTableLabel;
413
414 /// Used to set a uniqe ID for a Type Unit.
415 /// This counter represents number of DwarfTypeUnits created, not necessarily
416 /// number of type units that will be emitted.
417 unsigned NumTypeUnitsCreated = 0;
418
419 /// Whether to use the GNU TLS opcode (instead of the standard opcode).
420 bool UseGNUTLSOpcode;
421
422 /// Whether to use DWARF 2 bitfields (instead of the DWARF 4 format).
423 bool UseDWARF2Bitfields;
424
425 /// Whether to emit all linkage names, or just abstract subprograms.
426 bool UseAllLinkageNames;
427
428 /// Use inlined strings.
429 bool UseInlineStrings = false;
430
431 /// Allow emission of .debug_ranges section.
432 bool UseRangesSection = true;
433
434 /// True if the sections itself must be used as references and don't create
435 /// temp symbols inside DWARF sections.
436 bool UseSectionsAsReferences = false;
437
438 /// Allow emission of .debug_aranges section
439 bool UseARangesSection = false;
440
441 /// Generate DWARF v4 type units.
442 bool GenerateTypeUnits;
443
444 /// Emit a .debug_macro section instead of .debug_macinfo.
445 bool UseDebugMacroSection;
446
447 /// Avoid using DW_OP_convert due to consumer incompatibilities.
448 bool EnableOpConvert;
449
450public:
451 enum class MinimizeAddrInV5 {
452 Default,
453 Disabled,
454 Ranges,
455 Expressions,
456 Form,
457 };
458
459 enum class DWARF5AccelTableKind {
460 CU = 0,
461 TU = 1,
462 };
463
464private:
465 /// Instructions which should get is_stmt applied because they implement key
466 /// functionality for a source atom.
467 SmallDenseSet<const MachineInstr *> KeyInstructions;
468
469 /// Force the use of DW_AT_ranges even for single-entry range lists.
470 MinimizeAddrInV5 MinimizeAddr = MinimizeAddrInV5::Disabled;
471
472 /// DWARF5 Experimental Options
473 /// @{
474 AccelTableKind TheAccelTableKind;
475 bool HasAppleExtensionAttributes;
476 bool HasSplitDwarf;
477
478 /// Whether to generate the DWARF v5 string offsets table.
479 /// It consists of a series of contributions, each preceded by a header.
480 /// The pre-DWARF v5 string offsets table for split dwarf is, in contrast,
481 /// a monolithic sequence of string offsets.
482 bool UseSegmentedStringOffsetsTable;
483
484 /// Enable production of call site parameters needed to print the debug entry
485 /// values. Useful for testing purposes when a debugger does not support the
486 /// feature yet.
487 bool EmitDebugEntryValues;
488
489 /// Separated Dwarf Variables
490 /// In general these will all be for bits that are left in the
491 /// original object file, rather than things that are meant
492 /// to be in the .dwo sections.
493
494 /// Holder for the skeleton information.
495 DwarfFile SkeletonHolder;
496
497 /// Store file names for type units under fission in a line table
498 /// header that will be emitted into debug_line.dwo.
499 // FIXME: replace this with a map from comp_dir to table so that we
500 // can emit multiple tables during LTO each of which uses directory
501 // 0, referencing the comp_dir of all the type units that use it.
502 MCDwarfDwoLineTable SplitTypeUnitFileTable;
503 /// @}
504
505 /// True iff there are multiple CUs in this module.
506 bool SingleCU;
507 bool IsDarwin;
508
509 /// Map for tracking Fortran deferred CHARACTER lengths.
510 DenseMap<const DIStringType *, unsigned> StringTypeLocMap;
511
512 AddressPool AddrPool;
513
514 /// Accelerator tables.
515 DWARF5AccelTable AccelDebugNames;
516 DWARF5AccelTable AccelTypeUnitsDebugNames;
517 /// Used to hide which DWARF5AccelTable we are using now.
518 DWARF5AccelTable *CurrentDebugNames = &AccelDebugNames;
519 AccelTable<AppleAccelTableOffsetData> AccelNames;
520 AccelTable<AppleAccelTableOffsetData> AccelObjC;
521 AccelTable<AppleAccelTableOffsetData> AccelNamespace;
522 AccelTable<AppleAccelTableTypeData> AccelTypes;
523
524 /// Identify a debugger for "tuning" the debug info.
525 ///
526 /// The "tuning" should be used to set defaults for individual feature flags
527 /// in DwarfDebug; if a given feature has a more specific command-line option,
528 /// that option should take precedence over the tuning.
529 DebuggerKind DebuggerTuning = DebuggerKind::Default;
530
531 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
532
533 using InlinedEntity = DbgValueHistoryMap::InlinedEntity;
534
535 void ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
536 const DINode *Node,
537 const MDNode *Scope);
538
539 DbgEntity *createConcreteEntity(DwarfCompileUnit &TheCU,
540 LexicalScope &Scope,
541 const DINode *Node,
542 const DILocation *Location,
543 const MCSymbol *Sym = nullptr);
544
545 /// Construct a DIE for this abstract scope.
546 void constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, LexicalScope *Scope);
547
548 /// Construct DIEs for call site entries describing the calls in \p MF.
549 void constructCallSiteEntryDIEs(const DISubprogram &SP, DwarfCompileUnit &CU,
550 DIE &ScopeDIE, const MachineFunction &MF);
551
552 template <typename DataT>
553 void addAccelNameImpl(const DwarfUnit &Unit,
554 const DICompileUnit::DebugNameTableKind NameTableKind,
555 AccelTable<DataT> &AppleAccel, StringRef Name,
556 const DIE &Die);
557
558 void finishEntityDefinitions();
559
560 void finishSubprogramDefinitions();
561
562 /// Finish off debug information after all functions have been
563 /// processed.
564 void finalizeModuleInfo();
565
566 /// Emit the debug info section.
567 void emitDebugInfo();
568
569 /// Emit the abbreviation section.
570 void emitAbbreviations();
571
572 /// Emit the string offsets table header.
573 void emitStringOffsetsTableHeader();
574
575 /// Emit a specified accelerator table.
576 template <typename AccelTableT>
577 void emitAccel(AccelTableT &Accel, MCSection *Section, StringRef TableName);
578
579 /// Emit DWARF v5 accelerator table.
580 void emitAccelDebugNames();
581
582 /// Emit visible names into a hashed accelerator table section.
583 void emitAccelNames();
584
585 /// Emit objective C classes and categories into a hashed
586 /// accelerator table section.
587 void emitAccelObjC();
588
589 /// Emit namespace dies into a hashed accelerator table.
590 void emitAccelNamespaces();
591
592 /// Emit type dies into a hashed accelerator table.
593 void emitAccelTypes();
594
595 /// Emit visible names and types into debug pubnames and pubtypes sections.
596 void emitDebugPubSections();
597
598 void emitDebugPubSection(bool GnuStyle, StringRef Name,
599 DwarfCompileUnit *TheU,
600 const StringMap<const DIE *> &Globals);
601
602 /// Emit null-terminated strings into a debug str section.
603 void emitDebugStr();
604
605 /// Emit variable locations into a debug loc section.
606 void emitDebugLoc();
607
608 /// Emit variable locations into a debug loc dwo section.
609 void emitDebugLocDWO();
610
611 void emitDebugLocImpl(MCSection *Sec);
612
613 /// Emit address ranges into a debug aranges section.
614 void emitDebugARanges();
615
616 /// Emit address ranges into a debug ranges section.
617 void emitDebugRanges();
618 void emitDebugRangesDWO();
619 void emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section);
620
621 /// Emit macros into a debug macinfo section.
622 void emitDebugMacinfo();
623 /// Emit macros into a debug macinfo.dwo section.
624 void emitDebugMacinfoDWO();
625 void emitDebugMacinfoImpl(MCSection *Section);
626 void emitMacro(DIMacro &M);
627 void emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U);
628 void emitMacroFileImpl(DIMacroFile &F, DwarfCompileUnit &U,
629 unsigned StartFile, unsigned EndFile,
630 StringRef (*MacroFormToString)(unsigned Form));
631 void handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U);
632
633 /// DWARF 5 Experimental Split Dwarf Emitters
634
635 /// Initialize common features of skeleton units.
636 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
637 std::unique_ptr<DwarfCompileUnit> NewU);
638
639 /// Construct the split debug info compile unit for the debug info section.
640 /// In DWARF v5, the skeleton unit DIE may have the following attributes:
641 /// DW_AT_addr_base, DW_AT_comp_dir, DW_AT_dwo_name, DW_AT_high_pc,
642 /// DW_AT_low_pc, DW_AT_ranges, DW_AT_stmt_list, and DW_AT_str_offsets_base.
643 /// Prior to DWARF v5 it may also have DW_AT_GNU_dwo_id. DW_AT_GNU_dwo_name
644 /// is used instead of DW_AT_dwo_name, Dw_AT_GNU_addr_base instead of
645 /// DW_AT_addr_base, and DW_AT_GNU_ranges_base instead of DW_AT_rnglists_base.
646 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
647
648 /// Emit the debug info dwo section.
649 void emitDebugInfoDWO();
650
651 /// Emit the debug abbrev dwo section.
652 void emitDebugAbbrevDWO();
653
654 /// Emit the debug line dwo section.
655 void emitDebugLineDWO();
656
657 /// Emit the dwo stringoffsets table header.
658 void emitStringOffsetsTableHeaderDWO();
659
660 /// Emit the debug str dwo section.
661 void emitDebugStrDWO();
662
663 /// Emit DWO addresses.
664 void emitDebugAddr();
665
666 /// Flags to let the linker know we have emitted new style pubnames. Only
667 /// emit it here if we don't have a skeleton CU for split dwarf.
668 void addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const;
669
670 DwarfCompileUnit *getDwarfCompileUnit(const DICompileUnit *DIUnit);
671 /// Create new DwarfCompileUnit for the given metadata node with tag
672 /// DW_TAG_compile_unit.
673 DwarfCompileUnit &getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit);
674 void finishUnitAttributes(const DICompileUnit *DIUnit,
675 DwarfCompileUnit &NewCU);
676
677 /// Register a source line with debug info. Returns the unique
678 /// label that was emitted and which provides correspondence to the
679 /// source line list.
680 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
681 unsigned Flags, StringRef Location = {});
682
683 /// Populate LexicalScope entries with variables' info.
684 void collectEntityInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
685 DenseSet<InlinedEntity> &ProcessedVars);
686
687 /// Build the location list for all DBG_VALUEs in the
688 /// function that describe the same variable. If the resulting
689 /// list has only one entry that is valid for entire variable's
690 /// scope return true.
691 bool buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
692 const DbgValueHistoryMap::Entries &Entries);
693
694 /// Collect variable information from the side table maintained by MF.
695 void collectVariableInfoFromMFTable(DwarfCompileUnit &TheCU,
696 DenseSet<InlinedEntity> &P);
697
698 /// Emit the reference to the section.
699 void emitSectionReference(const DwarfCompileUnit &CU);
700
701 void findForceIsStmtInstrs(const MachineFunction *MF);
702
703 /// Compute instructions which should get is_stmt applied because they
704 /// implement key functionality for a source location atom, store results in
705 /// DwarfDebug::KeyInstructions.
706 void computeKeyInstructions(const MachineFunction *MF);
707
708protected:
709 /// Holder for the file specific debug information.
710 DwarfFile InfoHolder;
711 /// Gather pre-function debug information.
712 void beginFunctionImpl(const MachineFunction *MF) override;
713
714 /// Gather and emit post-function debug information.
715 void endFunctionImpl(const MachineFunction *MF) override;
716
717 /// Get Dwarf compile unit ID for line table.
718 unsigned getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU);
719
720 void skippedNonDebugFunction() override;
721
722 /// Target-specific debug info initialization at function start.
723 virtual void initializeTargetDebugInfo(const MachineFunction &MF) {}
724
725 /// Setters for target-specific DWARF configuration overrides.
726 /// Called from target DwarfDebug subclass constructors.
727 void setUseInlineStrings(bool V) { UseInlineStrings = V; }
728 void setUseRangesSection(bool V) { UseRangesSection = V; }
729 void setUseSectionsAsReferences(bool V) { UseSectionsAsReferences = V; }
730
731 /// Whether to attach ranges/low_pc to the compile unit DIE in endModule.
732 virtual bool shouldAttachCompileUnitRanges() const { return true; }
733
734 /// Target-specific source line recording.
735 virtual void recordTargetSourceLine(const DebugLoc &DL, unsigned Flags);
736
737 const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
738 return InfoHolder.getUnits();
739 }
740
741public:
742 //===--------------------------------------------------------------------===//
743 // Target hooks for debug info customization.
744 //
745
746 /// Whether the target requires resetting the base address in range/loc lists.
747 virtual bool shouldResetBaseAddress(const MCSection &Section) const {
748 return false;
749 }
750
751 /// Describes the storage kind of a debug variable for target hooks.
752 enum class VariableLocationKind { Global, Register, FrameIndex };
753
754 /// Extract target-specific address space information from a DIExpression.
755 /// Targets may strip address-space-encoding ops from the expression and
756 /// return the address space via \p TargetAddrSpace.
757 virtual const DIExpression *
758 adjustExpressionForTarget(const DIExpression *Expr,
759 std::optional<unsigned> &TargetAddrSpace) const {
760 return Expr;
761 }
762
763 /// Add target-specific attributes to a variable DIE (e.g.
764 /// DW_AT_address_class).
765 virtual void
766 addTargetVariableAttributes(DwarfCompileUnit &CU, DIE &Die,
767 std::optional<unsigned> TargetAddrSpace,
768 VariableLocationKind VarLocKind,
769 const GlobalVariable *GV = nullptr) const {}
770
771 //===--------------------------------------------------------------------===//
772 // Main entry points.
773 //
774 DwarfDebug(AsmPrinter *A);
775
776 ~DwarfDebug() override;
777
778 /// Emit all Dwarf sections that should come prior to the
779 /// content.
780 void beginModule(Module *M) override;
781
782 /// Emit all Dwarf sections that should come after the content.
783 void endModule() override;
784
785 /// Emits inital debug location directive. Returns instruction at which
786 /// the function prologue ends.
787 const MachineInstr *emitInitialLocDirective(const MachineFunction &MF,
788 unsigned CUID);
789
790 /// Process beginning of an instruction.
791 void beginInstruction(const MachineInstr *MI) override;
792
793 /// Process beginning of code alignment.
794 void beginCodeAlignment(const MachineBasicBlock &MBB) override;
795
796 /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
797 static uint64_t makeTypeSignature(StringRef Identifier);
798
799 /// Add a DIE to the set of types that we're going to pull into
800 /// type units.
801 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
802 DIE &Die, const DICompositeType *CTy);
803
804 /// Add a label so that arange data can be generated for it.
805 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(x: SCU); }
806
807 /// For symbols that have a size designated (e.g. common symbols),
808 /// this tracks that size.
809 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
810 SymSize[Sym] = Size;
811 }
812
813 /// Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
814 /// If not, we still might emit certain cases.
815 bool useAllLinkageNames() const { return UseAllLinkageNames; }
816
817 /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
818 /// standard DW_OP_form_tls_address opcode
819 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
820
821 /// Returns whether to use the DWARF2 format for bitfields instyead of the
822 /// DWARF4 format.
823 bool useDWARF2Bitfields() const { return UseDWARF2Bitfields; }
824
825 /// Returns whether to use inline strings.
826 bool useInlineStrings() const { return UseInlineStrings; }
827
828 /// Returns whether ranges section should be emitted.
829 bool useRangesSection() const { return UseRangesSection; }
830
831 /// Returns whether range encodings should be used for single entry range
832 /// lists.
833 bool alwaysUseRanges(const DwarfCompileUnit &) const;
834
835 // Returns whether novel exprloc addrx+offset encodings should be used to
836 // reduce debug_addr size.
837 bool useAddrOffsetExpressions() const {
838 return MinimizeAddr == MinimizeAddrInV5::Expressions;
839 }
840
841 // Returns whether addrx+offset LLVM extension form should be used to reduce
842 // debug_addr size.
843 bool useAddrOffsetForm() const {
844 return MinimizeAddr == MinimizeAddrInV5::Form;
845 }
846
847 /// Returns whether to use sections as labels rather than temp symbols.
848 bool useSectionsAsReferences() const {
849 return UseSectionsAsReferences;
850 }
851
852 /// Returns whether to generate DWARF v4 type units.
853 bool generateTypeUnits() const { return GenerateTypeUnits; }
854
855 // Experimental DWARF5 features.
856
857 /// Returns what kind (if any) of accelerator tables to emit.
858 AccelTableKind getAccelTableKind() const { return TheAccelTableKind; }
859
860 /// Seet TheAccelTableKind
861 void setTheAccelTableKind(AccelTableKind K) { TheAccelTableKind = K; };
862
863 bool useAppleExtensionAttributes() const {
864 return HasAppleExtensionAttributes;
865 }
866
867 /// Returns whether or not to change the current debug info for the
868 /// split dwarf proposal support.
869 bool useSplitDwarf() const { return HasSplitDwarf; }
870
871 /// Returns whether to generate a string offsets table with (possibly shared)
872 /// contributions from each CU and type unit. This implies the use of
873 /// DW_FORM_strx* indirect references with DWARF v5 and beyond. Note that
874 /// DW_FORM_GNU_str_index is also an indirect reference, but it is used with
875 /// a pre-DWARF v5 implementation of split DWARF sections, which uses a
876 /// monolithic string offsets table.
877 bool useSegmentedStringOffsetsTable() const {
878 return UseSegmentedStringOffsetsTable;
879 }
880
881 bool emitDebugEntryValues() const {
882 return EmitDebugEntryValues;
883 }
884
885 bool useOpConvert() const {
886 return EnableOpConvert;
887 }
888
889 bool shareAcrossDWOCUs() const;
890
891 /// Returns the Dwarf Version.
892 uint16_t getDwarfVersion() const;
893
894 /// Returns a suitable DWARF form to represent a section offset, i.e.
895 /// * DW_FORM_sec_offset for DWARF version >= 4;
896 /// * DW_FORM_data8 for 64-bit DWARFv3;
897 /// * DW_FORM_data4 for 32-bit DWARFv3 and DWARFv2.
898 dwarf::Form getDwarfSectionOffsetForm() const;
899
900 /// Returns the previous CU that was being updated
901 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
902 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
903
904 /// Terminate the line table by adding the last range label.
905 void terminateLineTable(const DwarfCompileUnit *CU);
906
907 /// Returns the entries for the .debug_loc section.
908 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
909
910 /// Emit an entry for the debug loc section. This can be used to
911 /// handle an entry that's going to be emitted into the debug loc section.
912 void emitDebugLocEntry(ByteStreamer &Streamer,
913 const DebugLocStream::Entry &Entry,
914 const DwarfCompileUnit *CU);
915
916 /// Emit the location for a debug loc entry, including the size header.
917 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
918 const DwarfCompileUnit *CU);
919
920 void addSubprogramNames(const DwarfUnit &Unit,
921 const DICompileUnit::DebugNameTableKind NameTableKind,
922 const DISubprogram *SP, DIE &Die);
923
924 AddressPool &getAddressPool() { return AddrPool; }
925
926 void addAccelName(const DwarfUnit &Unit,
927 const DICompileUnit::DebugNameTableKind NameTableKind,
928 StringRef Name, const DIE &Die);
929
930 void addAccelObjC(const DwarfUnit &Unit,
931 const DICompileUnit::DebugNameTableKind NameTableKind,
932 StringRef Name, const DIE &Die);
933
934 void addAccelNamespace(const DwarfUnit &Unit,
935 const DICompileUnit::DebugNameTableKind NameTableKind,
936 StringRef Name, const DIE &Die);
937
938 void addAccelType(const DwarfUnit &Unit,
939 const DICompileUnit::DebugNameTableKind NameTableKind,
940 StringRef Name, const DIE &Die, char Flags);
941
942 const MachineFunction *getCurrentFunction() const { return CurFn; }
943
944 /// A helper function to check whether the DIE for a given Scope is
945 /// going to be null.
946 bool isLexicalScopeDIENull(LexicalScope *Scope);
947
948 /// Find the matching DwarfCompileUnit for the given CU DIE.
949 DwarfCompileUnit *lookupCU(const DIE *Die) { return CUDieMap.lookup(Val: Die); }
950 const DwarfCompileUnit *lookupCU(const DIE *Die) const {
951 return CUDieMap.lookup(Val: Die);
952 }
953
954 /// Find the matching DwarfCompileUnit for the given SP referenced from SrcCU.
955 DwarfCompileUnit &getOrCreateAbstractSubprogramCU(const DISubprogram *SP,
956 DwarfCompileUnit &SrcCU);
957
958 unsigned getStringTypeLoc(const DIStringType *ST) const {
959 return StringTypeLocMap.lookup(Val: ST);
960 }
961
962 void addStringTypeLoc(const DIStringType *ST, unsigned Loc) {
963 assert(ST);
964 if (Loc)
965 StringTypeLocMap[ST] = Loc;
966 }
967
968 /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
969 ///
970 /// Returns whether we are "tuning" for a given debugger.
971 /// @{
972 bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
973 bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
974 bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
975 bool tuneForDBX() const { return DebuggerTuning == DebuggerKind::DBX; }
976 /// @}
977
978 const MCSymbol *getSectionLabel(const MCSection *S);
979 void insertSectionLabel(const MCSymbol *S);
980
981 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
982 const DbgValueLoc &Value,
983 DwarfExpression &DwarfExpr);
984
985 /// If the \p File has an MD5 checksum, return it as an MD5Result
986 /// allocated in the MCContext.
987 std::optional<MD5::MD5Result> getMD5AsBytes(const DIFile *File) const;
988
989 MDNodeSet &getLocalDeclsForScope(const DILocalScope *S) {
990 return LocalDeclsPerLS[S];
991 }
992
993 /// Sets the current DWARF5AccelTable to use.
994 void setCurrentDWARF5AccelTable(const DWARF5AccelTableKind Kind) {
995 switch (Kind) {
996 case DWARF5AccelTableKind::CU:
997 CurrentDebugNames = &AccelDebugNames;
998 break;
999 case DWARF5AccelTableKind::TU:
1000 CurrentDebugNames = &AccelTypeUnitsDebugNames;
1001 }
1002 }
1003 /// Returns either CU or TU DWARF5AccelTable.
1004 DWARF5AccelTable &getCurrentDWARF5AccelTable() { return *CurrentDebugNames; }
1005};
1006
1007} // end namespace llvm
1008
1009#endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
1010