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 "DebugLocEntry.h"
20 #include "DebugLocList.h"
21 #include "DwarfAccelTable.h"
22 #include "DwarfFile.h"
23 #include "llvm/ADT/DenseMap.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"
44 class DwarfCompileUnit;
48 class MachineModuleInfo;
50 //===----------------------------------------------------------------------===//
51 /// \brief This class is used to record source line correspondence.
53 unsigned Line; // Source line number.
54 unsigned Column; // Source column.
55 unsigned SourceID; // Source ID number.
56 MCSymbol *Label; // Label in code ID number.
58 SrcLineInfo(unsigned L, unsigned C, unsigned S, MCSymbol *label)
59 : Line(L), Column(C), SourceID(S), Label(label) {}
62 unsigned getLine() const { return Line; }
63 unsigned getColumn() const { return Column; }
64 unsigned getSourceID() const { return SourceID; }
65 MCSymbol *getLabel() const { return Label; }
68 //===----------------------------------------------------------------------===//
69 /// \brief This class is used to track local variable information.
71 /// - Variables whose location changes over time have a DotDebugLocOffset and
72 /// the other fields are not used.
74 /// - Variables that are described by multiple MMI table entries have multiple
75 /// expressions and frame indices.
77 DIVariable Var; /// Variable Descriptor.
78 SmallVector<DIExpression, 1> Expr; /// Complex address location expression.
79 DIE *TheDIE; /// Variable DIE.
80 unsigned DotDebugLocOffset; /// Offset in DotDebugLocEntries.
81 const MachineInstr *MInsn; /// DBG_VALUE instruction of the variable.
82 SmallVector<int, 1> FrameIndex; /// Frame index of the variable.
86 /// Construct a DbgVariable from a DIVariable.
87 DbgVariable(DIVariable V, DIExpression E, DwarfDebug *DD, int FI = ~0)
88 : Var(V), Expr(1, E), TheDIE(nullptr), DotDebugLocOffset(~0U),
89 MInsn(nullptr), DD(DD) {
90 FrameIndex.push_back(FI);
91 assert(!E || E->isValid());
94 /// Construct a DbgVariable from a DEBUG_VALUE.
95 /// AbstractVar may be NULL.
96 DbgVariable(const MachineInstr *DbgValue, DwarfDebug *DD)
97 : Var(DbgValue->getDebugVariable()),
98 Expr(1, DbgValue->getDebugExpression()), TheDIE(nullptr),
99 DotDebugLocOffset(~0U), MInsn(DbgValue), DD(DD) {
100 FrameIndex.push_back(~0);
104 DIVariable getVariable() const { return Var; }
105 const ArrayRef<DIExpression> getExpression() const { return Expr; }
106 void setDIE(DIE &D) { TheDIE = &D; }
107 DIE *getDIE() const { return TheDIE; }
108 void setDotDebugLocOffset(unsigned O) { DotDebugLocOffset = O; }
109 unsigned getDotDebugLocOffset() const { return DotDebugLocOffset; }
110 StringRef getName() const { return Var.getName(); }
111 const MachineInstr *getMInsn() const { return MInsn; }
112 const ArrayRef<int> getFrameIndex() const { return FrameIndex; }
114 void addMMIEntry(const DbgVariable &V) {
115 assert( DotDebugLocOffset == ~0U && !MInsn && "not an MMI entry");
116 assert(V.DotDebugLocOffset == ~0U && !V.MInsn && "not an MMI entry");
117 assert(V.Var == Var && "conflicting DIVariable");
119 if (V.getFrameIndex().back() != ~0) {
120 auto E = V.getExpression();
121 auto FI = V.getFrameIndex();
122 Expr.append(E.begin(), E.end());
123 FrameIndex.append(FI.begin(), FI.end());
125 assert(Expr.size() > 1
126 ? std::all_of(Expr.begin(), Expr.end(),
127 [](DIExpression &E) { return E.isBitPiece(); })
128 : (true && "conflicting locations for variable"));
131 // Translate tag to proper Dwarf tag.
132 dwarf::Tag getTag() const {
133 if (Var.getTag() == dwarf::DW_TAG_arg_variable)
134 return dwarf::DW_TAG_formal_parameter;
136 return dwarf::DW_TAG_variable;
138 /// \brief Return true if DbgVariable is artificial.
139 bool isArtificial() const {
140 if (Var.isArtificial())
142 if (getType().isArtificial())
147 bool isObjectPointer() const {
148 if (Var.isObjectPointer())
150 if (getType().isObjectPointer())
155 bool variableHasComplexAddress() const {
156 assert(Var && "Invalid complex DbgVariable!");
157 assert(Expr.size() == 1 &&
158 "variableHasComplexAddress() invoked on multi-FI variable");
159 return Expr.back().getNumElements() > 0;
161 bool isBlockByrefVariable() const;
162 DIType getType() const;
165 /// resolve - Look in the DwarfDebug map for the MDNode that
166 /// corresponds to the reference.
167 template <typename T> T resolve(DIRef<T> Ref) const;
171 /// \brief Helper used to pair up a symbol and its DWARF compile unit.
173 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
175 DwarfCompileUnit *CU;
178 /// \brief Collects and handles dwarf debug information.
179 class DwarfDebug : public AsmPrinterHandler {
180 // Target of Dwarf emission.
183 // Collected machine module information.
184 MachineModuleInfo *MMI;
186 // All DIEValues are allocated through this allocator.
187 BumpPtrAllocator DIEValueAllocator;
189 // Maps MDNode with its corresponding DwarfCompileUnit.
190 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
192 // Maps subprogram MDNode with its corresponding DwarfCompileUnit.
193 MapVector<const MDNode *, DwarfCompileUnit *> SPMap;
195 // Maps a CU DIE with its corresponding DwarfCompileUnit.
196 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
198 // List of all labels used in aranges generation.
199 std::vector<SymbolCU> ArangeLabels;
201 // Size of each symbol emitted (for those symbols that have a specific size).
202 DenseMap<const MCSymbol *, uint64_t> SymSize;
204 LexicalScopes LScopes;
206 // Collection of abstract variables.
207 DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
208 SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
210 // Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
211 // can refer to them in spite of insertions into this list.
212 SmallVector<DebugLocList, 4> DotDebugLocEntries;
214 // This is a collection of subprogram MDNodes that are processed to
216 SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
218 // Maps instruction with label emitted before instruction.
219 DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
221 // Maps instruction with label emitted after instruction.
222 DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
224 // History of DBG_VALUE and clobber instructions for each user variable.
225 // Variables are listed in order of appearance.
226 DbgValueHistoryMap DbgValues;
228 // Previous instruction's location information. This is used to determine
229 // label location to indicate scope boundries in dwarf debug info.
230 DebugLoc PrevInstLoc;
233 // This location indicates end of function prologue and beginning of function
235 DebugLoc PrologEndLoc;
237 // If nonnull, stores the current machine function we're processing.
238 const MachineFunction *CurFn;
240 // If nonnull, stores the current machine instruction we're processing.
241 const MachineInstr *CurMI;
243 // If nonnull, stores the CU in which the previous subprogram was contained.
244 const DwarfCompileUnit *PrevCU;
246 // As an optimization, there is no need to emit an entry in the directory
247 // table for the same directory as DW_AT_comp_dir.
248 StringRef CompilationDir;
250 // Holder for the file specific debug information.
251 DwarfFile InfoHolder;
253 // Holders for the various debug information flags that we might need to
254 // have exposed. See accessor functions below for description.
256 // Holder for imported entities.
257 typedef SmallVector<std::pair<const MDNode *, const MDNode *>, 32>
259 ImportedEntityMap ScopesWithImportedEntities;
261 // Map from MDNodes for user-defined types to the type units that describe
263 DenseMap<const MDNode *, const DwarfTypeUnit *> DwarfTypeUnits;
265 SmallVector<std::pair<std::unique_ptr<DwarfTypeUnit>, DICompositeType>, 1>
266 TypeUnitsUnderConstruction;
268 // Whether to emit the pubnames/pubtypes sections.
269 bool HasDwarfPubSections;
271 // Whether or not to use AT_ranges for compilation units.
274 // Whether we emitted a function into a section other than the default
276 bool UsedNonDefaultText;
278 // Whether to use the GNU TLS opcode (instead of the standard opcode).
279 bool UseGNUTLSOpcode;
281 // Version of dwarf we're emitting.
282 unsigned DwarfVersion;
284 // Maps from a type identifier to the actual MDNode.
285 DITypeIdentifierMap TypeIdentifierMap;
287 // DWARF5 Experimental Options
288 bool HasDwarfAccelTables;
291 // Separated Dwarf Variables
292 // In general these will all be for bits that are left in the
293 // original object file, rather than things that are meant
294 // to be in the .dwo sections.
296 // Holder for the skeleton information.
297 DwarfFile SkeletonHolder;
299 /// Store file names for type units under fission in a line table header that
300 /// will be emitted into debug_line.dwo.
301 // FIXME: replace this with a map from comp_dir to table so that we can emit
302 // multiple tables during LTO each of which uses directory 0, referencing the
303 // comp_dir of all the type units that use it.
304 MCDwarfDwoLineTable SplitTypeUnitFileTable;
306 // True iff there are multiple CUs in this module.
311 AddressPool AddrPool;
313 DwarfAccelTable AccelNames;
314 DwarfAccelTable AccelObjC;
315 DwarfAccelTable AccelNamespace;
316 DwarfAccelTable AccelTypes;
318 DenseMap<const Function *, DISubprogram> FunctionDIs;
320 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
322 const SmallVectorImpl<std::unique_ptr<DwarfUnit>> &getUnits() {
323 return InfoHolder.getUnits();
326 /// \brief Find abstract variable associated with Var.
327 DbgVariable *getExistingAbstractVariable(const DIVariable &DV,
328 DIVariable &Cleansed);
329 DbgVariable *getExistingAbstractVariable(const DIVariable &DV);
330 void createAbstractVariable(const DIVariable &DV, LexicalScope *Scope);
331 void ensureAbstractVariableIsCreated(const DIVariable &Var,
332 const MDNode *Scope);
333 void ensureAbstractVariableIsCreatedIfScoped(const DIVariable &Var,
334 const MDNode *Scope);
336 /// \brief Construct a DIE for this abstract scope.
337 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
339 /// \brief Compute the size and offset of a DIE given an incoming Offset.
340 unsigned computeSizeAndOffset(DIE *Die, unsigned Offset);
342 /// \brief Compute the size and offset of all the DIEs.
343 void computeSizeAndOffsets();
345 /// \brief Collect info for variables that were optimized out.
346 void collectDeadVariables();
348 void finishVariableDefinitions();
350 void finishSubprogramDefinitions();
352 /// \brief Finish off debug information after all functions have been
354 void finalizeModuleInfo();
356 /// \brief Emit the debug info section.
357 void emitDebugInfo();
359 /// \brief Emit the abbreviation section.
360 void emitAbbreviations();
362 /// \brief Emit a specified accelerator table.
363 void emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
364 StringRef TableName);
366 /// \brief Emit visible names into a hashed accelerator table section.
367 void emitAccelNames();
369 /// \brief Emit objective C classes and categories into a hashed
370 /// accelerator table section.
371 void emitAccelObjC();
373 /// \brief Emit namespace dies into a hashed accelerator table.
374 void emitAccelNamespaces();
376 /// \brief Emit type dies into a hashed accelerator table.
377 void emitAccelTypes();
379 /// \brief Emit visible names into a debug pubnames section.
380 /// \param GnuStyle determines whether or not we want to emit
381 /// additional information into the table ala newer gcc for gdb
383 void emitDebugPubNames(bool GnuStyle = false);
385 /// \brief Emit visible types into a debug pubtypes section.
386 /// \param GnuStyle determines whether or not we want to emit
387 /// additional information into the table ala newer gcc for gdb
389 void emitDebugPubTypes(bool GnuStyle = false);
391 void emitDebugPubSection(
392 bool GnuStyle, const MCSection *PSec, StringRef Name,
393 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
395 /// \brief Emit visible names into a debug str section.
398 /// \brief Emit visible names into a debug loc section.
401 /// \brief Emit visible names into a debug loc dwo section.
402 void emitDebugLocDWO();
404 /// \brief Emit visible names into a debug aranges section.
405 void emitDebugARanges();
407 /// \brief Emit visible names into a debug ranges section.
408 void emitDebugRanges();
410 /// \brief Emit inline info using custom format.
411 void emitDebugInlineInfo();
413 /// DWARF 5 Experimental Split Dwarf Emitters
415 /// \brief Initialize common features of skeleton units.
416 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
417 std::unique_ptr<DwarfUnit> NewU);
419 /// \brief Construct the split debug info compile unit for the debug info
421 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
423 /// \brief Construct the split debug info compile unit for the debug info
425 DwarfTypeUnit &constructSkeletonTU(DwarfTypeUnit &TU);
427 /// \brief Emit the debug info dwo section.
428 void emitDebugInfoDWO();
430 /// \brief Emit the debug abbrev dwo section.
431 void emitDebugAbbrevDWO();
433 /// \brief Emit the debug line dwo section.
434 void emitDebugLineDWO();
436 /// \brief Emit the debug str dwo section.
437 void emitDebugStrDWO();
439 /// Flags to let the linker know we have emitted new style pubnames. Only
440 /// emit it here if we don't have a skeleton CU for split dwarf.
441 void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
443 /// \brief Create new DwarfCompileUnit for the given metadata node with tag
444 /// DW_TAG_compile_unit.
445 DwarfCompileUnit &constructDwarfCompileUnit(DICompileUnit DIUnit);
447 /// \brief Construct imported_module or imported_declaration DIE.
448 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
451 /// \brief Register a source line with debug info. Returns the unique
452 /// label that was emitted and which provides correspondence to the
453 /// source line list.
454 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
457 /// \brief Indentify instructions that are marking the beginning of or
458 /// ending of a scope.
459 void identifyScopeMarkers();
461 /// \brief Populate LexicalScope entries with variables' info.
462 void collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
463 SmallPtrSetImpl<const MDNode *> &ProcessedVars);
465 /// \brief Build the location list for all DBG_VALUEs in the
466 /// function that describe the same variable.
467 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
468 const DbgValueHistoryMap::InstrRanges &Ranges);
470 /// \brief Collect variable information from the side table maintained
472 void collectVariableInfoFromMMITable(SmallPtrSetImpl<const MDNode *> &P);
474 /// \brief Ensure that a label will be emitted before MI.
475 void requestLabelBeforeInsn(const MachineInstr *MI) {
476 LabelsBeforeInsn.insert(std::make_pair(MI, nullptr));
479 /// \brief Ensure that a label will be emitted after MI.
480 void requestLabelAfterInsn(const MachineInstr *MI) {
481 LabelsAfterInsn.insert(std::make_pair(MI, nullptr));
485 //===--------------------------------------------------------------------===//
486 // Main entry points.
488 DwarfDebug(AsmPrinter *A, Module *M);
490 ~DwarfDebug() override;
492 /// \brief Emit all Dwarf sections that should come prior to the
496 /// \brief Emit all Dwarf sections that should come after the content.
497 void endModule() override;
499 /// \brief Gather pre-function debug information.
500 void beginFunction(const MachineFunction *MF) override;
502 /// \brief Gather and emit post-function debug information.
503 void endFunction(const MachineFunction *MF) override;
505 /// \brief Process beginning of an instruction.
506 void beginInstruction(const MachineInstr *MI) override;
508 /// \brief Process end of an instruction.
509 void endInstruction() override;
511 /// \brief Add a DIE to the set of types that we're going to pull into
513 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
514 DIE &Die, DICompositeType CTy);
516 /// \brief Add a label so that arange data can be generated for it.
517 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
519 /// \brief For symbols that have a size designated (e.g. common symbols),
520 /// this tracks that size.
521 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
525 /// \brief Returns whether to use DW_OP_GNU_push_tls_address, instead of the
526 /// standard DW_OP_form_tls_address opcode
527 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
529 // Experimental DWARF5 features.
531 /// \brief Returns whether or not to emit tables that dwarf consumers can
532 /// use to accelerate lookup.
533 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
535 /// \brief Returns whether or not to change the current debug info for the
536 /// split dwarf proposal support.
537 bool useSplitDwarf() const { return HasSplitDwarf; }
539 /// Returns the Dwarf Version.
540 unsigned getDwarfVersion() const { return DwarfVersion; }
542 /// Returns the previous CU that was being updated
543 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
544 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
546 /// Returns the entries for the .debug_loc section.
547 const SmallVectorImpl<DebugLocList> &
548 getDebugLocEntries() const {
549 return DotDebugLocEntries;
552 /// \brief Emit an entry for the debug loc section. This can be used to
553 /// handle an entry that's going to be emitted into the debug loc section.
554 void emitDebugLocEntry(ByteStreamer &Streamer,
555 const DebugLocEntry &Entry);
556 /// \brief emit a single value for the debug loc section.
557 void emitDebugLocValue(ByteStreamer &Streamer,
558 const DebugLocEntry::Value &Value,
559 unsigned PieceOffsetInBits = 0);
560 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
561 void emitLocPieces(ByteStreamer &Streamer,
562 const DITypeIdentifierMap &Map,
563 ArrayRef<DebugLocEntry::Value> Values);
565 /// Emit the location for a debug loc entry, including the size header.
566 void emitDebugLocEntryLocation(const DebugLocEntry &Entry);
568 /// Find the MDNode for the given reference.
569 template <typename T> T resolve(DIRef<T> Ref) const {
570 return Ref.resolve(TypeIdentifierMap);
572 template <typename T> T *resolve(TypedDebugNodeRef<T> Ref) const {
573 return Ref.resolve(TypeIdentifierMap);
576 /// \brief Return the TypeIdentifierMap.
577 const DITypeIdentifierMap &getTypeIdentifierMap() const {
578 return TypeIdentifierMap;
581 /// Find the DwarfCompileUnit for the given CU Die.
582 DwarfCompileUnit *lookupUnit(const DIE *CU) const {
583 return CUDieMap.lookup(CU);
585 /// isSubprogramContext - Return true if Context is either a subprogram
586 /// or another context nested inside a subprogram.
587 bool isSubprogramContext(const MDNode *Context);
589 void addSubprogramNames(DISubprogram SP, DIE &Die);
591 AddressPool &getAddressPool() { return AddrPool; }
593 void addAccelName(StringRef Name, const DIE &Die);
595 void addAccelObjC(StringRef Name, const DIE &Die);
597 void addAccelNamespace(StringRef Name, const DIE &Die);
599 void addAccelType(StringRef Name, const DIE &Die, char Flags);
601 const MachineFunction *getCurrentFunction() const { return CurFn; }
603 iterator_range<ImportedEntityMap::const_iterator>
604 findImportedEntitiesForScope(const MDNode *Scope) const {
605 return make_range(std::equal_range(
606 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
607 std::pair<const MDNode *, const MDNode *>(Scope, nullptr),
611 /// \brief A helper function to check whether the DIE for a given Scope is
612 /// going to be null.
613 bool isLexicalScopeDIENull(LexicalScope *Scope);
615 /// \brief Return Label preceding the instruction.
616 MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
618 /// \brief Return Label immediately following the instruction.
619 MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
621 // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
623 SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
624 return ProcessedSPNodes;
627 } // End of namespace llvm