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