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