xref: /llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h (revision f407dff50cdcbcfee9dd92397d3792627c3ac708)
1 //===- llvm/CodeGen/DwarfCompileUnit.h - Dwarf Compile Unit -----*- 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 compile unit.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFCOMPILEUNIT_H
14 #define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFCOMPILEUNIT_H
15 
16 #include "DwarfDebug.h"
17 #include "DwarfUnit.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/BinaryFormat/Dwarf.h"
24 #include "llvm/CodeGen/DbgEntityHistoryCalculator.h"
25 #include "llvm/CodeGen/LexicalScopes.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/Support/Casting.h"
28 #include <cstdint>
29 #include <memory>
30 
31 namespace llvm {
32 
33 class AsmPrinter;
34 class DIE;
35 class DIELoc;
36 class DIEValueList;
37 class DwarfFile;
38 class GlobalVariable;
39 class MCExpr;
40 class MCSymbol;
41 class MDNode;
42 
43 enum class UnitKind { Skeleton, Full };
44 
45 class DwarfCompileUnit final : public DwarfUnit {
46   bool HasRangeLists = false;
47 
48   /// The start of the unit line section, this is also
49   /// reused in appyStmtList.
50   MCSymbol *LineTableStartSym;
51 
52   /// Skeleton unit associated with this unit.
53   DwarfCompileUnit *Skeleton = nullptr;
54 
55   /// The start of the unit macro info within macro section.
56   MCSymbol *MacroLabelBegin;
57 
58   /// GlobalNames - A map of globally visible named entities for this unit.
59   StringMap<const DIE *> GlobalNames;
60 
61   /// GlobalTypes - A map of globally visible types for this unit.
62   StringMap<const DIE *> GlobalTypes;
63 
64   // List of ranges for a given compile unit.
65   SmallVector<RangeSpan, 2> CURanges;
66 
67   // The base address of this unit, if any. Used for relative references in
68   // ranges/locs.
69   const MCSymbol *BaseAddress = nullptr;
70 
71   using MDNodeSetVector =
72       SetVector<const MDNode *, SmallVector<const MDNode *, 4>,
73                 SmallPtrSet<const MDNode *, 4>>;
74 
75   // List of entities (either static locals, types or imports) that
76   // belong to subprograms within this CU.
77   MDNodeSetVector DeferredLocalDecls;
78 
79   // List of concrete lexical block scopes belong to subprograms within this CU.
80   DenseMap<const DILocalScope *, DIE *> LexicalBlockDIEs;
81 
82   // List of abstract local scopes (either DISubprogram or DILexicalBlock).
83   DenseMap<const DILocalScope *, DIE *> AbstractLocalScopeDIEs;
84 
85   DenseMap<const DINode *, std::unique_ptr<DbgEntity>> AbstractEntities;
86 
87   /// DWO ID for correlating skeleton and split units.
88   uint64_t DWOId = 0;
89 
90   const DIFile *LastFile = nullptr;
91   unsigned LastFileID;
92 
93   /// \anchor applyConcreteDbgVariableAttribute
94   /// \name applyConcreteDbgVariableAttribute
95   /// Overload set which applies attributes to \c VariableDie based on
96   /// the active variant of \c DV, which is passed as the first argument.
97   ///@{
98 
99   /// See \ref applyConcreteDbgVariableAttribute
100   void applyConcreteDbgVariableAttributes(const Loc::Single &Single,
101                                           const DbgVariable &DV,
102                                           DIE &VariableDie);
103   /// See \ref applyConcreteDbgVariableAttribute
104   void applyConcreteDbgVariableAttributes(const Loc::Multi &Multi,
105                                           const DbgVariable &DV,
106                                           DIE &VariableDie);
107   /// See \ref applyConcreteDbgVariableAttribute
108   void applyConcreteDbgVariableAttributes(const Loc::MMI &MMI,
109                                           const DbgVariable &DV,
110                                           DIE &VariableDie);
111   /// See \ref applyConcreteDbgVariableAttribute
112   void applyConcreteDbgVariableAttributes(const Loc::EntryValue &EntryValue,
113                                           const DbgVariable &DV,
114                                           DIE &VariableDie);
115   /// See \ref applyConcreteDbgVariableAttribute
116   void applyConcreteDbgVariableAttributes(const std::monostate &,
117                                           const DbgVariable &DV,
118                                           DIE &VariableDie);
119 
120   ///@}
121 
122   bool isDwoUnit() const override;
123 
124   DenseMap<const DILocalScope *, DIE *> &getAbstractScopeDIEs() {
125     if (isDwoUnit() && !DD->shareAcrossDWOCUs())
126       return AbstractLocalScopeDIEs;
127     return DU->getAbstractScopeDIEs();
128   }
129 
130   DenseMap<const DINode *, std::unique_ptr<DbgEntity>> &getAbstractEntities() {
131     if (isDwoUnit() && !DD->shareAcrossDWOCUs())
132       return AbstractEntities;
133     return DU->getAbstractEntities();
134   }
135 
136   void finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) override;
137 
138   /// Add info for Wasm-global-based relocation.
139   void addWasmRelocBaseGlobal(DIELoc *Loc, StringRef GlobalName,
140                               uint64_t GlobalIndex);
141 
142 public:
143   DwarfCompileUnit(unsigned UID, const DICompileUnit *Node, AsmPrinter *A,
144                    DwarfDebug *DW, DwarfFile *DWU,
145                    UnitKind Kind = UnitKind::Full);
146 
147   bool hasRangeLists() const { return HasRangeLists; }
148 
149   DwarfCompileUnit *getSkeleton() const {
150     return Skeleton;
151   }
152 
153   bool includeMinimalInlineScopes() const;
154 
155   bool emitFuncLineTableOffsets() const;
156 
157   void initStmtList();
158 
159   /// Apply the DW_AT_stmt_list from this compile unit to the specified DIE.
160   void applyStmtList(DIE &D);
161 
162   /// Get line table start symbol for this unit.
163   MCSymbol *getLineTableStartSym() const { return LineTableStartSym; }
164 
165   /// A pair of GlobalVariable and DIExpression.
166   struct GlobalExpr {
167     const GlobalVariable *Var;
168     const DIExpression *Expr;
169   };
170 
171   struct BaseTypeRef {
172     BaseTypeRef(unsigned BitSize, dwarf::TypeKind Encoding) :
173       BitSize(BitSize), Encoding(Encoding) {}
174     unsigned BitSize;
175     dwarf::TypeKind Encoding;
176     DIE *Die = nullptr;
177   };
178 
179   std::vector<BaseTypeRef> ExprRefedBaseTypes;
180 
181   /// Get or create global variable DIE.
182   DIE *
183   getOrCreateGlobalVariableDIE(const DIGlobalVariable *GV,
184                                ArrayRef<GlobalExpr> GlobalExprs);
185 
186   DIE *getOrCreateCommonBlock(const DICommonBlock *CB,
187                               ArrayRef<GlobalExpr> GlobalExprs);
188 
189   void addLocationAttribute(DIE *ToDIE, const DIGlobalVariable *GV,
190                             ArrayRef<GlobalExpr> GlobalExprs);
191 
192   /// addLabelAddress - Add a dwarf label attribute data and value using
193   /// either DW_FORM_addr or DW_FORM_GNU_addr_index.
194   void addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
195                        const MCSymbol *Label);
196 
197   /// addLocalLabelAddress - Add a dwarf label attribute data and value using
198   /// DW_FORM_addr only.
199   void addLocalLabelAddress(DIE &Die, dwarf::Attribute Attribute,
200                             const MCSymbol *Label);
201 
202   DwarfCompileUnit &getCU() override { return *this; }
203 
204   unsigned getOrCreateSourceID(const DIFile *File) override;
205 
206   /// addRange - Add an address range to the list of ranges for this unit.
207   void addRange(RangeSpan Range);
208 
209   void attachLowHighPC(DIE &D, const MCSymbol *Begin, const MCSymbol *End);
210 
211   /// Find DIE for the given subprogram and attach appropriate
212   /// DW_AT_low_pc, DW_AT_high_pc and DW_AT_LLVM_stmt_sequence attributes.
213   /// If there are global variables in this scope then create and insert DIEs
214   /// for these variables.
215   DIE &updateSubprogramScopeDIE(const DISubprogram *SP, MCSymbol *LineTableSym);
216 
217   void constructScopeDIE(LexicalScope *Scope, DIE &ParentScopeDIE);
218 
219   /// A helper function to construct a RangeSpanList for a given
220   /// lexical scope.
221   void addScopeRangeList(DIE &ScopeDIE, SmallVector<RangeSpan, 2> Range);
222 
223   void attachRangesOrLowHighPC(DIE &D, SmallVector<RangeSpan, 2> Ranges);
224 
225   void attachRangesOrLowHighPC(DIE &D,
226                                const SmallVectorImpl<InsnRange> &Ranges);
227 
228   /// This scope represents an inlined body of a function. Construct a
229   /// DIE to represent this concrete inlined copy of the function.
230   DIE *constructInlinedScopeDIE(LexicalScope *Scope, DIE &ParentScopeDIE);
231 
232   /// Construct new DW_TAG_lexical_block for this scope and
233   /// attach DW_AT_low_pc/DW_AT_high_pc labels.
234   DIE *constructLexicalScopeDIE(LexicalScope *Scope);
235 
236   /// Get a DIE for the given DILexicalBlock.
237   /// Note that this function assumes that the DIE has been already created
238   /// and it's an error, if it hasn't.
239   DIE *getLexicalBlockDIE(const DILexicalBlock *LB);
240 
241   /// Construct a DIE for the given DbgVariable.
242   DIE *constructVariableDIE(DbgVariable &DV, bool Abstract = false);
243 
244   /// Convenience overload which writes the DIE pointer into an out variable
245   /// ObjectPointer in addition to returning it.
246   DIE *constructVariableDIE(DbgVariable &DV, const LexicalScope &Scope,
247                             DIE *&ObjectPointer);
248 
249   /// Construct a DIE for the given DbgLabel.
250   DIE *constructLabelDIE(DbgLabel &DL, const LexicalScope &Scope);
251 
252   void createBaseTypeDIEs();
253 
254   /// Construct a DIE for a given scope.
255   /// This instance of 'getOrCreateContextDIE()' can handle DILocalScope.
256   DIE *getOrCreateContextDIE(const DIScope *Ty) override;
257 
258   /// Construct a DIE for this subprogram scope.
259   DIE &constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope,
260                                    MCSymbol *LineTableSym);
261 
262   DIE *createAndAddScopeChildren(LexicalScope *Scope, DIE &ScopeDIE);
263 
264   void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
265 
266   /// Whether to use the GNU analog for a DWARF5 tag, attribute, or location
267   /// atom. Only applicable when emitting otherwise DWARF4-compliant debug info.
268   bool useGNUAnalogForDwarf5Feature() const;
269 
270   /// This takes a DWARF 5 tag and returns it or a GNU analog.
271   dwarf::Tag getDwarf5OrGNUTag(dwarf::Tag Tag) const;
272 
273   /// This takes a DWARF 5 attribute and returns it or a GNU analog.
274   dwarf::Attribute getDwarf5OrGNUAttr(dwarf::Attribute Attr) const;
275 
276   /// This takes a DWARF 5 location atom and either returns it or a GNU analog.
277   dwarf::LocationAtom getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const;
278 
279   /// Construct a call site entry DIE describing a call within \p Scope to a
280   /// callee described by \p CalleeSP.
281   /// \p IsTail specifies whether the call is a tail call.
282   /// \p PCAddr points to the PC value after the call instruction.
283   /// \p CallAddr points to the PC value at the call instruction (or is null).
284   /// \p CallReg is a register location for an indirect call. For direct calls
285   /// the \p CallReg is set to 0.
286   DIE &constructCallSiteEntryDIE(DIE &ScopeDIE, const DISubprogram *CalleeSP,
287                                  bool IsTail, const MCSymbol *PCAddr,
288                                  const MCSymbol *CallAddr, unsigned CallReg);
289   /// Construct call site parameter DIEs for the \p CallSiteDIE. The \p Params
290   /// were collected by the \ref collectCallSiteParameters.
291   /// Note: The order of parameters does not matter, since debuggers recognize
292   ///       call site parameters by the DW_AT_location attribute.
293   void constructCallSiteParmEntryDIEs(DIE &CallSiteDIE,
294                                       SmallVector<DbgCallSiteParam, 4> &Params);
295 
296   /// Get or create a DIE for an imported entity.
297   DIE *getOrCreateImportedEntityDIE(const DIImportedEntity *IE);
298   DIE *constructImportedEntityDIE(const DIImportedEntity *IE);
299 
300   void finishSubprogramDefinition(const DISubprogram *SP);
301   void finishEntityDefinition(const DbgEntity *Entity);
302 
303   /// Find abstract variable associated with Var.
304   using InlinedEntity = DbgValueHistoryMap::InlinedEntity;
305   DbgEntity *getExistingAbstractEntity(const DINode *Node);
306   void createAbstractEntity(const DINode *Node, LexicalScope *Scope);
307 
308   /// Set the skeleton unit associated with this unit.
309   void setSkeleton(DwarfCompileUnit &Skel) { Skeleton = &Skel; }
310 
311   unsigned getHeaderSize() const override {
312     // DWARF v5 added the DWO ID to the header for split/skeleton units.
313     unsigned DWOIdSize =
314         DD->getDwarfVersion() >= 5 && DD->useSplitDwarf() ? sizeof(uint64_t)
315                                                           : 0;
316     return DwarfUnit::getHeaderSize() + DWOIdSize;
317   }
318   unsigned getLength() {
319     return Asm->getUnitLengthFieldByteSize() + // Length field
320            getHeaderSize() + getUnitDie().getSize();
321   }
322 
323   void emitHeader(bool UseOffsets) override;
324 
325   /// Add the DW_AT_addr_base attribute to the unit DIE.
326   void addAddrTableBase();
327 
328   MCSymbol *getMacroLabelBegin() const {
329     return MacroLabelBegin;
330   }
331 
332   /// Add a new global name to the compile unit.
333   void addGlobalName(StringRef Name, const DIE &Die,
334                      const DIScope *Context) override;
335 
336   /// Add a new global name present in a type unit to this compile unit.
337   void addGlobalNameForTypeUnit(StringRef Name, const DIScope *Context);
338 
339   /// Add a new global type to the compile unit.
340   void addGlobalTypeImpl(const DIType *Ty, const DIE &Die,
341                          const DIScope *Context) override;
342 
343   /// Add a new global type present in a type unit to this compile unit.
344   void addGlobalTypeUnitType(const DIType *Ty, const DIScope *Context);
345 
346   const StringMap<const DIE *> &getGlobalNames() const { return GlobalNames; }
347   const StringMap<const DIE *> &getGlobalTypes() const { return GlobalTypes; }
348 
349   /// Add DW_AT_location attribute for a DbgVariable based on provided
350   /// MachineLocation.
351   void addVariableAddress(const DbgVariable &DV, DIE &Die,
352                           MachineLocation Location);
353   /// Add an address attribute to a die based on the location provided.
354   void addAddress(DIE &Die, dwarf::Attribute Attribute,
355                   const MachineLocation &Location);
356 
357   /// Start with the address based on the location provided, and generate the
358   /// DWARF information necessary to find the actual variable (navigating the
359   /// extra location information encoded in the type) based on the starting
360   /// location.  Add the DWARF information to the die.
361   void addComplexAddress(const DIExpression *DIExpr, DIE &Die,
362                          dwarf::Attribute Attribute,
363                          const MachineLocation &Location);
364 
365   /// Add a Dwarf loclistptr attribute data and value.
366   void addLocationList(DIE &Die, dwarf::Attribute Attribute, unsigned Index);
367 
368   /// Add attributes to \p Var which reflect the common attributes of \p
369   /// VariableDie, namely those which are not dependant on the active variant.
370   void applyCommonDbgVariableAttributes(const DbgVariable &Var,
371                                         DIE &VariableDie);
372 
373   /// Add a Dwarf expression attribute data and value.
374   void addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr);
375 
376   void applySubprogramAttributesToDefinition(const DISubprogram *SP,
377                                              DIE &SPDie);
378 
379   void applyLabelAttributes(const DbgLabel &Label, DIE &LabelDie);
380 
381   /// getRanges - Get the list of ranges for this unit.
382   const SmallVectorImpl<RangeSpan> &getRanges() const { return CURanges; }
383   SmallVector<RangeSpan, 2> takeRanges() { return std::move(CURanges); }
384 
385   void setBaseAddress(const MCSymbol *Base) { BaseAddress = Base; }
386   const MCSymbol *getBaseAddress() const { return BaseAddress; }
387 
388   uint64_t getDWOId() const { return DWOId; }
389   void setDWOId(uint64_t DwoId) { DWOId = DwoId; }
390 
391   bool hasDwarfPubSections() const;
392 
393   void addBaseTypeRef(DIEValueList &Die, int64_t Idx);
394 
395   MDNodeSetVector &getDeferredLocalDecls() { return DeferredLocalDecls; }
396 };
397 
398 } // end namespace llvm
399 
400 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFCOMPILEUNIT_H
401