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