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 /// \brief This class is used to record source line correspondence.
54 unsigned Line; // Source line number.
55 unsigned Column; // Source column.
56 unsigned SourceID; // Source ID number.
57 MCSymbol *Label; // Label in code ID number.
59 SrcLineInfo(unsigned L, unsigned C, unsigned S, MCSymbol *label)
60 : Line(L), Column(C), SourceID(S), Label(label) {}
63 unsigned getLine() const { return Line; }
64 unsigned getColumn() const { return Column; }
65 unsigned getSourceID() const { return SourceID; }
66 MCSymbol *getLabel() const { return Label; }
69 //===----------------------------------------------------------------------===//
70 /// \brief This class is used to track local variable information.
72 /// - Variables whose location changes over time have a DebugLocListIndex and
73 /// the other fields are not used.
75 /// - Variables that are described by multiple MMI table entries have multiple
76 /// expressions and frame indices.
78 const DILocalVariable *Var; /// Variable Descriptor.
79 const DILocation *IA; /// Inlined at location.
80 SmallVector<const DIExpression *, 1>
81 Expr; /// Complex address location expression.
82 DIE *TheDIE; /// Variable DIE.
83 unsigned DebugLocListIndex; /// Offset in DebugLocs.
84 const MachineInstr *MInsn; /// DBG_VALUE instruction of the variable.
85 SmallVector<int, 1> FrameIndex; /// Frame index of the variable.
89 /// Construct a DbgVariable from a variable.
90 DbgVariable(const DILocalVariable *V, const DILocation *IA,
91 const DIExpression *E, DwarfDebug *DD, int FI = ~0)
92 : Var(V), IA(IA), Expr(1, E), TheDIE(nullptr), DebugLocListIndex(~0U),
93 MInsn(nullptr), DD(DD) {
94 FrameIndex.push_back(FI);
95 assert(!E || E->isValid());
98 /// Construct a DbgVariable from a DEBUG_VALUE.
99 /// AbstractVar may be NULL.
100 DbgVariable(const MachineInstr *DbgValue, DwarfDebug *DD)
101 : Var(DbgValue->getDebugVariable()),
102 IA(DbgValue->getDebugLoc()->getInlinedAt()),
103 Expr(1, DbgValue->getDebugExpression()), TheDIE(nullptr),
104 DebugLocListIndex(~0U), MInsn(DbgValue), DD(DD) {
105 FrameIndex.push_back(~0);
109 const DILocalVariable *getVariable() const { return Var; }
110 const DILocation *getInlinedAt() const { return IA; }
111 const ArrayRef<const DIExpression *> getExpression() const { return Expr; }
112 void setDIE(DIE &D) { TheDIE = &D; }
113 DIE *getDIE() const { return TheDIE; }
114 void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
115 unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
116 StringRef getName() const { return Var->getName(); }
117 const MachineInstr *getMInsn() const { return MInsn; }
118 const ArrayRef<int> getFrameIndex() const { return FrameIndex; }
120 void addMMIEntry(const DbgVariable &V) {
121 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
122 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
123 assert(V.Var == Var && "conflicting variable");
124 assert(V.IA == IA && "conflicting inlined-at location");
126 if (V.getFrameIndex().back() != ~0) {
127 auto E = V.getExpression();
128 auto FI = V.getFrameIndex();
129 Expr.append(E.begin(), E.end());
130 FrameIndex.append(FI.begin(), FI.end());
132 assert(Expr.size() > 1 ? std::all_of(Expr.begin(), Expr.end(),
133 [](const DIExpression *E) {
134 return E->isBitPiece();
136 : (true && "conflicting locations for variable"));
139 // Translate tag to proper Dwarf tag.
140 dwarf::Tag getTag() const {
141 if (Var->getTag() == dwarf::DW_TAG_arg_variable)
142 return dwarf::DW_TAG_formal_parameter;
144 return dwarf::DW_TAG_variable;
146 /// \brief Return true if DbgVariable is artificial.
147 bool isArtificial() const {
148 if (Var->isArtificial())
150 if (getType()->isArtificial())
155 bool isObjectPointer() const {
156 if (Var->isObjectPointer())
158 if (getType()->isObjectPointer())
163 bool variableHasComplexAddress() const {
164 assert(Var && "Invalid complex DbgVariable!");
165 assert(Expr.size() == 1 &&
166 "variableHasComplexAddress() invoked on multi-FI variable");
167 return Expr.back()->getNumElements() > 0;
169 bool isBlockByrefVariable() const;
170 const DIType *getType() const;
173 /// resolve - Look in the DwarfDebug map for the MDNode that
174 /// corresponds to the reference.
175 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const;
179 /// \brief Helper used to pair up a symbol and its DWARF compile unit.
181 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
183 DwarfCompileUnit *CU;
186 /// \brief Collects and handles dwarf debug information.
187 class DwarfDebug : public AsmPrinterHandler {
188 // Target of Dwarf emission.
191 // Collected machine module information.
192 MachineModuleInfo *MMI;
194 // All DIEValues are allocated through this allocator.
195 BumpPtrAllocator DIEValueAllocator;
197 // Maps MDNode with its corresponding DwarfCompileUnit.
198 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
200 // Maps subprogram MDNode with its corresponding DwarfCompileUnit.
201 MapVector<const MDNode *, DwarfCompileUnit *> SPMap;
203 // Maps a CU DIE with its corresponding DwarfCompileUnit.
204 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
206 // List of all labels used in aranges generation.
207 std::vector<SymbolCU> ArangeLabels;
209 // Size of each symbol emitted (for those symbols that have a specific size).
210 DenseMap<const MCSymbol *, uint64_t> SymSize;
212 LexicalScopes LScopes;
214 // Collection of abstract variables.
215 DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
216 SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
218 // Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
219 // can refer to them in spite of insertions into this list.
220 DebugLocStream DebugLocs;
222 // This is a collection of subprogram MDNodes that are processed to
224 SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
226 // Maps instruction with label emitted before instruction.
227 DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
229 // Maps instruction with label emitted after instruction.
230 DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
232 // History of DBG_VALUE and clobber instructions for each user variable.
233 // Variables are listed in order of appearance.
234 DbgValueHistoryMap DbgValues;
236 // Previous instruction's location information. This is used to determine
237 // label location to indicate scope boundries in dwarf debug info.
238 DebugLoc PrevInstLoc;
241 // This location indicates end of function prologue and beginning of function
243 DebugLoc PrologEndLoc;
245 // If nonnull, stores the current machine function we're processing.
246 const MachineFunction *CurFn;
248 // If nonnull, stores the current machine instruction we're processing.
249 const MachineInstr *CurMI;
251 // If nonnull, stores the CU in which the previous subprogram was contained.
252 const DwarfCompileUnit *PrevCU;
254 // As an optimization, there is no need to emit an entry in the directory
255 // table for the same directory as DW_AT_comp_dir.
256 StringRef CompilationDir;
258 // Holder for the file specific debug information.
259 DwarfFile InfoHolder;
261 // Holders for the various debug information flags that we might need to
262 // have exposed. See accessor functions below for description.
264 // Holder for imported entities.
265 typedef SmallVector<std::pair<const MDNode *, const MDNode *>, 32>
267 ImportedEntityMap ScopesWithImportedEntities;
269 // Map from MDNodes for user-defined types to the type units that describe
271 DenseMap<const MDNode *, const DwarfTypeUnit *> DwarfTypeUnits;
274 std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
275 TypeUnitsUnderConstruction;
277 // Whether to emit the pubnames/pubtypes sections.
278 bool HasDwarfPubSections;
280 // Whether or not to use AT_ranges for compilation units.
283 // Whether we emitted a function into a section other than the default
285 bool UsedNonDefaultText;
287 // Whether to use the GNU TLS opcode (instead of the standard opcode).
288 bool UseGNUTLSOpcode;
290 // Version of dwarf we're emitting.
291 unsigned DwarfVersion;
293 // Maps from a type identifier to the actual MDNode.
294 DITypeIdentifierMap TypeIdentifierMap;
296 // DWARF5 Experimental Options
297 bool HasDwarfAccelTables;
300 // Separated Dwarf Variables
301 // In general these will all be for bits that are left in the
302 // original object file, rather than things that are meant
303 // to be in the .dwo sections.
305 // Holder for the skeleton information.
306 DwarfFile SkeletonHolder;
308 /// Store file names for type units under fission in a line table header that
309 /// will be emitted into debug_line.dwo.
310 // FIXME: replace this with a map from comp_dir to table so that we can emit
311 // multiple tables during LTO each of which uses directory 0, referencing the
312 // comp_dir of all the type units that use it.
313 MCDwarfDwoLineTable SplitTypeUnitFileTable;
315 // True iff there are multiple CUs in this module.
320 AddressPool AddrPool;
322 DwarfAccelTable AccelNames;
323 DwarfAccelTable AccelObjC;
324 DwarfAccelTable AccelNamespace;
325 DwarfAccelTable AccelTypes;
327 DenseMap<const Function *, DISubprogram *> FunctionDIs;
329 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
331 const SmallVectorImpl<std::unique_ptr<DwarfUnit>> &getUnits() {
332 return InfoHolder.getUnits();
335 typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
337 /// \brief Find abstract variable associated with Var.
338 DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
339 const DILocalVariable *&Cleansed);
340 DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
341 void createAbstractVariable(const DILocalVariable *DV, LexicalScope *Scope);
342 void ensureAbstractVariableIsCreated(InlinedVariable Var,
343 const MDNode *Scope);
344 void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var,
345 const MDNode *Scope);
347 /// \brief Construct a DIE for this abstract scope.
348 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
350 /// \brief Compute the size and offset of a DIE given an incoming Offset.
351 unsigned computeSizeAndOffset(DIE *Die, unsigned Offset);
353 /// \brief Compute the size and offset of all the DIEs.
354 void computeSizeAndOffsets();
356 /// \brief Collect info for variables that were optimized out.
357 void collectDeadVariables();
359 void finishVariableDefinitions();
361 void finishSubprogramDefinitions();
363 /// \brief Finish off debug information after all functions have been
365 void finalizeModuleInfo();
367 /// \brief Emit the debug info section.
368 void emitDebugInfo();
370 /// \brief Emit the abbreviation section.
371 void emitAbbreviations();
373 /// \brief Emit a specified accelerator table.
374 void emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
375 StringRef TableName);
377 /// \brief Emit visible names into a hashed accelerator table section.
378 void emitAccelNames();
380 /// \brief Emit objective C classes and categories into a hashed
381 /// accelerator table section.
382 void emitAccelObjC();
384 /// \brief Emit namespace dies into a hashed accelerator table.
385 void emitAccelNamespaces();
387 /// \brief Emit type dies into a hashed accelerator table.
388 void emitAccelTypes();
390 /// \brief Emit visible names into a debug pubnames section.
391 /// \param GnuStyle determines whether or not we want to emit
392 /// additional information into the table ala newer gcc for gdb
394 void emitDebugPubNames(bool GnuStyle = false);
396 /// \brief Emit visible types into a debug pubtypes section.
397 /// \param GnuStyle determines whether or not we want to emit
398 /// additional information into the table ala newer gcc for gdb
400 void emitDebugPubTypes(bool GnuStyle = false);
402 void emitDebugPubSection(
403 bool GnuStyle, const MCSection *PSec, StringRef Name,
404 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
406 /// \brief Emit visible names into a debug str section.
409 /// \brief Emit visible names into a debug loc section.
412 /// \brief Emit visible names into a debug loc dwo section.
413 void emitDebugLocDWO();
415 /// \brief Emit visible names into a debug aranges section.
416 void emitDebugARanges();
418 /// \brief Emit visible names into a debug ranges section.
419 void emitDebugRanges();
421 /// \brief Emit inline info using custom format.
422 void emitDebugInlineInfo();
424 /// DWARF 5 Experimental Split Dwarf Emitters
426 /// \brief Initialize common features of skeleton units.
427 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
428 std::unique_ptr<DwarfUnit> NewU);
430 /// \brief Construct the split debug info compile unit for the debug info
432 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
434 /// \brief Construct the split debug info compile unit for the debug info
436 DwarfTypeUnit &constructSkeletonTU(DwarfTypeUnit &TU);
438 /// \brief Emit the debug info dwo section.
439 void emitDebugInfoDWO();
441 /// \brief Emit the debug abbrev dwo section.
442 void emitDebugAbbrevDWO();
444 /// \brief Emit the debug line dwo section.
445 void emitDebugLineDWO();
447 /// \brief Emit the debug str dwo section.
448 void emitDebugStrDWO();
450 /// Flags to let the linker know we have emitted new style pubnames. Only
451 /// emit it here if we don't have a skeleton CU for split dwarf.
452 void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
454 /// \brief Create new DwarfCompileUnit for the given metadata node with tag
455 /// DW_TAG_compile_unit.
456 DwarfCompileUnit &constructDwarfCompileUnit(const DICompileUnit *DIUnit);
458 /// \brief Construct imported_module or imported_declaration DIE.
459 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
460 const DIImportedEntity *N);
462 /// \brief Register a source line with debug info. Returns the unique
463 /// label that was emitted and which provides correspondence to the
464 /// source line list.
465 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
468 /// \brief Indentify instructions that are marking the beginning of or
469 /// ending of a scope.
470 void identifyScopeMarkers();
472 /// \brief Populate LexicalScope entries with variables' info.
473 void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
474 DenseSet<InlinedVariable> &ProcessedVars);
476 /// \brief Build the location list for all DBG_VALUEs in the
477 /// function that describe the same variable.
478 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
479 const DbgValueHistoryMap::InstrRanges &Ranges);
481 /// \brief Collect variable information from the side table maintained
483 void collectVariableInfoFromMMITable(DenseSet<InlinedVariable> &P);
485 /// \brief Ensure that a label will be emitted before MI.
486 void requestLabelBeforeInsn(const MachineInstr *MI) {
487 LabelsBeforeInsn.insert(std::make_pair(MI, nullptr));
490 /// \brief Ensure that a label will be emitted after MI.
491 void requestLabelAfterInsn(const MachineInstr *MI) {
492 LabelsAfterInsn.insert(std::make_pair(MI, nullptr));
496 //===--------------------------------------------------------------------===//
497 // Main entry points.
499 DwarfDebug(AsmPrinter *A, Module *M);
501 ~DwarfDebug() override;
503 /// \brief Emit all Dwarf sections that should come prior to the
507 /// \brief Emit all Dwarf sections that should come after the content.
508 void endModule() override;
510 /// \brief Gather pre-function debug information.
511 void beginFunction(const MachineFunction *MF) override;
513 /// \brief Gather and emit post-function debug information.
514 void endFunction(const MachineFunction *MF) override;
516 /// \brief Process beginning of an instruction.
517 void beginInstruction(const MachineInstr *MI) override;
519 /// \brief Process end of an instruction.
520 void endInstruction() override;
522 /// \brief Add a DIE to the set of types that we're going to pull into
524 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
525 DIE &Die, const DICompositeType *CTy);
527 /// \brief Add a label so that arange data can be generated for it.
528 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
530 /// \brief For symbols that have a size designated (e.g. common symbols),
531 /// this tracks that size.
532 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
536 /// \brief Returns whether to use DW_OP_GNU_push_tls_address, instead of the
537 /// standard DW_OP_form_tls_address opcode
538 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
540 // Experimental DWARF5 features.
542 /// \brief Returns whether or not to emit tables that dwarf consumers can
543 /// use to accelerate lookup.
544 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
546 /// \brief Returns whether or not to change the current debug info for the
547 /// split dwarf proposal support.
548 bool useSplitDwarf() const { return HasSplitDwarf; }
550 /// Returns the Dwarf Version.
551 unsigned getDwarfVersion() const { return DwarfVersion; }
553 /// Returns the previous CU that was being updated
554 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
555 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
557 /// Returns the entries for the .debug_loc section.
558 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
560 /// \brief Emit an entry for the debug loc section. This can be used to
561 /// handle an entry that's going to be emitted into the debug loc section.
562 void emitDebugLocEntry(ByteStreamer &Streamer,
563 const DebugLocStream::Entry &Entry);
565 /// Emit the location for a debug loc entry, including the size header.
566 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
568 /// Find the MDNode for the given reference.
569 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
570 return Ref.resolve(TypeIdentifierMap);
573 /// \brief Return the TypeIdentifierMap.
574 const DITypeIdentifierMap &getTypeIdentifierMap() const {
575 return TypeIdentifierMap;
578 /// Find the DwarfCompileUnit for the given CU Die.
579 DwarfCompileUnit *lookupUnit(const DIE *CU) const {
580 return CUDieMap.lookup(CU);
582 /// isSubprogramContext - Return true if Context is either a subprogram
583 /// or another context nested inside a subprogram.
584 bool isSubprogramContext(const MDNode *Context);
586 void addSubprogramNames(const DISubprogram *SP, DIE &Die);
588 AddressPool &getAddressPool() { return AddrPool; }
590 void addAccelName(StringRef Name, const DIE &Die);
592 void addAccelObjC(StringRef Name, const DIE &Die);
594 void addAccelNamespace(StringRef Name, const DIE &Die);
596 void addAccelType(StringRef Name, const DIE &Die, char Flags);
598 const MachineFunction *getCurrentFunction() const { return CurFn; }
600 iterator_range<ImportedEntityMap::const_iterator>
601 findImportedEntitiesForScope(const MDNode *Scope) const {
602 return make_range(std::equal_range(
603 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
604 std::pair<const MDNode *, const MDNode *>(Scope, nullptr),
608 /// \brief A helper function to check whether the DIE for a given Scope is
609 /// going to be null.
610 bool isLexicalScopeDIENull(LexicalScope *Scope);
612 /// \brief Return Label preceding the instruction.
613 MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
615 /// \brief Return Label immediately following the instruction.
616 MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
618 // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
620 SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
621 return ProcessedSPNodes;
624 } // End of namespace llvm