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