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 "AddressPool.h"
18 #include "DbgValueHistoryCalculator.h"
19 #include "DebugHandlerBase.h"
20 #include "DebugLocStream.h"
21 #include "DwarfFile.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/MapVector.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/BinaryFormat/Dwarf.h"
33 #include "llvm/CodeGen/AccelTable.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/IR/DebugInfoMetadata.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/MC/MCDwarf.h"
39 #include "llvm/Support/Allocator.h"
40 #include "llvm/Target/TargetOptions.h"
54 class DwarfCompileUnit;
58 class MachineFunction;
64 //===----------------------------------------------------------------------===//
65 /// This class is used to track local variable information.
67 /// Variables can be created from allocas, in which case they're generated from
68 /// the MMI table. Such variables can have multiple expressions and frame
71 /// Variables can be created from \c DBG_VALUE instructions. Those whose
72 /// location changes over time use \a DebugLocListIndex, while those with a
73 /// single instruction use \a MInsn and (optionally) a single entry of \a Expr.
75 /// Variables that have been optimized out use none of these fields.
77 const DILocalVariable *Var; /// Variable Descriptor.
78 const DILocation *IA; /// Inlined at location.
79 DIE *TheDIE = nullptr; /// Variable DIE.
80 unsigned DebugLocListIndex = ~0u; /// Offset in DebugLocs.
81 const MachineInstr *MInsn = nullptr; /// DBG_VALUE instruction.
83 struct FrameIndexExpr {
85 const DIExpression *Expr;
87 mutable SmallVector<FrameIndexExpr, 1>
88 FrameIndexExprs; /// Frame index + expression.
91 /// Construct a DbgVariable.
93 /// Creates a variable without any DW_AT_location. Call \a initializeMMI()
94 /// for MMI entries, or \a initializeDbgValue() for DBG_VALUE instructions.
95 DbgVariable(const DILocalVariable *V, const DILocation *IA)
98 /// Initialize from the MMI table.
99 void initializeMMI(const DIExpression *E, int FI) {
100 assert(FrameIndexExprs.empty() && "Already initialized?");
101 assert(!MInsn && "Already initialized?");
103 assert((!E || E->isValid()) && "Expected valid expression");
104 assert(FI != std::numeric_limits<int>::max() && "Expected valid index");
106 FrameIndexExprs.push_back({FI, E});
109 /// Initialize from a DBG_VALUE instruction.
110 void initializeDbgValue(const MachineInstr *DbgValue) {
111 assert(FrameIndexExprs.empty() && "Already initialized?");
112 assert(!MInsn && "Already initialized?");
114 assert(Var == DbgValue->getDebugVariable() && "Wrong variable");
115 assert(IA == DbgValue->getDebugLoc()->getInlinedAt() && "Wrong inlined-at");
118 if (auto *E = DbgValue->getDebugExpression())
119 if (E->getNumElements())
120 FrameIndexExprs.push_back({0, E});
124 const DILocalVariable *getVariable() const { return Var; }
125 const DILocation *getInlinedAt() const { return IA; }
127 const DIExpression *getSingleExpression() const {
128 assert(MInsn && FrameIndexExprs.size() <= 1);
129 return FrameIndexExprs.size() ? FrameIndexExprs[0].Expr : nullptr;
132 void setDIE(DIE &D) { TheDIE = &D; }
133 DIE *getDIE() const { return TheDIE; }
134 void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
135 unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
136 StringRef getName() const { return Var->getName(); }
137 const MachineInstr *getMInsn() const { return MInsn; }
138 /// Get the FI entries, sorted by fragment offset.
139 ArrayRef<FrameIndexExpr> getFrameIndexExprs() const;
140 bool hasFrameIndexExprs() const { return !FrameIndexExprs.empty(); }
141 void addMMIEntry(const DbgVariable &V);
143 // Translate tag to proper Dwarf tag.
144 dwarf::Tag getTag() const {
145 // FIXME: Why don't we just infer this tag and store it all along?
146 if (Var->isParameter())
147 return dwarf::DW_TAG_formal_parameter;
149 return dwarf::DW_TAG_variable;
152 /// Return true if DbgVariable is artificial.
153 bool isArtificial() const {
154 if (Var->isArtificial())
156 if (getType()->isArtificial())
161 bool isObjectPointer() const {
162 if (Var->isObjectPointer())
164 if (getType()->isObjectPointer())
169 bool hasComplexAddress() const {
170 assert(MInsn && "Expected DBG_VALUE, not MMI variable");
171 assert((FrameIndexExprs.empty() ||
172 (FrameIndexExprs.size() == 1 &&
173 FrameIndexExprs[0].Expr->getNumElements())) &&
174 "Invalid Expr for DBG_VALUE");
175 return !FrameIndexExprs.empty();
178 bool isBlockByrefVariable() const;
179 const DIType *getType() const;
182 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
183 return Ref.resolve();
187 /// Helper used to pair up a symbol and its DWARF compile unit.
189 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
192 DwarfCompileUnit *CU;
195 /// Collects and handles dwarf debug information.
196 class DwarfDebug : public DebugHandlerBase {
197 /// All DIEValues are allocated through this allocator.
198 BumpPtrAllocator DIEValueAllocator;
200 /// Maps MDNode with its corresponding DwarfCompileUnit.
201 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
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 /// Collection of abstract variables.
213 SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
215 /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
216 /// can refer to them in spite of insertions into this list.
217 DebugLocStream DebugLocs;
219 /// This is a collection of subprogram MDNodes that are processed to
221 SetVector<const DISubprogram *, SmallVector<const DISubprogram *, 16>,
222 SmallPtrSet<const DISubprogram *, 16>>
225 /// If nonnull, stores the current machine function we're processing.
226 const MachineFunction *CurFn = nullptr;
228 /// If nonnull, stores the CU in which the previous subprogram was contained.
229 const DwarfCompileUnit *PrevCU;
231 /// As an optimization, there is no need to emit an entry in the directory
232 /// table for the same directory as DW_AT_comp_dir.
233 StringRef CompilationDir;
235 /// Holder for the file specific debug information.
236 DwarfFile InfoHolder;
238 /// Holders for the various debug information flags that we might need to
239 /// have exposed. See accessor functions below for description.
241 /// Map from MDNodes for user-defined types to their type signatures. Also
242 /// used to keep track of which types we have emitted type units for.
243 DenseMap<const MDNode *, uint64_t> TypeSignatures;
246 std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
247 TypeUnitsUnderConstruction;
249 /// Whether to use the GNU TLS opcode (instead of the standard opcode).
250 bool UseGNUTLSOpcode;
252 /// Whether to use DWARF 2 bitfields (instead of the DWARF 4 format).
253 bool UseDWARF2Bitfields;
255 /// Whether to emit all linkage names, or just abstract subprograms.
256 bool UseAllLinkageNames;
258 /// DWARF5 Experimental Options
260 bool HasDwarfAccelTables;
261 bool HasAppleExtensionAttributes;
264 /// Whether to generate the DWARF v5 string offsets table.
265 /// It consists of a series of contributions, each preceded by a header.
266 /// The pre-DWARF v5 string offsets table for split dwarf is, in contrast,
267 /// a monolithic sequence of string offsets.
268 bool UseSegmentedStringOffsetsTable;
270 /// Separated Dwarf Variables
271 /// In general these will all be for bits that are left in the
272 /// original object file, rather than things that are meant
273 /// to be in the .dwo sections.
275 /// Holder for the skeleton information.
276 DwarfFile SkeletonHolder;
278 /// Store file names for type units under fission in a line table
279 /// header that will be emitted into debug_line.dwo.
280 // FIXME: replace this with a map from comp_dir to table so that we
281 // can emit multiple tables during LTO each of which uses directory
282 // 0, referencing the comp_dir of all the type units that use it.
283 MCDwarfDwoLineTable SplitTypeUnitFileTable;
286 /// True iff there are multiple CUs in this module.
290 AddressPool AddrPool;
292 /// Apple accelerator tables.
293 AppleAccelTable<AppleAccelTableOffsetData> AccelNames;
294 AppleAccelTable<AppleAccelTableOffsetData> AccelObjC;
295 AppleAccelTable<AppleAccelTableOffsetData> AccelNamespace;
296 AppleAccelTable<AppleAccelTableTypeData> AccelTypes;
298 // Identify a debugger for "tuning" the debug info.
299 DebuggerKind DebuggerTuning = DebuggerKind::Default;
301 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
303 const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
304 return InfoHolder.getUnits();
307 using InlinedVariable = DbgValueHistoryMap::InlinedVariable;
309 void ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable Var,
310 const MDNode *Scope);
311 void ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU, InlinedVariable Var,
312 const MDNode *Scope);
314 DbgVariable *createConcreteVariable(DwarfCompileUnit &TheCU,
315 LexicalScope &Scope, InlinedVariable IV);
317 /// Construct a DIE for this abstract scope.
318 void constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, LexicalScope *Scope);
320 void finishVariableDefinitions();
322 void finishSubprogramDefinitions();
324 /// Finish off debug information after all functions have been
326 void finalizeModuleInfo();
328 /// Emit the debug info section.
329 void emitDebugInfo();
331 /// Emit the abbreviation section.
332 void emitAbbreviations();
334 /// Emit the string offsets table header.
335 void emitStringOffsetsTableHeader();
337 /// Emit a specified accelerator table.
338 template <typename AccelTableT>
339 void emitAccel(AccelTableT &Accel, MCSection *Section, StringRef TableName);
341 /// Emit visible names into a hashed accelerator table section.
342 void emitAccelNames();
344 /// Emit objective C classes and categories into a hashed
345 /// accelerator table section.
346 void emitAccelObjC();
348 /// Emit namespace dies into a hashed accelerator table.
349 void emitAccelNamespaces();
351 /// Emit type dies into a hashed accelerator table.
352 void emitAccelTypes();
354 /// Emit visible names and types into debug pubnames and pubtypes sections.
355 void emitDebugPubSections();
357 void emitDebugPubSection(bool GnuStyle, StringRef Name,
358 DwarfCompileUnit *TheU,
359 const StringMap<const DIE *> &Globals);
361 /// Emit null-terminated strings into a debug str section.
364 /// Emit variable locations into a debug loc section.
367 /// Emit variable locations into a debug loc dwo section.
368 void emitDebugLocDWO();
370 /// Emit address ranges into a debug aranges section.
371 void emitDebugARanges();
373 /// Emit address ranges into a debug ranges section.
374 void emitDebugRanges();
376 /// Emit macros into a debug macinfo section.
377 void emitDebugMacinfo();
378 void emitMacro(DIMacro &M);
379 void emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U);
380 void handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U);
382 /// DWARF 5 Experimental Split Dwarf Emitters
384 /// Initialize common features of skeleton units.
385 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
386 std::unique_ptr<DwarfCompileUnit> NewU);
388 /// Construct the split debug info compile unit for the debug info
390 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
392 /// Emit the debug info dwo section.
393 void emitDebugInfoDWO();
395 /// Emit the debug abbrev dwo section.
396 void emitDebugAbbrevDWO();
398 /// Emit the debug line dwo section.
399 void emitDebugLineDWO();
401 /// Emit the dwo stringoffsets table header.
402 void emitStringOffsetsTableHeaderDWO();
404 /// Emit the debug str dwo section.
405 void emitDebugStrDWO();
407 /// Flags to let the linker know we have emitted new style pubnames. Only
408 /// emit it here if we don't have a skeleton CU for split dwarf.
409 void addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const;
411 /// Create new DwarfCompileUnit for the given metadata node with tag
412 /// DW_TAG_compile_unit.
413 DwarfCompileUnit &getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit);
415 /// Construct imported_module or imported_declaration DIE.
416 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
417 const DIImportedEntity *N);
419 /// Register a source line with debug info. Returns the unique
420 /// label that was emitted and which provides correspondence to the
421 /// source line list.
422 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
425 /// Populate LexicalScope entries with variables' info.
426 void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
427 DenseSet<InlinedVariable> &ProcessedVars);
429 /// Build the location list for all DBG_VALUEs in the
430 /// function that describe the same variable.
431 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
432 const DbgValueHistoryMap::InstrRanges &Ranges);
434 /// Collect variable information from the side table maintained by MF.
435 void collectVariableInfoFromMFTable(DwarfCompileUnit &TheCU,
436 DenseSet<InlinedVariable> &P);
439 /// Gather pre-function debug information.
440 void beginFunctionImpl(const MachineFunction *MF) override;
442 /// Gather and emit post-function debug information.
443 void endFunctionImpl(const MachineFunction *MF) override;
445 void skippedNonDebugFunction() override;
448 //===--------------------------------------------------------------------===//
449 // Main entry points.
451 DwarfDebug(AsmPrinter *A, Module *M);
453 ~DwarfDebug() override;
455 /// Emit all Dwarf sections that should come prior to the
459 /// Emit all Dwarf sections that should come after the content.
460 void endModule() override;
462 /// Process beginning of an instruction.
463 void beginInstruction(const MachineInstr *MI) override;
465 /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
466 static uint64_t makeTypeSignature(StringRef Identifier);
468 /// Add a DIE to the set of types that we're going to pull into
470 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
471 DIE &Die, const DICompositeType *CTy);
473 /// Add a label so that arange data can be generated for it.
474 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
476 /// For symbols that have a size designated (e.g. common symbols),
477 /// this tracks that size.
478 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
482 /// Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
483 /// If not, we still might emit certain cases.
484 bool useAllLinkageNames() const { return UseAllLinkageNames; }
486 /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
487 /// standard DW_OP_form_tls_address opcode
488 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
490 /// Returns whether to use the DWARF2 format for bitfields instyead of the
492 bool useDWARF2Bitfields() const { return UseDWARF2Bitfields; }
494 // Experimental DWARF5 features.
496 /// Returns whether or not to emit tables that dwarf consumers can
497 /// use to accelerate lookup.
498 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
500 bool useAppleExtensionAttributes() const {
501 return HasAppleExtensionAttributes;
504 /// Returns whether or not to change the current debug info for the
505 /// split dwarf proposal support.
506 bool useSplitDwarf() const { return HasSplitDwarf; }
508 /// Returns whether to generate a string offsets table with (possibly shared)
509 /// contributions from each CU and type unit. This implies the use of
510 /// DW_FORM_strx* indirect references with DWARF v5 and beyond. Note that
511 /// DW_FORM_GNU_str_index is also an indirect reference, but it is used with
512 /// a pre-DWARF v5 implementation of split DWARF sections, which uses a
513 /// monolithic string offsets table.
514 bool useSegmentedStringOffsetsTable() const {
515 return UseSegmentedStringOffsetsTable;
518 bool shareAcrossDWOCUs() const;
520 /// Returns the Dwarf Version.
521 uint16_t getDwarfVersion() const;
523 /// Returns the previous CU that was being updated
524 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
525 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
527 /// Returns the entries for the .debug_loc section.
528 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
530 /// Emit an entry for the debug loc section. This can be used to
531 /// handle an entry that's going to be emitted into the debug loc section.
532 void emitDebugLocEntry(ByteStreamer &Streamer,
533 const DebugLocStream::Entry &Entry);
535 /// Emit the location for a debug loc entry, including the size header.
536 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
538 /// Find the MDNode for the given reference.
539 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
540 return Ref.resolve();
543 void addSubprogramNames(const DISubprogram *SP, DIE &Die);
545 AddressPool &getAddressPool() { return AddrPool; }
547 void addAccelName(StringRef Name, const DIE &Die);
549 void addAccelObjC(StringRef Name, const DIE &Die);
551 void addAccelNamespace(StringRef Name, const DIE &Die);
553 void addAccelType(StringRef Name, const DIE &Die, char Flags);
555 const MachineFunction *getCurrentFunction() const { return CurFn; }
557 /// A helper function to check whether the DIE for a given Scope is
558 /// going to be null.
559 bool isLexicalScopeDIENull(LexicalScope *Scope);
561 /// Find the matching DwarfCompileUnit for the given CU DIE.
562 DwarfCompileUnit *lookupCU(const DIE *Die) { return CUDieMap.lookup(Die); }
564 /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
566 /// Returns whether we are "tuning" for a given debugger.
568 bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
569 bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
570 bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
574 } // end namespace llvm
576 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H