]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304222, and update
[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     FrameIndexExprs.append(V.FrameIndexExprs.begin(), V.FrameIndexExprs.end());
138     assert(all_of(FrameIndexExprs,
139                   [](FrameIndexExpr &FIE) {
140                     return FIE.Expr && FIE.Expr->isFragment();
141                   }) &&
142            "conflicting locations for variable");
143   }
144
145   // Translate tag to proper Dwarf tag.
146   dwarf::Tag getTag() const {
147     // FIXME: Why don't we just infer this tag and store it all along?
148     if (Var->isParameter())
149       return dwarf::DW_TAG_formal_parameter;
150
151     return dwarf::DW_TAG_variable;
152   }
153   /// Return true if DbgVariable is artificial.
154   bool isArtificial() const {
155     if (Var->isArtificial())
156       return true;
157     if (getType()->isArtificial())
158       return true;
159     return false;
160   }
161
162   bool isObjectPointer() const {
163     if (Var->isObjectPointer())
164       return true;
165     if (getType()->isObjectPointer())
166       return true;
167     return false;
168   }
169
170   bool hasComplexAddress() const {
171     assert(MInsn && "Expected DBG_VALUE, not MMI variable");
172     assert((FrameIndexExprs.empty() ||
173             (FrameIndexExprs.size() == 1 &&
174              FrameIndexExprs[0].Expr->getNumElements())) &&
175            "Invalid Expr for DBG_VALUE");
176     return !FrameIndexExprs.empty();
177   }
178   bool isBlockByrefVariable() const;
179   const DIType *getType() const;
180
181 private:
182   template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
183     return Ref.resolve();
184   }
185 };
186
187
188 /// Helper used to pair up a symbol and its DWARF compile unit.
189 struct SymbolCU {
190   SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
191   const MCSymbol *Sym;
192   DwarfCompileUnit *CU;
193 };
194
195 /// Collects and handles dwarf debug information.
196 class DwarfDebug : public DebugHandlerBase {
197   /// All DIEValues are allocated through this allocator.
198   BumpPtrAllocator DIEValueAllocator;
199
200   /// Maps MDNode with its corresponding DwarfCompileUnit.
201   MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
202
203   /// Maps a CU DIE with its corresponding DwarfCompileUnit.
204   DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
205
206   /// List of all labels used in aranges generation.
207   std::vector<SymbolCU> ArangeLabels;
208
209   /// Size of each symbol emitted (for those symbols that have a specific size).
210   DenseMap<const MCSymbol *, uint64_t> SymSize;
211
212   /// Collection of abstract variables.
213   SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
214
215   /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
216   /// can refer to them in spite of insertions into this list.
217   DebugLocStream DebugLocs;
218
219   /// This is a collection of subprogram MDNodes that are processed to
220   /// create DIEs.
221   SetVector<const DISubprogram *, SmallVector<const DISubprogram *, 16>,
222             SmallPtrSet<const DISubprogram *, 16>>
223       ProcessedSPNodes;
224
225   /// If nonnull, stores the current machine function we're processing.
226   const MachineFunction *CurFn;
227
228   /// If nonnull, stores the CU in which the previous subprogram was contained.
229   const DwarfCompileUnit *PrevCU;
230
231   /// As an optimization, there is no need to emit an entry in the directory
232   /// table for the same directory as DW_AT_comp_dir.
233   StringRef CompilationDir;
234
235   /// Holder for the file specific debug information.
236   DwarfFile InfoHolder;
237
238   /// Holders for the various debug information flags that we might need to
239   /// have exposed. See accessor functions below for description.
240
241   /// Map from MDNodes for user-defined types to their type signatures. Also
242   /// used to keep track of which types we have emitted type units for.
243   DenseMap<const MDNode *, uint64_t> TypeSignatures;
244
245   SmallVector<
246       std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
247       TypeUnitsUnderConstruction;
248
249   /// Whether to use the GNU TLS opcode (instead of the standard opcode).
250   bool UseGNUTLSOpcode;
251
252   /// Whether to use DWARF 2 bitfields (instead of the DWARF 4 format).
253   bool UseDWARF2Bitfields;
254
255   /// Whether to emit all linkage names, or just abstract subprograms.
256   bool UseAllLinkageNames;
257
258   /// DWARF5 Experimental Options
259   /// @{
260   bool HasDwarfAccelTables;
261   bool HasAppleExtensionAttributes;
262   bool HasSplitDwarf;
263
264   /// Separated Dwarf Variables
265   /// In general these will all be for bits that are left in the
266   /// original object file, rather than things that are meant
267   /// to be in the .dwo sections.
268
269   /// Holder for the skeleton information.
270   DwarfFile SkeletonHolder;
271
272   /// Store file names for type units under fission in a line table
273   /// header that will be emitted into debug_line.dwo.
274   // FIXME: replace this with a map from comp_dir to table so that we
275   // can emit multiple tables during LTO each of which uses directory
276   // 0, referencing the comp_dir of all the type units that use it.
277   MCDwarfDwoLineTable SplitTypeUnitFileTable;
278   /// @}
279   
280   /// True iff there are multiple CUs in this module.
281   bool SingleCU;
282   bool IsDarwin;
283
284   AddressPool AddrPool;
285
286   DwarfAccelTable AccelNames;
287   DwarfAccelTable AccelObjC;
288   DwarfAccelTable AccelNamespace;
289   DwarfAccelTable AccelTypes;
290
291   // Identify a debugger for "tuning" the debug info.
292   DebuggerKind DebuggerTuning;
293
294   /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
295   ///
296   /// Returns whether we are "tuning" for a given debugger.
297   /// Should be used only within the constructor, to set feature flags.
298   /// @{
299   bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
300   bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
301   bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
302   /// @}
303
304   MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
305
306   const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
307     return InfoHolder.getUnits();
308   }
309
310   typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
311
312   void ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable Var,
313                                        const MDNode *Scope);
314   void ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU, InlinedVariable Var,
315                                                const MDNode *Scope);
316
317   DbgVariable *createConcreteVariable(DwarfCompileUnit &TheCU,
318                                       LexicalScope &Scope, InlinedVariable IV);
319
320   /// Construct a DIE for this abstract scope.
321   void constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, LexicalScope *Scope);
322
323   void finishVariableDefinitions();
324
325   void finishSubprogramDefinitions();
326
327   /// Finish off debug information after all functions have been
328   /// processed.
329   void finalizeModuleInfo();
330
331   /// Emit the debug info section.
332   void emitDebugInfo();
333
334   /// Emit the abbreviation section.
335   void emitAbbreviations();
336
337   /// Emit a specified accelerator table.
338   void emitAccel(DwarfAccelTable &Accel, MCSection *Section,
339                  StringRef TableName);
340
341   /// Emit visible names into a hashed accelerator table section.
342   void emitAccelNames();
343
344   /// Emit objective C classes and categories into a hashed
345   /// accelerator table section.
346   void emitAccelObjC();
347
348   /// Emit namespace dies into a hashed accelerator table.
349   void emitAccelNamespaces();
350
351   /// Emit type dies into a hashed accelerator table.
352   void emitAccelTypes();
353
354   /// Emit visible names into a debug pubnames section.
355   /// \param GnuStyle determines whether or not we want to emit
356   /// additional information into the table ala newer gcc for gdb
357   /// index.
358   void emitDebugPubNames(bool GnuStyle = false);
359
360   /// Emit visible types into a debug pubtypes section.
361   /// \param GnuStyle determines whether or not we want to emit
362   /// additional information into the table ala newer gcc for gdb
363   /// index.
364   void emitDebugPubTypes(bool GnuStyle = false);
365
366   void emitDebugPubSection(
367       bool GnuStyle, MCSection *PSec, StringRef Name,
368       const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
369
370   /// Emit null-terminated strings into a debug str section.
371   void emitDebugStr();
372
373   /// Emit variable locations into a debug loc section.
374   void emitDebugLoc();
375
376   /// Emit variable locations into a debug loc dwo section.
377   void emitDebugLocDWO();
378
379   /// Emit address ranges into a debug aranges section.
380   void emitDebugARanges();
381
382   /// Emit address ranges into a debug ranges section.
383   void emitDebugRanges();
384
385   /// Emit macros into a debug macinfo section.
386   void emitDebugMacinfo();
387   void emitMacro(DIMacro &M);
388   void emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U);
389   void handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U);
390
391   /// DWARF 5 Experimental Split Dwarf Emitters
392
393   /// Initialize common features of skeleton units.
394   void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
395                         std::unique_ptr<DwarfCompileUnit> NewU);
396
397   /// Construct the split debug info compile unit for the debug info
398   /// section.
399   DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
400
401   /// Emit the debug info dwo section.
402   void emitDebugInfoDWO();
403
404   /// Emit the debug abbrev dwo section.
405   void emitDebugAbbrevDWO();
406
407   /// Emit the debug line dwo section.
408   void emitDebugLineDWO();
409
410   /// Emit the debug str dwo section.
411   void emitDebugStrDWO();
412
413   /// Flags to let the linker know we have emitted new style pubnames. Only
414   /// emit it here if we don't have a skeleton CU for split dwarf.
415   void addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const;
416
417   /// Create new DwarfCompileUnit for the given metadata node with tag
418   /// DW_TAG_compile_unit.
419   DwarfCompileUnit &getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit);
420
421   /// Construct imported_module or imported_declaration DIE.
422   void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
423                                         const DIImportedEntity *N);
424
425   /// Register a source line with debug info. Returns the unique
426   /// label that was emitted and which provides correspondence to the
427   /// source line list.
428   void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
429                         unsigned Flags);
430
431   /// Populate LexicalScope entries with variables' info.
432   void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
433                            DenseSet<InlinedVariable> &ProcessedVars);
434
435   /// Build the location list for all DBG_VALUEs in the
436   /// function that describe the same variable.
437   void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
438                          const DbgValueHistoryMap::InstrRanges &Ranges);
439
440   /// Collect variable information from the side table maintained by MF.
441   void collectVariableInfoFromMFTable(DwarfCompileUnit &TheCU,
442                                       DenseSet<InlinedVariable> &P);
443
444 protected:
445   /// Gather pre-function debug information.
446   void beginFunctionImpl(const MachineFunction *MF) override;
447
448   /// Gather and emit post-function debug information.
449   void endFunctionImpl(const MachineFunction *MF) override;
450
451   void skippedNonDebugFunction() override;
452
453 public:
454   //===--------------------------------------------------------------------===//
455   // Main entry points.
456   //
457   DwarfDebug(AsmPrinter *A, Module *M);
458
459   ~DwarfDebug() override;
460
461   /// Emit all Dwarf sections that should come prior to the
462   /// content.
463   void beginModule();
464
465   /// Emit all Dwarf sections that should come after the content.
466   void endModule() 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 we should emit all DW_AT_[MIPS_]linkage_name.
489   /// If not, we still might emit certain cases.
490   bool useAllLinkageNames() const { return UseAllLinkageNames; }
491
492   /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
493   /// standard DW_OP_form_tls_address opcode
494   bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
495
496   /// Returns whether to use the DWARF2 format for bitfields instyead of the
497   /// DWARF4 format.
498   bool useDWARF2Bitfields() const { return UseDWARF2Bitfields; }
499
500   // Experimental DWARF5 features.
501
502   /// Returns whether or not to emit tables that dwarf consumers can
503   /// use to accelerate lookup.
504   bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
505
506   bool useAppleExtensionAttributes() const {
507     return HasAppleExtensionAttributes;
508   }
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   bool shareAcrossDWOCUs() const;
515
516   /// Returns the Dwarf Version.
517   uint16_t getDwarfVersion() const;
518
519   /// Returns the previous CU that was being updated
520   const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
521   void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
522
523   /// Returns the entries for the .debug_loc section.
524   const DebugLocStream &getDebugLocs() const { return DebugLocs; }
525
526   /// Emit an entry for the debug loc section. This can be used to
527   /// handle an entry that's going to be emitted into the debug loc section.
528   void emitDebugLocEntry(ByteStreamer &Streamer,
529                          const DebugLocStream::Entry &Entry);
530
531   /// Emit the location for a debug loc entry, including the size header.
532   void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
533
534   /// Find the MDNode for the given reference.
535   template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
536     return Ref.resolve();
537   }
538
539   void addSubprogramNames(const DISubprogram *SP, DIE &Die);
540
541   AddressPool &getAddressPool() { return AddrPool; }
542
543   void addAccelName(StringRef Name, const DIE &Die);
544
545   void addAccelObjC(StringRef Name, const DIE &Die);
546
547   void addAccelNamespace(StringRef Name, const DIE &Die);
548
549   void addAccelType(StringRef Name, const DIE &Die, char Flags);
550
551   const MachineFunction *getCurrentFunction() const { return CurFn; }
552
553   /// A helper function to check whether the DIE for a given Scope is
554   /// going to be null.
555   bool isLexicalScopeDIENull(LexicalScope *Scope);
556
557   bool hasDwarfPubSections(bool includeMinimalInlineScopes) const;
558 };
559 } // End of namespace llvm
560
561 #endif