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