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