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 "DbgValueHistoryCalculator.h"
18 #include "DebugHandlerBase.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/MapVector.h"
25 #include "llvm/ADT/SetVector.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"
36 #include "llvm/Target/TargetOptions.h"
46 class DwarfCompileUnit;
50 class MachineModuleInfo;
52 //===----------------------------------------------------------------------===//
53 /// This class is used to track local variable information.
55 /// Variables can be created from allocas, in which case they're generated from
56 /// the MMI table. Such variables can have multiple expressions and frame
59 /// Variables can be created from \c DBG_VALUE instructions. Those whose
60 /// location changes over time use \a DebugLocListIndex, while those with a
61 /// single instruction use \a MInsn and (optionally) a single entry of \a Expr.
63 /// Variables that have been optimized out use none of these fields.
65 const DILocalVariable *Var; /// Variable Descriptor.
66 const DILocation *IA; /// Inlined at location.
67 DIE *TheDIE = nullptr; /// Variable DIE.
68 unsigned DebugLocListIndex = ~0u; /// Offset in DebugLocs.
69 const MachineInstr *MInsn = nullptr; /// DBG_VALUE instruction.
71 struct FrameIndexExpr {
73 const DIExpression *Expr;
75 mutable SmallVector<FrameIndexExpr, 1>
76 FrameIndexExprs; /// Frame index + expression.
79 /// Construct a DbgVariable.
81 /// Creates a variable without any DW_AT_location. Call \a initializeMMI()
82 /// for MMI entries, or \a initializeDbgValue() for DBG_VALUE instructions.
83 DbgVariable(const DILocalVariable *V, const DILocation *IA)
86 /// Initialize from the MMI table.
87 void initializeMMI(const DIExpression *E, int FI) {
88 assert(FrameIndexExprs.empty() && "Already initialized?");
89 assert(!MInsn && "Already initialized?");
91 assert((!E || E->isValid()) && "Expected valid expression");
92 assert(FI != INT_MAX && "Expected valid index");
94 FrameIndexExprs.push_back({FI, E});
97 /// Initialize from a DBG_VALUE instruction.
98 void initializeDbgValue(const MachineInstr *DbgValue) {
99 assert(FrameIndexExprs.empty() && "Already initialized?");
100 assert(!MInsn && "Already initialized?");
102 assert(Var == DbgValue->getDebugVariable() && "Wrong variable");
103 assert(IA == DbgValue->getDebugLoc()->getInlinedAt() && "Wrong inlined-at");
106 if (auto *E = DbgValue->getDebugExpression())
107 if (E->getNumElements())
108 FrameIndexExprs.push_back({0, E});
112 const DILocalVariable *getVariable() const { return Var; }
113 const DILocation *getInlinedAt() const { return IA; }
114 const DIExpression *getSingleExpression() const {
115 assert(MInsn && FrameIndexExprs.size() <= 1);
116 return FrameIndexExprs.size() ? FrameIndexExprs[0].Expr : nullptr;
118 void setDIE(DIE &D) { TheDIE = &D; }
119 DIE *getDIE() const { return TheDIE; }
120 void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
121 unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
122 StringRef getName() const { return Var->getName(); }
123 const MachineInstr *getMInsn() const { return MInsn; }
124 /// Get the FI entries, sorted by fragment offset.
125 ArrayRef<FrameIndexExpr> getFrameIndexExprs() const;
126 bool hasFrameIndexExprs() const { return !FrameIndexExprs.empty(); }
128 void addMMIEntry(const DbgVariable &V) {
129 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
130 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
131 assert(V.Var == Var && "conflicting variable");
132 assert(V.IA == IA && "conflicting inlined-at location");
134 assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
135 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
137 if (FrameIndexExprs.size()) {
138 auto *Expr = FrameIndexExprs.back().Expr;
139 // Get rid of duplicate non-fragment entries. More than one non-fragment
140 // dbg.declare makes no sense so ignore all but the first.
141 if (!Expr || !Expr->isFragment())
144 FrameIndexExprs.append(V.FrameIndexExprs.begin(), V.FrameIndexExprs.end());
145 assert(all_of(FrameIndexExprs,
146 [](FrameIndexExpr &FIE) {
147 return FIE.Expr && FIE.Expr->isFragment();
149 "conflicting locations for variable");
152 // Translate tag to proper Dwarf tag.
153 dwarf::Tag getTag() const {
154 // FIXME: Why don't we just infer this tag and store it all along?
155 if (Var->isParameter())
156 return dwarf::DW_TAG_formal_parameter;
158 return dwarf::DW_TAG_variable;
160 /// Return true if DbgVariable is artificial.
161 bool isArtificial() const {
162 if (Var->isArtificial())
164 if (getType()->isArtificial())
169 bool isObjectPointer() const {
170 if (Var->isObjectPointer())
172 if (getType()->isObjectPointer())
177 bool hasComplexAddress() const {
178 assert(MInsn && "Expected DBG_VALUE, not MMI variable");
179 assert((FrameIndexExprs.empty() ||
180 (FrameIndexExprs.size() == 1 &&
181 FrameIndexExprs[0].Expr->getNumElements())) &&
182 "Invalid Expr for DBG_VALUE");
183 return !FrameIndexExprs.empty();
185 bool isBlockByrefVariable() const;
186 const DIType *getType() const;
189 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
190 return Ref.resolve();
195 /// Helper used to pair up a symbol and its DWARF compile unit.
197 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
199 DwarfCompileUnit *CU;
202 /// Collects and handles dwarf debug information.
203 class DwarfDebug : public DebugHandlerBase {
204 /// All DIEValues are allocated through this allocator.
205 BumpPtrAllocator DIEValueAllocator;
207 /// Maps MDNode with its corresponding DwarfCompileUnit.
208 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
210 /// Maps a CU DIE with its corresponding DwarfCompileUnit.
211 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
213 /// List of all labels used in aranges generation.
214 std::vector<SymbolCU> ArangeLabels;
216 /// Size of each symbol emitted (for those symbols that have a specific size).
217 DenseMap<const MCSymbol *, uint64_t> SymSize;
219 /// Collection of abstract variables.
220 SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
222 /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
223 /// can refer to them in spite of insertions into this list.
224 DebugLocStream DebugLocs;
226 /// This is a collection of subprogram MDNodes that are processed to
228 SetVector<const DISubprogram *, SmallVector<const DISubprogram *, 16>,
229 SmallPtrSet<const DISubprogram *, 16>>
232 /// If nonnull, stores the current machine function we're processing.
233 const MachineFunction *CurFn;
235 /// If nonnull, stores the CU in which the previous subprogram was contained.
236 const DwarfCompileUnit *PrevCU;
238 /// As an optimization, there is no need to emit an entry in the directory
239 /// table for the same directory as DW_AT_comp_dir.
240 StringRef CompilationDir;
242 /// Holder for the file specific debug information.
243 DwarfFile InfoHolder;
245 /// Holders for the various debug information flags that we might need to
246 /// have exposed. See accessor functions below for description.
248 /// Map from MDNodes for user-defined types to their type signatures. Also
249 /// used to keep track of which types we have emitted type units for.
250 DenseMap<const MDNode *, uint64_t> TypeSignatures;
253 std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
254 TypeUnitsUnderConstruction;
256 /// Whether to use the GNU TLS opcode (instead of the standard opcode).
257 bool UseGNUTLSOpcode;
259 /// Whether to use DWARF 2 bitfields (instead of the DWARF 4 format).
260 bool UseDWARF2Bitfields;
262 /// Whether to emit all linkage names, or just abstract subprograms.
263 bool UseAllLinkageNames;
265 /// DWARF5 Experimental Options
267 bool HasDwarfAccelTables;
268 bool HasAppleExtensionAttributes;
271 /// Separated Dwarf Variables
272 /// In general these will all be for bits that are left in the
273 /// original object file, rather than things that are meant
274 /// to be in the .dwo sections.
276 /// Holder for the skeleton information.
277 DwarfFile SkeletonHolder;
279 /// Store file names for type units under fission in a line table
280 /// header that will be emitted into debug_line.dwo.
281 // FIXME: replace this with a map from comp_dir to table so that we
282 // can emit multiple tables during LTO each of which uses directory
283 // 0, referencing the comp_dir of all the type units that use it.
284 MCDwarfDwoLineTable SplitTypeUnitFileTable;
287 /// True iff there are multiple CUs in this module.
291 AddressPool AddrPool;
293 DwarfAccelTable AccelNames;
294 DwarfAccelTable AccelObjC;
295 DwarfAccelTable AccelNamespace;
296 DwarfAccelTable AccelTypes;
298 // Identify a debugger for "tuning" the debug info.
299 DebuggerKind DebuggerTuning;
301 /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
303 /// Returns whether we are "tuning" for a given debugger.
304 /// Should be used only within the constructor, to set feature flags.
306 bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
307 bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
308 bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
311 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
313 const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
314 return InfoHolder.getUnits();
317 typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
319 void ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable Var,
320 const MDNode *Scope);
321 void ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU, InlinedVariable Var,
322 const MDNode *Scope);
324 DbgVariable *createConcreteVariable(DwarfCompileUnit &TheCU,
325 LexicalScope &Scope, InlinedVariable IV);
327 /// Construct a DIE for this abstract scope.
328 void constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, LexicalScope *Scope);
330 void finishVariableDefinitions();
332 void finishSubprogramDefinitions();
334 /// Finish off debug information after all functions have been
336 void finalizeModuleInfo();
338 /// Emit the debug info section.
339 void emitDebugInfo();
341 /// Emit the abbreviation section.
342 void emitAbbreviations();
344 /// Emit a specified accelerator table.
345 void emitAccel(DwarfAccelTable &Accel, MCSection *Section,
346 StringRef TableName);
348 /// Emit visible names into a hashed accelerator table section.
349 void emitAccelNames();
351 /// Emit objective C classes and categories into a hashed
352 /// accelerator table section.
353 void emitAccelObjC();
355 /// Emit namespace dies into a hashed accelerator table.
356 void emitAccelNamespaces();
358 /// Emit type dies into a hashed accelerator table.
359 void emitAccelTypes();
361 /// Emit visible names into a debug pubnames section.
362 /// \param GnuStyle determines whether or not we want to emit
363 /// additional information into the table ala newer gcc for gdb
365 void emitDebugPubNames(bool GnuStyle = false);
367 /// Emit visible types into a debug pubtypes section.
368 /// \param GnuStyle determines whether or not we want to emit
369 /// additional information into the table ala newer gcc for gdb
371 void emitDebugPubTypes(bool GnuStyle = false);
373 void emitDebugPubSection(
374 bool GnuStyle, MCSection *PSec, StringRef Name,
375 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
377 /// Emit null-terminated strings into a debug str section.
380 /// Emit variable locations into a debug loc section.
383 /// Emit variable locations into a debug loc dwo section.
384 void emitDebugLocDWO();
386 /// Emit address ranges into a debug aranges section.
387 void emitDebugARanges();
389 /// Emit address ranges into a debug ranges section.
390 void emitDebugRanges();
392 /// Emit macros into a debug macinfo section.
393 void emitDebugMacinfo();
394 void emitMacro(DIMacro &M);
395 void emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U);
396 void handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U);
398 /// DWARF 5 Experimental Split Dwarf Emitters
400 /// Initialize common features of skeleton units.
401 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
402 std::unique_ptr<DwarfCompileUnit> NewU);
404 /// Construct the split debug info compile unit for the debug info
406 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
408 /// Emit the debug info dwo section.
409 void emitDebugInfoDWO();
411 /// Emit the debug abbrev dwo section.
412 void emitDebugAbbrevDWO();
414 /// Emit the debug line dwo section.
415 void emitDebugLineDWO();
417 /// Emit the debug str dwo section.
418 void emitDebugStrDWO();
420 /// Flags to let the linker know we have emitted new style pubnames. Only
421 /// emit it here if we don't have a skeleton CU for split dwarf.
422 void addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const;
424 /// Create new DwarfCompileUnit for the given metadata node with tag
425 /// DW_TAG_compile_unit.
426 DwarfCompileUnit &getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit);
428 /// Construct imported_module or imported_declaration DIE.
429 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
430 const DIImportedEntity *N);
432 /// Register a source line with debug info. Returns the unique
433 /// label that was emitted and which provides correspondence to the
434 /// source line list.
435 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
438 /// Populate LexicalScope entries with variables' info.
439 void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
440 DenseSet<InlinedVariable> &ProcessedVars);
442 /// Build the location list for all DBG_VALUEs in the
443 /// function that describe the same variable.
444 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
445 const DbgValueHistoryMap::InstrRanges &Ranges);
447 /// Collect variable information from the side table maintained by MF.
448 void collectVariableInfoFromMFTable(DwarfCompileUnit &TheCU,
449 DenseSet<InlinedVariable> &P);
452 /// Gather pre-function debug information.
453 void beginFunctionImpl(const MachineFunction *MF) override;
455 /// Gather and emit post-function debug information.
456 void endFunctionImpl(const MachineFunction *MF) override;
458 void skippedNonDebugFunction() override;
461 //===--------------------------------------------------------------------===//
462 // Main entry points.
464 DwarfDebug(AsmPrinter *A, Module *M);
466 ~DwarfDebug() override;
468 /// Emit all Dwarf sections that should come prior to the
472 /// Emit all Dwarf sections that should come after the content.
473 void endModule() override;
475 /// Process beginning of an instruction.
476 void beginInstruction(const MachineInstr *MI) override;
478 /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
479 static uint64_t makeTypeSignature(StringRef Identifier);
481 /// Add a DIE to the set of types that we're going to pull into
483 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
484 DIE &Die, const DICompositeType *CTy);
486 /// Add a label so that arange data can be generated for it.
487 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
489 /// For symbols that have a size designated (e.g. common symbols),
490 /// this tracks that size.
491 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
495 /// Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
496 /// If not, we still might emit certain cases.
497 bool useAllLinkageNames() const { return UseAllLinkageNames; }
499 /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
500 /// standard DW_OP_form_tls_address opcode
501 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
503 /// Returns whether to use the DWARF2 format for bitfields instyead of the
505 bool useDWARF2Bitfields() const { return UseDWARF2Bitfields; }
507 // Experimental DWARF5 features.
509 /// Returns whether or not to emit tables that dwarf consumers can
510 /// use to accelerate lookup.
511 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
513 bool useAppleExtensionAttributes() const {
514 return HasAppleExtensionAttributes;
517 /// Returns whether or not to change the current debug info for the
518 /// split dwarf proposal support.
519 bool useSplitDwarf() const { return HasSplitDwarf; }
521 bool shareAcrossDWOCUs() const;
523 /// Returns the Dwarf Version.
524 uint16_t getDwarfVersion() const;
526 /// Returns the previous CU that was being updated
527 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
528 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
530 /// Returns the entries for the .debug_loc section.
531 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
533 /// Emit an entry for the debug loc section. This can be used to
534 /// handle an entry that's going to be emitted into the debug loc section.
535 void emitDebugLocEntry(ByteStreamer &Streamer,
536 const DebugLocStream::Entry &Entry);
538 /// Emit the location for a debug loc entry, including the size header.
539 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
541 /// Find the MDNode for the given reference.
542 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
543 return Ref.resolve();
546 void addSubprogramNames(const DISubprogram *SP, DIE &Die);
548 AddressPool &getAddressPool() { return AddrPool; }
550 void addAccelName(StringRef Name, const DIE &Die);
552 void addAccelObjC(StringRef Name, const DIE &Die);
554 void addAccelNamespace(StringRef Name, const DIE &Die);
556 void addAccelType(StringRef Name, const DIE &Die, char Flags);
558 const MachineFunction *getCurrentFunction() const { return CurFn; }
560 /// A helper function to check whether the DIE for a given Scope is
561 /// going to be null.
562 bool isLexicalScopeDIENull(LexicalScope *Scope);
564 bool hasDwarfPubSections(bool includeMinimalInlineScopes) const;
566 } // End of namespace llvm