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"
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
57 /// indices. The \a Expr and \a FrameIndices array must match.
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 SmallVector<const DIExpression *, 1> Expr; /// Complex address.
68 DIE *TheDIE = nullptr; /// Variable DIE.
69 unsigned DebugLocListIndex = ~0u; /// Offset in DebugLocs.
70 const MachineInstr *MInsn = nullptr; /// DBG_VALUE instruction.
71 SmallVector<int, 1> FrameIndex; /// Frame index.
75 /// Construct a DbgVariable.
77 /// Creates a variable without any DW_AT_location. Call \a initializeMMI()
78 /// for MMI entries, or \a initializeDbgValue() for DBG_VALUE instructions.
79 DbgVariable(const DILocalVariable *V, const DILocation *IA, DwarfDebug *DD)
80 : Var(V), IA(IA), DD(DD) {}
82 /// Initialize from the MMI table.
83 void initializeMMI(const DIExpression *E, int FI) {
84 assert(Expr.empty() && "Already initialized?");
85 assert(FrameIndex.empty() && "Already initialized?");
86 assert(!MInsn && "Already initialized?");
88 assert((!E || E->isValid()) && "Expected valid expression");
89 assert(~FI && "Expected valid index");
92 FrameIndex.push_back(FI);
95 /// Initialize from a DBG_VALUE instruction.
96 void initializeDbgValue(const MachineInstr *DbgValue) {
97 assert(Expr.empty() && "Already initialized?");
98 assert(FrameIndex.empty() && "Already initialized?");
99 assert(!MInsn && "Already initialized?");
101 assert(Var == DbgValue->getDebugVariable() && "Wrong variable");
102 assert(IA == DbgValue->getDebugLoc()->getInlinedAt() && "Wrong inlined-at");
105 if (auto *E = DbgValue->getDebugExpression())
106 if (E->getNumElements())
111 const DILocalVariable *getVariable() const { return Var; }
112 const DILocation *getInlinedAt() const { return IA; }
113 ArrayRef<const DIExpression *> getExpression() const { return Expr; }
114 void setDIE(DIE &D) { TheDIE = &D; }
115 DIE *getDIE() const { return TheDIE; }
116 void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
117 unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
118 StringRef getName() const { return Var->getName(); }
119 const MachineInstr *getMInsn() const { return MInsn; }
120 ArrayRef<int> getFrameIndex() const { return FrameIndex; }
122 void addMMIEntry(const DbgVariable &V) {
123 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
124 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
125 assert(V.Var == Var && "conflicting variable");
126 assert(V.IA == IA && "conflicting inlined-at location");
128 assert(!FrameIndex.empty() && "Expected an MMI entry");
129 assert(!V.FrameIndex.empty() && "Expected an MMI entry");
130 assert(Expr.size() == FrameIndex.size() && "Mismatched expressions");
131 assert(V.Expr.size() == V.FrameIndex.size() && "Mismatched expressions");
133 Expr.append(V.Expr.begin(), V.Expr.end());
134 FrameIndex.append(V.FrameIndex.begin(), V.FrameIndex.end());
135 assert(std::all_of(Expr.begin(), Expr.end(), [](const DIExpression *E) {
136 return E && E->isBitPiece();
137 }) && "conflicting locations for variable");
140 // Translate tag to proper Dwarf tag.
141 dwarf::Tag getTag() const {
142 // FIXME: Why don't we just infer this tag and store it all along?
143 if (Var->isParameter())
144 return dwarf::DW_TAG_formal_parameter;
146 return dwarf::DW_TAG_variable;
148 /// Return true if DbgVariable is artificial.
149 bool isArtificial() const {
150 if (Var->isArtificial())
152 if (getType()->isArtificial())
157 bool isObjectPointer() const {
158 if (Var->isObjectPointer())
160 if (getType()->isObjectPointer())
165 bool hasComplexAddress() const {
166 assert(MInsn && "Expected DBG_VALUE, not MMI variable");
167 assert(FrameIndex.empty() && "Expected DBG_VALUE, not MMI variable");
169 (Expr.empty() || (Expr.size() == 1 && Expr.back()->getNumElements())) &&
170 "Invalid Expr for DBG_VALUE");
171 return !Expr.empty();
173 bool isBlockByrefVariable() const;
174 const DIType *getType() const;
177 /// Look in the DwarfDebug map for the MDNode that
178 /// corresponds to the reference.
179 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const;
183 /// Helper used to pair up a symbol and its DWARF compile unit.
185 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
187 DwarfCompileUnit *CU;
190 /// Collects and handles dwarf debug information.
191 class DwarfDebug : public AsmPrinterHandler {
192 /// Target of Dwarf emission.
195 /// Collected machine module information.
196 MachineModuleInfo *MMI;
198 /// All DIEValues are allocated through this allocator.
199 BumpPtrAllocator DIEValueAllocator;
201 /// Maps MDNode with its corresponding DwarfCompileUnit.
202 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
204 /// Maps subprogram MDNode with its corresponding DwarfCompileUnit.
205 MapVector<const MDNode *, DwarfCompileUnit *> SPMap;
207 /// Maps a CU DIE with its corresponding DwarfCompileUnit.
208 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
210 /// List of all labels used in aranges generation.
211 std::vector<SymbolCU> ArangeLabels;
213 /// Size of each symbol emitted (for those symbols that have a specific size).
214 DenseMap<const MCSymbol *, uint64_t> SymSize;
216 LexicalScopes LScopes;
218 /// Collection of abstract variables.
219 DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
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 SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
230 /// Maps instruction with label emitted before instruction.
231 DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
233 /// Maps instruction with label emitted after instruction.
234 DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
236 /// History of DBG_VALUE and clobber instructions for each user
237 /// variable. Variables are listed in order of appearance.
238 DbgValueHistoryMap DbgValues;
240 /// Previous instruction's location information. This is used to
241 /// determine label location to indicate scope boundries in dwarf
243 DebugLoc PrevInstLoc;
246 /// This location indicates end of function prologue and beginning of
248 DebugLoc PrologEndLoc;
250 /// If nonnull, stores the current machine function we're processing.
251 const MachineFunction *CurFn;
253 /// If nonnull, stores the current machine instruction we're processing.
254 const MachineInstr *CurMI;
256 /// If nonnull, stores the CU in which the previous subprogram was contained.
257 const DwarfCompileUnit *PrevCU;
259 /// As an optimization, there is no need to emit an entry in the directory
260 /// table for the same directory as DW_AT_comp_dir.
261 StringRef CompilationDir;
263 /// Holder for the file specific debug information.
264 DwarfFile InfoHolder;
266 /// Holders for the various debug information flags that we might need to
267 /// have exposed. See accessor functions below for description.
269 /// Map from MDNodes for user-defined types to the type units that
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 to use the GNU TLS opcode (instead of the standard opcode).
281 bool UseGNUTLSOpcode;
283 /// Whether to emit DW_AT_[MIPS_]linkage_name.
284 bool UseLinkageNames;
286 /// Version of dwarf we're emitting.
287 unsigned DwarfVersion;
289 /// Maps from a type identifier to the actual MDNode.
290 DITypeIdentifierMap TypeIdentifierMap;
292 /// DWARF5 Experimental Options
294 bool HasDwarfAccelTables;
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 DwarfAccelTable AccelNames;
320 DwarfAccelTable AccelObjC;
321 DwarfAccelTable AccelNamespace;
322 DwarfAccelTable AccelTypes;
324 // Identify a debugger for "tuning" the debug info.
325 DebuggerKind DebuggerTuning;
327 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
329 const SmallVectorImpl<std::unique_ptr<DwarfUnit>> &getUnits() {
330 return InfoHolder.getUnits();
333 typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
335 /// Find abstract variable associated with Var.
336 DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
337 const DILocalVariable *&Cleansed);
338 DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
339 void createAbstractVariable(const DILocalVariable *DV, LexicalScope *Scope);
340 void ensureAbstractVariableIsCreated(InlinedVariable Var,
341 const MDNode *Scope);
342 void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var,
343 const MDNode *Scope);
345 DbgVariable *createConcreteVariable(LexicalScope &Scope, InlinedVariable IV);
347 /// Construct a DIE for this abstract scope.
348 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
350 /// Collect info for variables that were optimized out.
351 void collectDeadVariables();
353 void finishVariableDefinitions();
355 void finishSubprogramDefinitions();
357 /// Finish off debug information after all functions have been
359 void finalizeModuleInfo();
361 /// Emit the debug info section.
362 void emitDebugInfo();
364 /// Emit the abbreviation section.
365 void emitAbbreviations();
367 /// Emit a specified accelerator table.
368 void emitAccel(DwarfAccelTable &Accel, MCSection *Section,
369 StringRef TableName);
371 /// Emit visible names into a hashed accelerator table section.
372 void emitAccelNames();
374 /// Emit objective C classes and categories into a hashed
375 /// accelerator table section.
376 void emitAccelObjC();
378 /// Emit namespace dies into a hashed accelerator table.
379 void emitAccelNamespaces();
381 /// Emit type dies into a hashed accelerator table.
382 void emitAccelTypes();
384 /// Emit visible names into a debug pubnames section.
385 /// \param GnuStyle determines whether or not we want to emit
386 /// additional information into the table ala newer gcc for gdb
388 void emitDebugPubNames(bool GnuStyle = false);
390 /// Emit visible types into a debug pubtypes 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 emitDebugPubTypes(bool GnuStyle = false);
396 void emitDebugPubSection(
397 bool GnuStyle, MCSection *PSec, StringRef Name,
398 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
400 /// Emit visible names into a debug str section.
403 /// Emit variable locations into a debug loc section.
406 /// Emit variable locations into a debug loc dwo section.
407 void emitDebugLocDWO();
409 /// Emit address ranges into a debug aranges section.
410 void emitDebugARanges();
412 /// Emit address ranges into a debug ranges section.
413 void emitDebugRanges();
415 /// Emit macros into a debug macinfo section.
416 void emitDebugMacinfo();
417 unsigned emitMacro(AsmStreamerBase *AS, DIMacro &M);
418 unsigned emitMacroFile(AsmStreamerBase *AS, DIMacroFile &F,
419 DwarfCompileUnit &U);
420 unsigned handleMacroNodes(AsmStreamerBase *AS, DIMacroNodeArray Nodes,
421 DwarfCompileUnit &U);
423 /// DWARF 5 Experimental Split Dwarf Emitters
425 /// Initialize common features of skeleton units.
426 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
427 std::unique_ptr<DwarfUnit> NewU);
429 /// Construct the split debug info compile unit for the debug info
431 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
433 /// Emit the debug info dwo section.
434 void emitDebugInfoDWO();
436 /// Emit the debug abbrev dwo section.
437 void emitDebugAbbrevDWO();
439 /// Emit the debug line dwo section.
440 void emitDebugLineDWO();
442 /// Emit the debug str dwo section.
443 void emitDebugStrDWO();
445 /// Flags to let the linker know we have emitted new style pubnames. Only
446 /// emit it here if we don't have a skeleton CU for split dwarf.
447 void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
449 /// Create new DwarfCompileUnit for the given metadata node with tag
450 /// DW_TAG_compile_unit.
451 DwarfCompileUnit &constructDwarfCompileUnit(const DICompileUnit *DIUnit);
453 /// Construct imported_module or imported_declaration DIE.
454 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
455 const DIImportedEntity *N);
457 /// Register a source line with debug info. Returns the unique
458 /// label that was emitted and which provides correspondence to the
459 /// source line list.
460 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
463 /// Indentify instructions that are marking the beginning of or
464 /// ending of a scope.
465 void identifyScopeMarkers();
467 /// Populate LexicalScope entries with variables' info.
468 void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
469 DenseSet<InlinedVariable> &ProcessedVars);
471 /// Build the location list for all DBG_VALUEs in the
472 /// function that describe the same variable.
473 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
474 const DbgValueHistoryMap::InstrRanges &Ranges);
476 /// Collect variable information from the side table maintained
478 void collectVariableInfoFromMMITable(DenseSet<InlinedVariable> &P);
480 /// Ensure that a label will be emitted before MI.
481 void requestLabelBeforeInsn(const MachineInstr *MI) {
482 LabelsBeforeInsn.insert(std::make_pair(MI, nullptr));
485 /// Ensure that a label will be emitted after MI.
486 void requestLabelAfterInsn(const MachineInstr *MI) {
487 LabelsAfterInsn.insert(std::make_pair(MI, nullptr));
491 //===--------------------------------------------------------------------===//
492 // Main entry points.
494 DwarfDebug(AsmPrinter *A, Module *M);
496 ~DwarfDebug() override;
498 /// Emit all Dwarf sections that should come prior to the
502 /// Emit all Dwarf sections that should come after the content.
503 void endModule() override;
505 /// Gather pre-function debug information.
506 void beginFunction(const MachineFunction *MF) override;
508 /// Gather and emit post-function debug information.
509 void endFunction(const MachineFunction *MF) override;
511 /// Process beginning of an instruction.
512 void beginInstruction(const MachineInstr *MI) override;
514 /// Process end of an instruction.
515 void endInstruction() override;
517 /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
518 static uint64_t makeTypeSignature(StringRef Identifier);
520 /// 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 DICompositeType *CTy);
525 /// Add a label so that arange data can be generated for it.
526 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
528 /// 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 /// Returns whether to emit DW_AT_[MIPS_]linkage_name.
535 bool useLinkageNames() const { return UseLinkageNames; }
537 /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
538 /// standard DW_OP_form_tls_address opcode
539 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
541 /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
543 /// Returns whether we are "tuning" for a given debugger.
545 bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
546 bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
547 bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
550 // Experimental DWARF5 features.
552 /// Returns whether or not to emit tables that dwarf consumers can
553 /// use to accelerate lookup.
554 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
556 /// Returns whether or not to change the current debug info for the
557 /// split dwarf proposal support.
558 bool useSplitDwarf() const { return HasSplitDwarf; }
560 /// Returns the Dwarf Version.
561 unsigned getDwarfVersion() const { return DwarfVersion; }
563 /// Returns the previous CU that was being updated
564 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
565 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
567 /// Returns the entries for the .debug_loc section.
568 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
570 /// Emit an entry for the debug loc section. This can be used to
571 /// handle an entry that's going to be emitted into the debug loc section.
572 void emitDebugLocEntry(ByteStreamer &Streamer,
573 const DebugLocStream::Entry &Entry);
575 /// Emit the location for a debug loc entry, including the size header.
576 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
578 /// Find the MDNode for the given reference.
579 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
580 return Ref.resolve(TypeIdentifierMap);
583 /// Return the TypeIdentifierMap.
584 const DITypeIdentifierMap &getTypeIdentifierMap() const {
585 return TypeIdentifierMap;
588 /// Find the DwarfCompileUnit for the given CU Die.
589 DwarfCompileUnit *lookupUnit(const DIE *CU) const {
590 return CUDieMap.lookup(CU);
593 void addSubprogramNames(const DISubprogram *SP, DIE &Die);
595 AddressPool &getAddressPool() { return AddrPool; }
597 void addAccelName(StringRef Name, const DIE &Die);
599 void addAccelObjC(StringRef Name, const DIE &Die);
601 void addAccelNamespace(StringRef Name, const DIE &Die);
603 void addAccelType(StringRef Name, const DIE &Die, char Flags);
605 const MachineFunction *getCurrentFunction() const { return CurFn; }
607 /// A helper function to check whether the DIE for a given Scope is
608 /// going to be null.
609 bool isLexicalScopeDIENull(LexicalScope *Scope);
611 /// Return Label preceding the instruction.
612 MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
614 /// Return Label immediately following the instruction.
615 MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
617 // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
619 SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
620 return ProcessedSPNodes;
623 } // End of namespace llvm