1//===-- llvm/CodeGen/DwarfUnit.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_DWARFUNIT_H
14#define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFUNIT_H
15
16#include "DwarfDebug.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/CodeGen/AsmPrinter.h"
19#include "llvm/CodeGen/DIE.h"
20#include "llvm/IR/DebugInfoMetadata.h"
21#include "llvm/Target/TargetMachine.h"
22#include <optional>
23#include <string>
24
25namespace llvm {
26
27class ConstantFP;
28class ConstantInt;
29class DwarfCompileUnit;
30class MCDwarfDwoLineTable;
31class MCSymbol;
32
33//===----------------------------------------------------------------------===//
34/// This dwarf writer support class manages information associated with a
35/// source file.
36class DwarfUnit : public DIEUnit {
37protected:
38 /// A numeric ID unique among all CUs in the module
39 unsigned UniqueID;
40 /// MDNode for the compile unit.
41 const DICompileUnit *CUNode;
42
43 // All DIEValues are allocated through this allocator.
44 BumpPtrAllocator DIEValueAllocator;
45
46 /// Target of Dwarf emission.
47 AsmPrinter *Asm;
48
49 /// The start of the unit within its section.
50 MCSymbol *LabelBegin = nullptr;
51
52 /// Emitted at the end of the CU and used to compute the CU Length field.
53 MCSymbol *EndLabel = nullptr;
54
55 // Holders for some common dwarf information.
56 DwarfDebug *DD;
57 DwarfFile *DU;
58
59 /// An anonymous type for index type. Owned by DIEUnit.
60 DIE *IndexTyDie = nullptr;
61
62 /// Tracks the mapping of unit level debug information variables to debug
63 /// information entries.
64 DenseMap<const MDNode *, DIE *> MDNodeToDieMap;
65
66 /// A list of all the DIEBlocks in use.
67 std::vector<DIEBlock *> DIEBlocks;
68
69 /// A list of all the DIELocs in use.
70 std::vector<DIELoc *> DIELocs;
71
72 /// This map is used to keep track of subprogram DIEs that need
73 /// DW_AT_containing_type attribute. This attribute points to a DIE that
74 /// corresponds to the MDNode mapped with the subprogram DIE.
75 DenseMap<DIE *, const DINode *> ContainingTypeMap;
76
77 DwarfUnit(dwarf::Tag, const DICompileUnit *Node, AsmPrinter *A,
78 DwarfDebug *DW, DwarfFile *DWU, unsigned UniqueID = 0);
79
80 bool applySubprogramDefinitionAttributes(const DISubprogram *SP, DIE &SPDie, bool Minimal);
81
82 bool isShareableAcrossCUs(const DINode *D) const;
83
84 template <typename T>
85 void addAttribute(DIEValueList &Die, dwarf::Attribute Attribute,
86 dwarf::Form Form, T &&Value) {
87 // For strict DWARF mode, only generate attributes available to current
88 // DWARF version.
89 // Attribute 0 is used when emitting form-encoded values in blocks, which
90 // don't have attributes (only forms) so we cannot detect their DWARF
91 // version compatibility here and assume they are compatible.
92 if (Attribute != 0 && Asm->TM.Options.DebugStrictDwarf &&
93 DD->getDwarfVersion() < dwarf::AttributeVersion(A: Attribute))
94 return;
95
96 Die.addValue(Alloc&: DIEValueAllocator,
97 V: DIEValue(Attribute, Form, std::forward<T>(Value)));
98 }
99
100public:
101 /// Gets Unique ID for this unit.
102 unsigned getUniqueID() const { return UniqueID; }
103 // Accessors.
104 AsmPrinter* getAsmPrinter() const { return Asm; }
105 /// Get the the symbol for start of the section for this unit.
106 MCSymbol *getLabelBegin() const {
107 assert(LabelBegin && "LabelBegin is not initialized");
108 return LabelBegin;
109 }
110 MCSymbol *getEndLabel() const { return EndLabel; }
111 llvm::dwarf::SourceLanguage getSourceLanguage() const;
112 const DICompileUnit *getCUNode() const { return CUNode; }
113 DwarfDebug &getDwarfDebug() const { return *DD; }
114
115 /// Return true if this compile unit has something to write out.
116 bool hasContent() const { return getUnitDie().hasChildren(); }
117
118 /// Get string containing language specific context for a global name.
119 ///
120 /// Walks the metadata parent chain in a language specific manner (using the
121 /// compile unit language) and returns it as a string. This is done at the
122 /// metadata level because DIEs may not currently have been added to the
123 /// parent context and walking the DIEs looking for names is more expensive
124 /// than walking the metadata.
125 std::string getParentContextString(const DIScope *Context) const;
126
127 /// Add a new global name to the compile unit.
128 virtual void addGlobalName(StringRef Name, const DIE &Die,
129 const DIScope *Context) = 0;
130
131 /// Add a new global type to the compile unit.
132 virtual void addGlobalTypeImpl(const DIType *Ty, const DIE &Die,
133 const DIScope *Context) = 0;
134
135 void addGlobalType(const DIType *Ty, const DIE &Die, const DIScope *Context);
136
137 /// Returns the DIE map slot for the specified debug variable.
138 ///
139 /// We delegate the request to DwarfDebug when the MDNode can be part of the
140 /// type system, since DIEs for the type system can be shared across CUs and
141 /// the mappings are kept in DwarfDebug.
142 DIE *getDIE(const DINode *D) const;
143
144 /// Returns a fresh newly allocated DIELoc.
145 DIELoc *getDIELoc() { return new (DIEValueAllocator) DIELoc; }
146
147 /// Insert DIE into the map.
148 ///
149 /// We delegate the request to DwarfDebug when the MDNode can be part of the
150 /// type system, since DIEs for the type system can be shared across CUs and
151 /// the mappings are kept in DwarfDebug.
152 void insertDIE(const DINode *Desc, DIE *D);
153
154 void insertDIE(DIE *D);
155
156 /// Add a flag that is true to the DIE.
157 void addFlag(DIE &Die, dwarf::Attribute Attribute);
158
159 /// Add an unsigned integer attribute data and value.
160 void addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
161 std::optional<dwarf::Form> Form, uint64_t Integer);
162
163 void addUInt(DIEValueList &Block, dwarf::Form Form, uint64_t Integer);
164
165 /// Add an signed integer attribute data and value.
166 void addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
167 std::optional<dwarf::Form> Form, int64_t Integer);
168
169 void addSInt(DIEValueList &Die, std::optional<dwarf::Form> Form,
170 int64_t Integer);
171
172 /// Add an integer attribute data and value; value may be any width.
173 void addInt(DIE &Die, dwarf::Attribute Attribute, const APInt &Integer,
174 bool Unsigned);
175
176 /// Add a string attribute data and value.
177 ///
178 /// We always emit a reference to the string pool instead of immediate
179 /// strings so that DIEs have more predictable sizes. In the case of split
180 /// dwarf we emit an index into another table which gets us the static offset
181 /// into the string table.
182 void addString(DIE &Die, dwarf::Attribute Attribute, StringRef Str);
183
184 /// Add a Dwarf label attribute data and value.
185 void addLabel(DIEValueList &Die, dwarf::Attribute Attribute, dwarf::Form Form,
186 const MCSymbol *Label);
187
188 void addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label);
189
190 /// Add an offset into a section attribute data and value.
191 void addSectionOffset(DIE &Die, dwarf::Attribute Attribute, uint64_t Integer);
192
193 /// Add a dwarf op address data and value using the form given and an
194 /// op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
195 void addOpAddress(DIELoc &Die, const MCSymbol *Sym);
196 void addPoolOpAddress(DIEValueList &Die, const MCSymbol *Label);
197
198 /// Add a label delta attribute data and value.
199 void addLabelDelta(DIEValueList &Die, dwarf::Attribute Attribute,
200 const MCSymbol *Hi, const MCSymbol *Lo);
201
202 /// Add a DIE attribute data and value.
203 void addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry);
204
205 /// Add a DIE attribute data and value.
206 void addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIEEntry Entry);
207
208 /// Add a type's DW_AT_signature and set the declaration flag.
209 void addDIETypeSignature(DIE &Die, uint64_t Signature);
210
211 /// Add block data.
212 void addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc);
213
214 /// Add block data.
215 void addBlock(DIE &Die, dwarf::Attribute Attribute, DIEBlock *Block);
216 void addBlock(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
217 DIEBlock *Block);
218
219 /// Add an expression as block data.
220 void addBlock(DIE &Die, dwarf::Attribute Attribute, const DIExpression *Expr);
221
222 /// Add location information to specified debug information entry.
223 void addSourceLine(DIE &Die, unsigned Line, unsigned Column,
224 const DIFile *File);
225 void addSourceLine(DIE &Die, const DILocalVariable *V);
226 void addSourceLine(DIE &Die, const DIGlobalVariable *G);
227 void addSourceLine(DIE &Die, const DISubprogram *SP);
228 void addSourceLine(DIE &Die, const DILabel *L);
229 void addSourceLine(DIE &Die, const DIType *Ty);
230 void addSourceLine(DIE &Die, const DIObjCProperty *Ty);
231
232 /// Add constant value entry in variable DIE.
233 void addConstantValue(DIE &Die, const ConstantInt *CI, const DIType *Ty);
234 void addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty);
235 void addConstantValue(DIE &Die, const APInt &Val, bool Unsigned);
236 void addConstantValue(DIE &Die, uint64_t Val, const DIType *Ty);
237 void addConstantValue(DIE &Die, bool Unsigned, uint64_t Val);
238
239 /// Add constant value entry in variable DIE.
240 void addConstantFPValue(DIE &Die, const ConstantFP *CFP);
241
242 /// Add a linkage name, if it isn't empty.
243 void addLinkageName(DIE &Die, StringRef LinkageName);
244
245 /// Add template parameters in buffer.
246 void addTemplateParams(DIE &Buffer, DINodeArray TParams);
247
248 /// Add thrown types.
249 void addThrownTypes(DIE &Die, DINodeArray ThrownTypes);
250
251 /// Add the accessibility attribute.
252 void addAccess(DIE &Die, DINode::DIFlags Flags);
253
254 /// Add a new type attribute to the specified entity.
255 ///
256 /// This takes and attribute parameter because DW_AT_friend attributes are
257 /// also type references.
258 void addType(DIE &Entity, const DIType *Ty,
259 dwarf::Attribute Attribute = dwarf::DW_AT_type);
260
261 DIE *getOrCreateNameSpace(const DINamespace *NS);
262 DIE *getOrCreateModule(const DIModule *M);
263 virtual DIE *getOrCreateSubprogramDIE(const DISubprogram *SP,
264 const Function *FnHint,
265 bool Minimal = false);
266
267 void applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
268 bool SkipSPAttributes = false);
269
270 /// Creates type DIE with specific context.
271 DIE *createTypeDIE(const DIScope *Context, DIE &ContextDIE, const DIType *Ty);
272
273 /// Find existing DIE or create new DIE for the given type.
274 virtual DIE *getOrCreateTypeDIE(const MDNode *TyNode);
275
276 /// Get context owner's DIE.
277 virtual DIE *getOrCreateContextDIE(const DIScope *Context);
278
279 /// Construct DIEs for types that contain vtables.
280 void constructContainingTypeDIEs();
281
282 /// Construct function argument DIEs.
283 ///
284 /// \returns The index of the object parameter in \c Args if one exists.
285 /// Returns std::nullopt otherwise.
286 std::optional<unsigned> constructSubprogramArguments(DIE &Buffer,
287 DITypeArray Args);
288
289 /// Create a DIE with the given Tag, add the DIE to its parent, and
290 /// call insertDIE if MD is not null.
291 DIE &createAndAddDIE(dwarf::Tag Tag, DIE &Parent, const DINode *N = nullptr);
292
293 bool useSegmentedStringOffsetsTable() const {
294 return DD->useSegmentedStringOffsetsTable();
295 }
296
297 /// Compute the size of a header for this unit, not including the initial
298 /// length field.
299 virtual unsigned getHeaderSize() const {
300 return sizeof(int16_t) + // DWARF version number
301 Asm->getDwarfOffsetByteSize() + // Offset Into Abbrev. Section
302 sizeof(int8_t) + // Pointer Size (in bytes)
303 (DD->getDwarfVersion() >= 5 ? sizeof(int8_t)
304 : 0); // DWARF v5 unit type
305 }
306
307 /// Emit the header for this unit, not including the initial length field.
308 virtual void emitHeader(bool UseOffsets) = 0;
309
310 /// Add the DW_AT_str_offsets_base attribute to the unit DIE.
311 void addStringOffsetsStart();
312
313 /// Add the DW_AT_rnglists_base attribute to the unit DIE.
314 void addRnglistsBase();
315
316 virtual DwarfCompileUnit &getCU() = 0;
317
318 void constructTypeDIE(DIE &Buffer, const DICompositeType *CTy);
319
320 /// addSectionDelta - Add a label delta attribute data and value.
321 void addSectionDelta(DIE &Die, dwarf::Attribute Attribute, const MCSymbol *Hi,
322 const MCSymbol *Lo);
323
324 /// Add a Dwarf section label attribute data and value.
325 void addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
326 const MCSymbol *Label, const MCSymbol *Sec);
327
328 /// Add DW_TAG_LLVM_annotation.
329 void addAnnotation(DIE &Buffer, DINodeArray Annotations);
330
331 /// Get context owner's DIE.
332 DIE *createTypeDIE(const DICompositeType *Ty);
333
334 /// If this is a named finished type then include it in the list of types for
335 /// the accelerator tables.
336 void updateAcceleratorTables(const DIScope *Context, const DIType *Ty,
337 const DIE &TyDIE);
338
339protected:
340 ~DwarfUnit() override;
341
342 /// Create new static data member DIE.
343 DIE *getOrCreateStaticMemberDIE(const DIDerivedType *DT);
344
345 /// Look up the source ID for the given file. If none currently exists,
346 /// create a new ID and insert it in the line table.
347 virtual unsigned getOrCreateSourceID(const DIFile *File) = 0;
348
349 /// Emit the common part of the header for this unit.
350 void emitCommonHeader(bool UseOffsets, dwarf::UnitType UT);
351
352 bool shouldPlaceInUnitDIE(const DISubprogram *SP, bool Minimal) {
353 // Add subprogram declarations to the CU die directly.
354 return Minimal || SP->getDeclaration();
355 }
356
357 DIE *getOrCreateSubprogramContextDIE(const DISubprogram *SP,
358 bool IgnoreScope) {
359 if (IgnoreScope)
360 return &getUnitDie();
361 return getOrCreateContextDIE(Context: SP->getScope());
362 }
363
364private:
365 DISourceLanguageName getLanguage() const {
366 return CUNode->getSourceLanguage();
367 }
368
369 /// A helper to add a wide integer constant to a DIE using a block
370 /// form.
371 void addIntAsBlock(DIE &Die, dwarf::Attribute Attribute, const APInt &Val);
372
373 // Add discriminant constants to a DW_TAG_variant DIE.
374 void addDiscriminant(DIE &Variant, Constant *Discriminant, bool IsUnsigned);
375
376 void constructTypeDIE(DIE &Buffer, const DIBasicType *BTy);
377 void constructTypeDIE(DIE &Buffer, const DIFixedPointType *BTy);
378 void constructTypeDIE(DIE &Buffer, const DIStringType *BTy);
379 void constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy);
380 void constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy);
381 void constructSubrangeDIE(DIE &Buffer, const DISubrangeType *SR,
382 bool ForArray = false);
383 void constructSubrangeDIE(DIE &Buffer, const DISubrange *SR);
384 void constructGenericSubrangeDIE(DIE &Buffer, const DIGenericSubrange *SR);
385 void constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy);
386 void constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy);
387 DIE &constructMemberDIE(DIE &Buffer, const DIDerivedType *DT);
388 void constructTemplateTypeParameterDIE(DIE &Buffer,
389 const DITemplateTypeParameter *TP);
390 void constructTemplateValueParameterDIE(DIE &Buffer,
391 const DITemplateValueParameter *TVP);
392
393 /// Return the default lower bound for an array.
394 ///
395 /// If the DWARF version doesn't handle the language, return -1.
396 int64_t getDefaultLowerBound() const;
397
398 /// Get an anonymous type for index type.
399 DIE *getIndexTyDie();
400
401 /// Set D as anonymous type for index which can be reused later.
402 void setIndexTyDie(DIE *D) { IndexTyDie = D; }
403
404 virtual void finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) = 0;
405
406 virtual bool isDwoUnit() const = 0;
407 const MCSymbol *getCrossSectionRelativeBaseAddress() const override;
408
409 /// Returns 'true' if the current DwarfVersion is compatible
410 /// with the specified \p Version.
411 bool isCompatibleWithVersion(uint16_t Version) const;
412};
413
414class DwarfTypeUnit final : public DwarfUnit {
415 uint64_t TypeSignature;
416 const DIE *Ty;
417 DwarfCompileUnit &CU;
418 MCDwarfDwoLineTable *SplitLineTable;
419 bool UsedLineTable = false;
420
421 unsigned getOrCreateSourceID(const DIFile *File) override;
422 void finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) override;
423 bool isDwoUnit() const override;
424
425public:
426 DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A, DwarfDebug *DW,
427 DwarfFile *DWU, unsigned UniqueID,
428 MCDwarfDwoLineTable *SplitLineTable = nullptr);
429
430 void setTypeSignature(uint64_t Signature) { TypeSignature = Signature; }
431 /// Returns Type Signature.
432 uint64_t getTypeSignature() const { return TypeSignature; }
433 void setType(const DIE *Ty) { this->Ty = Ty; }
434
435 /// Emit the header for this unit, not including the initial length field.
436 void emitHeader(bool UseOffsets) override;
437 unsigned getHeaderSize() const override {
438 return DwarfUnit::getHeaderSize() + sizeof(uint64_t) + // Type Signature
439 Asm->getDwarfOffsetByteSize(); // Type DIE Offset
440 }
441 void addGlobalName(StringRef Name, const DIE &Die,
442 const DIScope *Context) override;
443 void addGlobalTypeImpl(const DIType *Ty, const DIE &Die,
444 const DIScope *Context) override;
445 DwarfCompileUnit &getCU() override { return CU; }
446};
447} // end llvm namespace
448#endif
449