• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- llvm/CodeGen/DwarfDebug.h - Dwarf Debug Framework --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for writing dwarf debug info into asm files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
14 #define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
15 
16 #include "AddressPool.h"
17 #include "DebugLocStream.h"
18 #include "DebugLocEntry.h"
19 #include "DwarfFile.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/MapVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/BinaryFormat/Dwarf.h"
31 #include "llvm/CodeGen/AccelTable.h"
32 #include "llvm/CodeGen/DbgEntityHistoryCalculator.h"
33 #include "llvm/CodeGen/DebugHandlerBase.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/IR/DebugInfoMetadata.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/MC/MCDwarf.h"
39 #include "llvm/Support/Allocator.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include <cassert>
42 #include <cstdint>
43 #include <limits>
44 #include <memory>
45 #include <utility>
46 #include <vector>
47 
48 namespace llvm {
49 
50 class AsmPrinter;
51 class ByteStreamer;
52 class DIE;
53 class DwarfCompileUnit;
54 class DwarfExpression;
55 class DwarfTypeUnit;
56 class DwarfUnit;
57 class LexicalScope;
58 class MachineFunction;
59 class MCSection;
60 class MCSymbol;
61 class Module;
62 
63 //===----------------------------------------------------------------------===//
64 /// This class is defined as the common parent of DbgVariable and DbgLabel
65 /// such that it could levarage polymorphism to extract common code for
66 /// DbgVariable and DbgLabel.
67 class DbgEntity {
68   const DINode *Entity;
69   const DILocation *InlinedAt;
70   DIE *TheDIE = nullptr;
71   unsigned SubclassID;
72 
73 public:
74   enum DbgEntityKind {
75     DbgVariableKind,
76     DbgLabelKind
77   };
78 
DbgEntity(const DINode * N,const DILocation * IA,unsigned ID)79   DbgEntity(const DINode *N, const DILocation *IA, unsigned ID)
80     : Entity(N), InlinedAt(IA), SubclassID(ID) {}
~DbgEntity()81   virtual ~DbgEntity() {}
82 
83   /// Accessors.
84   /// @{
getEntity()85   const DINode *getEntity() const { return Entity; }
getInlinedAt()86   const DILocation *getInlinedAt() const { return InlinedAt; }
getDIE()87   DIE *getDIE() const { return TheDIE; }
getDbgEntityID()88   unsigned getDbgEntityID() const { return SubclassID; }
89   /// @}
90 
setDIE(DIE & D)91   void setDIE(DIE &D) { TheDIE = &D; }
92 
classof(const DbgEntity * N)93   static bool classof(const DbgEntity *N) {
94     switch (N->getDbgEntityID()) {
95     default:
96       return false;
97     case DbgVariableKind:
98     case DbgLabelKind:
99       return true;
100     }
101   }
102 };
103 
104 //===----------------------------------------------------------------------===//
105 /// This class is used to track local variable information.
106 ///
107 /// Variables can be created from allocas, in which case they're generated from
108 /// the MMI table.  Such variables can have multiple expressions and frame
109 /// indices.
110 ///
111 /// Variables can be created from \c DBG_VALUE instructions.  Those whose
112 /// location changes over time use \a DebugLocListIndex, while those with a
113 /// single location use \a ValueLoc and (optionally) a single entry of \a Expr.
114 ///
115 /// Variables that have been optimized out use none of these fields.
116 class DbgVariable : public DbgEntity {
117   /// Index of the entry list in DebugLocs.
118   unsigned DebugLocListIndex = ~0u;
119   /// DW_OP_LLVM_tag_offset value from DebugLocs.
120   Optional<uint8_t> DebugLocListTagOffset;
121 
122   /// Single value location description.
123   std::unique_ptr<DbgValueLoc> ValueLoc = nullptr;
124 
125   struct FrameIndexExpr {
126     int FI;
127     const DIExpression *Expr;
128   };
129   mutable SmallVector<FrameIndexExpr, 1>
130       FrameIndexExprs; /// Frame index + expression.
131 
132 public:
133   /// Construct a DbgVariable.
134   ///
135   /// Creates a variable without any DW_AT_location.  Call \a initializeMMI()
136   /// for MMI entries, or \a initializeDbgValue() for DBG_VALUE instructions.
DbgVariable(const DILocalVariable * V,const DILocation * IA)137   DbgVariable(const DILocalVariable *V, const DILocation *IA)
138       : DbgEntity(V, IA, DbgVariableKind) {}
139 
140   /// Initialize from the MMI table.
initializeMMI(const DIExpression * E,int FI)141   void initializeMMI(const DIExpression *E, int FI) {
142     assert(FrameIndexExprs.empty() && "Already initialized?");
143     assert(!ValueLoc.get() && "Already initialized?");
144 
145     assert((!E || E->isValid()) && "Expected valid expression");
146     assert(FI != std::numeric_limits<int>::max() && "Expected valid index");
147 
148     FrameIndexExprs.push_back({FI, E});
149   }
150 
151   // Initialize variable's location.
initializeDbgValue(DbgValueLoc Value)152   void initializeDbgValue(DbgValueLoc Value) {
153     assert(FrameIndexExprs.empty() && "Already initialized?");
154     assert(!ValueLoc && "Already initialized?");
155     assert(!Value.getExpression()->isFragment() && "Fragments not supported.");
156 
157     ValueLoc = std::make_unique<DbgValueLoc>(Value);
158     if (auto *E = ValueLoc->getExpression())
159       if (E->getNumElements())
160         FrameIndexExprs.push_back({0, E});
161   }
162 
163   /// Initialize from a DBG_VALUE instruction.
164   void initializeDbgValue(const MachineInstr *DbgValue);
165 
166   // Accessors.
getVariable()167   const DILocalVariable *getVariable() const {
168     return cast<DILocalVariable>(getEntity());
169   }
170 
getSingleExpression()171   const DIExpression *getSingleExpression() const {
172     assert(ValueLoc.get() && FrameIndexExprs.size() <= 1);
173     return FrameIndexExprs.size() ? FrameIndexExprs[0].Expr : nullptr;
174   }
175 
setDebugLocListIndex(unsigned O)176   void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
getDebugLocListIndex()177   unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
setDebugLocListTagOffset(uint8_t O)178   void setDebugLocListTagOffset(uint8_t O) { DebugLocListTagOffset = O; }
getDebugLocListTagOffset()179   Optional<uint8_t> getDebugLocListTagOffset() const { return DebugLocListTagOffset; }
getName()180   StringRef getName() const { return getVariable()->getName(); }
getValueLoc()181   const DbgValueLoc *getValueLoc() const { return ValueLoc.get(); }
182   /// Get the FI entries, sorted by fragment offset.
183   ArrayRef<FrameIndexExpr> getFrameIndexExprs() const;
hasFrameIndexExprs()184   bool hasFrameIndexExprs() const { return !FrameIndexExprs.empty(); }
185   void addMMIEntry(const DbgVariable &V);
186 
187   // Translate tag to proper Dwarf tag.
getTag()188   dwarf::Tag getTag() const {
189     // FIXME: Why don't we just infer this tag and store it all along?
190     if (getVariable()->isParameter())
191       return dwarf::DW_TAG_formal_parameter;
192 
193     return dwarf::DW_TAG_variable;
194   }
195 
196   /// Return true if DbgVariable is artificial.
isArtificial()197   bool isArtificial() const {
198     if (getVariable()->isArtificial())
199       return true;
200     if (getType()->isArtificial())
201       return true;
202     return false;
203   }
204 
isObjectPointer()205   bool isObjectPointer() const {
206     if (getVariable()->isObjectPointer())
207       return true;
208     if (getType()->isObjectPointer())
209       return true;
210     return false;
211   }
212 
hasComplexAddress()213   bool hasComplexAddress() const {
214     assert(ValueLoc.get() && "Expected DBG_VALUE, not MMI variable");
215     assert((FrameIndexExprs.empty() ||
216             (FrameIndexExprs.size() == 1 &&
217              FrameIndexExprs[0].Expr->getNumElements())) &&
218            "Invalid Expr for DBG_VALUE");
219     return !FrameIndexExprs.empty();
220   }
221 
222   const DIType *getType() const;
223 
classof(const DbgEntity * N)224   static bool classof(const DbgEntity *N) {
225     return N->getDbgEntityID() == DbgVariableKind;
226   }
227 };
228 
229 //===----------------------------------------------------------------------===//
230 /// This class is used to track label information.
231 ///
232 /// Labels are collected from \c DBG_LABEL instructions.
233 class DbgLabel : public DbgEntity {
234   const MCSymbol *Sym;                  /// Symbol before DBG_LABEL instruction.
235 
236 public:
237   /// We need MCSymbol information to generate DW_AT_low_pc.
238   DbgLabel(const DILabel *L, const DILocation *IA, const MCSymbol *Sym = nullptr)
DbgEntity(L,IA,DbgLabelKind)239       : DbgEntity(L, IA, DbgLabelKind), Sym(Sym) {}
240 
241   /// Accessors.
242   /// @{
getLabel()243   const DILabel *getLabel() const { return cast<DILabel>(getEntity()); }
getSymbol()244   const MCSymbol *getSymbol() const { return Sym; }
245 
getName()246   StringRef getName() const { return getLabel()->getName(); }
247   /// @}
248 
249   /// Translate tag to proper Dwarf tag.
getTag()250   dwarf::Tag getTag() const {
251     return dwarf::DW_TAG_label;
252   }
253 
classof(const DbgEntity * N)254   static bool classof(const DbgEntity *N) {
255     return N->getDbgEntityID() == DbgLabelKind;
256   }
257 };
258 
259 /// Used for tracking debug info about call site parameters.
260 class DbgCallSiteParam {
261 private:
262   unsigned Register; ///< Parameter register at the callee entry point.
263   DbgValueLoc Value; ///< Corresponding location for the parameter value at
264                      ///< the call site.
265 public:
DbgCallSiteParam(unsigned Reg,DbgValueLoc Val)266   DbgCallSiteParam(unsigned Reg, DbgValueLoc Val)
267       : Register(Reg), Value(Val) {
268     assert(Reg && "Parameter register cannot be undef");
269   }
270 
getRegister()271   unsigned getRegister() const { return Register; }
getValue()272   DbgValueLoc getValue() const { return Value; }
273 };
274 
275 /// Collection used for storing debug call site parameters.
276 using ParamSet = SmallVector<DbgCallSiteParam, 4>;
277 
278 /// Helper used to pair up a symbol and its DWARF compile unit.
279 struct SymbolCU {
SymbolCUSymbolCU280   SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
281 
282   const MCSymbol *Sym;
283   DwarfCompileUnit *CU;
284 };
285 
286 /// The kind of accelerator tables we should emit.
287 enum class AccelTableKind {
288   Default, ///< Platform default.
289   None,    ///< None.
290   Apple,   ///< .apple_names, .apple_namespaces, .apple_types, .apple_objc.
291   Dwarf,   ///< DWARF v5 .debug_names.
292 };
293 
294 /// Collects and handles dwarf debug information.
295 class DwarfDebug : public DebugHandlerBase {
296   /// All DIEValues are allocated through this allocator.
297   BumpPtrAllocator DIEValueAllocator;
298 
299   /// Maps MDNode with its corresponding DwarfCompileUnit.
300   MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
301 
302   /// Maps a CU DIE with its corresponding DwarfCompileUnit.
303   DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
304 
305   /// List of all labels used in aranges generation.
306   std::vector<SymbolCU> ArangeLabels;
307 
308   /// Size of each symbol emitted (for those symbols that have a specific size).
309   DenseMap<const MCSymbol *, uint64_t> SymSize;
310 
311   /// Collection of abstract variables/labels.
312   SmallVector<std::unique_ptr<DbgEntity>, 64> ConcreteEntities;
313 
314   /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
315   /// can refer to them in spite of insertions into this list.
316   DebugLocStream DebugLocs;
317 
318   /// This is a collection of subprogram MDNodes that are processed to
319   /// create DIEs.
320   SetVector<const DISubprogram *, SmallVector<const DISubprogram *, 16>,
321             SmallPtrSet<const DISubprogram *, 16>>
322       ProcessedSPNodes;
323 
324   /// If nonnull, stores the current machine function we're processing.
325   const MachineFunction *CurFn = nullptr;
326 
327   /// If nonnull, stores the CU in which the previous subprogram was contained.
328   const DwarfCompileUnit *PrevCU = nullptr;
329 
330   /// As an optimization, there is no need to emit an entry in the directory
331   /// table for the same directory as DW_AT_comp_dir.
332   StringRef CompilationDir;
333 
334   /// Holder for the file specific debug information.
335   DwarfFile InfoHolder;
336 
337   /// Holders for the various debug information flags that we might need to
338   /// have exposed. See accessor functions below for description.
339 
340   /// Map from MDNodes for user-defined types to their type signatures. Also
341   /// used to keep track of which types we have emitted type units for.
342   DenseMap<const MDNode *, uint64_t> TypeSignatures;
343 
344   DenseMap<const MCSection *, const MCSymbol *> SectionLabels;
345 
346   SmallVector<
347       std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
348       TypeUnitsUnderConstruction;
349 
350   /// Whether to use the GNU TLS opcode (instead of the standard opcode).
351   bool UseGNUTLSOpcode;
352 
353   /// Whether to use DWARF 2 bitfields (instead of the DWARF 4 format).
354   bool UseDWARF2Bitfields;
355 
356   /// Whether to emit all linkage names, or just abstract subprograms.
357   bool UseAllLinkageNames;
358 
359   /// Use inlined strings.
360   bool UseInlineStrings = false;
361 
362   /// Allow emission of .debug_ranges section.
363   bool UseRangesSection = true;
364 
365   /// True if the sections itself must be used as references and don't create
366   /// temp symbols inside DWARF sections.
367   bool UseSectionsAsReferences = false;
368 
369   ///Allow emission of the .debug_loc section.
370   bool UseLocSection = true;
371 
372   /// Generate DWARF v4 type units.
373   bool GenerateTypeUnits;
374 
375   /// Emit a .debug_macro section instead of .debug_macinfo.
376   bool UseDebugMacroSection;
377 
378   /// Avoid using DW_OP_convert due to consumer incompatibilities.
379   bool EnableOpConvert;
380 
381   /// DWARF5 Experimental Options
382   /// @{
383   AccelTableKind TheAccelTableKind;
384   bool HasAppleExtensionAttributes;
385   bool HasSplitDwarf;
386 
387   /// Whether to generate the DWARF v5 string offsets table.
388   /// It consists of a series of contributions, each preceded by a header.
389   /// The pre-DWARF v5 string offsets table for split dwarf is, in contrast,
390   /// a monolithic sequence of string offsets.
391   bool UseSegmentedStringOffsetsTable;
392 
393   /// Enable production of call site parameters needed to print the debug entry
394   /// values. Useful for testing purposes when a debugger does not support the
395   /// feature yet.
396   bool EmitDebugEntryValues;
397 
398   /// Separated Dwarf Variables
399   /// In general these will all be for bits that are left in the
400   /// original object file, rather than things that are meant
401   /// to be in the .dwo sections.
402 
403   /// Holder for the skeleton information.
404   DwarfFile SkeletonHolder;
405 
406   /// Store file names for type units under fission in a line table
407   /// header that will be emitted into debug_line.dwo.
408   // FIXME: replace this with a map from comp_dir to table so that we
409   // can emit multiple tables during LTO each of which uses directory
410   // 0, referencing the comp_dir of all the type units that use it.
411   MCDwarfDwoLineTable SplitTypeUnitFileTable;
412   /// @}
413 
414   /// True iff there are multiple CUs in this module.
415   bool SingleCU;
416   bool IsDarwin;
417 
418   /// Map for tracking Fortran deferred CHARACTER lengths.
419   DenseMap<const DIStringType *, unsigned> StringTypeLocMap;
420 
421   AddressPool AddrPool;
422 
423   /// Accelerator tables.
424   AccelTable<DWARF5AccelTableData> AccelDebugNames;
425   AccelTable<AppleAccelTableOffsetData> AccelNames;
426   AccelTable<AppleAccelTableOffsetData> AccelObjC;
427   AccelTable<AppleAccelTableOffsetData> AccelNamespace;
428   AccelTable<AppleAccelTableTypeData> AccelTypes;
429 
430   // Identify a debugger for "tuning" the debug info.
431   DebuggerKind DebuggerTuning = DebuggerKind::Default;
432 
433   MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
434 
getUnits()435   const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
436     return InfoHolder.getUnits();
437   }
438 
439   using InlinedEntity = DbgValueHistoryMap::InlinedEntity;
440 
441   void ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
442                                      const DINode *Node,
443                                      const MDNode *Scope);
444   void ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
445                                              const DINode *Node,
446                                              const MDNode *Scope);
447 
448   DbgEntity *createConcreteEntity(DwarfCompileUnit &TheCU,
449                                   LexicalScope &Scope,
450                                   const DINode *Node,
451                                   const DILocation *Location,
452                                   const MCSymbol *Sym = nullptr);
453 
454   /// Construct a DIE for this abstract scope.
455   void constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, LexicalScope *Scope);
456 
457   /// Construct a DIE for the subprogram definition \p SP and return it.
458   DIE &constructSubprogramDefinitionDIE(const DISubprogram *SP);
459 
460   /// Construct DIEs for call site entries describing the calls in \p MF.
461   void constructCallSiteEntryDIEs(const DISubprogram &SP, DwarfCompileUnit &CU,
462                                   DIE &ScopeDIE, const MachineFunction &MF);
463 
464   template <typename DataT>
465   void addAccelNameImpl(const DICompileUnit &CU, AccelTable<DataT> &AppleAccel,
466                         StringRef Name, const DIE &Die);
467 
468   void finishEntityDefinitions();
469 
470   void finishSubprogramDefinitions();
471 
472   /// Finish off debug information after all functions have been
473   /// processed.
474   void finalizeModuleInfo();
475 
476   /// Emit the debug info section.
477   void emitDebugInfo();
478 
479   /// Emit the abbreviation section.
480   void emitAbbreviations();
481 
482   /// Emit the string offsets table header.
483   void emitStringOffsetsTableHeader();
484 
485   /// Emit a specified accelerator table.
486   template <typename AccelTableT>
487   void emitAccel(AccelTableT &Accel, MCSection *Section, StringRef TableName);
488 
489   /// Emit DWARF v5 accelerator table.
490   void emitAccelDebugNames();
491 
492   /// Emit visible names into a hashed accelerator table section.
493   void emitAccelNames();
494 
495   /// Emit objective C classes and categories into a hashed
496   /// accelerator table section.
497   void emitAccelObjC();
498 
499   /// Emit namespace dies into a hashed accelerator table.
500   void emitAccelNamespaces();
501 
502   /// Emit type dies into a hashed accelerator table.
503   void emitAccelTypes();
504 
505   /// Emit visible names and types into debug pubnames and pubtypes sections.
506   void emitDebugPubSections();
507 
508   void emitDebugPubSection(bool GnuStyle, StringRef Name,
509                            DwarfCompileUnit *TheU,
510                            const StringMap<const DIE *> &Globals);
511 
512   /// Emit null-terminated strings into a debug str section.
513   void emitDebugStr();
514 
515   /// Emit variable locations into a debug loc section.
516   void emitDebugLoc();
517 
518   /// Emit variable locations into a debug loc dwo section.
519   void emitDebugLocDWO();
520 
521   void emitDebugLocImpl(MCSection *Sec);
522 
523   /// Emit address ranges into a debug aranges section.
524   void emitDebugARanges();
525 
526   /// Emit address ranges into a debug ranges section.
527   void emitDebugRanges();
528   void emitDebugRangesDWO();
529   void emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section);
530 
531   /// Emit macros into a debug macinfo section.
532   void emitDebugMacinfo();
533   /// Emit macros into a debug macinfo.dwo section.
534   void emitDebugMacinfoDWO();
535   void emitDebugMacinfoImpl(MCSection *Section);
536   void emitMacro(DIMacro &M);
537   void emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U);
538   void emitMacroFileImpl(DIMacroFile &F, DwarfCompileUnit &U,
539                          unsigned StartFile, unsigned EndFile,
540                          StringRef (*MacroFormToString)(unsigned Form));
541   void handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U);
542 
543   /// DWARF 5 Experimental Split Dwarf Emitters
544 
545   /// Initialize common features of skeleton units.
546   void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
547                         std::unique_ptr<DwarfCompileUnit> NewU);
548 
549   /// Construct the split debug info compile unit for the debug info section.
550   /// In DWARF v5, the skeleton unit DIE may have the following attributes:
551   /// DW_AT_addr_base, DW_AT_comp_dir, DW_AT_dwo_name, DW_AT_high_pc,
552   /// DW_AT_low_pc, DW_AT_ranges, DW_AT_stmt_list, and DW_AT_str_offsets_base.
553   /// Prior to DWARF v5 it may also have DW_AT_GNU_dwo_id. DW_AT_GNU_dwo_name
554   /// is used instead of DW_AT_dwo_name, Dw_AT_GNU_addr_base instead of
555   /// DW_AT_addr_base, and DW_AT_GNU_ranges_base instead of DW_AT_rnglists_base.
556   DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
557 
558   /// Emit the debug info dwo section.
559   void emitDebugInfoDWO();
560 
561   /// Emit the debug abbrev dwo section.
562   void emitDebugAbbrevDWO();
563 
564   /// Emit the debug line dwo section.
565   void emitDebugLineDWO();
566 
567   /// Emit the dwo stringoffsets table header.
568   void emitStringOffsetsTableHeaderDWO();
569 
570   /// Emit the debug str dwo section.
571   void emitDebugStrDWO();
572 
573   /// Emit DWO addresses.
574   void emitDebugAddr();
575 
576   /// Flags to let the linker know we have emitted new style pubnames. Only
577   /// emit it here if we don't have a skeleton CU for split dwarf.
578   void addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const;
579 
580   /// Create new DwarfCompileUnit for the given metadata node with tag
581   /// DW_TAG_compile_unit.
582   DwarfCompileUnit &getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit);
583   void finishUnitAttributes(const DICompileUnit *DIUnit,
584                             DwarfCompileUnit &NewCU);
585 
586   /// Construct imported_module or imported_declaration DIE.
587   void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
588                                         const DIImportedEntity *N);
589 
590   /// Register a source line with debug info. Returns the unique
591   /// label that was emitted and which provides correspondence to the
592   /// source line list.
593   void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
594                         unsigned Flags);
595 
596   /// Populate LexicalScope entries with variables' info.
597   void collectEntityInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
598                          DenseSet<InlinedEntity> &ProcessedVars);
599 
600   /// Build the location list for all DBG_VALUEs in the
601   /// function that describe the same variable. If the resulting
602   /// list has only one entry that is valid for entire variable's
603   /// scope return true.
604   bool buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
605                          const DbgValueHistoryMap::Entries &Entries);
606 
607   /// Collect variable information from the side table maintained by MF.
608   void collectVariableInfoFromMFTable(DwarfCompileUnit &TheCU,
609                                       DenseSet<InlinedEntity> &P);
610 
611   /// Emit the reference to the section.
612   void emitSectionReference(const DwarfCompileUnit &CU);
613 
614 protected:
615   /// Gather pre-function debug information.
616   void beginFunctionImpl(const MachineFunction *MF) override;
617 
618   /// Gather and emit post-function debug information.
619   void endFunctionImpl(const MachineFunction *MF) override;
620 
621   void skippedNonDebugFunction() override;
622 
623 public:
624   //===--------------------------------------------------------------------===//
625   // Main entry points.
626   //
627   DwarfDebug(AsmPrinter *A);
628 
629   ~DwarfDebug() override;
630 
631   /// Emit all Dwarf sections that should come prior to the
632   /// content.
633   void beginModule(Module *M) override;
634 
635   /// Emit all Dwarf sections that should come after the content.
636   void endModule() override;
637 
638   /// Emits inital debug location directive.
639   DebugLoc emitInitialLocDirective(const MachineFunction &MF, unsigned CUID);
640 
641   /// Process beginning of an instruction.
642   void beginInstruction(const MachineInstr *MI) override;
643 
644   /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
645   static uint64_t makeTypeSignature(StringRef Identifier);
646 
647   /// Add a DIE to the set of types that we're going to pull into
648   /// type units.
649   void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
650                             DIE &Die, const DICompositeType *CTy);
651 
652   class NonTypeUnitContext {
653     DwarfDebug *DD;
654     decltype(DwarfDebug::TypeUnitsUnderConstruction) TypeUnitsUnderConstruction;
655     bool AddrPoolUsed;
656     friend class DwarfDebug;
657     NonTypeUnitContext(DwarfDebug *DD);
658   public:
659     NonTypeUnitContext(NonTypeUnitContext&&) = default;
660     ~NonTypeUnitContext();
661   };
662 
663   NonTypeUnitContext enterNonTypeUnitContext();
664 
665   /// Add a label so that arange data can be generated for it.
addArangeLabel(SymbolCU SCU)666   void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
667 
668   /// For symbols that have a size designated (e.g. common symbols),
669   /// this tracks that size.
setSymbolSize(const MCSymbol * Sym,uint64_t Size)670   void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
671     SymSize[Sym] = Size;
672   }
673 
674   /// Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
675   /// If not, we still might emit certain cases.
useAllLinkageNames()676   bool useAllLinkageNames() const { return UseAllLinkageNames; }
677 
678   /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
679   /// standard DW_OP_form_tls_address opcode
useGNUTLSOpcode()680   bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
681 
682   /// Returns whether to use the DWARF2 format for bitfields instyead of the
683   /// DWARF4 format.
useDWARF2Bitfields()684   bool useDWARF2Bitfields() const { return UseDWARF2Bitfields; }
685 
686   /// Returns whether to use inline strings.
useInlineStrings()687   bool useInlineStrings() const { return UseInlineStrings; }
688 
689   /// Returns whether ranges section should be emitted.
useRangesSection()690   bool useRangesSection() const { return UseRangesSection; }
691 
692   /// Returns whether to use sections as labels rather than temp symbols.
useSectionsAsReferences()693   bool useSectionsAsReferences() const {
694     return UseSectionsAsReferences;
695   }
696 
697   /// Returns whether .debug_loc section should be emitted.
useLocSection()698   bool useLocSection() const { return UseLocSection; }
699 
700   /// Returns whether to generate DWARF v4 type units.
generateTypeUnits()701   bool generateTypeUnits() const { return GenerateTypeUnits; }
702 
703   // Experimental DWARF5 features.
704 
705   /// Returns what kind (if any) of accelerator tables to emit.
getAccelTableKind()706   AccelTableKind getAccelTableKind() const { return TheAccelTableKind; }
707 
useAppleExtensionAttributes()708   bool useAppleExtensionAttributes() const {
709     return HasAppleExtensionAttributes;
710   }
711 
712   /// Returns whether or not to change the current debug info for the
713   /// split dwarf proposal support.
useSplitDwarf()714   bool useSplitDwarf() const { return HasSplitDwarf; }
715 
716   /// Returns whether to generate a string offsets table with (possibly shared)
717   /// contributions from each CU and type unit. This implies the use of
718   /// DW_FORM_strx* indirect references with DWARF v5 and beyond. Note that
719   /// DW_FORM_GNU_str_index is also an indirect reference, but it is used with
720   /// a pre-DWARF v5 implementation of split DWARF sections, which uses a
721   /// monolithic string offsets table.
useSegmentedStringOffsetsTable()722   bool useSegmentedStringOffsetsTable() const {
723     return UseSegmentedStringOffsetsTable;
724   }
725 
emitDebugEntryValues()726   bool emitDebugEntryValues() const {
727     return EmitDebugEntryValues;
728   }
729 
useOpConvert()730   bool useOpConvert() const {
731     return EnableOpConvert;
732   }
733 
734   bool shareAcrossDWOCUs() const;
735 
736   /// Returns the Dwarf Version.
737   uint16_t getDwarfVersion() const;
738 
739   /// Returns a suitable DWARF form to represent a section offset, i.e.
740   /// * DW_FORM_sec_offset for DWARF version >= 4;
741   /// * DW_FORM_data8 for 64-bit DWARFv3;
742   /// * DW_FORM_data4 for 32-bit DWARFv3 and DWARFv2.
743   dwarf::Form getDwarfSectionOffsetForm() const;
744 
745   /// Returns the previous CU that was being updated
getPrevCU()746   const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
setPrevCU(const DwarfCompileUnit * PrevCU)747   void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
748 
749   /// Returns the entries for the .debug_loc section.
getDebugLocs()750   const DebugLocStream &getDebugLocs() const { return DebugLocs; }
751 
752   /// Emit an entry for the debug loc section. This can be used to
753   /// handle an entry that's going to be emitted into the debug loc section.
754   void emitDebugLocEntry(ByteStreamer &Streamer,
755                          const DebugLocStream::Entry &Entry,
756                          const DwarfCompileUnit *CU);
757 
758   /// Emit the location for a debug loc entry, including the size header.
759   void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
760                                  const DwarfCompileUnit *CU);
761 
762   void addSubprogramNames(const DICompileUnit &CU, const DISubprogram *SP,
763                           DIE &Die);
764 
getAddressPool()765   AddressPool &getAddressPool() { return AddrPool; }
766 
767   void addAccelName(const DICompileUnit &CU, StringRef Name, const DIE &Die);
768 
769   void addAccelObjC(const DICompileUnit &CU, StringRef Name, const DIE &Die);
770 
771   void addAccelNamespace(const DICompileUnit &CU, StringRef Name,
772                          const DIE &Die);
773 
774   void addAccelType(const DICompileUnit &CU, StringRef Name, const DIE &Die,
775                     char Flags);
776 
getCurrentFunction()777   const MachineFunction *getCurrentFunction() const { return CurFn; }
778 
779   /// A helper function to check whether the DIE for a given Scope is
780   /// going to be null.
781   bool isLexicalScopeDIENull(LexicalScope *Scope);
782 
783   /// Find the matching DwarfCompileUnit for the given CU DIE.
lookupCU(const DIE * Die)784   DwarfCompileUnit *lookupCU(const DIE *Die) { return CUDieMap.lookup(Die); }
lookupCU(const DIE * Die)785   const DwarfCompileUnit *lookupCU(const DIE *Die) const {
786     return CUDieMap.lookup(Die);
787   }
788 
getStringTypeLoc(const DIStringType * ST)789   unsigned getStringTypeLoc(const DIStringType *ST) const {
790     auto I = StringTypeLocMap.find(ST);
791     return I != StringTypeLocMap.end() ? I->second : 0;
792   }
793 
addStringTypeLoc(const DIStringType * ST,unsigned Loc)794   void addStringTypeLoc(const DIStringType *ST, unsigned Loc) {
795     assert(ST);
796     if (Loc)
797       StringTypeLocMap[ST] = Loc;
798   }
799 
800   /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
801   ///
802   /// Returns whether we are "tuning" for a given debugger.
803   /// @{
tuneForGDB()804   bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
tuneForLLDB()805   bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
tuneForSCE()806   bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
807   /// @}
808 
809   const MCSymbol *getSectionLabel(const MCSection *S);
810   void insertSectionLabel(const MCSymbol *S);
811 
812   static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
813                                 const DbgValueLoc &Value,
814                                 DwarfExpression &DwarfExpr);
815 
816   /// If the \p File has an MD5 checksum, return it as an MD5Result
817   /// allocated in the MCContext.
818   Optional<MD5::MD5Result> getMD5AsBytes(const DIFile *File) const;
819 };
820 
821 } // end namespace llvm
822 
823 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
824