1 //===-- llvm/CodeGen/DwarfDebug.h - Dwarf Debug Framework ------*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
15 #define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
17 #include "AsmPrinterHandler.h"
18 #include "DbgValueHistoryCalculator.h"
19 #include "DebugLocStream.h"
20 #include "DwarfAccelTable.h"
21 #include "DwarfFile.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/DenseSet.h"
24 #include "llvm/ADT/FoldingSet.h"
25 #include "llvm/ADT/MapVector.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/CodeGen/DIE.h"
29 #include "llvm/CodeGen/LexicalScopes.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DebugLoc.h"
33 #include "llvm/MC/MCDwarf.h"
34 #include "llvm/MC/MachineLocation.h"
35 #include "llvm/Support/Allocator.h"
45 class DwarfCompileUnit;
49 class MachineModuleInfo;
51 //===----------------------------------------------------------------------===//
52 /// This class is used to track local variable information.
54 /// Variables can be created from allocas, in which case they're generated from
55 /// the MMI table. Such variables can have multiple expressions and frame
56 /// indices. The \a Expr and \a FrameIndices array must match.
58 /// Variables can be created from \c DBG_VALUE instructions. Those whose
59 /// location changes over time use \a DebugLocListIndex, while those with a
60 /// single instruction use \a MInsn and (optionally) a single entry of \a Expr.
62 /// Variables that have been optimized out use none of these fields.
64 const DILocalVariable *Var; /// Variable Descriptor.
65 const DILocation *IA; /// Inlined at location.
66 SmallVector<const DIExpression *, 1> Expr; /// Complex address.
67 DIE *TheDIE = nullptr; /// Variable DIE.
68 unsigned DebugLocListIndex = ~0u; /// Offset in DebugLocs.
69 const MachineInstr *MInsn = nullptr; /// DBG_VALUE instruction.
70 SmallVector<int, 1> FrameIndex; /// Frame index.
74 /// Construct a DbgVariable.
76 /// Creates a variable without any DW_AT_location. Call \a initializeMMI()
77 /// for MMI entries, or \a initializeDbgValue() for DBG_VALUE instructions.
78 DbgVariable(const DILocalVariable *V, const DILocation *IA, DwarfDebug *DD)
79 : Var(V), IA(IA), DD(DD) {}
81 /// Initialize from the MMI table.
82 void initializeMMI(const DIExpression *E, int FI) {
83 assert(Expr.empty() && "Already initialized?");
84 assert(FrameIndex.empty() && "Already initialized?");
85 assert(!MInsn && "Already initialized?");
87 assert((!E || E->isValid()) && "Expected valid expression");
88 assert(~FI && "Expected valid index");
91 FrameIndex.push_back(FI);
94 /// Initialize from a DBG_VALUE instruction.
95 void initializeDbgValue(const MachineInstr *DbgValue) {
96 assert(Expr.empty() && "Already initialized?");
97 assert(FrameIndex.empty() && "Already initialized?");
98 assert(!MInsn && "Already initialized?");
100 assert(Var == DbgValue->getDebugVariable() && "Wrong variable");
101 assert(IA == DbgValue->getDebugLoc()->getInlinedAt() && "Wrong inlined-at");
104 if (auto *E = DbgValue->getDebugExpression())
105 if (E->getNumElements())
110 const DILocalVariable *getVariable() const { return Var; }
111 const DILocation *getInlinedAt() const { return IA; }
112 ArrayRef<const DIExpression *> getExpression() const { return Expr; }
113 void setDIE(DIE &D) { TheDIE = &D; }
114 DIE *getDIE() const { return TheDIE; }
115 void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
116 unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
117 StringRef getName() const { return Var->getName(); }
118 const MachineInstr *getMInsn() const { return MInsn; }
119 ArrayRef<int> getFrameIndex() const { return FrameIndex; }
121 void addMMIEntry(const DbgVariable &V) {
122 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
123 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
124 assert(V.Var == Var && "conflicting variable");
125 assert(V.IA == IA && "conflicting inlined-at location");
127 assert(!FrameIndex.empty() && "Expected an MMI entry");
128 assert(!V.FrameIndex.empty() && "Expected an MMI entry");
129 assert(Expr.size() == FrameIndex.size() && "Mismatched expressions");
130 assert(V.Expr.size() == V.FrameIndex.size() && "Mismatched expressions");
132 Expr.append(V.Expr.begin(), V.Expr.end());
133 FrameIndex.append(V.FrameIndex.begin(), V.FrameIndex.end());
134 assert(std::all_of(Expr.begin(), Expr.end(), [](const DIExpression *E) {
135 return E && E->isBitPiece();
136 }) && "conflicting locations for variable");
139 // Translate tag to proper Dwarf tag.
140 dwarf::Tag getTag() const {
141 // FIXME: Why don't we just infer this tag and store it all along?
142 if (Var->isParameter())
143 return dwarf::DW_TAG_formal_parameter;
145 return dwarf::DW_TAG_variable;
147 /// Return true if DbgVariable is artificial.
148 bool isArtificial() const {
149 if (Var->isArtificial())
151 if (getType()->isArtificial())
156 bool isObjectPointer() const {
157 if (Var->isObjectPointer())
159 if (getType()->isObjectPointer())
164 bool hasComplexAddress() const {
165 assert(MInsn && "Expected DBG_VALUE, not MMI variable");
166 assert(FrameIndex.empty() && "Expected DBG_VALUE, not MMI variable");
168 (Expr.empty() || (Expr.size() == 1 && Expr.back()->getNumElements())) &&
169 "Invalid Expr for DBG_VALUE");
170 return !Expr.empty();
172 bool isBlockByrefVariable() const;
173 const DIType *getType() const;
176 /// Look in the DwarfDebug map for the MDNode that
177 /// corresponds to the reference.
178 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const;
182 /// Helper used to pair up a symbol and its DWARF compile unit.
184 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
186 DwarfCompileUnit *CU;
189 /// Identify a debugger for "tuning" the debug info.
191 /// The "debugger tuning" concept allows us to present a more intuitive
192 /// interface that unpacks into different sets of defaults for the various
193 /// individual feature-flag settings, that suit the preferences of the
194 /// various debuggers. However, it's worth remembering that debuggers are
195 /// not the only consumers of debug info, and some variations in DWARF might
196 /// better be treated as target/platform issues. Fundamentally,
197 /// o if the feature is useful (or not) to a particular debugger, regardless
198 /// of the target, that's a tuning decision;
199 /// o if the feature is useful (or not) on a particular platform, regardless
200 /// of the debugger, that's a target decision.
201 /// It's not impossible to see both factors in some specific case.
203 /// The "tuning" should be used to set defaults for individual feature flags
204 /// in DwarfDebug; if a given feature has a more specific command-line option,
205 /// that option should take precedence over the tuning.
206 enum class DebuggerKind {
207 Default, // No specific tuning requested.
208 GDB, // Tune debug info for gdb.
209 LLDB, // Tune debug info for lldb.
210 SCE // Tune debug info for SCE targets (e.g. PS4).
213 /// Collects and handles dwarf debug information.
214 class DwarfDebug : public AsmPrinterHandler {
215 /// Target of Dwarf emission.
218 /// Collected machine module information.
219 MachineModuleInfo *MMI;
221 /// All DIEValues are allocated through this allocator.
222 BumpPtrAllocator DIEValueAllocator;
224 /// Maps MDNode with its corresponding DwarfCompileUnit.
225 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
227 /// Maps subprogram MDNode with its corresponding DwarfCompileUnit.
228 MapVector<const MDNode *, DwarfCompileUnit *> SPMap;
230 /// Maps a CU DIE with its corresponding DwarfCompileUnit.
231 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
233 /// List of all labels used in aranges generation.
234 std::vector<SymbolCU> ArangeLabels;
236 /// Size of each symbol emitted (for those symbols that have a specific size).
237 DenseMap<const MCSymbol *, uint64_t> SymSize;
239 LexicalScopes LScopes;
241 /// Collection of abstract variables.
242 DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
243 SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
245 /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
246 /// can refer to them in spite of insertions into this list.
247 DebugLocStream DebugLocs;
249 /// This is a collection of subprogram MDNodes that are processed to
251 SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
253 /// Maps instruction with label emitted before instruction.
254 DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
256 /// Maps instruction with label emitted after instruction.
257 DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
259 /// History of DBG_VALUE and clobber instructions for each user
260 /// variable. Variables are listed in order of appearance.
261 DbgValueHistoryMap DbgValues;
263 /// Previous instruction's location information. This is used to
264 /// determine label location to indicate scope boundries in dwarf
266 DebugLoc PrevInstLoc;
269 /// This location indicates end of function prologue and beginning of
271 DebugLoc PrologEndLoc;
273 /// If nonnull, stores the current machine function we're processing.
274 const MachineFunction *CurFn;
276 /// If nonnull, stores the current machine instruction we're processing.
277 const MachineInstr *CurMI;
279 /// If nonnull, stores the CU in which the previous subprogram was contained.
280 const DwarfCompileUnit *PrevCU;
282 /// As an optimization, there is no need to emit an entry in the directory
283 /// table for the same directory as DW_AT_comp_dir.
284 StringRef CompilationDir;
286 /// Holder for the file specific debug information.
287 DwarfFile InfoHolder;
289 /// Holders for the various debug information flags that we might need to
290 /// have exposed. See accessor functions below for description.
292 /// Map from MDNodes for user-defined types to the type units that
294 DenseMap<const MDNode *, const DwarfTypeUnit *> DwarfTypeUnits;
297 std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
298 TypeUnitsUnderConstruction;
300 /// Whether to emit the pubnames/pubtypes sections.
301 bool HasDwarfPubSections;
303 /// Whether to use the GNU TLS opcode (instead of the standard opcode).
304 bool UseGNUTLSOpcode;
306 /// Whether to emit DW_AT_[MIPS_]linkage_name.
307 bool UseLinkageNames;
309 /// Version of dwarf we're emitting.
310 unsigned DwarfVersion;
312 /// Maps from a type identifier to the actual MDNode.
313 DITypeIdentifierMap TypeIdentifierMap;
315 /// DWARF5 Experimental Options
317 bool HasDwarfAccelTables;
320 /// Separated Dwarf Variables
321 /// In general these will all be for bits that are left in the
322 /// original object file, rather than things that are meant
323 /// to be in the .dwo sections.
325 /// Holder for the skeleton information.
326 DwarfFile SkeletonHolder;
328 /// Store file names for type units under fission in a line table
329 /// header that will be emitted into debug_line.dwo.
330 // FIXME: replace this with a map from comp_dir to table so that we
331 // can emit multiple tables during LTO each of which uses directory
332 // 0, referencing the comp_dir of all the type units that use it.
333 MCDwarfDwoLineTable SplitTypeUnitFileTable;
336 /// True iff there are multiple CUs in this module.
340 AddressPool AddrPool;
342 DwarfAccelTable AccelNames;
343 DwarfAccelTable AccelObjC;
344 DwarfAccelTable AccelNamespace;
345 DwarfAccelTable AccelTypes;
347 // Identify a debugger for "tuning" the debug info.
348 DebuggerKind DebuggerTuning;
350 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
352 const SmallVectorImpl<std::unique_ptr<DwarfUnit>> &getUnits() {
353 return InfoHolder.getUnits();
356 typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
358 /// Find abstract variable associated with Var.
359 DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
360 const DILocalVariable *&Cleansed);
361 DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
362 void createAbstractVariable(const DILocalVariable *DV, LexicalScope *Scope);
363 void ensureAbstractVariableIsCreated(InlinedVariable Var,
364 const MDNode *Scope);
365 void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var,
366 const MDNode *Scope);
368 DbgVariable *createConcreteVariable(LexicalScope &Scope, InlinedVariable IV);
370 /// Construct a DIE for this abstract scope.
371 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
373 /// Collect info for variables that were optimized out.
374 void collectDeadVariables();
376 void finishVariableDefinitions();
378 void finishSubprogramDefinitions();
380 /// Finish off debug information after all functions have been
382 void finalizeModuleInfo();
384 /// Emit the debug info section.
385 void emitDebugInfo();
387 /// Emit the abbreviation section.
388 void emitAbbreviations();
390 /// Emit a specified accelerator table.
391 void emitAccel(DwarfAccelTable &Accel, MCSection *Section,
392 StringRef TableName);
394 /// Emit visible names into a hashed accelerator table section.
395 void emitAccelNames();
397 /// Emit objective C classes and categories into a hashed
398 /// accelerator table section.
399 void emitAccelObjC();
401 /// Emit namespace dies into a hashed accelerator table.
402 void emitAccelNamespaces();
404 /// Emit type dies into a hashed accelerator table.
405 void emitAccelTypes();
407 /// Emit visible names into a debug pubnames section.
408 /// \param GnuStyle determines whether or not we want to emit
409 /// additional information into the table ala newer gcc for gdb
411 void emitDebugPubNames(bool GnuStyle = false);
413 /// Emit visible types into a debug pubtypes section.
414 /// \param GnuStyle determines whether or not we want to emit
415 /// additional information into the table ala newer gcc for gdb
417 void emitDebugPubTypes(bool GnuStyle = false);
419 void emitDebugPubSection(
420 bool GnuStyle, MCSection *PSec, StringRef Name,
421 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
423 /// Emit visible names into a debug str section.
426 /// Emit visible names into a debug loc section.
429 /// Emit visible names into a debug loc dwo section.
430 void emitDebugLocDWO();
432 /// Emit visible names into a debug aranges section.
433 void emitDebugARanges();
435 /// Emit visible names into a debug ranges section.
436 void emitDebugRanges();
438 /// DWARF 5 Experimental Split Dwarf Emitters
440 /// Initialize common features of skeleton units.
441 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
442 std::unique_ptr<DwarfUnit> NewU);
444 /// Construct the split debug info compile unit for the debug info
446 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
448 /// Emit the debug info dwo section.
449 void emitDebugInfoDWO();
451 /// Emit the debug abbrev dwo section.
452 void emitDebugAbbrevDWO();
454 /// Emit the debug line dwo section.
455 void emitDebugLineDWO();
457 /// Emit the debug str dwo section.
458 void emitDebugStrDWO();
460 /// Flags to let the linker know we have emitted new style pubnames. Only
461 /// emit it here if we don't have a skeleton CU for split dwarf.
462 void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
464 /// Create new DwarfCompileUnit for the given metadata node with tag
465 /// DW_TAG_compile_unit.
466 DwarfCompileUnit &constructDwarfCompileUnit(const DICompileUnit *DIUnit);
468 /// Construct imported_module or imported_declaration DIE.
469 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
470 const DIImportedEntity *N);
472 /// Register a source line with debug info. Returns the unique
473 /// label that was emitted and which provides correspondence to the
474 /// source line list.
475 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
478 /// Indentify instructions that are marking the beginning of or
479 /// ending of a scope.
480 void identifyScopeMarkers();
482 /// Populate LexicalScope entries with variables' info.
483 void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
484 DenseSet<InlinedVariable> &ProcessedVars);
486 /// Build the location list for all DBG_VALUEs in the
487 /// function that describe the same variable.
488 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
489 const DbgValueHistoryMap::InstrRanges &Ranges);
491 /// Collect variable information from the side table maintained
493 void collectVariableInfoFromMMITable(DenseSet<InlinedVariable> &P);
495 /// Ensure that a label will be emitted before MI.
496 void requestLabelBeforeInsn(const MachineInstr *MI) {
497 LabelsBeforeInsn.insert(std::make_pair(MI, nullptr));
500 /// Ensure that a label will be emitted after MI.
501 void requestLabelAfterInsn(const MachineInstr *MI) {
502 LabelsAfterInsn.insert(std::make_pair(MI, nullptr));
506 //===--------------------------------------------------------------------===//
507 // Main entry points.
509 DwarfDebug(AsmPrinter *A, Module *M);
511 ~DwarfDebug() override;
513 /// Emit all Dwarf sections that should come prior to the
517 /// Emit all Dwarf sections that should come after the content.
518 void endModule() override;
520 /// Gather pre-function debug information.
521 void beginFunction(const MachineFunction *MF) override;
523 /// Gather and emit post-function debug information.
524 void endFunction(const MachineFunction *MF) override;
526 /// Process beginning of an instruction.
527 void beginInstruction(const MachineInstr *MI) override;
529 /// Process end of an instruction.
530 void endInstruction() override;
532 /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
533 static uint64_t makeTypeSignature(StringRef Identifier);
535 /// Add a DIE to the set of types that we're going to pull into
537 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
538 DIE &Die, const DICompositeType *CTy);
540 /// Add a label so that arange data can be generated for it.
541 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
543 /// For symbols that have a size designated (e.g. common symbols),
544 /// this tracks that size.
545 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
549 /// Returns whether to emit DW_AT_[MIPS_]linkage_name.
550 bool useLinkageNames() const { return UseLinkageNames; }
552 /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
553 /// standard DW_OP_form_tls_address opcode
554 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
556 /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
558 /// Returns whether we are "tuning" for a given debugger.
560 bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
561 bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
562 bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
565 // Experimental DWARF5 features.
567 /// Returns whether or not to emit tables that dwarf consumers can
568 /// use to accelerate lookup.
569 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
571 /// Returns whether or not to change the current debug info for the
572 /// split dwarf proposal support.
573 bool useSplitDwarf() const { return HasSplitDwarf; }
575 /// Returns the Dwarf Version.
576 unsigned getDwarfVersion() const { return DwarfVersion; }
578 /// Returns the previous CU that was being updated
579 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
580 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
582 /// Returns the entries for the .debug_loc section.
583 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
585 /// Emit an entry for the debug loc section. This can be used to
586 /// handle an entry that's going to be emitted into the debug loc section.
587 void emitDebugLocEntry(ByteStreamer &Streamer,
588 const DebugLocStream::Entry &Entry);
590 /// Emit the location for a debug loc entry, including the size header.
591 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
593 /// Find the MDNode for the given reference.
594 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
595 return Ref.resolve(TypeIdentifierMap);
598 /// Return the TypeIdentifierMap.
599 const DITypeIdentifierMap &getTypeIdentifierMap() const {
600 return TypeIdentifierMap;
603 /// Find the DwarfCompileUnit for the given CU Die.
604 DwarfCompileUnit *lookupUnit(const DIE *CU) const {
605 return CUDieMap.lookup(CU);
608 void addSubprogramNames(const DISubprogram *SP, DIE &Die);
610 AddressPool &getAddressPool() { return AddrPool; }
612 void addAccelName(StringRef Name, const DIE &Die);
614 void addAccelObjC(StringRef Name, const DIE &Die);
616 void addAccelNamespace(StringRef Name, const DIE &Die);
618 void addAccelType(StringRef Name, const DIE &Die, char Flags);
620 const MachineFunction *getCurrentFunction() const { return CurFn; }
622 /// A helper function to check whether the DIE for a given Scope is
623 /// going to be null.
624 bool isLexicalScopeDIENull(LexicalScope *Scope);
626 /// Return Label preceding the instruction.
627 MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
629 /// Return Label immediately following the instruction.
630 MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
632 // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
634 SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
635 return ProcessedSPNodes;
638 } // End of namespace llvm