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 DIVariable Var; /// Variable Descriptor.
79 DILocation IA; /// Inlined at location.
80 SmallVector<DIExpression, 1> Expr; /// Complex address location expression.
81 DIE *TheDIE; /// Variable DIE.
82 unsigned DebugLocListIndex; /// Offset in DebugLocs.
83 const MachineInstr *MInsn; /// DBG_VALUE instruction of the variable.
84 SmallVector<int, 1> FrameIndex; /// Frame index of the variable.
88 /// Construct a DbgVariable from a DIVariable.
89 DbgVariable(DIVariable V, DILocation IA, DIExpression E, DwarfDebug *DD,
91 : Var(V), IA(IA), Expr(1, E), TheDIE(nullptr), DebugLocListIndex(~0U),
92 MInsn(nullptr), DD(DD) {
93 FrameIndex.push_back(FI);
94 assert(!E || E->isValid());
97 /// Construct a DbgVariable from a DEBUG_VALUE.
98 /// AbstractVar may be NULL.
99 DbgVariable(const MachineInstr *DbgValue, DwarfDebug *DD)
100 : Var(DbgValue->getDebugVariable()),
101 IA(DbgValue->getDebugLoc()->getInlinedAt()),
102 Expr(1, DbgValue->getDebugExpression()), TheDIE(nullptr),
103 DebugLocListIndex(~0U), MInsn(DbgValue), DD(DD) {
104 FrameIndex.push_back(~0);
108 DIVariable getVariable() const { return Var; }
109 DILocation getInlinedAt() const { return IA; }
110 const ArrayRef<DIExpression> getExpression() const { return Expr; }
111 void setDIE(DIE &D) { TheDIE = &D; }
112 DIE *getDIE() const { return TheDIE; }
113 void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
114 unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
115 StringRef getName() const { return Var->getName(); }
116 const MachineInstr *getMInsn() const { return MInsn; }
117 const ArrayRef<int> getFrameIndex() const { return FrameIndex; }
119 void addMMIEntry(const DbgVariable &V) {
120 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
121 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
122 assert(V.Var == Var && "conflicting DIVariable");
123 assert(V.IA == IA && "conflicting inlined-at location");
125 if (V.getFrameIndex().back() != ~0) {
126 auto E = V.getExpression();
127 auto FI = V.getFrameIndex();
128 Expr.append(E.begin(), E.end());
129 FrameIndex.append(FI.begin(), FI.end());
131 assert(Expr.size() > 1
132 ? std::all_of(Expr.begin(), Expr.end(),
133 [](DIExpression &E) { return E->isBitPiece(); })
134 : (true && "conflicting locations for variable"));
137 // Translate tag to proper Dwarf tag.
138 dwarf::Tag getTag() const {
139 if (Var->getTag() == dwarf::DW_TAG_arg_variable)
140 return dwarf::DW_TAG_formal_parameter;
142 return dwarf::DW_TAG_variable;
144 /// \brief Return true if DbgVariable is artificial.
145 bool isArtificial() const {
146 if (Var->isArtificial())
148 if (getType()->isArtificial())
153 bool isObjectPointer() const {
154 if (Var->isObjectPointer())
156 if (getType()->isObjectPointer())
161 bool variableHasComplexAddress() const {
162 assert(Var && "Invalid complex DbgVariable!");
163 assert(Expr.size() == 1 &&
164 "variableHasComplexAddress() invoked on multi-FI variable");
165 return Expr.back()->getNumElements() > 0;
167 bool isBlockByrefVariable() const;
168 const MDType *getType() const;
171 /// resolve - Look in the DwarfDebug map for the MDNode that
172 /// corresponds to the reference.
173 template <typename T> T *resolve(TypedDebugNodeRef<T> Ref) const;
177 /// \brief Helper used to pair up a symbol and its DWARF compile unit.
179 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
181 DwarfCompileUnit *CU;
184 /// \brief Collects and handles dwarf debug information.
185 class DwarfDebug : public AsmPrinterHandler {
186 // Target of Dwarf emission.
189 // Collected machine module information.
190 MachineModuleInfo *MMI;
192 // All DIEValues are allocated through this allocator.
193 BumpPtrAllocator DIEValueAllocator;
195 // Maps MDNode with its corresponding DwarfCompileUnit.
196 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
198 // Maps subprogram MDNode with its corresponding DwarfCompileUnit.
199 MapVector<const MDNode *, DwarfCompileUnit *> SPMap;
201 // Maps a CU DIE with its corresponding DwarfCompileUnit.
202 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
204 // List of all labels used in aranges generation.
205 std::vector<SymbolCU> ArangeLabels;
207 // Size of each symbol emitted (for those symbols that have a specific size).
208 DenseMap<const MCSymbol *, uint64_t> SymSize;
210 LexicalScopes LScopes;
212 // Collection of abstract variables.
213 DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
214 SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
216 // Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
217 // can refer to them in spite of insertions into this list.
218 DebugLocStream DebugLocs;
220 // This is a collection of subprogram MDNodes that are processed to
222 SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
224 // Maps instruction with label emitted before instruction.
225 DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
227 // Maps instruction with label emitted after instruction.
228 DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
230 // History of DBG_VALUE and clobber instructions for each user variable.
231 // Variables are listed in order of appearance.
232 DbgValueHistoryMap DbgValues;
234 // Previous instruction's location information. This is used to determine
235 // label location to indicate scope boundries in dwarf debug info.
236 DebugLoc PrevInstLoc;
239 // This location indicates end of function prologue and beginning of function
241 DebugLoc PrologEndLoc;
243 // If nonnull, stores the current machine function we're processing.
244 const MachineFunction *CurFn;
246 // If nonnull, stores the current machine instruction we're processing.
247 const MachineInstr *CurMI;
249 // If nonnull, stores the CU in which the previous subprogram was contained.
250 const DwarfCompileUnit *PrevCU;
252 // As an optimization, there is no need to emit an entry in the directory
253 // table for the same directory as DW_AT_comp_dir.
254 StringRef CompilationDir;
256 // Holder for the file specific debug information.
257 DwarfFile InfoHolder;
259 // Holders for the various debug information flags that we might need to
260 // have exposed. See accessor functions below for description.
262 // Holder for imported entities.
263 typedef SmallVector<std::pair<const MDNode *, const MDNode *>, 32>
265 ImportedEntityMap ScopesWithImportedEntities;
267 // Map from MDNodes for user-defined types to the type units that describe
269 DenseMap<const MDNode *, const DwarfTypeUnit *> DwarfTypeUnits;
272 std::pair<std::unique_ptr<DwarfTypeUnit>, const MDCompositeType *>, 1>
273 TypeUnitsUnderConstruction;
275 // Whether to emit the pubnames/pubtypes sections.
276 bool HasDwarfPubSections;
278 // Whether or not to use AT_ranges for compilation units.
281 // Whether we emitted a function into a section other than the default
283 bool UsedNonDefaultText;
285 // Whether to use the GNU TLS opcode (instead of the standard opcode).
286 bool UseGNUTLSOpcode;
288 // Version of dwarf we're emitting.
289 unsigned DwarfVersion;
291 // Maps from a type identifier to the actual MDNode.
292 DITypeIdentifierMap TypeIdentifierMap;
294 // DWARF5 Experimental Options
295 bool HasDwarfAccelTables;
298 // Separated Dwarf Variables
299 // In general these will all be for bits that are left in the
300 // original object file, rather than things that are meant
301 // to be in the .dwo sections.
303 // Holder for the skeleton information.
304 DwarfFile SkeletonHolder;
306 /// Store file names for type units under fission in a line table header that
307 /// will be emitted into debug_line.dwo.
308 // FIXME: replace this with a map from comp_dir to table so that we can emit
309 // multiple tables during LTO each of which uses directory 0, referencing the
310 // comp_dir of all the type units that use it.
311 MCDwarfDwoLineTable SplitTypeUnitFileTable;
313 // True iff there are multiple CUs in this module.
318 AddressPool AddrPool;
320 DwarfAccelTable AccelNames;
321 DwarfAccelTable AccelObjC;
322 DwarfAccelTable AccelNamespace;
323 DwarfAccelTable AccelTypes;
325 DenseMap<const Function *, MDSubprogram *> FunctionDIs;
327 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
329 const SmallVectorImpl<std::unique_ptr<DwarfUnit>> &getUnits() {
330 return InfoHolder.getUnits();
333 typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
335 /// \brief Find abstract variable associated with Var.
336 DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
337 DIVariable &Cleansed);
338 DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
339 void createAbstractVariable(const DIVariable &DV, LexicalScope *Scope);
340 void ensureAbstractVariableIsCreated(InlinedVariable Var,
341 const MDNode *Scope);
342 void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var,
343 const MDNode *Scope);
345 /// \brief Construct a DIE for this abstract scope.
346 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
348 /// \brief Compute the size and offset of a DIE given an incoming Offset.
349 unsigned computeSizeAndOffset(DIE *Die, unsigned Offset);
351 /// \brief Compute the size and offset of all the DIEs.
352 void computeSizeAndOffsets();
354 /// \brief Collect info for variables that were optimized out.
355 void collectDeadVariables();
357 void finishVariableDefinitions();
359 void finishSubprogramDefinitions();
361 /// \brief Finish off debug information after all functions have been
363 void finalizeModuleInfo();
365 /// \brief Emit the debug info section.
366 void emitDebugInfo();
368 /// \brief Emit the abbreviation section.
369 void emitAbbreviations();
371 /// \brief Emit a specified accelerator table.
372 void emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
373 StringRef TableName);
375 /// \brief Emit visible names into a hashed accelerator table section.
376 void emitAccelNames();
378 /// \brief Emit objective C classes and categories into a hashed
379 /// accelerator table section.
380 void emitAccelObjC();
382 /// \brief Emit namespace dies into a hashed accelerator table.
383 void emitAccelNamespaces();
385 /// \brief Emit type dies into a hashed accelerator table.
386 void emitAccelTypes();
388 /// \brief Emit visible names into a debug pubnames section.
389 /// \param GnuStyle determines whether or not we want to emit
390 /// additional information into the table ala newer gcc for gdb
392 void emitDebugPubNames(bool GnuStyle = false);
394 /// \brief Emit visible types into a debug pubtypes section.
395 /// \param GnuStyle determines whether or not we want to emit
396 /// additional information into the table ala newer gcc for gdb
398 void emitDebugPubTypes(bool GnuStyle = false);
400 void emitDebugPubSection(
401 bool GnuStyle, const MCSection *PSec, StringRef Name,
402 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
404 /// \brief Emit visible names into a debug str section.
407 /// \brief Emit visible names into a debug loc section.
410 /// \brief Emit visible names into a debug loc dwo section.
411 void emitDebugLocDWO();
413 /// \brief Emit visible names into a debug aranges section.
414 void emitDebugARanges();
416 /// \brief Emit visible names into a debug ranges section.
417 void emitDebugRanges();
419 /// \brief Emit inline info using custom format.
420 void emitDebugInlineInfo();
422 /// DWARF 5 Experimental Split Dwarf Emitters
424 /// \brief Initialize common features of skeleton units.
425 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
426 std::unique_ptr<DwarfUnit> NewU);
428 /// \brief Construct the split debug info compile unit for the debug info
430 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
432 /// \brief Construct the split debug info compile unit for the debug info
434 DwarfTypeUnit &constructSkeletonTU(DwarfTypeUnit &TU);
436 /// \brief Emit the debug info dwo section.
437 void emitDebugInfoDWO();
439 /// \brief Emit the debug abbrev dwo section.
440 void emitDebugAbbrevDWO();
442 /// \brief Emit the debug line dwo section.
443 void emitDebugLineDWO();
445 /// \brief Emit the debug str dwo section.
446 void emitDebugStrDWO();
448 /// Flags to let the linker know we have emitted new style pubnames. Only
449 /// emit it here if we don't have a skeleton CU for split dwarf.
450 void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
452 /// \brief Create new DwarfCompileUnit for the given metadata node with tag
453 /// DW_TAG_compile_unit.
454 DwarfCompileUnit &constructDwarfCompileUnit(DICompileUnit DIUnit);
456 /// \brief Construct imported_module or imported_declaration DIE.
457 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
460 /// \brief Register a source line with debug info. Returns the unique
461 /// label that was emitted and which provides correspondence to the
462 /// source line list.
463 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
466 /// \brief Indentify instructions that are marking the beginning of or
467 /// ending of a scope.
468 void identifyScopeMarkers();
470 /// \brief Populate LexicalScope entries with variables' info.
471 void collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
472 DenseSet<InlinedVariable> &ProcessedVars);
474 /// \brief Build the location list for all DBG_VALUEs in the
475 /// function that describe the same variable.
476 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
477 const DbgValueHistoryMap::InstrRanges &Ranges);
479 /// \brief Collect variable information from the side table maintained
481 void collectVariableInfoFromMMITable(DenseSet<InlinedVariable> &P);
483 /// \brief Ensure that a label will be emitted before MI.
484 void requestLabelBeforeInsn(const MachineInstr *MI) {
485 LabelsBeforeInsn.insert(std::make_pair(MI, nullptr));
488 /// \brief Ensure that a label will be emitted after MI.
489 void requestLabelAfterInsn(const MachineInstr *MI) {
490 LabelsAfterInsn.insert(std::make_pair(MI, nullptr));
494 //===--------------------------------------------------------------------===//
495 // Main entry points.
497 DwarfDebug(AsmPrinter *A, Module *M);
499 ~DwarfDebug() override;
501 /// \brief Emit all Dwarf sections that should come prior to the
505 /// \brief Emit all Dwarf sections that should come after the content.
506 void endModule() override;
508 /// \brief Gather pre-function debug information.
509 void beginFunction(const MachineFunction *MF) override;
511 /// \brief Gather and emit post-function debug information.
512 void endFunction(const MachineFunction *MF) override;
514 /// \brief Process beginning of an instruction.
515 void beginInstruction(const MachineInstr *MI) override;
517 /// \brief Process end of an instruction.
518 void endInstruction() override;
520 /// \brief Add a DIE to the set of types that we're going to pull into
522 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
523 DIE &Die, const MDCompositeType *CTy);
525 /// \brief Add a label so that arange data can be generated for it.
526 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
528 /// \brief For symbols that have a size designated (e.g. common symbols),
529 /// this tracks that size.
530 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
534 /// \brief Returns whether to use DW_OP_GNU_push_tls_address, instead of the
535 /// standard DW_OP_form_tls_address opcode
536 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
538 // Experimental DWARF5 features.
540 /// \brief Returns whether or not to emit tables that dwarf consumers can
541 /// use to accelerate lookup.
542 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
544 /// \brief Returns whether or not to change the current debug info for the
545 /// split dwarf proposal support.
546 bool useSplitDwarf() const { return HasSplitDwarf; }
548 /// Returns the Dwarf Version.
549 unsigned getDwarfVersion() const { return DwarfVersion; }
551 /// Returns the previous CU that was being updated
552 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
553 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
555 /// Returns the entries for the .debug_loc section.
556 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
558 /// \brief Emit an entry for the debug loc section. This can be used to
559 /// handle an entry that's going to be emitted into the debug loc section.
560 void emitDebugLocEntry(ByteStreamer &Streamer,
561 const DebugLocStream::Entry &Entry);
563 /// Emit the location for a debug loc entry, including the size header.
564 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
566 /// Find the MDNode for the given reference.
567 template <typename T> T *resolve(TypedDebugNodeRef<T> Ref) const {
568 return Ref.resolve(TypeIdentifierMap);
571 /// \brief Return the TypeIdentifierMap.
572 const DITypeIdentifierMap &getTypeIdentifierMap() const {
573 return TypeIdentifierMap;
576 /// Find the DwarfCompileUnit for the given CU Die.
577 DwarfCompileUnit *lookupUnit(const DIE *CU) const {
578 return CUDieMap.lookup(CU);
580 /// isSubprogramContext - Return true if Context is either a subprogram
581 /// or another context nested inside a subprogram.
582 bool isSubprogramContext(const MDNode *Context);
584 void addSubprogramNames(DISubprogram SP, DIE &Die);
586 AddressPool &getAddressPool() { return AddrPool; }
588 void addAccelName(StringRef Name, const DIE &Die);
590 void addAccelObjC(StringRef Name, const DIE &Die);
592 void addAccelNamespace(StringRef Name, const DIE &Die);
594 void addAccelType(StringRef Name, const DIE &Die, char Flags);
596 const MachineFunction *getCurrentFunction() const { return CurFn; }
598 iterator_range<ImportedEntityMap::const_iterator>
599 findImportedEntitiesForScope(const MDNode *Scope) const {
600 return make_range(std::equal_range(
601 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
602 std::pair<const MDNode *, const MDNode *>(Scope, nullptr),
606 /// \brief A helper function to check whether the DIE for a given Scope is
607 /// going to be null.
608 bool isLexicalScopeDIENull(LexicalScope *Scope);
610 /// \brief Return Label preceding the instruction.
611 MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
613 /// \brief Return Label immediately following the instruction.
614 MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
616 // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
618 SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
619 return ProcessedSPNodes;
622 } // End of namespace llvm