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 
getAbstractSPDies()95   DenseMap<const MDNode *, DIE *> &getAbstractSPDies() {
96     if (isDwoUnit() && !DD->shareAcrossDWOCUs())
97       return AbstractSPDies;
98     return DU->getAbstractSPDies();
99   }
100 
getAbstractEntities()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 
hasRangeLists()114   bool hasRangeLists() const { return HasRangeLists; }
getUniqueID()115   unsigned getUniqueID() const { return UniqueID; }
116 
getSkeleton()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.
getLineTableStartSym()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 {
BaseTypeRefBaseTypeRef138     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 
getCU()168   DwarfCompileUnit &getCU() override { return *this; }
169 
170   unsigned getOrCreateSourceID(const DIFile *File) override;
171 
addImportedEntity(const DIImportedEntity * IE)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 CalleeDIE.
253   /// \p CalleeDIE is a declaration or definition subprogram DIE for the callee.
254   /// For indirect calls \p CalleeDIE is set to nullptr.
255   /// \p IsTail specifies whether the call is a tail call.
256   /// \p PCAddr points to the PC value after the call instruction.
257   /// \p CallAddr points to the PC value at the call instruction (or is null).
258   /// \p CallReg is a register location for an indirect call. For direct calls
259   /// the \p CallReg is set to 0.
260   DIE &constructCallSiteEntryDIE(DIE &ScopeDIE, DIE *CalleeDIE, bool IsTail,
261                                  const MCSymbol *PCAddr,
262                                  const MCSymbol *CallAddr, unsigned CallReg);
263   /// Construct call site parameter DIEs for the \p CallSiteDIE. The \p Params
264   /// were collected by the \ref collectCallSiteParameters.
265   /// Note: The order of parameters does not matter, since debuggers recognize
266   ///       call site parameters by the DW_AT_location attribute.
267   void constructCallSiteParmEntryDIEs(DIE &CallSiteDIE,
268                                       SmallVector<DbgCallSiteParam, 4> &Params);
269 
270   /// Construct import_module DIE.
271   DIE *constructImportedEntityDIE(const DIImportedEntity *Module);
272 
273   void finishSubprogramDefinition(const DISubprogram *SP);
274   void finishEntityDefinition(const DbgEntity *Entity);
275 
276   /// Find abstract variable associated with Var.
277   using InlinedEntity = DbgValueHistoryMap::InlinedEntity;
278   DbgEntity *getExistingAbstractEntity(const DINode *Node);
279   void createAbstractEntity(const DINode *Node, LexicalScope *Scope);
280 
281   /// Set the skeleton unit associated with this unit.
setSkeleton(DwarfCompileUnit & Skel)282   void setSkeleton(DwarfCompileUnit &Skel) { Skeleton = &Skel; }
283 
getHeaderSize()284   unsigned getHeaderSize() const override {
285     // DWARF v5 added the DWO ID to the header for split/skeleton units.
286     unsigned DWOIdSize =
287         DD->getDwarfVersion() >= 5 && DD->useSplitDwarf() ? sizeof(uint64_t)
288                                                           : 0;
289     return DwarfUnit::getHeaderSize() + DWOIdSize;
290   }
getLength()291   unsigned getLength() {
292     return Asm->getUnitLengthFieldByteSize() + // Length field
293            getHeaderSize() + getUnitDie().getSize();
294   }
295 
296   void emitHeader(bool UseOffsets) override;
297 
298   /// Add the DW_AT_addr_base attribute to the unit DIE.
299   void addAddrTableBase();
300 
getLabelBegin()301   MCSymbol *getLabelBegin() const {
302     assert(LabelBegin && "LabelBegin is not initialized");
303     return LabelBegin;
304   }
305 
getMacroLabelBegin()306   MCSymbol *getMacroLabelBegin() const {
307     return MacroLabelBegin;
308   }
309 
310   /// Add a new global name to the compile unit.
311   void addGlobalName(StringRef Name, const DIE &Die,
312                      const DIScope *Context) override;
313 
314   /// Add a new global name present in a type unit to this compile unit.
315   void addGlobalNameForTypeUnit(StringRef Name, const DIScope *Context);
316 
317   /// Add a new global type to the compile unit.
318   void addGlobalType(const DIType *Ty, const DIE &Die,
319                      const DIScope *Context) override;
320 
321   /// Add a new global type present in a type unit to this compile unit.
322   void addGlobalTypeUnitType(const DIType *Ty, const DIScope *Context);
323 
getGlobalNames()324   const StringMap<const DIE *> &getGlobalNames() const { return GlobalNames; }
getGlobalTypes()325   const StringMap<const DIE *> &getGlobalTypes() const { return GlobalTypes; }
326 
327   /// Add DW_AT_location attribute for a DbgVariable based on provided
328   /// MachineLocation.
329   void addVariableAddress(const DbgVariable &DV, DIE &Die,
330                           MachineLocation Location);
331   /// Add an address attribute to a die based on the location provided.
332   void addAddress(DIE &Die, dwarf::Attribute Attribute,
333                   const MachineLocation &Location);
334 
335   /// Start with the address based on the location provided, and generate the
336   /// DWARF information necessary to find the actual variable (navigating the
337   /// extra location information encoded in the type) based on the starting
338   /// location.  Add the DWARF information to the die.
339   void addComplexAddress(const DbgVariable &DV, DIE &Die,
340                          dwarf::Attribute Attribute,
341                          const MachineLocation &Location);
342 
343   /// Add a Dwarf loclistptr attribute data and value.
344   void addLocationList(DIE &Die, dwarf::Attribute Attribute, unsigned Index);
345   void applyVariableAttributes(const DbgVariable &Var, DIE &VariableDie);
346 
347   /// Add a Dwarf expression attribute data and value.
348   void addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr);
349 
350   void applySubprogramAttributesToDefinition(const DISubprogram *SP,
351                                              DIE &SPDie);
352 
353   void applyLabelAttributes(const DbgLabel &Label, DIE &LabelDie);
354 
355   /// getRanges - Get the list of ranges for this unit.
getRanges()356   const SmallVectorImpl<RangeSpan> &getRanges() const { return CURanges; }
takeRanges()357   SmallVector<RangeSpan, 2> takeRanges() { return std::move(CURanges); }
358 
setBaseAddress(const MCSymbol * Base)359   void setBaseAddress(const MCSymbol *Base) { BaseAddress = Base; }
getBaseAddress()360   const MCSymbol *getBaseAddress() const { return BaseAddress; }
361 
getDWOId()362   uint64_t getDWOId() const { return DWOId; }
setDWOId(uint64_t DwoId)363   void setDWOId(uint64_t DwoId) { DWOId = DwoId; }
364 
365   bool hasDwarfPubSections() const;
366 
367   void addBaseTypeRef(DIEValueList &Die, int64_t Idx);
368 };
369 
370 } // end namespace llvm
371 
372 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFCOMPILEUNIT_H
373