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