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