1 //===-- llvm/CodeGen/DwarfDebug.h - Dwarf Debug Framework ------*- C++ -*--===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
15 #define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
16 
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/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"
37 #include <memory>
38 
39 namespace llvm {
40 
41 class AsmPrinter;
42 class ByteStreamer;
43 class ConstantInt;
44 class ConstantFP;
45 class DebugLocEntry;
46 class DwarfCompileUnit;
47 class DwarfDebug;
48 class DwarfTypeUnit;
49 class DwarfUnit;
50 class MachineModuleInfo;
51 
52 //===----------------------------------------------------------------------===//
53 /// This class is used to track local variable information.
54 ///
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.
58 ///
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.
62 ///
63 /// Variables that have been optimized out use none of these fields.
64 class DbgVariable {
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.
72   DwarfDebug *DD;
73 
74 public:
75   /// Construct a DbgVariable.
76   ///
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) {}
81 
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?");
87 
88     assert((!E || E->isValid()) && "Expected valid expression");
89     assert(~FI && "Expected valid index");
90 
91     Expr.push_back(E);
92     FrameIndex.push_back(FI);
93   }
94 
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?");
100 
101     assert(Var == DbgValue->getDebugVariable() && "Wrong variable");
102     assert(IA == DbgValue->getDebugLoc()->getInlinedAt() && "Wrong inlined-at");
103 
104     MInsn = DbgValue;
105     if (auto *E = DbgValue->getDebugExpression())
106       if (E->getNumElements())
107         Expr.push_back(E);
108   }
109 
110   // Accessors.
111   const DILocalVariable *getVariable() const { return Var; }
112   const DILocation *getInlinedAt() const { return IA; }
113   ArrayRef<const DIExpression *> getExpression() const { return Expr; }
114   const DIExpression *getSingleExpression() const {
115     assert(MInsn && Expr.size() <= 1);
116     return Expr.size() ? Expr[0] : nullptr;
117   }
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   ArrayRef<int> getFrameIndex() const { return FrameIndex; }
125 
126   void addMMIEntry(const DbgVariable &V) {
127     assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
128     assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
129     assert(V.Var == Var && "conflicting variable");
130     assert(V.IA == IA && "conflicting inlined-at location");
131 
132     assert(!FrameIndex.empty() && "Expected an MMI entry");
133     assert(!V.FrameIndex.empty() && "Expected an MMI entry");
134     assert(Expr.size() == FrameIndex.size() && "Mismatched expressions");
135     assert(V.Expr.size() == V.FrameIndex.size() && "Mismatched expressions");
136 
137     Expr.append(V.Expr.begin(), V.Expr.end());
138     FrameIndex.append(V.FrameIndex.begin(), V.FrameIndex.end());
139     assert(std::all_of(Expr.begin(), Expr.end(), [](const DIExpression *E) {
140              return E && E->isBitPiece();
141            }) && "conflicting locations for variable");
142   }
143 
144   // Translate tag to proper Dwarf tag.
145   dwarf::Tag getTag() const {
146     // FIXME: Why don't we just infer this tag and store it all along?
147     if (Var->isParameter())
148       return dwarf::DW_TAG_formal_parameter;
149 
150     return dwarf::DW_TAG_variable;
151   }
152   /// Return true if DbgVariable is artificial.
153   bool isArtificial() const {
154     if (Var->isArtificial())
155       return true;
156     if (getType()->isArtificial())
157       return true;
158     return false;
159   }
160 
161   bool isObjectPointer() const {
162     if (Var->isObjectPointer())
163       return true;
164     if (getType()->isObjectPointer())
165       return true;
166     return false;
167   }
168 
169   bool hasComplexAddress() const {
170     assert(MInsn && "Expected DBG_VALUE, not MMI variable");
171     assert(FrameIndex.empty() && "Expected DBG_VALUE, not MMI variable");
172     assert(
173         (Expr.empty() || (Expr.size() == 1 && Expr.back()->getNumElements())) &&
174         "Invalid Expr for DBG_VALUE");
175     return !Expr.empty();
176   }
177   bool isBlockByrefVariable() const;
178   const DIType *getType() const;
179 
180 private:
181   /// Look in the DwarfDebug map for the MDNode that
182   /// corresponds to the reference.
183   template <typename T> T *resolve(TypedDINodeRef<T> Ref) const;
184 };
185 
186 
187 /// Helper used to pair up a symbol and its DWARF compile unit.
188 struct SymbolCU {
189   SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
190   const MCSymbol *Sym;
191   DwarfCompileUnit *CU;
192 };
193 
194 /// Collects and handles dwarf debug information.
195 class DwarfDebug : public DebugHandlerBase {
196   /// All DIEValues are allocated through this allocator.
197   BumpPtrAllocator DIEValueAllocator;
198 
199   /// Maps MDNode with its corresponding DwarfCompileUnit.
200   MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
201 
202   /// Maps subprogram MDNode with its corresponding DwarfCompileUnit.
203   MapVector<const MDNode *, DwarfCompileUnit *> SPMap;
204 
205   /// Maps a CU DIE with its corresponding DwarfCompileUnit.
206   DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
207 
208   /// List of all labels used in aranges generation.
209   std::vector<SymbolCU> ArangeLabels;
210 
211   /// Size of each symbol emitted (for those symbols that have a specific size).
212   DenseMap<const MCSymbol *, uint64_t> SymSize;
213 
214   /// Collection of abstract variables.
215   DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
216   SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
217 
218   /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
219   /// can refer to them in spite of insertions into this list.
220   DebugLocStream DebugLocs;
221 
222   /// This is a collection of subprogram MDNodes that are processed to
223   /// create DIEs.
224   SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
225 
226   /// If nonnull, stores the current machine function we're processing.
227   const MachineFunction *CurFn;
228 
229   /// If nonnull, stores the CU in which the previous subprogram was contained.
230   const DwarfCompileUnit *PrevCU;
231 
232   /// As an optimization, there is no need to emit an entry in the directory
233   /// table for the same directory as DW_AT_comp_dir.
234   StringRef CompilationDir;
235 
236   /// Holder for the file specific debug information.
237   DwarfFile InfoHolder;
238 
239   /// Holders for the various debug information flags that we might need to
240   /// have exposed. See accessor functions below for description.
241 
242   /// Map from MDNodes for user-defined types to their type signatures. Also
243   /// used to keep track of which types we have emitted type units for.
244   DenseMap<const MDNode *, uint64_t> TypeSignatures;
245 
246   SmallVector<
247       std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
248       TypeUnitsUnderConstruction;
249 
250   /// Whether to emit the pubnames/pubtypes sections.
251   bool HasDwarfPubSections;
252 
253   /// Whether to use the GNU TLS opcode (instead of the standard opcode).
254   bool UseGNUTLSOpcode;
255 
256   /// Whether to emit DW_AT_[MIPS_]linkage_name.
257   bool UseLinkageNames;
258 
259   /// Version of dwarf we're emitting.
260   unsigned DwarfVersion;
261 
262   /// Maps from a type identifier to the actual MDNode.
263   DITypeIdentifierMap TypeIdentifierMap;
264 
265   /// DWARF5 Experimental Options
266   /// @{
267   bool HasDwarfAccelTables;
268   bool HasSplitDwarf;
269 
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.
274 
275   /// Holder for the skeleton information.
276   DwarfFile SkeletonHolder;
277 
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;
284   /// @}
285 
286   /// True iff there are multiple CUs in this module.
287   bool SingleCU;
288   bool IsDarwin;
289 
290   AddressPool AddrPool;
291 
292   DwarfAccelTable AccelNames;
293   DwarfAccelTable AccelObjC;
294   DwarfAccelTable AccelNamespace;
295   DwarfAccelTable AccelTypes;
296 
297   // Identify a debugger for "tuning" the debug info.
298   DebuggerKind DebuggerTuning;
299 
300   MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
301 
302   const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
303     return InfoHolder.getUnits();
304   }
305 
306   typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
307 
308   /// Find abstract variable associated with Var.
309   DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
310                                            const DILocalVariable *&Cleansed);
311   DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
312   void createAbstractVariable(const DILocalVariable *DV, LexicalScope *Scope);
313   void ensureAbstractVariableIsCreated(InlinedVariable Var,
314                                        const MDNode *Scope);
315   void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var,
316                                                const MDNode *Scope);
317 
318   DbgVariable *createConcreteVariable(LexicalScope &Scope, InlinedVariable IV);
319 
320   /// Construct a DIE for this abstract scope.
321   void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
322 
323   /// Collect info for variables that were optimized out.
324   void collectDeadVariables();
325 
326   void finishVariableDefinitions();
327 
328   void finishSubprogramDefinitions();
329 
330   /// Finish off debug information after all functions have been
331   /// processed.
332   void finalizeModuleInfo();
333 
334   /// Emit the debug info section.
335   void emitDebugInfo();
336 
337   /// Emit the abbreviation section.
338   void emitAbbreviations();
339 
340   /// Emit a specified accelerator table.
341   void emitAccel(DwarfAccelTable &Accel, MCSection *Section,
342                  StringRef TableName);
343 
344   /// Emit visible names into a hashed accelerator table section.
345   void emitAccelNames();
346 
347   /// Emit objective C classes and categories into a hashed
348   /// accelerator table section.
349   void emitAccelObjC();
350 
351   /// Emit namespace dies into a hashed accelerator table.
352   void emitAccelNamespaces();
353 
354   /// Emit type dies into a hashed accelerator table.
355   void emitAccelTypes();
356 
357   /// Emit visible names into a debug pubnames section.
358   /// \param GnuStyle determines whether or not we want to emit
359   /// additional information into the table ala newer gcc for gdb
360   /// index.
361   void emitDebugPubNames(bool GnuStyle = false);
362 
363   /// Emit visible types into a debug pubtypes section.
364   /// \param GnuStyle determines whether or not we want to emit
365   /// additional information into the table ala newer gcc for gdb
366   /// index.
367   void emitDebugPubTypes(bool GnuStyle = false);
368 
369   void emitDebugPubSection(
370       bool GnuStyle, MCSection *PSec, StringRef Name,
371       const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
372 
373   /// Emit null-terminated strings into a debug str section.
374   void emitDebugStr();
375 
376   /// Emit variable locations into a debug loc section.
377   void emitDebugLoc();
378 
379   /// Emit variable locations into a debug loc dwo section.
380   void emitDebugLocDWO();
381 
382   /// Emit address ranges into a debug aranges section.
383   void emitDebugARanges();
384 
385   /// Emit address ranges into a debug ranges section.
386   void emitDebugRanges();
387 
388   /// Emit macros into a debug macinfo section.
389   void emitDebugMacinfo();
390   void emitMacro(DIMacro &M);
391   void emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U);
392   void handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U);
393 
394   /// DWARF 5 Experimental Split Dwarf Emitters
395 
396   /// Initialize common features of skeleton units.
397   void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
398                         std::unique_ptr<DwarfCompileUnit> NewU);
399 
400   /// Construct the split debug info compile unit for the debug info
401   /// section.
402   DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
403 
404   /// Emit the debug info dwo section.
405   void emitDebugInfoDWO();
406 
407   /// Emit the debug abbrev dwo section.
408   void emitDebugAbbrevDWO();
409 
410   /// Emit the debug line dwo section.
411   void emitDebugLineDWO();
412 
413   /// Emit the debug str dwo section.
414   void emitDebugStrDWO();
415 
416   /// Flags to let the linker know we have emitted new style pubnames. Only
417   /// emit it here if we don't have a skeleton CU for split dwarf.
418   void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
419 
420   /// Create new DwarfCompileUnit for the given metadata node with tag
421   /// DW_TAG_compile_unit.
422   DwarfCompileUnit &constructDwarfCompileUnit(const DICompileUnit *DIUnit);
423 
424   /// Construct imported_module or imported_declaration DIE.
425   void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
426                                         const DIImportedEntity *N);
427 
428   /// Register a source line with debug info. Returns the unique
429   /// label that was emitted and which provides correspondence to the
430   /// source line list.
431   void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
432                         unsigned Flags);
433 
434   /// Populate LexicalScope entries with variables' info.
435   void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
436                            DenseSet<InlinedVariable> &ProcessedVars);
437 
438   /// Build the location list for all DBG_VALUEs in the
439   /// function that describe the same variable.
440   void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
441                          const DbgValueHistoryMap::InstrRanges &Ranges);
442 
443   /// Collect variable information from the side table maintained
444   /// by MMI.
445   void collectVariableInfoFromMMITable(DenseSet<InlinedVariable> &P);
446 
447 public:
448   //===--------------------------------------------------------------------===//
449   // Main entry points.
450   //
451   DwarfDebug(AsmPrinter *A, Module *M);
452 
453   ~DwarfDebug() override;
454 
455   /// Emit all Dwarf sections that should come prior to the
456   /// content.
457   void beginModule();
458 
459   /// Emit all Dwarf sections that should come after the content.
460   void endModule() override;
461 
462   /// Gather pre-function debug information.
463   void beginFunction(const MachineFunction *MF) override;
464 
465   /// Gather and emit post-function debug information.
466   void endFunction(const MachineFunction *MF) override;
467 
468   /// Process beginning of an instruction.
469   void beginInstruction(const MachineInstr *MI) override;
470 
471   /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
472   static uint64_t makeTypeSignature(StringRef Identifier);
473 
474   /// Add a DIE to the set of types that we're going to pull into
475   /// type units.
476   void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
477                             DIE &Die, const DICompositeType *CTy);
478 
479   /// Add a label so that arange data can be generated for it.
480   void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
481 
482   /// For symbols that have a size designated (e.g. common symbols),
483   /// this tracks that size.
484   void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
485     SymSize[Sym] = Size;
486   }
487 
488   /// Returns whether to emit DW_AT_[MIPS_]linkage_name.
489   bool useLinkageNames() const { return UseLinkageNames; }
490 
491   /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
492   /// standard DW_OP_form_tls_address opcode
493   bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
494 
495   /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
496   ///
497   /// Returns whether we are "tuning" for a given debugger.
498   /// @{
499   bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
500   bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
501   bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
502   /// @}
503 
504   // Experimental DWARF5 features.
505 
506   /// Returns whether or not to emit tables that dwarf consumers can
507   /// use to accelerate lookup.
508   bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
509 
510   /// Returns whether or not to change the current debug info for the
511   /// split dwarf proposal support.
512   bool useSplitDwarf() const { return HasSplitDwarf; }
513 
514   /// Returns the Dwarf Version.
515   unsigned getDwarfVersion() const { return DwarfVersion; }
516 
517   /// Returns the previous CU that was being updated
518   const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
519   void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
520 
521   /// Returns the entries for the .debug_loc section.
522   const DebugLocStream &getDebugLocs() const { return DebugLocs; }
523 
524   /// Emit an entry for the debug loc section. This can be used to
525   /// handle an entry that's going to be emitted into the debug loc section.
526   void emitDebugLocEntry(ByteStreamer &Streamer,
527                          const DebugLocStream::Entry &Entry);
528 
529   /// Emit the location for a debug loc entry, including the size header.
530   void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
531 
532   /// Find the MDNode for the given reference.
533   template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
534     return Ref.resolve(TypeIdentifierMap);
535   }
536 
537   /// Return the TypeIdentifierMap.
538   const DITypeIdentifierMap &getTypeIdentifierMap() const {
539     return TypeIdentifierMap;
540   }
541 
542   /// Find the DwarfCompileUnit for the given CU Die.
543   DwarfCompileUnit *lookupUnit(const DIE *CU) const {
544     return CUDieMap.lookup(CU);
545   }
546 
547   void addSubprogramNames(const DISubprogram *SP, DIE &Die);
548 
549   AddressPool &getAddressPool() { return AddrPool; }
550 
551   void addAccelName(StringRef Name, const DIE &Die);
552 
553   void addAccelObjC(StringRef Name, const DIE &Die);
554 
555   void addAccelNamespace(StringRef Name, const DIE &Die);
556 
557   void addAccelType(StringRef Name, const DIE &Die, char Flags);
558 
559   const MachineFunction *getCurrentFunction() const { return CurFn; }
560 
561   /// A helper function to check whether the DIE for a given Scope is
562   /// going to be null.
563   bool isLexicalScopeDIENull(LexicalScope *Scope);
564 
565   // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
566 
567   SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
568     return ProcessedSPNodes;
569   }
570 };
571 } // End of namespace llvm
572 
573 #endif
574