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/MapVector.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/CodeGen/DIE.h"
28 #include "llvm/CodeGen/LexicalScopes.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/DebugLoc.h"
32 #include "llvm/MC/MCDwarf.h"
33 #include "llvm/MC/MachineLocation.h"
34 #include "llvm/Support/Allocator.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include <memory>
37 
38 namespace llvm {
39 
40 class AsmPrinter;
41 class ByteStreamer;
42 class ConstantInt;
43 class ConstantFP;
44 class DebugLocEntry;
45 class DwarfCompileUnit;
46 class DwarfDebug;
47 class DwarfTypeUnit;
48 class DwarfUnit;
49 class MachineModuleInfo;
50 
51 //===----------------------------------------------------------------------===//
52 /// This class is used to track local variable information.
53 ///
54 /// Variables can be created from allocas, in which case they're generated from
55 /// the MMI table.  Such variables can have multiple expressions and frame
56 /// indices.  The \a Expr and \a FrameIndices array must match.
57 ///
58 /// Variables can be created from \c DBG_VALUE instructions.  Those whose
59 /// location changes over time use \a DebugLocListIndex, while those with a
60 /// single instruction use \a MInsn and (optionally) a single entry of \a Expr.
61 ///
62 /// Variables that have been optimized out use none of these fields.
63 class DbgVariable {
64   const DILocalVariable *Var;                /// Variable Descriptor.
65   const DILocation *IA;                      /// Inlined at location.
66   SmallVector<const DIExpression *, 1> Expr; /// Complex address.
67   DIE *TheDIE = nullptr;                     /// Variable DIE.
68   unsigned DebugLocListIndex = ~0u;          /// Offset in DebugLocs.
69   const MachineInstr *MInsn = nullptr;       /// DBG_VALUE instruction.
70   SmallVector<int, 1> FrameIndex;            /// Frame index.
71 
72 public:
73   /// Construct a DbgVariable.
74   ///
75   /// Creates a variable without any DW_AT_location.  Call \a initializeMMI()
76   /// for MMI entries, or \a initializeDbgValue() for DBG_VALUE instructions.
77   DbgVariable(const DILocalVariable *V, const DILocation *IA)
78       : Var(V), IA(IA) {}
79 
80   /// Initialize from the MMI table.
81   void initializeMMI(const DIExpression *E, int FI) {
82     assert(Expr.empty() && "Already initialized?");
83     assert(FrameIndex.empty() && "Already initialized?");
84     assert(!MInsn && "Already initialized?");
85 
86     assert((!E || E->isValid()) && "Expected valid expression");
87     assert(~FI && "Expected valid index");
88 
89     Expr.push_back(E);
90     FrameIndex.push_back(FI);
91   }
92 
93   /// Initialize from a DBG_VALUE instruction.
94   void initializeDbgValue(const MachineInstr *DbgValue) {
95     assert(Expr.empty() && "Already initialized?");
96     assert(FrameIndex.empty() && "Already initialized?");
97     assert(!MInsn && "Already initialized?");
98 
99     assert(Var == DbgValue->getDebugVariable() && "Wrong variable");
100     assert(IA == DbgValue->getDebugLoc()->getInlinedAt() && "Wrong inlined-at");
101 
102     MInsn = DbgValue;
103     if (auto *E = DbgValue->getDebugExpression())
104       if (E->getNumElements())
105         Expr.push_back(E);
106   }
107 
108   // Accessors.
109   const DILocalVariable *getVariable() const { return Var; }
110   const DILocation *getInlinedAt() const { return IA; }
111   ArrayRef<const DIExpression *> getExpression() const { return Expr; }
112   const DIExpression *getSingleExpression() const {
113     assert(MInsn && Expr.size() <= 1);
114     return Expr.size() ? Expr[0] : nullptr;
115   }
116   void setDIE(DIE &D) { TheDIE = &D; }
117   DIE *getDIE() const { return TheDIE; }
118   void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
119   unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
120   StringRef getName() const { return Var->getName(); }
121   const MachineInstr *getMInsn() const { return MInsn; }
122   ArrayRef<int> getFrameIndex() const { return FrameIndex; }
123 
124   void addMMIEntry(const DbgVariable &V) {
125     assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
126     assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
127     assert(V.Var == Var && "conflicting variable");
128     assert(V.IA == IA && "conflicting inlined-at location");
129 
130     assert(!FrameIndex.empty() && "Expected an MMI entry");
131     assert(!V.FrameIndex.empty() && "Expected an MMI entry");
132     assert(Expr.size() == FrameIndex.size() && "Mismatched expressions");
133     assert(V.Expr.size() == V.FrameIndex.size() && "Mismatched expressions");
134 
135     Expr.append(V.Expr.begin(), V.Expr.end());
136     FrameIndex.append(V.FrameIndex.begin(), V.FrameIndex.end());
137     assert(all_of(Expr, [](const DIExpression *E) {
138              return E && E->isFragment();
139            }) && "conflicting locations for variable");
140   }
141 
142   // Translate tag to proper Dwarf tag.
143   dwarf::Tag getTag() const {
144     // FIXME: Why don't we just infer this tag and store it all along?
145     if (Var->isParameter())
146       return dwarf::DW_TAG_formal_parameter;
147 
148     return dwarf::DW_TAG_variable;
149   }
150   /// Return true if DbgVariable is artificial.
151   bool isArtificial() const {
152     if (Var->isArtificial())
153       return true;
154     if (getType()->isArtificial())
155       return true;
156     return false;
157   }
158 
159   bool isObjectPointer() const {
160     if (Var->isObjectPointer())
161       return true;
162     if (getType()->isObjectPointer())
163       return true;
164     return false;
165   }
166 
167   bool hasComplexAddress() const {
168     assert(MInsn && "Expected DBG_VALUE, not MMI variable");
169     assert(FrameIndex.empty() && "Expected DBG_VALUE, not MMI variable");
170     assert(
171         (Expr.empty() || (Expr.size() == 1 && Expr.back()->getNumElements())) &&
172         "Invalid Expr for DBG_VALUE");
173     return !Expr.empty();
174   }
175   bool isBlockByrefVariable() const;
176   const DIType *getType() const;
177 
178 private:
179   template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
180     return Ref.resolve();
181   }
182 };
183 
184 
185 /// Helper used to pair up a symbol and its DWARF compile unit.
186 struct SymbolCU {
187   SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
188   const MCSymbol *Sym;
189   DwarfCompileUnit *CU;
190 };
191 
192 /// Collects and handles dwarf debug information.
193 class DwarfDebug : public DebugHandlerBase {
194   /// All DIEValues are allocated through this allocator.
195   BumpPtrAllocator DIEValueAllocator;
196 
197   /// Maps MDNode with its corresponding DwarfCompileUnit.
198   MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
199 
200   /// Maps a CU DIE with its corresponding DwarfCompileUnit.
201   DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
202 
203   /// List of all labels used in aranges generation.
204   std::vector<SymbolCU> ArangeLabels;
205 
206   /// Size of each symbol emitted (for those symbols that have a specific size).
207   DenseMap<const MCSymbol *, uint64_t> SymSize;
208 
209   /// Collection of abstract variables.
210   DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
211   SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
212 
213   /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
214   /// can refer to them in spite of insertions into this list.
215   DebugLocStream DebugLocs;
216 
217   /// This is a collection of subprogram MDNodes that are processed to
218   /// create DIEs.
219   SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
220 
221   /// If nonnull, stores the current machine function we're processing.
222   const MachineFunction *CurFn;
223 
224   /// If nonnull, stores the CU in which the previous subprogram was contained.
225   const DwarfCompileUnit *PrevCU;
226 
227   /// As an optimization, there is no need to emit an entry in the directory
228   /// table for the same directory as DW_AT_comp_dir.
229   StringRef CompilationDir;
230 
231   /// Holder for the file specific debug information.
232   DwarfFile InfoHolder;
233 
234   /// Holders for the various debug information flags that we might need to
235   /// have exposed. See accessor functions below for description.
236 
237   /// Map from MDNodes for user-defined types to their type signatures. Also
238   /// used to keep track of which types we have emitted type units for.
239   DenseMap<const MDNode *, uint64_t> TypeSignatures;
240 
241   SmallVector<
242       std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
243       TypeUnitsUnderConstruction;
244 
245   /// Whether to emit the pubnames/pubtypes sections.
246   bool HasDwarfPubSections;
247 
248   /// Whether to use the GNU TLS opcode (instead of the standard opcode).
249   bool UseGNUTLSOpcode;
250 
251   /// Whether to use DWARF 2 bitfields (instead of the DWARF 4 format).
252   bool UseDWARF2Bitfields;
253 
254   /// Whether to emit all linkage names, or just abstract subprograms.
255   bool UseAllLinkageNames;
256 
257   /// DWARF5 Experimental Options
258   /// @{
259   bool HasDwarfAccelTables;
260   bool HasAppleExtensionAttributes;
261   bool HasSplitDwarf;
262 
263   /// Separated Dwarf Variables
264   /// In general these will all be for bits that are left in the
265   /// original object file, rather than things that are meant
266   /// to be in the .dwo sections.
267 
268   /// Holder for the skeleton information.
269   DwarfFile SkeletonHolder;
270 
271   /// Store file names for type units under fission in a line table
272   /// header that will be emitted into debug_line.dwo.
273   // FIXME: replace this with a map from comp_dir to table so that we
274   // can emit multiple tables during LTO each of which uses directory
275   // 0, referencing the comp_dir of all the type units that use it.
276   MCDwarfDwoLineTable SplitTypeUnitFileTable;
277   /// @}
278 
279   /// True iff there are multiple CUs in this module.
280   bool SingleCU;
281   bool IsDarwin;
282 
283   AddressPool AddrPool;
284 
285   DwarfAccelTable AccelNames;
286   DwarfAccelTable AccelObjC;
287   DwarfAccelTable AccelNamespace;
288   DwarfAccelTable AccelTypes;
289 
290   // Identify a debugger for "tuning" the debug info.
291   DebuggerKind DebuggerTuning;
292 
293   /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
294   ///
295   /// Returns whether we are "tuning" for a given debugger.
296   /// Should be used only within the constructor, to set feature flags.
297   /// @{
298   bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
299   bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
300   bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
301   /// @}
302 
303   MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
304 
305   const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
306     return InfoHolder.getUnits();
307   }
308 
309   typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
310 
311   /// Find abstract variable associated with Var.
312   DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
313                                            const DILocalVariable *&Cleansed);
314   DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
315   void createAbstractVariable(const DILocalVariable *DV, LexicalScope *Scope);
316   void ensureAbstractVariableIsCreated(InlinedVariable Var,
317                                        const MDNode *Scope);
318   void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var,
319                                                const MDNode *Scope);
320 
321   DbgVariable *createConcreteVariable(LexicalScope &Scope, InlinedVariable IV);
322 
323   /// Construct a DIE for this abstract scope.
324   void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
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 by MF.
444   void collectVariableInfoFromMFTable(DenseSet<InlinedVariable> &P);
445 
446 public:
447   //===--------------------------------------------------------------------===//
448   // Main entry points.
449   //
450   DwarfDebug(AsmPrinter *A, Module *M);
451 
452   ~DwarfDebug() override;
453 
454   /// Emit all Dwarf sections that should come prior to the
455   /// content.
456   void beginModule();
457 
458   /// Emit all Dwarf sections that should come after the content.
459   void endModule() override;
460 
461   /// Gather pre-function debug information.
462   void beginFunction(const MachineFunction *MF) override;
463 
464   /// Gather and emit post-function debug information.
465   void endFunction(const MachineFunction *MF) override;
466 
467   /// Process beginning of an instruction.
468   void beginInstruction(const MachineInstr *MI) override;
469 
470   /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
471   static uint64_t makeTypeSignature(StringRef Identifier);
472 
473   /// Add a DIE to the set of types that we're going to pull into
474   /// type units.
475   void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
476                             DIE &Die, const DICompositeType *CTy);
477 
478   /// Add a label so that arange data can be generated for it.
479   void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
480 
481   /// For symbols that have a size designated (e.g. common symbols),
482   /// this tracks that size.
483   void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
484     SymSize[Sym] = Size;
485   }
486 
487   /// Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
488   /// If not, we still might emit certain cases.
489   bool useAllLinkageNames() const { return UseAllLinkageNames; }
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   /// Returns whether to use the DWARF2 format for bitfields instyead of the
496   /// DWARF4 format.
497   bool useDWARF2Bitfields() const { return UseDWARF2Bitfields; }
498 
499   // Experimental DWARF5 features.
500 
501   /// Returns whether or not to emit tables that dwarf consumers can
502   /// use to accelerate lookup.
503   bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
504 
505   bool useAppleExtensionAttributes() const {
506     return HasAppleExtensionAttributes;
507   }
508 
509   /// Returns whether or not to change the current debug info for the
510   /// split dwarf proposal support.
511   bool useSplitDwarf() const { return HasSplitDwarf; }
512 
513   /// Returns the Dwarf Version.
514   uint16_t getDwarfVersion() const;
515 
516   /// Returns the previous CU that was being updated
517   const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
518   void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
519 
520   /// Returns the entries for the .debug_loc section.
521   const DebugLocStream &getDebugLocs() const { return DebugLocs; }
522 
523   /// Emit an entry for the debug loc section. This can be used to
524   /// handle an entry that's going to be emitted into the debug loc section.
525   void emitDebugLocEntry(ByteStreamer &Streamer,
526                          const DebugLocStream::Entry &Entry);
527 
528   /// Emit the location for a debug loc entry, including the size header.
529   void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
530 
531   /// Find the MDNode for the given reference.
532   template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
533     return Ref.resolve();
534   }
535 
536   void addSubprogramNames(const DISubprogram *SP, DIE &Die);
537 
538   AddressPool &getAddressPool() { return AddrPool; }
539 
540   void addAccelName(StringRef Name, const DIE &Die);
541 
542   void addAccelObjC(StringRef Name, const DIE &Die);
543 
544   void addAccelNamespace(StringRef Name, const DIE &Die);
545 
546   void addAccelType(StringRef Name, const DIE &Die, char Flags);
547 
548   const MachineFunction *getCurrentFunction() const { return CurFn; }
549 
550   /// A helper function to check whether the DIE for a given Scope is
551   /// going to be null.
552   bool isLexicalScopeDIENull(LexicalScope *Scope);
553 
554   // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
555 
556   SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
557     return ProcessedSPNodes;
558   }
559 };
560 } // End of namespace llvm
561 
562 #endif
563