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