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
31namespace llvm {
32
33class AsmPrinter;
34class DIE;
35class DIELoc;
36class DIEValueList;
37class DwarfFile;
38class GlobalVariable;
39class MCExpr;
40class MCSymbol;
41class MDNode;
42
43enum class UnitKind { Skeleton, Full };
44
45class 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 SmallPtrSet<const DISubprogram *, 8> FinalizedAbstractSubprograms;
85
86 // List of inlined lexical block scopes that belong to subprograms within this
87 // CU.
88 DenseMap<const DILocalScope *, SmallVector<DIE *, 2>> InlinedLocalScopeDIEs;
89
90 DenseMap<const DINode *, std::unique_ptr<DbgEntity>> AbstractEntities;
91
92 /// Cache of artificial DIEs created for DW_OP_LLVM_implicit_pointer
93 /// lowering, keyed by (pointee type, constant value). Enables reuse when
94 /// multiple pointer variables reference the same constant.
95 DenseMap<std::pair<const DIType *, int64_t>, DIE *> ImplicitPointerDIEs;
96
97 // Set of scope nodes referenced by global variables in this CU.
98 SmallPtrSet<const MDNode *, 4> GlobalVarScopes;
99
100 /// DWO ID for correlating skeleton and split units.
101 uint64_t DWOId = 0;
102
103 const DIFile *LastFile = nullptr;
104 unsigned LastFileID;
105
106 /// \anchor applyConcreteDbgVariableAttribute
107 /// \name applyConcreteDbgVariableAttribute
108 /// Overload set which applies attributes to \c VariableDie based on
109 /// the active variant of \c DV, which is passed as the first argument.
110 ///@{
111
112 /// See \ref applyConcreteDbgVariableAttribute
113 void applyConcreteDbgVariableAttributes(const Loc::Single &Single,
114 const DbgVariable &DV,
115 DIE &VariableDie);
116 /// See \ref applyConcreteDbgVariableAttribute
117 void applyConcreteDbgVariableAttributes(const Loc::Multi &Multi,
118 const DbgVariable &DV,
119 DIE &VariableDie);
120 /// See \ref applyConcreteDbgVariableAttribute
121 void applyConcreteDbgVariableAttributes(const Loc::MMI &MMI,
122 const DbgVariable &DV,
123 DIE &VariableDie);
124 /// See \ref applyConcreteDbgVariableAttribute
125 void applyConcreteDbgVariableAttributes(const Loc::EntryValue &EntryValue,
126 const DbgVariable &DV,
127 DIE &VariableDie);
128 /// See \ref applyConcreteDbgVariableAttribute
129 void applyConcreteDbgVariableAttributes(const std::monostate &,
130 const DbgVariable &DV,
131 DIE &VariableDie);
132
133 ///@}
134
135 /// Lower DW_OP_LLVM_implicit_pointer by creating an artificial variable DIE
136 /// for the dereferenced value and emitting DW_OP_implicit_pointer (DWARF 5)
137 /// or DW_OP_GNU_implicit_pointer (DWARF 4) for the pointer's location.
138 ///
139 /// \returns true if the implicit pointer was handled successfully.
140 bool emitImplicitPointerLocation(const Loc::Single &Single,
141 const DbgVariable &DV, DIE &VariableDie);
142
143 bool isDwoUnit() const override;
144
145 DenseMap<const DILocalScope *, DIE *> &getAbstractScopeDIEs() {
146 if (isDwoUnit() && !DD->shareAcrossDWOCUs())
147 return AbstractLocalScopeDIEs;
148 return DU->getAbstractScopeDIEs();
149 }
150
151 DenseMap<const DINode *, std::unique_ptr<DbgEntity>> &getAbstractEntities() {
152 if (isDwoUnit() && !DD->shareAcrossDWOCUs())
153 return AbstractEntities;
154 return DU->getAbstractEntities();
155 }
156
157 auto &getFinalizedAbstractSubprograms() {
158 if (isDwoUnit() && !DD->shareAcrossDWOCUs())
159 return FinalizedAbstractSubprograms;
160 return DU->getFinalizedAbstractSubprograms();
161 }
162
163 /// \returns true if \ref ScopeNode contains a GlobalVariable.
164 bool hasGlobalVariableInScope(const DILocalScope *ScopeNode);
165
166 void finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) override;
167
168 /// Add info for Wasm-global-based relocation.
169 void addWasmRelocBaseGlobal(DIELoc *Loc, StringRef GlobalName,
170 uint64_t GlobalIndex);
171
172 /// Create context DIE for abstract subprogram.
173 /// \returns The context DIE and the compile unit where abstract
174 /// DIE should be constructed.
175 std::pair<DIE *, DwarfCompileUnit *>
176 getOrCreateAbstractSubprogramContextDIE(const DISubprogram *SP);
177
178 /// Create new DIE for abstract subprogram.
179 DIE &createAbstractSubprogramDIE(const DISubprogram *SP, DIE *ContextDIE,
180 DwarfCompileUnit *ContextCU);
181
182 /// Add a location exprloc to \p DIE with attribute \p Attribute at
183 /// for \p Location modified by raw DIExpression \p Expr.
184 void addLocationWithExpr(DIE &Die, dwarf::Attribute Attribute,
185 const MachineLocation &Location,
186 ArrayRef<uint64_t> Expr);
187
188public:
189 DwarfCompileUnit(unsigned UID, const DICompileUnit *Node, AsmPrinter *A,
190 DwarfDebug *DW, DwarfFile *DWU,
191 UnitKind Kind = UnitKind::Full);
192
193 bool hasRangeLists() const { return HasRangeLists; }
194
195 DwarfCompileUnit *getSkeleton() const {
196 return Skeleton;
197 }
198
199 bool includeMinimalInlineScopes() const;
200
201 bool emitFuncLineTableOffsets() const;
202
203 void initStmtList();
204
205 /// Apply the DW_AT_stmt_list from this compile unit to the specified DIE.
206 void applyStmtList(DIE &D);
207
208 /// Get line table start symbol for this unit.
209 MCSymbol *getLineTableStartSym() const { return LineTableStartSym; }
210
211 /// A pair of GlobalVariable and DIExpression.
212 struct GlobalExpr {
213 const GlobalVariable *Var;
214 const DIExpression *Expr;
215 };
216
217 struct BaseTypeRef {
218 BaseTypeRef(unsigned BitSize, dwarf::TypeKind Encoding) :
219 BitSize(BitSize), Encoding(Encoding) {}
220 unsigned BitSize;
221 dwarf::TypeKind Encoding;
222 DIE *Die = nullptr;
223 };
224
225 std::vector<BaseTypeRef> ExprRefedBaseTypes;
226
227 /// Get or create global variable DIE.
228 DIE *
229 getOrCreateGlobalVariableDIE(const DIGlobalVariable *GV,
230 ArrayRef<GlobalExpr> GlobalExprs);
231
232 DIE *getOrCreateCommonBlock(const DICommonBlock *CB,
233 ArrayRef<GlobalExpr> GlobalExprs);
234
235 void addLocationAttribute(DIE *ToDIE, const DIGlobalVariable *GV,
236 ArrayRef<GlobalExpr> GlobalExprs);
237
238 /// addLabelAddress - Add a dwarf label attribute data and value using
239 /// either DW_FORM_addr or DW_FORM_GNU_addr_index.
240 void addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
241 const MCSymbol *Label);
242
243 /// addLocalLabelAddress - Add a dwarf label attribute data and value using
244 /// DW_FORM_addr only.
245 void addLocalLabelAddress(DIE &Die, dwarf::Attribute Attribute,
246 const MCSymbol *Label);
247
248 DwarfCompileUnit &getCU() override { return *this; }
249
250 unsigned getOrCreateSourceID(const DIFile *File) override;
251
252 /// addRange - Add an address range to the list of ranges for this unit.
253 void addRange(RangeSpan Range);
254
255 void attachLowHighPC(DIE &D, const MCSymbol *Begin, const MCSymbol *End);
256
257 /// Find DIE for the given subprogram and attach appropriate
258 /// DW_AT_low_pc, DW_AT_high_pc and DW_AT_LLVM_stmt_sequence attributes.
259 /// If there are global variables in this scope then create and insert DIEs
260 /// for these variables.
261 DIE &updateSubprogramScopeDIE(const DISubprogram *SP, const Function &F,
262 MCSymbol *LineTableSym);
263
264 void constructScopeDIE(LexicalScope *Scope, DIE &ParentScopeDIE);
265
266 /// A helper function to construct a RangeSpanList for a given
267 /// lexical scope.
268 void addScopeRangeList(DIE &ScopeDIE, SmallVector<RangeSpan, 2> Range);
269
270 void attachRangesOrLowHighPC(DIE &D, SmallVector<RangeSpan, 2> Ranges);
271
272 void attachRangesOrLowHighPC(DIE &D,
273 const SmallVectorImpl<InsnRange> &Ranges);
274
275 /// This scope represents an inlined body of a function. Construct a
276 /// DIE to represent this concrete inlined copy of the function.
277 DIE *constructInlinedScopeDIE(LexicalScope *Scope, DIE &ParentScopeDIE);
278
279 /// Get if available or create a new DW_TAG_lexical_block for the given
280 /// LexicalScope and attach DW_AT_low_pc/DW_AT_high_pc labels.
281 DIE *getOrCreateLexicalBlockDIE(LexicalScope *Scope, DIE &ParentDIE);
282
283 /// Construct a DIE for the given DbgVariable.
284 DIE *constructVariableDIE(DbgVariable &DV, bool Abstract = false);
285
286 /// Convenience overload which writes the DIE pointer into an out variable
287 /// ObjectPointer in addition to returning it.
288 DIE *constructVariableDIE(DbgVariable &DV, const LexicalScope &Scope,
289 DIE *&ObjectPointer);
290
291 /// Construct a DIE for the given DbgLabel.
292 DIE *constructLabelDIE(DbgLabel &DL, const LexicalScope &Scope);
293
294 void createBaseTypeDIEs();
295
296 /// Construct a DIE for a given scope.
297 /// This instance of 'getOrCreateContextDIE()' can handle DILocalScope.
298 DIE *getOrCreateContextDIE(const DIScope *Ty) override;
299
300 /// Get DW_TAG_lexical_block for the given DILexicalBlock if available,
301 /// or the most close parent DIE, if no correspoding DW_TAG_lexical_block
302 /// exists.
303 DIE *getLocalContextDIE(const DILexicalBlock *LB);
304
305 DIE *getOrCreateSubprogramDIE(const DISubprogram *SP, const Function *F,
306 bool Minimal = false) override;
307
308 /// Construct a DIE for this subprogram scope.
309 DIE &constructSubprogramScopeDIE(const DISubprogram *Sub, const Function &F,
310 LexicalScope *Scope, MCSymbol *LineTableSym);
311
312 DIE *createAndAddScopeChildren(LexicalScope *Scope, DIE &ScopeDIE);
313
314 /// Create an abstract subprogram DIE, that should later be populated
315 /// by \ref constructAbstractSubprogramScopeDIE.
316 DIE &getOrCreateAbstractSubprogramDIE(const DISubprogram *SP);
317 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
318
319 /// Whether to use the GNU analog for a DWARF5 tag, attribute, or location
320 /// atom. Only applicable when emitting otherwise DWARF4-compliant debug info.
321 bool useGNUAnalogForDwarf5Feature() const;
322
323 /// This takes a DWARF 5 tag and returns it or a GNU analog.
324 dwarf::Tag getDwarf5OrGNUTag(dwarf::Tag Tag) const;
325
326 /// This takes a DWARF 5 attribute and returns it or a GNU analog.
327 dwarf::Attribute getDwarf5OrGNUAttr(dwarf::Attribute Attr) const;
328
329 /// This takes a DWARF 5 location atom and either returns it or a GNU analog.
330 dwarf::LocationAtom getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const;
331
332 /// Construct a call site entry DIE describing a call within \p Scope to a
333 /// callee described by \p CalleeSP and \p CalleeF.
334 /// \p IsTail specifies whether the call is a tail call.
335 /// \p PCAddr points to the PC value after the call instruction.
336 /// \p CallAddr points to the PC value at the call instruction (or is null).
337 /// \p CallTarget a location holding the target address for an indirect call.
338 /// For direct calls \p CallTarget register is set to 0.
339 /// \p Offset from \p CallTarget register value if the location is indirect.
340 DIE &constructCallSiteEntryDIE(DIE &ScopeDIE, const DISubprogram *CalleeSP,
341 const Function *CalleeF, bool IsTail,
342 const MCSymbol *PCAddr,
343 const MCSymbol *CallAddr,
344 MachineLocation CallTarget, int64_t Offset,
345 DIType *AllocSiteTy);
346 /// Construct call site parameter DIEs for the \p CallSiteDIE. The \p Params
347 /// were collected by the \ref collectCallSiteParameters.
348 /// Note: The order of parameters does not matter, since debuggers recognize
349 /// call site parameters by the DW_AT_location attribute.
350 void constructCallSiteParmEntryDIEs(DIE &CallSiteDIE,
351 SmallVector<DbgCallSiteParam, 4> &Params);
352
353 /// Get or create a DIE for an imported entity.
354 DIE *getOrCreateImportedEntityDIE(const DIImportedEntity *IE);
355 DIE *constructImportedEntityDIE(const DIImportedEntity *IE);
356
357 void finishSubprogramDefinition(const DISubprogram *SP);
358 void finishEntityDefinition(const DbgEntity *Entity);
359 void attachLexicalScopesAbstractOrigins();
360
361 /// Find abstract variable associated with Var.
362 using InlinedEntity = DbgValueHistoryMap::InlinedEntity;
363 DbgEntity *getExistingAbstractEntity(const DINode *Node);
364 void createAbstractEntity(const DINode *Node, LexicalScope *Scope);
365
366 /// Set the skeleton unit associated with this unit.
367 void setSkeleton(DwarfCompileUnit &Skel) { Skeleton = &Skel; }
368
369 unsigned getHeaderSize() const override {
370 // DWARF v5 added the DWO ID to the header for split/skeleton units.
371 unsigned DWOIdSize =
372 DD->getDwarfVersion() >= 5 && DD->useSplitDwarf() ? sizeof(uint64_t)
373 : 0;
374 return DwarfUnit::getHeaderSize() + DWOIdSize;
375 }
376 unsigned getLength() {
377 return Asm->getUnitLengthFieldByteSize() + // Length field
378 getHeaderSize() + getUnitDie().getSize();
379 }
380
381 void emitHeader(bool UseOffsets) override;
382
383 /// Add the DW_AT_addr_base attribute to the unit DIE.
384 void addAddrTableBase();
385
386 MCSymbol *getMacroLabelBegin() const {
387 return MacroLabelBegin;
388 }
389
390 /// Add a new global name to the compile unit.
391 void addGlobalName(StringRef Name, const DIE &Die,
392 const DIScope *Context) override;
393
394 /// Add a new global name present in a type unit to this compile unit.
395 void addGlobalNameForTypeUnit(StringRef Name, const DIScope *Context);
396
397 /// Add a new global type to the compile unit.
398 void addGlobalTypeImpl(const DIType *Ty, const DIE &Die,
399 const DIScope *Context) override;
400
401 /// Add a new global type present in a type unit to this compile unit.
402 void addGlobalTypeUnitType(const DIType *Ty, const DIScope *Context);
403
404 const StringMap<const DIE *> &getGlobalNames() const { return GlobalNames; }
405 const StringMap<const DIE *> &getGlobalTypes() const { return GlobalTypes; }
406
407 /// Add DW_AT_location attribute for a DbgVariable based on provided
408 /// MachineLocation.
409 void addVariableAddress(const DbgVariable &DV, DIE &Die,
410 MachineLocation Location);
411 /// Add an address attribute to a die based on the location provided.
412 void addAddress(DIE &Die, dwarf::Attribute Attribute,
413 const MachineLocation &Location);
414
415 /// Add a memory location exprloc to \p DIE with attribute \p Attribute
416 /// at \p Location + \p Offset.
417 void addMemoryLocation(DIE &Die, dwarf::Attribute Attribute,
418 const MachineLocation &Location, int64_t Offset);
419 /// Start with the address based on the location provided, and generate the
420 /// DWARF information necessary to find the actual variable (navigating the
421 /// extra location information encoded in the type) based on the starting
422 /// location. Add the DWARF information to the die.
423 void addComplexAddress(const DIExpression *DIExpr, DIE &Die,
424 dwarf::Attribute Attribute,
425 const MachineLocation &Location);
426
427 /// Add a Dwarf loclistptr attribute data and value.
428 void addLocationList(DIE &Die, dwarf::Attribute Attribute, unsigned Index);
429
430 /// Add attributes to \p Var which reflect the common attributes of \p
431 /// VariableDie, namely those which are not dependant on the active variant.
432 void applyCommonDbgVariableAttributes(const DbgVariable &Var,
433 DIE &VariableDie);
434
435 /// Add a Dwarf expression attribute data and value.
436 void addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr);
437
438 void applySubprogramAttributesToDefinition(const DISubprogram *SP,
439 DIE &SPDie);
440
441 void applyLabelAttributes(const DbgLabel &Label, DIE &LabelDie);
442
443 /// getRanges - Get the list of ranges for this unit.
444 const SmallVectorImpl<RangeSpan> &getRanges() const { return CURanges; }
445 SmallVector<RangeSpan, 2> takeRanges() { return std::move(CURanges); }
446
447 void setBaseAddress(const MCSymbol *Base) { BaseAddress = Base; }
448 const MCSymbol *getBaseAddress() const { return BaseAddress; }
449
450 uint64_t getDWOId() const { return DWOId; }
451 void setDWOId(uint64_t DwoId) { DWOId = DwoId; }
452
453 bool hasDwarfPubSections() const;
454
455 void addBaseTypeRef(DIEValueList &Die, int64_t Idx);
456
457 MDNodeSetVector &getDeferredLocalDecls() { return DeferredLocalDecls; }
458
459 void addLinkageNamesToDeclarations(const DwarfDebug &DD,
460 const DISubprogram &CalleeSP,
461 DIE &CalleeDIE);
462};
463
464} // end namespace llvm
465
466#endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFCOMPILEUNIT_H
467