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 CODEGEN_ASMPRINTER_DWARFDEBUG_H__
15 #define CODEGEN_ASMPRINTER_DWARFDEBUG_H__
17 #include "DwarfFile.h"
18 #include "AsmPrinterHandler.h"
20 #include "DebugLocEntry.h"
21 #include "DebugLocList.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/MapVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/FoldingSet.h"
27 #include "llvm/CodeGen/LexicalScopes.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DebugLoc.h"
30 #include "llvm/MC/MachineLocation.h"
31 #include "llvm/MC/MCDwarf.h"
32 #include "llvm/Support/Allocator.h"
42 class DwarfCompileUnit;
46 class MachineModuleInfo;
48 //===----------------------------------------------------------------------===//
49 /// \brief This class is used to record source line correspondence.
51 unsigned Line; // Source line number.
52 unsigned Column; // Source column.
53 unsigned SourceID; // Source ID number.
54 MCSymbol *Label; // Label in code ID number.
56 SrcLineInfo(unsigned L, unsigned C, unsigned S, MCSymbol *label)
57 : Line(L), Column(C), SourceID(S), Label(label) {}
60 unsigned getLine() const { return Line; }
61 unsigned getColumn() const { return Column; }
62 unsigned getSourceID() const { return SourceID; }
63 MCSymbol *getLabel() const { return Label; }
66 //===----------------------------------------------------------------------===//
67 /// \brief This class is used to track local variable information.
69 DIVariable Var; // Variable Descriptor.
70 DIE *TheDIE; // Variable DIE.
71 unsigned DotDebugLocOffset; // Offset in DotDebugLocEntries.
72 DbgVariable *AbsVar; // Corresponding Abstract variable, if any.
73 const MachineInstr *MInsn; // DBG_VALUE instruction of the variable.
78 // AbsVar may be NULL.
79 DbgVariable(DIVariable V, DbgVariable *AV, DwarfDebug *DD)
80 : Var(V), TheDIE(0), DotDebugLocOffset(~0U), AbsVar(AV), MInsn(0),
81 FrameIndex(~0), DD(DD) {}
84 DIVariable getVariable() const { return Var; }
85 void setDIE(DIE *D) { TheDIE = D; }
86 DIE *getDIE() const { return TheDIE; }
87 void setDotDebugLocOffset(unsigned O) { DotDebugLocOffset = O; }
88 unsigned getDotDebugLocOffset() const { return DotDebugLocOffset; }
89 StringRef getName() const { return Var.getName(); }
90 DbgVariable *getAbstractVariable() const { return AbsVar; }
91 const MachineInstr *getMInsn() const { return MInsn; }
92 void setMInsn(const MachineInstr *M) { MInsn = M; }
93 int getFrameIndex() const { return FrameIndex; }
94 void setFrameIndex(int FI) { FrameIndex = FI; }
95 // Translate tag to proper Dwarf tag.
96 dwarf::Tag getTag() const {
97 if (Var.getTag() == dwarf::DW_TAG_arg_variable)
98 return dwarf::DW_TAG_formal_parameter;
100 return dwarf::DW_TAG_variable;
102 /// \brief Return true if DbgVariable is artificial.
103 bool isArtificial() const {
104 if (Var.isArtificial())
106 if (getType().isArtificial())
111 bool isObjectPointer() const {
112 if (Var.isObjectPointer())
114 if (getType().isObjectPointer())
119 bool variableHasComplexAddress() const {
120 assert(Var.isVariable() && "Invalid complex DbgVariable!");
121 return Var.hasComplexAddress();
123 bool isBlockByrefVariable() const;
124 unsigned getNumAddrElements() const {
125 assert(Var.isVariable() && "Invalid complex DbgVariable!");
126 return Var.getNumAddrElements();
128 uint64_t getAddrElement(unsigned i) const { return Var.getAddrElement(i); }
129 DIType getType() const;
132 /// resolve - Look in the DwarfDebug map for the MDNode that
133 /// corresponds to the reference.
134 template <typename T> T resolve(DIRef<T> Ref) const;
138 /// \brief Helper used to pair up a symbol and its DWARF compile unit.
140 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
142 DwarfCompileUnit *CU;
145 /// \brief Collects and handles dwarf debug information.
146 class DwarfDebug : public AsmPrinterHandler {
147 // Target of Dwarf emission.
150 // Collected machine module information.
151 MachineModuleInfo *MMI;
153 // All DIEValues are allocated through this allocator.
154 BumpPtrAllocator DIEValueAllocator;
156 // Handle to the compile unit used for the inline extension handling,
157 // this is just so that the DIEValue allocator has a place to store
158 // the particular elements.
159 // FIXME: Store these off of DwarfDebug instead?
160 DwarfCompileUnit *FirstCU;
162 // Maps MDNode with its corresponding DwarfCompileUnit.
163 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
165 // Maps subprogram MDNode with its corresponding DwarfCompileUnit.
166 DenseMap<const MDNode *, DwarfCompileUnit *> SPMap;
168 // Maps a CU DIE with its corresponding DwarfCompileUnit.
169 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
171 /// Maps MDNodes for type system with the corresponding DIEs. These DIEs can
172 /// be shared across CUs, that is why we keep the map here instead
173 /// of in DwarfCompileUnit.
174 DenseMap<const MDNode *, DIE *> MDTypeNodeToDieMap;
176 // List of all labels used in aranges generation.
177 std::vector<SymbolCU> ArangeLabels;
179 // Size of each symbol emitted (for those symbols that have a specific size).
180 DenseMap<const MCSymbol *, uint64_t> SymSize;
182 // Provides a unique id per text section.
183 typedef DenseMap<const MCSection *, SmallVector<SymbolCU, 8> > SectionMapType;
184 SectionMapType SectionMap;
186 // List of arguments for current function.
187 SmallVector<DbgVariable *, 8> CurrentFnArguments;
189 LexicalScopes LScopes;
191 // Collection of abstract subprogram DIEs.
192 DenseMap<const MDNode *, DIE *> AbstractSPDies;
194 // Collection of dbg variables of a scope.
195 typedef DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >
197 ScopeVariablesMap ScopeVariables;
199 // Collection of abstract variables.
200 DenseMap<const MDNode *, DbgVariable *> AbstractVariables;
202 // Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
203 // can refer to them in spite of insertions into this list.
204 SmallVector<DebugLocList, 4> DotDebugLocEntries;
206 // Collection of subprogram DIEs that are marked (at the end of the module)
208 SmallPtrSet<DIE *, 4> InlinedSubprogramDIEs;
210 // This is a collection of subprogram MDNodes that are processed to
212 SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
214 // Maps instruction with label emitted before instruction.
215 DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
217 // Maps instruction with label emitted after instruction.
218 DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
220 // Every user variable mentioned by a DBG_VALUE instruction in order of
222 SmallVector<const MDNode *, 8> UserVariables;
224 // For each user variable, keep a list of DBG_VALUE instructions in order.
225 // The list can also contain normal instructions that clobber the previous
227 typedef DenseMap<const MDNode *, SmallVector<const MachineInstr *, 4> >
229 DbgValueHistoryMap DbgValues;
231 // Previous instruction's location information. This is used to determine
232 // label location to indicate scope boundries in dwarf debug info.
233 DebugLoc PrevInstLoc;
236 // This location indicates end of function prologue and beginning of function
238 DebugLoc PrologEndLoc;
240 // If nonnull, stores the current machine function we're processing.
241 const MachineFunction *CurFn;
243 // If nonnull, stores the current machine instruction we're processing.
244 const MachineInstr *CurMI;
246 // If nonnull, stores the section that the previous function was allocated to
248 const MCSection *PrevSection;
250 // If nonnull, stores the CU in which the previous subprogram was contained.
251 const DwarfCompileUnit *PrevCU;
253 // Section Symbols: these are assembler temporary labels that are emitted at
254 // the beginning of each supported dwarf section. These are used to form
255 // section offsets and are created by EmitSectionLabels.
256 MCSymbol *DwarfInfoSectionSym, *DwarfAbbrevSectionSym;
257 MCSymbol *DwarfStrSectionSym, *TextSectionSym, *DwarfDebugRangeSectionSym;
258 MCSymbol *DwarfDebugLocSectionSym, *DwarfLineSectionSym, *DwarfAddrSectionSym;
259 MCSymbol *FunctionBeginSym, *FunctionEndSym;
260 MCSymbol *DwarfInfoDWOSectionSym, *DwarfAbbrevDWOSectionSym;
261 MCSymbol *DwarfStrDWOSectionSym;
262 MCSymbol *DwarfGnuPubNamesSectionSym, *DwarfGnuPubTypesSectionSym;
264 // As an optimization, there is no need to emit an entry in the directory
265 // table for the same directory as DW_AT_comp_dir.
266 StringRef CompilationDir;
268 // Counter for assigning globally unique IDs for ranges.
269 unsigned GlobalRangeCount;
271 // Holder for the file specific debug information.
272 DwarfFile InfoHolder;
274 // Holders for the various debug information flags that we might need to
275 // have exposed. See accessor functions below for description.
277 // Holder for imported entities.
278 typedef SmallVector<std::pair<const MDNode *, const MDNode *>, 32>
280 ImportedEntityMap ScopesWithImportedEntities;
282 // Map from MDNodes for user-defined types to the type units that describe
284 DenseMap<const MDNode *, const DwarfTypeUnit *> DwarfTypeUnits;
286 // Whether to emit the pubnames/pubtypes sections.
287 bool HasDwarfPubSections;
289 // Whether or not to use AT_ranges for compilation units.
292 // Whether we emitted a function into a section other than the default
294 bool UsedNonDefaultText;
296 // Version of dwarf we're emitting.
297 unsigned DwarfVersion;
299 // Maps from a type identifier to the actual MDNode.
300 DITypeIdentifierMap TypeIdentifierMap;
302 // DWARF5 Experimental Options
303 bool HasDwarfAccelTables;
306 // Separated Dwarf Variables
307 // In general these will all be for bits that are left in the
308 // original object file, rather than things that are meant
309 // to be in the .dwo sections.
311 // Holder for the skeleton information.
312 DwarfFile SkeletonHolder;
314 /// Store file names for type units under fission in a line table header that
315 /// will be emitted into debug_line.dwo.
316 // FIXME: replace this with a map from comp_dir to table so that we can emit
317 // multiple tables during LTO each of which uses directory 0, referencing the
318 // comp_dir of all the type units that use it.
319 MCDwarfDwoLineTable SplitTypeUnitFileTable;
321 // True iff there are multiple CUs in this module.
324 AddressPool AddrPool;
326 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
328 void addScopeVariable(LexicalScope *LS, DbgVariable *Var);
330 const SmallVectorImpl<std::unique_ptr<DwarfUnit>> &getUnits() {
331 return InfoHolder.getUnits();
334 /// \brief Find abstract variable associated with Var.
335 DbgVariable *findAbstractVariable(DIVariable &Var, DebugLoc Loc);
337 /// \brief Find DIE for the given subprogram and attach appropriate
338 /// DW_AT_low_pc and DW_AT_high_pc attributes. If there are global
339 /// variables in this scope then create and insert DIEs for these
341 DIE *updateSubprogramScopeDIE(DwarfCompileUnit &SPCU, DISubprogram SP);
343 /// \brief A helper function to check whether the DIE for a given Scope is
344 /// going to be null.
345 bool isLexicalScopeDIENull(LexicalScope *Scope);
347 /// \brief A helper function to construct a RangeSpanList for a given
349 void addScopeRangeList(DwarfCompileUnit &TheCU, DIE *ScopeDIE,
350 const SmallVectorImpl<InsnRange> &Range);
352 /// \brief Construct new DW_TAG_lexical_block for this scope and
353 /// attach DW_AT_low_pc/DW_AT_high_pc labels.
354 DIE *constructLexicalScopeDIE(DwarfCompileUnit &TheCU, LexicalScope *Scope);
356 /// \brief This scope represents inlined body of a function. Construct
357 /// DIE to represent this concrete inlined copy of the function.
358 DIE *constructInlinedScopeDIE(DwarfCompileUnit &TheCU, LexicalScope *Scope);
360 /// \brief Construct a DIE for this scope.
361 DIE *constructScopeDIE(DwarfCompileUnit &TheCU, LexicalScope *Scope);
362 /// A helper function to create children of a Scope DIE.
363 DIE *createScopeChildrenDIE(DwarfCompileUnit &TheCU, LexicalScope *Scope,
364 SmallVectorImpl<DIE *> &Children);
366 /// \brief Emit initial Dwarf sections with a label at the start of each one.
367 void emitSectionLabels();
369 /// \brief Compute the size and offset of a DIE given an incoming Offset.
370 unsigned computeSizeAndOffset(DIE *Die, unsigned Offset);
372 /// \brief Compute the size and offset of all the DIEs.
373 void computeSizeAndOffsets();
375 /// \brief Attach DW_AT_inline attribute with inlined subprogram DIEs.
376 void computeInlinedDIEs();
378 /// \brief Collect info for variables that were optimized out.
379 void collectDeadVariables();
381 /// \brief Finish off debug information after all functions have been
383 void finalizeModuleInfo();
385 /// \brief Emit labels to close any remaining sections that have been left
389 /// \brief Emit the debug info section.
390 void emitDebugInfo();
392 /// \brief Emit the abbreviation section.
393 void emitAbbreviations();
395 /// \brief Emit the last address of the section and the end of
397 void emitEndOfLineMatrix(unsigned SectionEnd);
399 /// \brief Emit visible names into a hashed accelerator table section.
400 void emitAccelNames();
402 /// \brief Emit objective C classes and categories into a hashed
403 /// accelerator table section.
404 void emitAccelObjC();
406 /// \brief Emit namespace dies into a hashed accelerator table.
407 void emitAccelNamespaces();
409 /// \brief Emit type dies into a hashed accelerator table.
410 void emitAccelTypes();
412 /// \brief Emit visible names into a debug pubnames section.
413 /// \param GnuStyle determines whether or not we want to emit
414 /// additional information into the table ala newer gcc for gdb
416 void emitDebugPubNames(bool GnuStyle = false);
418 /// \brief Emit visible types into a debug pubtypes section.
419 /// \param GnuStyle determines whether or not we want to emit
420 /// additional information into the table ala newer gcc for gdb
422 void emitDebugPubTypes(bool GnuStyle = false);
425 emitDebugPubSection(bool GnuStyle, const MCSection *PSec, StringRef Name,
426 const StringMap<const DIE *> &(DwarfUnit::*Accessor)()
429 /// \brief Emit visible names into a debug str section.
432 /// \brief Emit visible names into a debug loc section.
435 /// \brief Emit visible names into a debug loc dwo section.
436 void emitDebugLocDWO();
438 /// \brief Emit visible names into a debug aranges section.
439 void emitDebugARanges();
441 /// \brief Emit visible names into a debug ranges section.
442 void emitDebugRanges();
444 /// \brief Emit inline info using custom format.
445 void emitDebugInlineInfo();
447 /// DWARF 5 Experimental Split Dwarf Emitters
449 /// \brief Initialize common features of skeleton units.
450 void initSkeletonUnit(const DwarfUnit &U, DIE *Die,
451 std::unique_ptr<DwarfUnit> NewU);
453 /// \brief Construct the split debug info compile unit for the debug info
455 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
457 /// \brief Construct the split debug info compile unit for the debug info
459 DwarfTypeUnit &constructSkeletonTU(DwarfTypeUnit &TU);
461 /// \brief Emit the debug info dwo section.
462 void emitDebugInfoDWO();
464 /// \brief Emit the debug abbrev dwo section.
465 void emitDebugAbbrevDWO();
467 /// \brief Emit the debug line dwo section.
468 void emitDebugLineDWO();
470 /// \brief Emit the debug str dwo section.
471 void emitDebugStrDWO();
473 /// Flags to let the linker know we have emitted new style pubnames. Only
474 /// emit it here if we don't have a skeleton CU for split dwarf.
475 void addGnuPubAttributes(DwarfUnit &U, DIE *D) const;
477 /// \brief Create new DwarfCompileUnit for the given metadata node with tag
478 /// DW_TAG_compile_unit.
479 DwarfCompileUnit &constructDwarfCompileUnit(DICompileUnit DIUnit);
481 /// \brief Construct subprogram DIE.
482 void constructSubprogramDIE(DwarfCompileUnit &TheCU, const MDNode *N);
484 /// \brief Construct imported_module or imported_declaration DIE.
485 void constructImportedEntityDIE(DwarfCompileUnit &TheCU, const MDNode *N);
487 /// \brief Construct import_module DIE.
488 void constructImportedEntityDIE(DwarfCompileUnit &TheCU, const MDNode *N,
491 /// \brief Construct import_module DIE.
492 void constructImportedEntityDIE(DwarfCompileUnit &TheCU,
493 const DIImportedEntity &Module, DIE *Context);
495 /// \brief Register a source line with debug info. Returns the unique
496 /// label that was emitted and which provides correspondence to the
497 /// source line list.
498 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
501 /// \brief Indentify instructions that are marking the beginning of or
502 /// ending of a scope.
503 void identifyScopeMarkers();
505 /// \brief If Var is an current function argument that add it in
506 /// CurrentFnArguments list.
507 bool addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope);
509 /// \brief Populate LexicalScope entries with variables' info.
510 void collectVariableInfo(SmallPtrSet<const MDNode *, 16> &ProcessedVars);
512 /// \brief Collect variable information from the side table maintained
514 void collectVariableInfoFromMMITable(SmallPtrSet<const MDNode *, 16> &P);
516 /// \brief Ensure that a label will be emitted before MI.
517 void requestLabelBeforeInsn(const MachineInstr *MI) {
518 LabelsBeforeInsn.insert(std::make_pair(MI, (MCSymbol *)0));
521 /// \brief Return Label preceding the instruction.
522 MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
524 /// \brief Ensure that a label will be emitted after MI.
525 void requestLabelAfterInsn(const MachineInstr *MI) {
526 LabelsAfterInsn.insert(std::make_pair(MI, (MCSymbol *)0));
529 /// \brief Return Label immediately following the instruction.
530 MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
532 void attachLowHighPC(DwarfCompileUnit &Unit, DIE *D, MCSymbol *Begin,
536 //===--------------------------------------------------------------------===//
537 // Main entry points.
539 DwarfDebug(AsmPrinter *A, Module *M);
541 void insertDIE(const MDNode *TypeMD, DIE *Die) {
542 MDTypeNodeToDieMap.insert(std::make_pair(TypeMD, Die));
544 DIE *getDIE(const MDNode *TypeMD) {
545 return MDTypeNodeToDieMap.lookup(TypeMD);
548 /// \brief Emit all Dwarf sections that should come prior to the
552 /// \brief Emit all Dwarf sections that should come after the content.
553 void endModule() override;
555 /// \brief Gather pre-function debug information.
556 void beginFunction(const MachineFunction *MF) override;
558 /// \brief Gather and emit post-function debug information.
559 void endFunction(const MachineFunction *MF) override;
561 /// \brief Process beginning of an instruction.
562 void beginInstruction(const MachineInstr *MI) override;
564 /// \brief Process end of an instruction.
565 void endInstruction() override;
567 /// \brief Add a DIE to the set of types that we're going to pull into
569 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
570 DIE *Die, DICompositeType CTy);
572 /// \brief Add a label so that arange data can be generated for it.
573 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
575 /// \brief For symbols that have a size designated (e.g. common symbols),
576 /// this tracks that size.
577 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
581 /// \brief Recursively Emits a debug information entry.
582 void emitDIE(DIE &Die);
584 // Experimental DWARF5 features.
586 /// \brief Returns whether or not to emit tables that dwarf consumers can
587 /// use to accelerate lookup.
588 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
590 /// \brief Returns whether or not to change the current debug info for the
591 /// split dwarf proposal support.
592 bool useSplitDwarf() const { return HasSplitDwarf; }
594 /// Returns the Dwarf Version.
595 unsigned getDwarfVersion() const { return DwarfVersion; }
597 /// Returns the section symbol for the .debug_loc section.
598 MCSymbol *getDebugLocSym() const { return DwarfDebugLocSectionSym; }
600 /// Returns the previous section that was emitted into.
601 const MCSection *getPrevSection() const { return PrevSection; }
603 /// Returns the previous CU that was being updated
604 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
606 /// Returns the entries for the .debug_loc section.
607 const SmallVectorImpl<DebugLocList> &
608 getDebugLocEntries() const {
609 return DotDebugLocEntries;
612 /// \brief Emit an entry for the debug loc section. This can be used to
613 /// handle an entry that's going to be emitted into the debug loc section.
614 void emitDebugLocEntry(ByteStreamer &Streamer, const DebugLocEntry &Entry);
616 /// Emit the location for a debug loc entry, including the size header.
617 void emitDebugLocEntryLocation(const DebugLocEntry &Entry);
619 /// Find the MDNode for the given reference.
620 template <typename T> T resolve(DIRef<T> Ref) const {
621 return Ref.resolve(TypeIdentifierMap);
624 /// \brief Return the TypeIdentifierMap.
625 const DITypeIdentifierMap &getTypeIdentifierMap() const {
626 return TypeIdentifierMap;
629 /// Find the DwarfCompileUnit for the given CU Die.
630 DwarfCompileUnit *lookupUnit(const DIE *CU) const {
631 return CUDieMap.lookup(CU);
633 /// isSubprogramContext - Return true if Context is either a subprogram
634 /// or another context nested inside a subprogram.
635 bool isSubprogramContext(const MDNode *Context);
637 AddressPool &getAddressPool() { return AddrPool; }
639 } // End of namespace llvm