xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h --------------*- 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 Microsoft CodeView debug info.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
14 #define LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
15 
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/PointerUnion.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/CodeGen/DbgEntityHistoryCalculator.h"
26 #include "llvm/CodeGen/DebugHandlerBase.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/DebugInfo/CodeView/CodeView.h"
29 #include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
30 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
31 #include "llvm/IR/DebugLoc.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/Compiler.h"
34 #include <cstdint>
35 #include <map>
36 #include <string>
37 #include <tuple>
38 #include <unordered_map>
39 #include <utility>
40 #include <vector>
41 
42 namespace llvm {
43 
44 struct ClassInfo;
45 class StringRef;
46 class AsmPrinter;
47 class Function;
48 class GlobalVariable;
49 class MCSectionCOFF;
50 class MCStreamer;
51 class MCSymbol;
52 class MachineFunction;
53 
54 /// Collects and handles line tables information in a CodeView format.
55 class LLVM_LIBRARY_VISIBILITY CodeViewDebug : public DebugHandlerBase {
56 public:
57   struct LocalVarDef {
58     /// Indicates that variable data is stored in memory relative to the
59     /// specified register.
60     int InMemory : 1;
61 
62     /// Offset of variable data in memory.
63     int DataOffset : 31;
64 
65     /// Non-zero if this is a piece of an aggregate.
66     uint16_t IsSubfield : 1;
67 
68     /// Offset into aggregate.
69     uint16_t StructOffset : 15;
70 
71     /// Register containing the data or the register base of the memory
72     /// location containing the data.
73     uint16_t CVRegister;
74 
toOpaqueValueLocalVarDef75     uint64_t static toOpaqueValue(const LocalVarDef DR) {
76       uint64_t Val = 0;
77       std::memcpy(&Val, &DR, sizeof(Val));
78       return Val;
79     }
80 
createFromOpaqueValueLocalVarDef81     LocalVarDef static createFromOpaqueValue(uint64_t Val) {
82       LocalVarDef DR;
83       std::memcpy(&DR, &Val, sizeof(Val));
84       return DR;
85     }
86   };
87 
88   static_assert(sizeof(uint64_t) == sizeof(LocalVarDef));
89 
90 private:
91   MCStreamer &OS;
92   BumpPtrAllocator Allocator;
93   codeview::GlobalTypeTableBuilder TypeTable;
94 
95   /// Whether to emit type record hashes into .debug$H.
96   bool EmitDebugGlobalHashes = false;
97 
98   /// The codeview CPU type used by the translation unit.
99   codeview::CPUType TheCPU;
100 
101   static LocalVarDef createDefRangeMem(uint16_t CVRegister, int Offset);
102 
103   /// Similar to DbgVariable in DwarfDebug, but not dwarf-specific.
104   struct LocalVariable {
105     const DILocalVariable *DIVar = nullptr;
106     MapVector<LocalVarDef,
107               SmallVector<std::pair<const MCSymbol *, const MCSymbol *>, 1>>
108         DefRanges;
109     bool UseReferenceType = false;
110     std::optional<APSInt> ConstantValue;
111   };
112 
113   struct CVGlobalVariable {
114     const DIGlobalVariable *DIGV;
115     PointerUnion<const GlobalVariable *, const DIExpression *> GVInfo;
116   };
117 
118   struct InlineSite {
119     SmallVector<LocalVariable, 1> InlinedLocals;
120     SmallVector<const DILocation *, 1> ChildSites;
121     const DISubprogram *Inlinee = nullptr;
122 
123     /// The ID of the inline site or function used with .cv_loc. Not a type
124     /// index.
125     unsigned SiteFuncId = 0;
126   };
127 
128   // Combines information from DILexicalBlock and LexicalScope.
129   struct LexicalBlock {
130     SmallVector<LocalVariable, 1> Locals;
131     SmallVector<CVGlobalVariable, 1> Globals;
132     SmallVector<LexicalBlock *, 1> Children;
133     const MCSymbol *Begin;
134     const MCSymbol *End;
135     StringRef Name;
136   };
137 
138   struct JumpTableInfo {
139     codeview::JumpTableEntrySize EntrySize;
140     const MCSymbol *Base;
141     uint64_t BaseOffset;
142     const MCSymbol *Branch;
143     const MCSymbol *Table;
144     size_t TableSize;
145   };
146 
147   // For each function, store a vector of labels to its instructions, as well as
148   // to the end of the function.
149   struct FunctionInfo {
150     FunctionInfo() = default;
151 
152     // Uncopyable.
153     FunctionInfo(const FunctionInfo &FI) = delete;
154 
155     /// Map from inlined call site to inlined instructions and child inlined
156     /// call sites. Listed in program order.
157     std::unordered_map<const DILocation *, InlineSite> InlineSites;
158 
159     /// Ordered list of top-level inlined call sites.
160     SmallVector<const DILocation *, 1> ChildSites;
161 
162     /// Set of all functions directly inlined into this one.
163     SmallSet<codeview::TypeIndex, 1> Inlinees;
164 
165     SmallVector<LocalVariable, 1> Locals;
166     SmallVector<CVGlobalVariable, 1> Globals;
167 
168     std::unordered_map<const DILexicalBlockBase*, LexicalBlock> LexicalBlocks;
169 
170     // Lexical blocks containing local variables.
171     SmallVector<LexicalBlock *, 1> ChildBlocks;
172 
173     std::vector<std::pair<MCSymbol *, MDNode *>> Annotations;
174     std::vector<std::tuple<const MCSymbol *, const MCSymbol *, const DIType *>>
175         HeapAllocSites;
176 
177     std::vector<JumpTableInfo> JumpTables;
178 
179     const MCSymbol *Begin = nullptr;
180     const MCSymbol *End = nullptr;
181     unsigned FuncId = 0;
182     unsigned LastFileId = 0;
183 
184     /// Number of bytes allocated in the prologue for all local stack objects.
185     unsigned FrameSize = 0;
186 
187     /// Number of bytes of parameters on the stack.
188     unsigned ParamSize = 0;
189 
190     /// Number of bytes pushed to save CSRs.
191     unsigned CSRSize = 0;
192 
193     /// Adjustment to apply on x86 when using the VFRAME frame pointer.
194     int OffsetAdjustment = 0;
195 
196     /// Two-bit value indicating which register is the designated frame pointer
197     /// register for local variables. Included in S_FRAMEPROC.
198     codeview::EncodedFramePtrReg EncodedLocalFramePtrReg =
199         codeview::EncodedFramePtrReg::None;
200 
201     /// Two-bit value indicating which register is the designated frame pointer
202     /// register for stack parameters. Included in S_FRAMEPROC.
203     codeview::EncodedFramePtrReg EncodedParamFramePtrReg =
204         codeview::EncodedFramePtrReg::None;
205 
206     codeview::FrameProcedureOptions FrameProcOpts;
207 
208     bool HasStackRealignment = false;
209 
210     bool HaveLineInfo = false;
211 
212     bool HasFramePointer = false;
213   };
214   FunctionInfo *CurFn = nullptr;
215 
216   codeview::SourceLanguage CurrentSourceLanguage =
217       codeview::SourceLanguage::Masm;
218 
219   // This map records the constant offset in DIExpression of the
220   // DIGlobalVariableExpression referencing the DIGlobalVariable.
221   DenseMap<const DIGlobalVariable *, uint64_t> CVGlobalVariableOffsets;
222 
223   // Map used to separate variables according to the lexical scope they belong
224   // in.  This is populated by recordLocalVariable() before
225   // collectLexicalBlocks() separates the variables between the FunctionInfo
226   // and LexicalBlocks.
227   DenseMap<const LexicalScope *, SmallVector<LocalVariable, 1>> ScopeVariables;
228 
229   // Map to separate global variables according to the lexical scope they
230   // belong in. A null local scope represents the global scope.
231   typedef SmallVector<CVGlobalVariable, 1> GlobalVariableList;
232   DenseMap<const DIScope*, std::unique_ptr<GlobalVariableList> > ScopeGlobals;
233 
234   // Array of global variables which  need to be emitted into a COMDAT section.
235   SmallVector<CVGlobalVariable, 1> ComdatVariables;
236 
237   // Array of non-COMDAT global variables.
238   SmallVector<CVGlobalVariable, 1> GlobalVariables;
239 
240   /// List of static const data members to be emitted as S_CONSTANTs.
241   SmallVector<const DIDerivedType *, 4> StaticConstMembers;
242 
243   /// The set of comdat .debug$S sections that we've seen so far. Each section
244   /// must start with a magic version number that must only be emitted once.
245   /// This set tracks which sections we've already opened.
246   DenseSet<MCSectionCOFF *> ComdatDebugSections;
247 
248   /// Switch to the appropriate .debug$S section for GVSym. If GVSym, the symbol
249   /// of an emitted global value, is in a comdat COFF section, this will switch
250   /// to a new .debug$S section in that comdat. This method ensures that the
251   /// section starts with the magic version number on first use. If GVSym is
252   /// null, uses the main .debug$S section.
253   void switchToDebugSectionForSymbol(const MCSymbol *GVSym);
254 
255   /// The next available function index for use with our .cv_* directives. Not
256   /// to be confused with type indices for LF_FUNC_ID records.
257   unsigned NextFuncId = 0;
258 
259   InlineSite &getInlineSite(const DILocation *InlinedAt,
260                             const DISubprogram *Inlinee);
261 
262   codeview::TypeIndex getFuncIdForSubprogram(const DISubprogram *SP);
263 
264   void calculateRanges(LocalVariable &Var,
265                        const DbgValueHistoryMap::Entries &Entries);
266 
267   /// Remember some debug info about each function. Keep it in a stable order to
268   /// emit at the end of the TU.
269   MapVector<const Function *, std::unique_ptr<FunctionInfo>> FnDebugInfo;
270 
271   /// Map from full file path to .cv_file id. Full paths are built from DIFiles
272   /// and are stored in FileToFilepathMap;
273   DenseMap<StringRef, unsigned> FileIdMap;
274 
275   /// All inlined subprograms in the order they should be emitted.
276   SmallSetVector<const DISubprogram *, 4> InlinedSubprograms;
277 
278   /// Map from a pair of DI metadata nodes and its DI type (or scope) that can
279   /// be nullptr, to CodeView type indices. Primarily indexed by
280   /// {DIType*, DIType*} and {DISubprogram*, DIType*}.
281   ///
282   /// The second entry in the key is needed for methods as DISubroutineType
283   /// representing static method type are shared with non-method function type.
284   DenseMap<std::pair<const DINode *, const DIType *>, codeview::TypeIndex>
285       TypeIndices;
286 
287   /// Map from DICompositeType* to complete type index. Non-record types are
288   /// always looked up in the normal TypeIndices map.
289   DenseMap<const DICompositeType *, codeview::TypeIndex> CompleteTypeIndices;
290 
291   /// Complete record types to emit after all active type lowerings are
292   /// finished.
293   SmallVector<const DICompositeType *, 4> DeferredCompleteTypes;
294 
295   /// Number of type lowering frames active on the stack.
296   unsigned TypeEmissionLevel = 0;
297 
298   codeview::TypeIndex VBPType;
299 
300   const DISubprogram *CurrentSubprogram = nullptr;
301 
302   // The UDTs we have seen while processing types; each entry is a pair of type
303   // index and type name.
304   std::vector<std::pair<std::string, const DIType *>> LocalUDTs;
305   std::vector<std::pair<std::string, const DIType *>> GlobalUDTs;
306 
307   using FileToFilepathMapTy = std::map<const DIFile *, std::string>;
308   FileToFilepathMapTy FileToFilepathMap;
309 
310   StringRef getFullFilepath(const DIFile *File);
311 
312   unsigned maybeRecordFile(const DIFile *F);
313 
314   void maybeRecordLocation(const DebugLoc &DL, const MachineFunction *MF);
315 
316   void clear();
317 
setCurrentSubprogram(const DISubprogram * SP)318   void setCurrentSubprogram(const DISubprogram *SP) {
319     CurrentSubprogram = SP;
320     LocalUDTs.clear();
321   }
322 
323   /// Emit the magic version number at the start of a CodeView type or symbol
324   /// section. Appears at the front of every .debug$S or .debug$T or .debug$P
325   /// section.
326   void emitCodeViewMagicVersion();
327 
328   void emitTypeInformation();
329 
330   void emitTypeGlobalHashes();
331 
332   void emitObjName();
333 
334   void emitCompilerInformation();
335 
336   void emitBuildInfo();
337 
338   void emitInlineeLinesSubsection();
339 
340   void emitDebugInfoForThunk(const Function *GV,
341                              FunctionInfo &FI,
342                              const MCSymbol *Fn);
343 
344   void emitDebugInfoForFunction(const Function *GV, FunctionInfo &FI);
345 
346   void emitDebugInfoForRetainedTypes();
347 
348   void emitDebugInfoForUDTs(
349       const std::vector<std::pair<std::string, const DIType *>> &UDTs);
350 
351   void collectDebugInfoForGlobals();
352   void emitDebugInfoForGlobals();
353   void emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals);
354   void emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,
355                                 const std::string &QualifiedName);
356   void emitDebugInfoForGlobal(const CVGlobalVariable &CVGV);
357   void emitStaticConstMemberList();
358 
359   /// Opens a subsection of the given kind in a .debug$S codeview section.
360   /// Returns an end label for use with endCVSubsection when the subsection is
361   /// finished.
362   MCSymbol *beginCVSubsection(codeview::DebugSubsectionKind Kind);
363   void endCVSubsection(MCSymbol *EndLabel);
364 
365   /// Opens a symbol record of the given kind. Returns an end label for use with
366   /// endSymbolRecord.
367   MCSymbol *beginSymbolRecord(codeview::SymbolKind Kind);
368   void endSymbolRecord(MCSymbol *SymEnd);
369 
370   /// Emits an S_END, S_INLINESITE_END, or S_PROC_ID_END record. These records
371   /// are empty, so we emit them with a simpler assembly sequence that doesn't
372   /// involve labels.
373   void emitEndSymbolRecord(codeview::SymbolKind EndKind);
374 
375   void emitInlinedCallSite(const FunctionInfo &FI, const DILocation *InlinedAt,
376                            const InlineSite &Site);
377 
378   void emitInlinees(const SmallSet<codeview::TypeIndex, 1> &Inlinees);
379 
380   using InlinedEntity = DbgValueHistoryMap::InlinedEntity;
381 
382   void collectGlobalVariableInfo();
383   void collectVariableInfo(const DISubprogram *SP);
384 
385   void collectVariableInfoFromMFTable(DenseSet<InlinedEntity> &Processed);
386 
387   // Construct the lexical block tree for a routine, pruning emptpy lexical
388   // scopes, and populate it with local variables.
389   void collectLexicalBlockInfo(SmallVectorImpl<LexicalScope *> &Scopes,
390                                SmallVectorImpl<LexicalBlock *> &Blocks,
391                                SmallVectorImpl<LocalVariable> &Locals,
392                                SmallVectorImpl<CVGlobalVariable> &Globals);
393   void collectLexicalBlockInfo(LexicalScope &Scope,
394                                SmallVectorImpl<LexicalBlock *> &ParentBlocks,
395                                SmallVectorImpl<LocalVariable> &ParentLocals,
396                                SmallVectorImpl<CVGlobalVariable> &ParentGlobals);
397 
398   /// Records information about a local variable in the appropriate scope. In
399   /// particular, locals from inlined code live inside the inlining site.
400   void recordLocalVariable(LocalVariable &&Var, const LexicalScope *LS);
401 
402   /// Emits local variables in the appropriate order.
403   void emitLocalVariableList(const FunctionInfo &FI,
404                              ArrayRef<LocalVariable> Locals);
405 
406   /// Emits an S_LOCAL record and its associated defined ranges.
407   void emitLocalVariable(const FunctionInfo &FI, const LocalVariable &Var);
408 
409   /// Emits a sequence of lexical block scopes and their children.
410   void emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
411                             const FunctionInfo& FI);
412 
413   /// Emit a lexical block scope and its children.
414   void emitLexicalBlock(const LexicalBlock &Block, const FunctionInfo& FI);
415 
416   /// Translates the DIType to codeview if necessary and returns a type index
417   /// for it.
418   codeview::TypeIndex getTypeIndex(const DIType *Ty,
419                                    const DIType *ClassTy = nullptr);
420 
421   codeview::TypeIndex
422   getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
423                          const DISubroutineType *SubroutineTy);
424 
425   codeview::TypeIndex getTypeIndexForReferenceTo(const DIType *Ty);
426 
427   codeview::TypeIndex getMemberFunctionType(const DISubprogram *SP,
428                                             const DICompositeType *Class);
429 
430   codeview::TypeIndex getScopeIndex(const DIScope *Scope);
431 
432   codeview::TypeIndex getVBPTypeIndex();
433 
434   void addToUDTs(const DIType *Ty);
435 
436   void addUDTSrcLine(const DIType *Ty, codeview::TypeIndex TI);
437 
438   codeview::TypeIndex lowerType(const DIType *Ty, const DIType *ClassTy);
439   codeview::TypeIndex lowerTypeAlias(const DIDerivedType *Ty);
440   codeview::TypeIndex lowerTypeArray(const DICompositeType *Ty);
441   codeview::TypeIndex lowerTypeString(const DIStringType *Ty);
442   codeview::TypeIndex lowerTypeBasic(const DIBasicType *Ty);
443   codeview::TypeIndex lowerTypePointer(
444       const DIDerivedType *Ty,
445       codeview::PointerOptions PO = codeview::PointerOptions::None);
446   codeview::TypeIndex lowerTypeMemberPointer(
447       const DIDerivedType *Ty,
448       codeview::PointerOptions PO = codeview::PointerOptions::None);
449   codeview::TypeIndex lowerTypeModifier(const DIDerivedType *Ty);
450   codeview::TypeIndex lowerTypeFunction(const DISubroutineType *Ty);
451   codeview::TypeIndex lowerTypeVFTableShape(const DIDerivedType *Ty);
452   codeview::TypeIndex lowerTypeMemberFunction(
453       const DISubroutineType *Ty, const DIType *ClassTy, int ThisAdjustment,
454       bool IsStaticMethod,
455       codeview::FunctionOptions FO = codeview::FunctionOptions::None);
456   codeview::TypeIndex lowerTypeEnum(const DICompositeType *Ty);
457   codeview::TypeIndex lowerTypeClass(const DICompositeType *Ty);
458   codeview::TypeIndex lowerTypeUnion(const DICompositeType *Ty);
459 
460   /// Symbol records should point to complete types, but type records should
461   /// always point to incomplete types to avoid cycles in the type graph. Only
462   /// use this entry point when generating symbol records. The complete and
463   /// incomplete type indices only differ for record types. All other types use
464   /// the same index.
465   codeview::TypeIndex getCompleteTypeIndex(const DIType *Ty);
466 
467   codeview::TypeIndex lowerCompleteTypeClass(const DICompositeType *Ty);
468   codeview::TypeIndex lowerCompleteTypeUnion(const DICompositeType *Ty);
469 
470   struct TypeLoweringScope;
471 
472   void emitDeferredCompleteTypes();
473 
474   void collectMemberInfo(ClassInfo &Info, const DIDerivedType *DDTy);
475   ClassInfo collectClassInfo(const DICompositeType *Ty);
476 
477   /// Common record member lowering functionality for record types, which are
478   /// structs, classes, and unions. Returns the field list index and the member
479   /// count.
480   std::tuple<codeview::TypeIndex, codeview::TypeIndex, unsigned, bool>
481   lowerRecordFieldList(const DICompositeType *Ty);
482 
483   /// Inserts {{Node, ClassTy}, TI} into TypeIndices and checks for duplicates.
484   codeview::TypeIndex recordTypeIndexForDINode(const DINode *Node,
485                                                codeview::TypeIndex TI,
486                                                const DIType *ClassTy = nullptr);
487 
488   /// Collect the names of parent scopes, innermost to outermost. Return the
489   /// innermost subprogram scope if present. Ensure that parent type scopes are
490   /// inserted into the type table.
491   const DISubprogram *
492   collectParentScopeNames(const DIScope *Scope,
493                           SmallVectorImpl<StringRef> &ParentScopeNames);
494   std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name);
495   std::string getFullyQualifiedName(const DIScope *Scope);
496 
497   unsigned getPointerSizeInBytes();
498 
499   void discoverJumpTableBranches(const MachineFunction *MF, bool isThumb);
500   void collectDebugInfoForJumpTables(const MachineFunction *MF, bool isThumb);
501   void emitDebugInfoForJumpTables(const FunctionInfo &FI);
502 
503 protected:
504   /// Gather pre-function debug information.
505   void beginFunctionImpl(const MachineFunction *MF) override;
506 
507   /// Gather post-function debug information.
508   void endFunctionImpl(const MachineFunction *) override;
509 
510   /// Check if the current module is in Fortran.
moduleIsInFortran()511   bool moduleIsInFortran() {
512     return CurrentSourceLanguage == codeview::SourceLanguage::Fortran;
513   }
514 
515 public:
516   CodeViewDebug(AsmPrinter *AP);
517 
518   void beginModule(Module *M) override;
519 
520   /// Emit the COFF section that holds the line table information.
521   void endModule() override;
522 
523   /// Process beginning of an instruction.
524   void beginInstruction(const MachineInstr *MI) override;
525 };
526 
527 template <> struct DenseMapInfo<CodeViewDebug::LocalVarDef> {
528 
529   static inline CodeViewDebug::LocalVarDef getEmptyKey() {
530     return CodeViewDebug::LocalVarDef::createFromOpaqueValue(~0ULL);
531   }
532 
533   static inline CodeViewDebug::LocalVarDef getTombstoneKey() {
534     return CodeViewDebug::LocalVarDef::createFromOpaqueValue(~0ULL - 1ULL);
535   }
536 
537   static unsigned getHashValue(const CodeViewDebug::LocalVarDef &DR) {
538     return CodeViewDebug::LocalVarDef::toOpaqueValue(DR) * 37ULL;
539   }
540 
541   static bool isEqual(const CodeViewDebug::LocalVarDef &LHS,
542                       const CodeViewDebug::LocalVarDef &RHS) {
543     return CodeViewDebug::LocalVarDef::toOpaqueValue(LHS) ==
544            CodeViewDebug::LocalVarDef::toOpaqueValue(RHS);
545   }
546 };
547 
548 } // end namespace llvm
549 
550 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
551