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