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