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 DIVariable Var; // Variable Descriptor.
72 DIExpression Expr; // Complex address location expression.
73 DIE *TheDIE; // Variable DIE.
74 unsigned DotDebugLocOffset; // Offset in DotDebugLocEntries.
75 const MachineInstr *MInsn; // DBG_VALUE instruction of the variable.
80 /// Construct a DbgVariable from a DIVariable.
81 DbgVariable(DIVariable V, DIExpression E, DwarfDebug *DD)
82 : Var(V), Expr(E), TheDIE(nullptr), DotDebugLocOffset(~0U),
83 MInsn(nullptr), FrameIndex(~0), DD(DD) {
84 assert(Var.Verify() && Expr.Verify());
87 /// Construct a DbgVariable from a DEBUG_VALUE.
88 /// AbstractVar may be NULL.
89 DbgVariable(const MachineInstr *DbgValue, DwarfDebug *DD)
90 : Var(DbgValue->getDebugVariable()), Expr(DbgValue->getDebugExpression()),
91 TheDIE(nullptr), DotDebugLocOffset(~0U), MInsn(DbgValue),
92 FrameIndex(~0), DD(DD) {}
95 DIVariable getVariable() const { return Var; }
96 DIExpression getExpression() const { return Expr; }
97 void setDIE(DIE &D) { TheDIE = &D; }
98 DIE *getDIE() const { return TheDIE; }
99 void setDotDebugLocOffset(unsigned O) { DotDebugLocOffset = O; }
100 unsigned getDotDebugLocOffset() const { return DotDebugLocOffset; }
101 StringRef getName() const { return Var.getName(); }
102 const MachineInstr *getMInsn() const { return MInsn; }
103 int getFrameIndex() const { return FrameIndex; }
104 void setFrameIndex(int FI) { FrameIndex = FI; }
105 // Translate tag to proper Dwarf tag.
106 dwarf::Tag getTag() const {
107 if (Var.getTag() == dwarf::DW_TAG_arg_variable)
108 return dwarf::DW_TAG_formal_parameter;
110 return dwarf::DW_TAG_variable;
112 /// \brief Return true if DbgVariable is artificial.
113 bool isArtificial() const {
114 if (Var.isArtificial())
116 if (getType().isArtificial())
121 bool isObjectPointer() const {
122 if (Var.isObjectPointer())
124 if (getType().isObjectPointer())
129 bool variableHasComplexAddress() const {
130 assert(Var.isVariable() && "Invalid complex DbgVariable!");
131 return Expr.getNumElements() > 0;
133 bool isBlockByrefVariable() const;
134 unsigned getNumAddrElements() const {
135 assert(Var.isVariable() && "Invalid complex DbgVariable!");
136 return Expr.getNumElements();
138 uint64_t getAddrElement(unsigned i) const { return Expr.getElement(i); }
139 DIType getType() const;
142 /// resolve - Look in the DwarfDebug map for the MDNode that
143 /// corresponds to the reference.
144 template <typename T> T resolve(DIRef<T> Ref) const;
148 /// \brief Helper used to pair up a symbol and its DWARF compile unit.
150 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
152 DwarfCompileUnit *CU;
155 /// \brief Collects and handles dwarf debug information.
156 class DwarfDebug : public AsmPrinterHandler {
157 // Target of Dwarf emission.
160 // Collected machine module information.
161 MachineModuleInfo *MMI;
163 // All DIEValues are allocated through this allocator.
164 BumpPtrAllocator DIEValueAllocator;
166 // Maps MDNode with its corresponding DwarfCompileUnit.
167 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
169 // Maps subprogram MDNode with its corresponding DwarfCompileUnit.
170 MapVector<const MDNode *, DwarfCompileUnit *> SPMap;
172 // Maps a CU DIE with its corresponding DwarfCompileUnit.
173 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
175 // List of all labels used in aranges generation.
176 std::vector<SymbolCU> ArangeLabels;
178 // Size of each symbol emitted (for those symbols that have a specific size).
179 DenseMap<const MCSymbol *, uint64_t> SymSize;
181 // Provides a unique id per text section.
182 typedef DenseMap<const MCSection *, SmallVector<SymbolCU, 8> > SectionMapType;
183 SectionMapType SectionMap;
185 LexicalScopes LScopes;
187 // Collection of abstract variables.
188 DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
189 SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
191 // Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
192 // can refer to them in spite of insertions into this list.
193 SmallVector<DebugLocList, 4> DotDebugLocEntries;
195 // This is a collection of subprogram MDNodes that are processed to
197 SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
199 // Maps instruction with label emitted before instruction.
200 DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
202 // Maps instruction with label emitted after instruction.
203 DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
205 // History of DBG_VALUE and clobber instructions for each user variable.
206 // Variables are listed in order of appearance.
207 DbgValueHistoryMap DbgValues;
209 // Previous instruction's location information. This is used to determine
210 // label location to indicate scope boundries in dwarf debug info.
211 DebugLoc PrevInstLoc;
214 // This location indicates end of function prologue and beginning of function
216 DebugLoc PrologEndLoc;
218 // If nonnull, stores the current machine function we're processing.
219 const MachineFunction *CurFn;
221 // If nonnull, stores the current machine instruction we're processing.
222 const MachineInstr *CurMI;
224 // If nonnull, stores the CU in which the previous subprogram was contained.
225 const DwarfCompileUnit *PrevCU;
227 // Section Symbols: these are assembler temporary labels that are emitted at
228 // the beginning of each supported dwarf section. These are used to form
229 // section offsets and are created by EmitSectionLabels.
230 MCSymbol *DwarfInfoSectionSym, *DwarfAbbrevSectionSym;
231 MCSymbol *DwarfStrSectionSym, *TextSectionSym, *DwarfDebugRangeSectionSym;
232 MCSymbol *DwarfDebugLocSectionSym, *DwarfLineSectionSym, *DwarfAddrSectionSym;
233 MCSymbol *FunctionBeginSym, *FunctionEndSym;
234 MCSymbol *DwarfInfoDWOSectionSym, *DwarfAbbrevDWOSectionSym;
235 MCSymbol *DwarfTypesDWOSectionSym;
236 MCSymbol *DwarfStrDWOSectionSym;
237 MCSymbol *DwarfGnuPubNamesSectionSym, *DwarfGnuPubTypesSectionSym;
239 // As an optimization, there is no need to emit an entry in the directory
240 // table for the same directory as DW_AT_comp_dir.
241 StringRef CompilationDir;
243 // Counter for assigning globally unique IDs for ranges.
244 unsigned GlobalRangeCount;
246 // Holder for the file specific debug information.
247 DwarfFile InfoHolder;
249 // Holders for the various debug information flags that we might need to
250 // have exposed. See accessor functions below for description.
252 // Holder for imported entities.
253 typedef SmallVector<std::pair<const MDNode *, const MDNode *>, 32>
255 ImportedEntityMap ScopesWithImportedEntities;
257 // Map from MDNodes for user-defined types to the type units that describe
259 DenseMap<const MDNode *, const DwarfTypeUnit *> DwarfTypeUnits;
261 SmallVector<std::pair<std::unique_ptr<DwarfTypeUnit>, DICompositeType>, 1> TypeUnitsUnderConstruction;
263 // Whether to emit the pubnames/pubtypes sections.
264 bool HasDwarfPubSections;
266 // Whether or not to use AT_ranges for compilation units.
269 // Whether we emitted a function into a section other than the default
271 bool UsedNonDefaultText;
273 // Version of dwarf we're emitting.
274 unsigned DwarfVersion;
276 // Maps from a type identifier to the actual MDNode.
277 DITypeIdentifierMap TypeIdentifierMap;
279 // DWARF5 Experimental Options
280 bool HasDwarfAccelTables;
283 // Separated Dwarf Variables
284 // In general these will all be for bits that are left in the
285 // original object file, rather than things that are meant
286 // to be in the .dwo sections.
288 // Holder for the skeleton information.
289 DwarfFile SkeletonHolder;
291 /// Store file names for type units under fission in a line table header that
292 /// will be emitted into debug_line.dwo.
293 // FIXME: replace this with a map from comp_dir to table so that we can emit
294 // multiple tables during LTO each of which uses directory 0, referencing the
295 // comp_dir of all the type units that use it.
296 MCDwarfDwoLineTable SplitTypeUnitFileTable;
298 // True iff there are multiple CUs in this module.
302 AddressPool AddrPool;
304 DwarfAccelTable AccelNames;
305 DwarfAccelTable AccelObjC;
306 DwarfAccelTable AccelNamespace;
307 DwarfAccelTable AccelTypes;
309 DenseMap<const Function *, DISubprogram> FunctionDIs;
311 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
313 const SmallVectorImpl<std::unique_ptr<DwarfUnit>> &getUnits() {
314 return InfoHolder.getUnits();
317 /// \brief Find abstract variable associated with Var.
318 DbgVariable *getExistingAbstractVariable(const DIVariable &DV,
319 DIVariable &Cleansed);
320 DbgVariable *getExistingAbstractVariable(const DIVariable &DV);
321 void createAbstractVariable(const DIVariable &DV, LexicalScope *Scope);
322 void ensureAbstractVariableIsCreated(const DIVariable &Var,
323 const MDNode *Scope);
324 void ensureAbstractVariableIsCreatedIfScoped(const DIVariable &Var,
325 const MDNode *Scope);
327 /// \brief Construct a DIE for this abstract scope.
328 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
330 /// \brief Emit initial Dwarf sections with a label at the start of each one.
331 void emitSectionLabels();
333 /// \brief Compute the size and offset of a DIE given an incoming Offset.
334 unsigned computeSizeAndOffset(DIE *Die, unsigned Offset);
336 /// \brief Compute the size and offset of all the DIEs.
337 void computeSizeAndOffsets();
339 /// \brief Collect info for variables that were optimized out.
340 void collectDeadVariables();
342 void finishVariableDefinitions();
344 void finishSubprogramDefinitions();
346 /// \brief Finish off debug information after all functions have been
348 void finalizeModuleInfo();
350 /// \brief Emit labels to close any remaining sections that have been left
354 /// \brief Emit the debug info section.
355 void emitDebugInfo();
357 /// \brief Emit the abbreviation section.
358 void emitAbbreviations();
360 /// \brief Emit the last address of the section and the end of
362 void emitEndOfLineMatrix(unsigned SectionEnd);
364 /// \brief Emit a specified accelerator table.
365 void emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
366 StringRef TableName, StringRef SymName);
368 /// \brief Emit visible names into a hashed accelerator table section.
369 void emitAccelNames();
371 /// \brief Emit objective C classes and categories into a hashed
372 /// accelerator table section.
373 void emitAccelObjC();
375 /// \brief Emit namespace dies into a hashed accelerator table.
376 void emitAccelNamespaces();
378 /// \brief Emit type dies into a hashed accelerator table.
379 void emitAccelTypes();
381 /// \brief Emit visible names into a debug pubnames section.
382 /// \param GnuStyle determines whether or not we want to emit
383 /// additional information into the table ala newer gcc for gdb
385 void emitDebugPubNames(bool GnuStyle = false);
387 /// \brief Emit visible types into a debug pubtypes section.
388 /// \param GnuStyle determines whether or not we want to emit
389 /// additional information into the table ala newer gcc for gdb
391 void emitDebugPubTypes(bool GnuStyle = false);
393 void emitDebugPubSection(
394 bool GnuStyle, const MCSection *PSec, StringRef Name,
395 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
397 /// \brief Emit visible names into a debug str section.
400 /// \brief Emit visible names into a debug loc section.
403 /// \brief Emit visible names into a debug loc dwo section.
404 void emitDebugLocDWO();
406 /// \brief Emit visible names into a debug aranges section.
407 void emitDebugARanges();
409 /// \brief Emit visible names into a debug ranges section.
410 void emitDebugRanges();
412 /// \brief Emit inline info using custom format.
413 void emitDebugInlineInfo();
415 /// DWARF 5 Experimental Split Dwarf Emitters
417 /// \brief Initialize common features of skeleton units.
418 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
419 std::unique_ptr<DwarfUnit> NewU);
421 /// \brief Construct the split debug info compile unit for the debug info
423 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
425 /// \brief Construct the split debug info compile unit for the debug info
427 DwarfTypeUnit &constructSkeletonTU(DwarfTypeUnit &TU);
429 /// \brief Emit the debug info dwo section.
430 void emitDebugInfoDWO();
432 /// \brief Emit the debug abbrev dwo section.
433 void emitDebugAbbrevDWO();
435 /// \brief Emit the debug line dwo section.
436 void emitDebugLineDWO();
438 /// \brief Emit the debug str dwo section.
439 void emitDebugStrDWO();
441 /// Flags to let the linker know we have emitted new style pubnames. Only
442 /// emit it here if we don't have a skeleton CU for split dwarf.
443 void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
445 /// \brief Create new DwarfCompileUnit for the given metadata node with tag
446 /// DW_TAG_compile_unit.
447 DwarfCompileUnit &constructDwarfCompileUnit(DICompileUnit DIUnit);
449 /// \brief Construct imported_module or imported_declaration DIE.
450 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
453 /// \brief Register a source line with debug info. Returns the unique
454 /// label that was emitted and which provides correspondence to the
455 /// source line list.
456 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
459 /// \brief Indentify instructions that are marking the beginning of or
460 /// ending of a scope.
461 void identifyScopeMarkers();
463 /// \brief Populate LexicalScope entries with variables' info.
464 void collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
465 SmallPtrSetImpl<const MDNode *> &ProcessedVars);
467 /// \brief Build the location list for all DBG_VALUEs in the
468 /// function that describe the same variable.
469 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
470 const DbgValueHistoryMap::InstrRanges &Ranges);
472 /// \brief Collect variable information from the side table maintained
474 void collectVariableInfoFromMMITable(SmallPtrSetImpl<const MDNode *> &P);
476 /// \brief Ensure that a label will be emitted before MI.
477 void requestLabelBeforeInsn(const MachineInstr *MI) {
478 LabelsBeforeInsn.insert(std::make_pair(MI, nullptr));
481 /// \brief Ensure that a label will be emitted after MI.
482 void requestLabelAfterInsn(const MachineInstr *MI) {
483 LabelsAfterInsn.insert(std::make_pair(MI, nullptr));
487 //===--------------------------------------------------------------------===//
488 // Main entry points.
490 DwarfDebug(AsmPrinter *A, Module *M);
492 ~DwarfDebug() override;
494 /// \brief Emit all Dwarf sections that should come prior to the
498 /// \brief Emit all Dwarf sections that should come after the content.
499 void endModule() override;
501 /// \brief Gather pre-function debug information.
502 void beginFunction(const MachineFunction *MF) override;
504 /// \brief Gather and emit post-function debug information.
505 void endFunction(const MachineFunction *MF) override;
507 /// \brief Process beginning of an instruction.
508 void beginInstruction(const MachineInstr *MI) override;
510 /// \brief Process end of an instruction.
511 void endInstruction() override;
513 /// \brief Add a DIE to the set of types that we're going to pull into
515 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
516 DIE &Die, DICompositeType CTy);
518 /// \brief Add a label so that arange data can be generated for it.
519 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
521 /// \brief For symbols that have a size designated (e.g. common symbols),
522 /// this tracks that size.
523 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
527 /// \brief Recursively Emits a debug information entry.
528 void emitDIE(DIE &Die);
530 // Experimental DWARF5 features.
532 /// \brief Returns whether or not to emit tables that dwarf consumers can
533 /// use to accelerate lookup.
534 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
536 /// \brief Returns whether or not to change the current debug info for the
537 /// split dwarf proposal support.
538 bool useSplitDwarf() const { return HasSplitDwarf; }
540 /// Returns the Dwarf Version.
541 unsigned getDwarfVersion() const { return DwarfVersion; }
543 /// Returns the section symbol for the .debug_loc section.
544 MCSymbol *getDebugLocSym() const { return DwarfDebugLocSectionSym; }
546 /// Returns the section symbol for the .debug_str section.
547 MCSymbol *getDebugStrSym() const { return DwarfStrSectionSym; }
549 /// Returns the section symbol for the .debug_ranges section.
550 MCSymbol *getRangeSectionSym() const { return DwarfDebugRangeSectionSym; }
552 /// Returns the previous CU that was being updated
553 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
554 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
556 /// Returns the entries for the .debug_loc section.
557 const SmallVectorImpl<DebugLocList> &
558 getDebugLocEntries() const {
559 return DotDebugLocEntries;
562 /// \brief Emit an entry for the debug loc section. This can be used to
563 /// handle an entry that's going to be emitted into the debug loc section.
564 void emitDebugLocEntry(ByteStreamer &Streamer, const DebugLocEntry &Entry);
565 /// \brief emit a single value for the debug loc section.
566 void emitDebugLocValue(ByteStreamer &Streamer,
567 const DebugLocEntry::Value &Value,
568 unsigned PieceOffsetInBits = 0);
569 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
570 void emitLocPieces(ByteStreamer &Streamer,
571 const DITypeIdentifierMap &Map,
572 ArrayRef<DebugLocEntry::Value> Values);
574 /// Emit the location for a debug loc entry, including the size header.
575 void emitDebugLocEntryLocation(const DebugLocEntry &Entry);
577 /// Find the MDNode for the given reference.
578 template <typename T> T resolve(DIRef<T> Ref) const {
579 return Ref.resolve(TypeIdentifierMap);
582 /// \brief Return the TypeIdentifierMap.
583 const DITypeIdentifierMap &getTypeIdentifierMap() const {
584 return TypeIdentifierMap;
587 /// Find the DwarfCompileUnit for the given CU Die.
588 DwarfCompileUnit *lookupUnit(const DIE *CU) const {
589 return CUDieMap.lookup(CU);
591 /// isSubprogramContext - Return true if Context is either a subprogram
592 /// or another context nested inside a subprogram.
593 bool isSubprogramContext(const MDNode *Context);
595 void addSubprogramNames(DISubprogram SP, DIE &Die);
597 AddressPool &getAddressPool() { return AddrPool; }
599 void addAccelName(StringRef Name, const DIE &Die);
601 void addAccelObjC(StringRef Name, const DIE &Die);
603 void addAccelNamespace(StringRef Name, const DIE &Die);
605 void addAccelType(StringRef Name, const DIE &Die, char Flags);
607 const MachineFunction *getCurrentFunction() const { return CurFn; }
608 const MCSymbol *getFunctionBeginSym() const { return FunctionBeginSym; }
609 const MCSymbol *getFunctionEndSym() const { return FunctionEndSym; }
611 iterator_range<ImportedEntityMap::const_iterator>
612 findImportedEntitiesForScope(const MDNode *Scope) const {
613 return make_range(std::equal_range(
614 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
615 std::pair<const MDNode *, const MDNode *>(Scope, nullptr),
619 /// \brief A helper function to check whether the DIE for a given Scope is
620 /// going to be null.
621 bool isLexicalScopeDIENull(LexicalScope *Scope);
623 /// \brief Return Label preceding the instruction.
624 MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
626 /// \brief Return Label immediately following the instruction.
627 MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
629 // FIXME: Consider rolling ranges up into DwarfDebug since we use a single
630 // range_base anyway, so there's no need to keep them as separate per-CU range
631 // lists. (though one day we might end up with a range.dwo section, in which
632 // case it'd go to DwarfFile)
633 unsigned getNextRangeNumber() { return GlobalRangeCount++; }
635 // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
637 SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
638 return ProcessedSPNodes;
641 } // End of namespace llvm