]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h
MFV r323912: 8592 ZFS channel programs - rollback
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / CodeGen / AsmPrinter / DwarfDebug.h
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/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"
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.
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   DIE *TheDIE = nullptr;                     /// Variable DIE.
68   unsigned DebugLocListIndex = ~0u;          /// Offset in DebugLocs.
69   const MachineInstr *MInsn = nullptr;       /// DBG_VALUE instruction.
70
71   struct FrameIndexExpr {
72     int FI;
73     const DIExpression *Expr;
74   };
75   mutable SmallVector<FrameIndexExpr, 1>
76       FrameIndexExprs; /// Frame index + expression.
77
78 public:
79   /// Construct a DbgVariable.
80   ///
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)
84       : Var(V), IA(IA) {}
85
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?");
90
91     assert((!E || E->isValid()) && "Expected valid expression");
92     assert(FI != INT_MAX && "Expected valid index");
93
94     FrameIndexExprs.push_back({FI, E});
95   }
96
97   /// Initialize from a DBG_VALUE instruction.
98   void initializeDbgValue(const MachineInstr *DbgValue) {
99     assert(FrameIndexExprs.empty() && "Already initialized?");
100     assert(!MInsn && "Already initialized?");
101
102     assert(Var == DbgValue->getDebugVariable() && "Wrong variable");
103     assert(IA == DbgValue->getDebugLoc()->getInlinedAt() && "Wrong inlined-at");
104
105     MInsn = DbgValue;
106     if (auto *E = DbgValue->getDebugExpression())
107       if (E->getNumElements())
108         FrameIndexExprs.push_back({0, E});
109   }
110
111   // Accessors.
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;
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   /// Get the FI entries, sorted by fragment offset.
125   ArrayRef<FrameIndexExpr> getFrameIndexExprs() const;
126   bool hasFrameIndexExprs() const { return !FrameIndexExprs.empty(); }
127
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");
133
134     assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
135     assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
136
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())
142         return;
143     }
144     FrameIndexExprs.append(V.FrameIndexExprs.begin(), V.FrameIndexExprs.end());
145     assert(all_of(FrameIndexExprs,
146                   [](FrameIndexExpr &FIE) {
147                     return FIE.Expr && FIE.Expr->isFragment();
148                   }) &&
149            "conflicting locations for variable");
150   }
151
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;
157
158     return dwarf::DW_TAG_variable;
159   }
160   /// Return true if DbgVariable is artificial.
161   bool isArtificial() const {
162     if (Var->isArtificial())
163       return true;
164     if (getType()->isArtificial())
165       return true;
166     return false;
167   }
168
169   bool isObjectPointer() const {
170     if (Var->isObjectPointer())
171       return true;
172     if (getType()->isObjectPointer())
173       return true;
174     return false;
175   }
176
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();
184   }
185   bool isBlockByrefVariable() const;
186   const DIType *getType() const;
187
188 private:
189   template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
190     return Ref.resolve();
191   }
192 };
193
194
195 /// Helper used to pair up a symbol and its DWARF compile unit.
196 struct SymbolCU {
197   SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
198   const MCSymbol *Sym;
199   DwarfCompileUnit *CU;
200 };
201
202 /// Collects and handles dwarf debug information.
203 class DwarfDebug : public DebugHandlerBase {
204   /// All DIEValues are allocated through this allocator.
205   BumpPtrAllocator DIEValueAllocator;
206
207   /// Maps MDNode with its corresponding DwarfCompileUnit.
208   MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
209
210   /// Maps a CU DIE with its corresponding DwarfCompileUnit.
211   DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
212
213   /// List of all labels used in aranges generation.
214   std::vector<SymbolCU> ArangeLabels;
215
216   /// Size of each symbol emitted (for those symbols that have a specific size).
217   DenseMap<const MCSymbol *, uint64_t> SymSize;
218
219   /// Collection of abstract variables.
220   SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
221
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;
225
226   /// This is a collection of subprogram MDNodes that are processed to
227   /// create DIEs.
228   SetVector<const DISubprogram *, SmallVector<const DISubprogram *, 16>,
229             SmallPtrSet<const DISubprogram *, 16>>
230       ProcessedSPNodes;
231
232   /// If nonnull, stores the current machine function we're processing.
233   const MachineFunction *CurFn;
234
235   /// If nonnull, stores the CU in which the previous subprogram was contained.
236   const DwarfCompileUnit *PrevCU;
237
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;
241
242   /// Holder for the file specific debug information.
243   DwarfFile InfoHolder;
244
245   /// Holders for the various debug information flags that we might need to
246   /// have exposed. See accessor functions below for description.
247
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;
251
252   SmallVector<
253       std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
254       TypeUnitsUnderConstruction;
255
256   /// Whether to use the GNU TLS opcode (instead of the standard opcode).
257   bool UseGNUTLSOpcode;
258
259   /// Whether to use DWARF 2 bitfields (instead of the DWARF 4 format).
260   bool UseDWARF2Bitfields;
261
262   /// Whether to emit all linkage names, or just abstract subprograms.
263   bool UseAllLinkageNames;
264
265   /// DWARF5 Experimental Options
266   /// @{
267   bool HasDwarfAccelTables;
268   bool HasAppleExtensionAttributes;
269   bool HasSplitDwarf;
270
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.
275
276   /// Holder for the skeleton information.
277   DwarfFile SkeletonHolder;
278
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;
285   /// @}
286   
287   /// True iff there are multiple CUs in this module.
288   bool SingleCU;
289   bool IsDarwin;
290
291   AddressPool AddrPool;
292
293   DwarfAccelTable AccelNames;
294   DwarfAccelTable AccelObjC;
295   DwarfAccelTable AccelNamespace;
296   DwarfAccelTable AccelTypes;
297
298   // Identify a debugger for "tuning" the debug info.
299   DebuggerKind DebuggerTuning;
300
301   /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
302   ///
303   /// Returns whether we are "tuning" for a given debugger.
304   /// Should be used only within the constructor, to set feature flags.
305   /// @{
306   bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
307   bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
308   bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
309   /// @}
310
311   MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
312
313   const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
314     return InfoHolder.getUnits();
315   }
316
317   typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
318
319   void ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable Var,
320                                        const MDNode *Scope);
321   void ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU, InlinedVariable Var,
322                                                const MDNode *Scope);
323
324   DbgVariable *createConcreteVariable(DwarfCompileUnit &TheCU,
325                                       LexicalScope &Scope, InlinedVariable IV);
326
327   /// Construct a DIE for this abstract scope.
328   void constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, LexicalScope *Scope);
329
330   void finishVariableDefinitions();
331
332   void finishSubprogramDefinitions();
333
334   /// Finish off debug information after all functions have been
335   /// processed.
336   void finalizeModuleInfo();
337
338   /// Emit the debug info section.
339   void emitDebugInfo();
340
341   /// Emit the abbreviation section.
342   void emitAbbreviations();
343
344   /// Emit a specified accelerator table.
345   void emitAccel(DwarfAccelTable &Accel, MCSection *Section,
346                  StringRef TableName);
347
348   /// Emit visible names into a hashed accelerator table section.
349   void emitAccelNames();
350
351   /// Emit objective C classes and categories into a hashed
352   /// accelerator table section.
353   void emitAccelObjC();
354
355   /// Emit namespace dies into a hashed accelerator table.
356   void emitAccelNamespaces();
357
358   /// Emit type dies into a hashed accelerator table.
359   void emitAccelTypes();
360
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
364   /// index.
365   void emitDebugPubNames(bool GnuStyle = false);
366
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
370   /// index.
371   void emitDebugPubTypes(bool GnuStyle = false);
372
373   void emitDebugPubSection(
374       bool GnuStyle, MCSection *PSec, StringRef Name,
375       const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
376
377   /// Emit null-terminated strings into a debug str section.
378   void emitDebugStr();
379
380   /// Emit variable locations into a debug loc section.
381   void emitDebugLoc();
382
383   /// Emit variable locations into a debug loc dwo section.
384   void emitDebugLocDWO();
385
386   /// Emit address ranges into a debug aranges section.
387   void emitDebugARanges();
388
389   /// Emit address ranges into a debug ranges section.
390   void emitDebugRanges();
391
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);
397
398   /// DWARF 5 Experimental Split Dwarf Emitters
399
400   /// Initialize common features of skeleton units.
401   void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
402                         std::unique_ptr<DwarfCompileUnit> NewU);
403
404   /// Construct the split debug info compile unit for the debug info
405   /// section.
406   DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
407
408   /// Emit the debug info dwo section.
409   void emitDebugInfoDWO();
410
411   /// Emit the debug abbrev dwo section.
412   void emitDebugAbbrevDWO();
413
414   /// Emit the debug line dwo section.
415   void emitDebugLineDWO();
416
417   /// Emit the debug str dwo section.
418   void emitDebugStrDWO();
419
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;
423
424   /// Create new DwarfCompileUnit for the given metadata node with tag
425   /// DW_TAG_compile_unit.
426   DwarfCompileUnit &getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit);
427
428   /// Construct imported_module or imported_declaration DIE.
429   void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
430                                         const DIImportedEntity *N);
431
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,
436                         unsigned Flags);
437
438   /// Populate LexicalScope entries with variables' info.
439   void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
440                            DenseSet<InlinedVariable> &ProcessedVars);
441
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);
446
447   /// Collect variable information from the side table maintained by MF.
448   void collectVariableInfoFromMFTable(DwarfCompileUnit &TheCU,
449                                       DenseSet<InlinedVariable> &P);
450
451 protected:
452   /// Gather pre-function debug information.
453   void beginFunctionImpl(const MachineFunction *MF) override;
454
455   /// Gather and emit post-function debug information.
456   void endFunctionImpl(const MachineFunction *MF) override;
457
458   void skippedNonDebugFunction() override;
459
460 public:
461   //===--------------------------------------------------------------------===//
462   // Main entry points.
463   //
464   DwarfDebug(AsmPrinter *A, Module *M);
465
466   ~DwarfDebug() override;
467
468   /// Emit all Dwarf sections that should come prior to the
469   /// content.
470   void beginModule();
471
472   /// Emit all Dwarf sections that should come after the content.
473   void endModule() override;
474
475   /// Process beginning of an instruction.
476   void beginInstruction(const MachineInstr *MI) override;
477
478   /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
479   static uint64_t makeTypeSignature(StringRef Identifier);
480
481   /// Add a DIE to the set of types that we're going to pull into
482   /// type units.
483   void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
484                             DIE &Die, const DICompositeType *CTy);
485
486   /// Add a label so that arange data can be generated for it.
487   void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
488
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 {
492     SymSize[Sym] = Size;
493   }
494
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; }
498
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; }
502
503   /// Returns whether to use the DWARF2 format for bitfields instyead of the
504   /// DWARF4 format.
505   bool useDWARF2Bitfields() const { return UseDWARF2Bitfields; }
506
507   // Experimental DWARF5 features.
508
509   /// Returns whether or not to emit tables that dwarf consumers can
510   /// use to accelerate lookup.
511   bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
512
513   bool useAppleExtensionAttributes() const {
514     return HasAppleExtensionAttributes;
515   }
516
517   /// Returns whether or not to change the current debug info for the
518   /// split dwarf proposal support.
519   bool useSplitDwarf() const { return HasSplitDwarf; }
520
521   bool shareAcrossDWOCUs() const;
522
523   /// Returns the Dwarf Version.
524   uint16_t getDwarfVersion() const;
525
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; }
529
530   /// Returns the entries for the .debug_loc section.
531   const DebugLocStream &getDebugLocs() const { return DebugLocs; }
532
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);
537
538   /// Emit the location for a debug loc entry, including the size header.
539   void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
540
541   /// Find the MDNode for the given reference.
542   template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
543     return Ref.resolve();
544   }
545
546   void addSubprogramNames(const DISubprogram *SP, DIE &Die);
547
548   AddressPool &getAddressPool() { return AddrPool; }
549
550   void addAccelName(StringRef Name, const DIE &Die);
551
552   void addAccelObjC(StringRef Name, const DIE &Die);
553
554   void addAccelNamespace(StringRef Name, const DIE &Die);
555
556   void addAccelType(StringRef Name, const DIE &Die, char Flags);
557
558   const MachineFunction *getCurrentFunction() const { return CurFn; }
559
560   /// A helper function to check whether the DIE for a given Scope is
561   /// going to be null.
562   bool isLexicalScopeDIENull(LexicalScope *Scope);
563
564   bool hasDwarfPubSections(bool includeMinimalInlineScopes) const;
565 };
566 } // End of namespace llvm
567
568 #endif