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 /// The kind of accelerator tables we should emit.
196 enum class AccelTableKind {
197 Default, ///< Platform default.
199 Apple, ///< .apple_names, .apple_namespaces, .apple_types, .apple_objc.
200 Dwarf, ///< DWARF v5 .debug_names.
203 /// Collects and handles dwarf debug information.
204 class DwarfDebug : public DebugHandlerBase {
205 /// All DIEValues are allocated through this allocator.
206 BumpPtrAllocator DIEValueAllocator;
208 /// Maps MDNode with its corresponding DwarfCompileUnit.
209 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
211 /// Maps a CU DIE with its corresponding DwarfCompileUnit.
212 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
214 /// List of all labels used in aranges generation.
215 std::vector<SymbolCU> ArangeLabels;
217 /// Size of each symbol emitted (for those symbols that have a specific size).
218 DenseMap<const MCSymbol *, uint64_t> SymSize;
220 /// Collection of abstract variables.
221 SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
223 /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
224 /// can refer to them in spite of insertions into this list.
225 DebugLocStream DebugLocs;
227 /// This is a collection of subprogram MDNodes that are processed to
229 SetVector<const DISubprogram *, SmallVector<const DISubprogram *, 16>,
230 SmallPtrSet<const DISubprogram *, 16>>
233 /// If nonnull, stores the current machine function we're processing.
234 const MachineFunction *CurFn = nullptr;
236 /// If nonnull, stores the CU in which the previous subprogram was contained.
237 const DwarfCompileUnit *PrevCU;
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 /// Holder for the file specific debug information.
244 DwarfFile InfoHolder;
246 /// Holders for the various debug information flags that we might need to
247 /// have exposed. See accessor functions below for description.
249 /// Map from MDNodes for user-defined types to their type signatures. Also
250 /// used to keep track of which types we have emitted type units for.
251 DenseMap<const MDNode *, uint64_t> TypeSignatures;
254 std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
255 TypeUnitsUnderConstruction;
257 /// Whether to use the GNU TLS opcode (instead of the standard opcode).
258 bool UseGNUTLSOpcode;
260 /// Whether to use DWARF 2 bitfields (instead of the DWARF 4 format).
261 bool UseDWARF2Bitfields;
263 /// Whether to emit all linkage names, or just abstract subprograms.
264 bool UseAllLinkageNames;
266 /// Use inlined strings.
267 bool UseInlineStrings = false;
269 /// Whether to emit DWARF pub sections or not.
270 bool UsePubSections = true;
272 /// Allow emission of .debug_ranges section.
273 bool UseRangesSection = true;
275 /// True if the sections itself must be used as references and don't create
276 /// temp symbols inside DWARF sections.
277 bool UseSectionsAsReferences = false;
279 ///Allow emission of the .debug_loc section.
280 bool UseLocSection = true;
282 /// Generate DWARF v4 type units.
283 bool GenerateTypeUnits;
285 /// DWARF5 Experimental Options
287 AccelTableKind TheAccelTableKind;
288 bool HasAppleExtensionAttributes;
291 /// Whether to generate the DWARF v5 string offsets table.
292 /// It consists of a series of contributions, each preceded by a header.
293 /// The pre-DWARF v5 string offsets table for split dwarf is, in contrast,
294 /// a monolithic sequence of string offsets.
295 bool UseSegmentedStringOffsetsTable;
297 /// Separated Dwarf Variables
298 /// In general these will all be for bits that are left in the
299 /// original object file, rather than things that are meant
300 /// to be in the .dwo sections.
302 /// Holder for the skeleton information.
303 DwarfFile SkeletonHolder;
305 /// Store file names for type units under fission in a line table
306 /// header that will be emitted into debug_line.dwo.
307 // FIXME: replace this with a map from comp_dir to table so that we
308 // can emit multiple tables during LTO each of which uses directory
309 // 0, referencing the comp_dir of all the type units that use it.
310 MCDwarfDwoLineTable SplitTypeUnitFileTable;
313 /// True iff there are multiple CUs in this module.
317 AddressPool AddrPool;
319 /// Accelerator tables.
320 AccelTable<DWARF5AccelTableData> AccelDebugNames;
321 AccelTable<AppleAccelTableOffsetData> AccelNames;
322 AccelTable<AppleAccelTableOffsetData> AccelObjC;
323 AccelTable<AppleAccelTableOffsetData> AccelNamespace;
324 AccelTable<AppleAccelTableTypeData> AccelTypes;
326 // Identify a debugger for "tuning" the debug info.
327 DebuggerKind DebuggerTuning = DebuggerKind::Default;
329 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
331 const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
332 return InfoHolder.getUnits();
335 using InlinedVariable = DbgValueHistoryMap::InlinedVariable;
337 void ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable IV,
338 const MDNode *Scope);
339 void ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU, InlinedVariable IV,
340 const MDNode *Scope);
342 DbgVariable *createConcreteVariable(DwarfCompileUnit &TheCU,
343 LexicalScope &Scope, InlinedVariable IV);
345 /// Construct a DIE for this abstract scope.
346 void constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, LexicalScope *Scope);
348 template <typename DataT>
349 void addAccelNameImpl(AccelTable<DataT> &AppleAccel, StringRef Name,
352 void finishVariableDefinitions();
354 void finishSubprogramDefinitions();
356 /// Finish off debug information after all functions have been
358 void finalizeModuleInfo();
360 /// Emit the debug info section.
361 void emitDebugInfo();
363 /// Emit the abbreviation section.
364 void emitAbbreviations();
366 /// Emit the string offsets table header.
367 void emitStringOffsetsTableHeader();
369 /// Emit a specified accelerator table.
370 template <typename AccelTableT>
371 void emitAccel(AccelTableT &Accel, MCSection *Section, StringRef TableName);
373 /// Emit DWARF v5 accelerator table.
374 void emitAccelDebugNames();
376 /// Emit visible names into a hashed accelerator table section.
377 void emitAccelNames();
379 /// Emit objective C classes and categories into a hashed
380 /// accelerator table section.
381 void emitAccelObjC();
383 /// Emit namespace dies into a hashed accelerator table.
384 void emitAccelNamespaces();
386 /// Emit type dies into a hashed accelerator table.
387 void emitAccelTypes();
389 /// Emit visible names and types into debug pubnames and pubtypes sections.
390 void emitDebugPubSections();
392 void emitDebugPubSection(bool GnuStyle, StringRef Name,
393 DwarfCompileUnit *TheU,
394 const StringMap<const DIE *> &Globals);
396 /// Emit null-terminated strings into a debug str section.
399 /// Emit variable locations into a debug loc section.
402 /// Emit variable locations into a debug loc dwo section.
403 void emitDebugLocDWO();
405 /// Emit address ranges into a debug aranges section.
406 void emitDebugARanges();
408 /// Emit address ranges into a debug ranges section.
409 void emitDebugRanges();
411 /// Emit range lists into a DWARF v5 debug rnglists section.
412 void emitDebugRnglists();
414 /// Emit macros into a debug macinfo section.
415 void emitDebugMacinfo();
416 void emitMacro(DIMacro &M);
417 void emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U);
418 void handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U);
420 /// DWARF 5 Experimental Split Dwarf Emitters
422 /// Initialize common features of skeleton units.
423 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
424 std::unique_ptr<DwarfCompileUnit> NewU);
426 /// Construct the split debug info compile unit for the debug info section.
427 /// In DWARF v5, the skeleton unit DIE may have the following attributes:
428 /// DW_AT_addr_base, DW_AT_comp_dir, DW_AT_dwo_name, DW_AT_high_pc,
429 /// DW_AT_low_pc, DW_AT_ranges, DW_AT_stmt_list, and DW_AT_str_offsets_base.
430 /// Prior to DWARF v5 it may also have DW_AT_GNU_dwo_id. DW_AT_GNU_dwo_name
431 /// is used instead of DW_AT_dwo_name, Dw_AT_GNU_addr_base instead of
432 /// DW_AT_addr_base, and DW_AT_GNU_ranges_base instead of DW_AT_rnglists_base.
433 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
435 /// Emit the debug info dwo section.
436 void emitDebugInfoDWO();
438 /// Emit the debug abbrev dwo section.
439 void emitDebugAbbrevDWO();
441 /// Emit the debug line dwo section.
442 void emitDebugLineDWO();
444 /// Emit the dwo stringoffsets table header.
445 void emitStringOffsetsTableHeaderDWO();
447 /// 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(DwarfCompileUnit &U, DIE &D) const;
454 /// Create new DwarfCompileUnit for the given metadata node with tag
455 /// DW_TAG_compile_unit.
456 DwarfCompileUnit &getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit);
458 /// Construct imported_module or imported_declaration DIE.
459 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
460 const DIImportedEntity *N);
462 /// 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 /// Populate LexicalScope entries with variables' info.
469 void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
470 DenseSet<InlinedVariable> &ProcessedVars);
472 /// Build the location list for all DBG_VALUEs in the
473 /// function that describe the same variable.
474 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
475 const DbgValueHistoryMap::InstrRanges &Ranges);
477 /// Collect variable information from the side table maintained by MF.
478 void collectVariableInfoFromMFTable(DwarfCompileUnit &TheCU,
479 DenseSet<InlinedVariable> &P);
481 /// Emit the reference to the section.
482 void emitSectionReference(const DwarfCompileUnit &CU);
485 /// Gather pre-function debug information.
486 void beginFunctionImpl(const MachineFunction *MF) override;
488 /// Gather and emit post-function debug information.
489 void endFunctionImpl(const MachineFunction *MF) override;
491 void skippedNonDebugFunction() override;
494 //===--------------------------------------------------------------------===//
495 // Main entry points.
497 DwarfDebug(AsmPrinter *A, Module *M);
499 ~DwarfDebug() override;
501 /// Emit all Dwarf sections that should come prior to the
505 /// Emit all Dwarf sections that should come after the content.
506 void endModule() override;
508 /// Process beginning of an instruction.
509 void beginInstruction(const MachineInstr *MI) override;
511 /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
512 static uint64_t makeTypeSignature(StringRef Identifier);
514 /// Add a DIE to the set of types that we're going to pull into
516 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
517 DIE &Die, const DICompositeType *CTy);
519 /// Add a label so that arange data can be generated for it.
520 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
522 /// For symbols that have a size designated (e.g. common symbols),
523 /// this tracks that size.
524 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
528 /// Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
529 /// If not, we still might emit certain cases.
530 bool useAllLinkageNames() const { return UseAllLinkageNames; }
532 /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
533 /// standard DW_OP_form_tls_address opcode
534 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
536 /// Returns whether to use the DWARF2 format for bitfields instyead of the
538 bool useDWARF2Bitfields() const { return UseDWARF2Bitfields; }
540 /// Returns whether to use inline strings.
541 bool useInlineStrings() const { return UseInlineStrings; }
543 /// Returns whether GNU pub sections should be emitted.
544 bool usePubSections() const { return UsePubSections; }
546 /// Returns whether ranges section should be emitted.
547 bool useRangesSection() const { return UseRangesSection; }
549 /// Returns whether to use sections as labels rather than temp symbols.
550 bool useSectionsAsReferences() const {
551 return UseSectionsAsReferences;
554 /// Returns whether .debug_loc section should be emitted.
555 bool useLocSection() const { return UseLocSection; }
557 /// Returns whether to generate DWARF v4 type units.
558 bool generateTypeUnits() const { return GenerateTypeUnits; }
560 // Experimental DWARF5 features.
562 /// Returns what kind (if any) of accelerator tables to emit.
563 AccelTableKind getAccelTableKind() const { return TheAccelTableKind; }
565 bool useAppleExtensionAttributes() const {
566 return HasAppleExtensionAttributes;
569 /// Returns whether or not to change the current debug info for the
570 /// split dwarf proposal support.
571 bool useSplitDwarf() const { return HasSplitDwarf; }
573 /// Returns whether to generate a string offsets table with (possibly shared)
574 /// contributions from each CU and type unit. This implies the use of
575 /// DW_FORM_strx* indirect references with DWARF v5 and beyond. Note that
576 /// DW_FORM_GNU_str_index is also an indirect reference, but it is used with
577 /// a pre-DWARF v5 implementation of split DWARF sections, which uses a
578 /// monolithic string offsets table.
579 bool useSegmentedStringOffsetsTable() const {
580 return UseSegmentedStringOffsetsTable;
583 bool shareAcrossDWOCUs() const;
585 /// Returns the Dwarf Version.
586 uint16_t getDwarfVersion() const;
588 /// Returns the previous CU that was being updated
589 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
590 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
592 /// Returns the entries for the .debug_loc section.
593 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
595 /// Emit an entry for the debug loc section. This can be used to
596 /// handle an entry that's going to be emitted into the debug loc section.
597 void emitDebugLocEntry(ByteStreamer &Streamer,
598 const DebugLocStream::Entry &Entry);
600 /// Emit the location for a debug loc entry, including the size header.
601 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
603 /// Find the MDNode for the given reference.
604 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
605 return Ref.resolve();
608 void addSubprogramNames(const DISubprogram *SP, DIE &Die);
610 AddressPool &getAddressPool() { return AddrPool; }
612 void addAccelName(StringRef Name, const DIE &Die);
614 void addAccelObjC(StringRef Name, const DIE &Die);
616 void addAccelNamespace(StringRef Name, const DIE &Die);
618 void addAccelType(StringRef Name, const DIE &Die, char Flags);
620 const MachineFunction *getCurrentFunction() const { return CurFn; }
622 /// A helper function to check whether the DIE for a given Scope is
623 /// going to be null.
624 bool isLexicalScopeDIENull(LexicalScope *Scope);
626 /// Find the matching DwarfCompileUnit for the given CU DIE.
627 DwarfCompileUnit *lookupCU(const DIE *Die) { return CUDieMap.lookup(Die); }
628 const DwarfCompileUnit *lookupCU(const DIE *Die) const {
629 return CUDieMap.lookup(Die);
632 /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
634 /// Returns whether we are "tuning" for a given debugger.
636 bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
637 bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
638 bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
642 } // end namespace llvm
644 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H