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