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