1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h --------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains support for writing Microsoft CodeView debug info.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
14 #define LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
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"
38 #include <unordered_map>
52 class MachineFunction
;
54 /// Collects and handles line tables information in a CodeView format.
55 class LLVM_LIBRARY_VISIBILITY CodeViewDebug
: public DebugHandlerBase
{
58 /// Indicates that variable data is stored in memory relative to the
59 /// specified register.
62 /// Offset of variable data in memory.
65 /// Non-zero if this is a piece of an aggregate.
66 uint16_t IsSubfield
: 1;
68 /// Offset into aggregate.
69 uint16_t StructOffset
: 15;
71 /// Register containing the data or the register base of the memory
72 /// location containing the data.
75 uint64_t static toOpaqueValue(const LocalVarDef DR
) {
77 std::memcpy(&Val
, &DR
, sizeof(Val
));
81 LocalVarDef
static createFromOpaqueValue(uint64_t Val
) {
83 std::memcpy(&DR
, &Val
, sizeof(Val
));
88 static_assert(sizeof(uint64_t) == sizeof(LocalVarDef
));
92 BumpPtrAllocator Allocator
;
93 codeview::GlobalTypeTableBuilder TypeTable
;
95 /// Whether to emit type record hashes into .debug$H.
96 bool EmitDebugGlobalHashes
= false;
98 /// The codeview CPU type used by the translation unit.
99 codeview::CPUType TheCPU
;
101 static LocalVarDef
createDefRangeMem(uint16_t CVRegister
, int Offset
);
103 /// Similar to DbgVariable in DwarfDebug, but not dwarf-specific.
104 struct LocalVariable
{
105 const DILocalVariable
*DIVar
= nullptr;
106 MapVector
<LocalVarDef
,
107 SmallVector
<std::pair
<const MCSymbol
*, const MCSymbol
*>, 1>>
109 bool UseReferenceType
= false;
110 std::optional
<APSInt
> ConstantValue
;
113 struct CVGlobalVariable
{
114 const DIGlobalVariable
*DIGV
;
115 PointerUnion
<const GlobalVariable
*, const DIExpression
*> GVInfo
;
119 SmallVector
<LocalVariable
, 1> InlinedLocals
;
120 SmallVector
<const DILocation
*, 1> ChildSites
;
121 const DISubprogram
*Inlinee
= nullptr;
123 /// The ID of the inline site or function used with .cv_loc. Not a type
125 unsigned SiteFuncId
= 0;
128 // Combines information from DILexicalBlock and LexicalScope.
129 struct LexicalBlock
{
130 SmallVector
<LocalVariable
, 1> Locals
;
131 SmallVector
<CVGlobalVariable
, 1> Globals
;
132 SmallVector
<LexicalBlock
*, 1> Children
;
133 const MCSymbol
*Begin
;
138 struct JumpTableInfo
{
139 codeview::JumpTableEntrySize EntrySize
;
140 const MCSymbol
*Base
;
142 const MCSymbol
*Branch
;
143 const MCSymbol
*Table
;
147 // For each function, store a vector of labels to its instructions, as well as
148 // to the end of the function.
149 struct FunctionInfo
{
150 FunctionInfo() = default;
153 FunctionInfo(const FunctionInfo
&FI
) = delete;
155 /// Map from inlined call site to inlined instructions and child inlined
156 /// call sites. Listed in program order.
157 std::unordered_map
<const DILocation
*, InlineSite
> InlineSites
;
159 /// Ordered list of top-level inlined call sites.
160 SmallVector
<const DILocation
*, 1> ChildSites
;
162 /// Set of all functions directly inlined into this one.
163 SmallSet
<codeview::TypeIndex
, 1> Inlinees
;
165 SmallVector
<LocalVariable
, 1> Locals
;
166 SmallVector
<CVGlobalVariable
, 1> Globals
;
168 std::unordered_map
<const DILexicalBlockBase
*, LexicalBlock
> LexicalBlocks
;
170 // Lexical blocks containing local variables.
171 SmallVector
<LexicalBlock
*, 1> ChildBlocks
;
173 std::vector
<std::pair
<MCSymbol
*, MDNode
*>> Annotations
;
174 std::vector
<std::tuple
<const MCSymbol
*, const MCSymbol
*, const DIType
*>>
177 std::vector
<JumpTableInfo
> JumpTables
;
179 const MCSymbol
*Begin
= nullptr;
180 const MCSymbol
*End
= nullptr;
182 unsigned LastFileId
= 0;
184 /// Number of bytes allocated in the prologue for all local stack objects.
185 unsigned FrameSize
= 0;
187 /// Number of bytes of parameters on the stack.
188 unsigned ParamSize
= 0;
190 /// Number of bytes pushed to save CSRs.
191 unsigned CSRSize
= 0;
193 /// Adjustment to apply on x86 when using the VFRAME frame pointer.
194 int OffsetAdjustment
= 0;
196 /// Two-bit value indicating which register is the designated frame pointer
197 /// register for local variables. Included in S_FRAMEPROC.
198 codeview::EncodedFramePtrReg EncodedLocalFramePtrReg
=
199 codeview::EncodedFramePtrReg::None
;
201 /// Two-bit value indicating which register is the designated frame pointer
202 /// register for stack parameters. Included in S_FRAMEPROC.
203 codeview::EncodedFramePtrReg EncodedParamFramePtrReg
=
204 codeview::EncodedFramePtrReg::None
;
206 codeview::FrameProcedureOptions FrameProcOpts
;
208 bool HasStackRealignment
= false;
210 bool HaveLineInfo
= false;
212 bool HasFramePointer
= false;
214 FunctionInfo
*CurFn
= nullptr;
216 codeview::SourceLanguage CurrentSourceLanguage
=
217 codeview::SourceLanguage::Masm
;
219 // This map records the constant offset in DIExpression of the
220 // DIGlobalVariableExpression referencing the DIGlobalVariable.
221 DenseMap
<const DIGlobalVariable
*, uint64_t> CVGlobalVariableOffsets
;
223 // Map used to seperate variables according to the lexical scope they belong
224 // in. This is populated by recordLocalVariable() before
225 // collectLexicalBlocks() separates the variables between the FunctionInfo
226 // and LexicalBlocks.
227 DenseMap
<const LexicalScope
*, SmallVector
<LocalVariable
, 1>> ScopeVariables
;
229 // Map to separate global variables according to the lexical scope they
230 // belong in. A null local scope represents the global scope.
231 typedef SmallVector
<CVGlobalVariable
, 1> GlobalVariableList
;
232 DenseMap
<const DIScope
*, std::unique_ptr
<GlobalVariableList
> > ScopeGlobals
;
234 // Array of global variables which need to be emitted into a COMDAT section.
235 SmallVector
<CVGlobalVariable
, 1> ComdatVariables
;
237 // Array of non-COMDAT global variables.
238 SmallVector
<CVGlobalVariable
, 1> GlobalVariables
;
240 /// List of static const data members to be emitted as S_CONSTANTs.
241 SmallVector
<const DIDerivedType
*, 4> StaticConstMembers
;
243 /// The set of comdat .debug$S sections that we've seen so far. Each section
244 /// must start with a magic version number that must only be emitted once.
245 /// This set tracks which sections we've already opened.
246 DenseSet
<MCSectionCOFF
*> ComdatDebugSections
;
248 /// Switch to the appropriate .debug$S section for GVSym. If GVSym, the symbol
249 /// of an emitted global value, is in a comdat COFF section, this will switch
250 /// to a new .debug$S section in that comdat. This method ensures that the
251 /// section starts with the magic version number on first use. If GVSym is
252 /// null, uses the main .debug$S section.
253 void switchToDebugSectionForSymbol(const MCSymbol
*GVSym
);
255 /// The next available function index for use with our .cv_* directives. Not
256 /// to be confused with type indices for LF_FUNC_ID records.
257 unsigned NextFuncId
= 0;
259 InlineSite
&getInlineSite(const DILocation
*InlinedAt
,
260 const DISubprogram
*Inlinee
);
262 codeview::TypeIndex
getFuncIdForSubprogram(const DISubprogram
*SP
);
264 void calculateRanges(LocalVariable
&Var
,
265 const DbgValueHistoryMap::Entries
&Entries
);
267 /// Remember some debug info about each function. Keep it in a stable order to
268 /// emit at the end of the TU.
269 MapVector
<const Function
*, std::unique_ptr
<FunctionInfo
>> FnDebugInfo
;
271 /// Map from full file path to .cv_file id. Full paths are built from DIFiles
272 /// and are stored in FileToFilepathMap;
273 DenseMap
<StringRef
, unsigned> FileIdMap
;
275 /// All inlined subprograms in the order they should be emitted.
276 SmallSetVector
<const DISubprogram
*, 4> InlinedSubprograms
;
278 /// Map from a pair of DI metadata nodes and its DI type (or scope) that can
279 /// be nullptr, to CodeView type indices. Primarily indexed by
280 /// {DIType*, DIType*} and {DISubprogram*, DIType*}.
282 /// The second entry in the key is needed for methods as DISubroutineType
283 /// representing static method type are shared with non-method function type.
284 DenseMap
<std::pair
<const DINode
*, const DIType
*>, codeview::TypeIndex
>
287 /// Map from DICompositeType* to complete type index. Non-record types are
288 /// always looked up in the normal TypeIndices map.
289 DenseMap
<const DICompositeType
*, codeview::TypeIndex
> CompleteTypeIndices
;
291 /// Complete record types to emit after all active type lowerings are
293 SmallVector
<const DICompositeType
*, 4> DeferredCompleteTypes
;
295 /// Number of type lowering frames active on the stack.
296 unsigned TypeEmissionLevel
= 0;
298 codeview::TypeIndex VBPType
;
300 const DISubprogram
*CurrentSubprogram
= nullptr;
302 // The UDTs we have seen while processing types; each entry is a pair of type
303 // index and type name.
304 std::vector
<std::pair
<std::string
, const DIType
*>> LocalUDTs
;
305 std::vector
<std::pair
<std::string
, const DIType
*>> GlobalUDTs
;
307 using FileToFilepathMapTy
= std::map
<const DIFile
*, std::string
>;
308 FileToFilepathMapTy FileToFilepathMap
;
310 StringRef
getFullFilepath(const DIFile
*File
);
312 unsigned maybeRecordFile(const DIFile
*F
);
314 void maybeRecordLocation(const DebugLoc
&DL
, const MachineFunction
*MF
);
318 void setCurrentSubprogram(const DISubprogram
*SP
) {
319 CurrentSubprogram
= SP
;
323 /// Emit the magic version number at the start of a CodeView type or symbol
324 /// section. Appears at the front of every .debug$S or .debug$T or .debug$P
326 void emitCodeViewMagicVersion();
328 void emitTypeInformation();
330 void emitTypeGlobalHashes();
334 void emitCompilerInformation();
336 void emitBuildInfo();
338 void emitInlineeLinesSubsection();
340 void emitDebugInfoForThunk(const Function
*GV
,
344 void emitDebugInfoForFunction(const Function
*GV
, FunctionInfo
&FI
);
346 void emitDebugInfoForRetainedTypes();
348 void emitDebugInfoForUDTs(
349 const std::vector
<std::pair
<std::string
, const DIType
*>> &UDTs
);
351 void collectDebugInfoForGlobals();
352 void emitDebugInfoForGlobals();
353 void emitGlobalVariableList(ArrayRef
<CVGlobalVariable
> Globals
);
354 void emitConstantSymbolRecord(const DIType
*DTy
, APSInt
&Value
,
355 const std::string
&QualifiedName
);
356 void emitDebugInfoForGlobal(const CVGlobalVariable
&CVGV
);
357 void emitStaticConstMemberList();
359 /// Opens a subsection of the given kind in a .debug$S codeview section.
360 /// Returns an end label for use with endCVSubsection when the subsection is
362 MCSymbol
*beginCVSubsection(codeview::DebugSubsectionKind Kind
);
363 void endCVSubsection(MCSymbol
*EndLabel
);
365 /// Opens a symbol record of the given kind. Returns an end label for use with
367 MCSymbol
*beginSymbolRecord(codeview::SymbolKind Kind
);
368 void endSymbolRecord(MCSymbol
*SymEnd
);
370 /// Emits an S_END, S_INLINESITE_END, or S_PROC_ID_END record. These records
371 /// are empty, so we emit them with a simpler assembly sequence that doesn't
373 void emitEndSymbolRecord(codeview::SymbolKind EndKind
);
375 void emitInlinedCallSite(const FunctionInfo
&FI
, const DILocation
*InlinedAt
,
376 const InlineSite
&Site
);
378 void emitInlinees(const SmallSet
<codeview::TypeIndex
, 1> &Inlinees
);
380 using InlinedEntity
= DbgValueHistoryMap::InlinedEntity
;
382 void collectGlobalVariableInfo();
383 void collectVariableInfo(const DISubprogram
*SP
);
385 void collectVariableInfoFromMFTable(DenseSet
<InlinedEntity
> &Processed
);
387 // Construct the lexical block tree for a routine, pruning emptpy lexical
388 // scopes, and populate it with local variables.
389 void collectLexicalBlockInfo(SmallVectorImpl
<LexicalScope
*> &Scopes
,
390 SmallVectorImpl
<LexicalBlock
*> &Blocks
,
391 SmallVectorImpl
<LocalVariable
> &Locals
,
392 SmallVectorImpl
<CVGlobalVariable
> &Globals
);
393 void collectLexicalBlockInfo(LexicalScope
&Scope
,
394 SmallVectorImpl
<LexicalBlock
*> &ParentBlocks
,
395 SmallVectorImpl
<LocalVariable
> &ParentLocals
,
396 SmallVectorImpl
<CVGlobalVariable
> &ParentGlobals
);
398 /// Records information about a local variable in the appropriate scope. In
399 /// particular, locals from inlined code live inside the inlining site.
400 void recordLocalVariable(LocalVariable
&&Var
, const LexicalScope
*LS
);
402 /// Emits local variables in the appropriate order.
403 void emitLocalVariableList(const FunctionInfo
&FI
,
404 ArrayRef
<LocalVariable
> Locals
);
406 /// Emits an S_LOCAL record and its associated defined ranges.
407 void emitLocalVariable(const FunctionInfo
&FI
, const LocalVariable
&Var
);
409 /// Emits a sequence of lexical block scopes and their children.
410 void emitLexicalBlockList(ArrayRef
<LexicalBlock
*> Blocks
,
411 const FunctionInfo
& FI
);
413 /// Emit a lexical block scope and its children.
414 void emitLexicalBlock(const LexicalBlock
&Block
, const FunctionInfo
& FI
);
416 /// Translates the DIType to codeview if necessary and returns a type index
418 codeview::TypeIndex
getTypeIndex(const DIType
*Ty
,
419 const DIType
*ClassTy
= nullptr);
422 getTypeIndexForThisPtr(const DIDerivedType
*PtrTy
,
423 const DISubroutineType
*SubroutineTy
);
425 codeview::TypeIndex
getTypeIndexForReferenceTo(const DIType
*Ty
);
427 codeview::TypeIndex
getMemberFunctionType(const DISubprogram
*SP
,
428 const DICompositeType
*Class
);
430 codeview::TypeIndex
getScopeIndex(const DIScope
*Scope
);
432 codeview::TypeIndex
getVBPTypeIndex();
434 void addToUDTs(const DIType
*Ty
);
436 void addUDTSrcLine(const DIType
*Ty
, codeview::TypeIndex TI
);
438 codeview::TypeIndex
lowerType(const DIType
*Ty
, const DIType
*ClassTy
);
439 codeview::TypeIndex
lowerTypeAlias(const DIDerivedType
*Ty
);
440 codeview::TypeIndex
lowerTypeArray(const DICompositeType
*Ty
);
441 codeview::TypeIndex
lowerTypeString(const DIStringType
*Ty
);
442 codeview::TypeIndex
lowerTypeBasic(const DIBasicType
*Ty
);
443 codeview::TypeIndex
lowerTypePointer(
444 const DIDerivedType
*Ty
,
445 codeview::PointerOptions PO
= codeview::PointerOptions::None
);
446 codeview::TypeIndex
lowerTypeMemberPointer(
447 const DIDerivedType
*Ty
,
448 codeview::PointerOptions PO
= codeview::PointerOptions::None
);
449 codeview::TypeIndex
lowerTypeModifier(const DIDerivedType
*Ty
);
450 codeview::TypeIndex
lowerTypeFunction(const DISubroutineType
*Ty
);
451 codeview::TypeIndex
lowerTypeVFTableShape(const DIDerivedType
*Ty
);
452 codeview::TypeIndex
lowerTypeMemberFunction(
453 const DISubroutineType
*Ty
, const DIType
*ClassTy
, int ThisAdjustment
,
455 codeview::FunctionOptions FO
= codeview::FunctionOptions::None
);
456 codeview::TypeIndex
lowerTypeEnum(const DICompositeType
*Ty
);
457 codeview::TypeIndex
lowerTypeClass(const DICompositeType
*Ty
);
458 codeview::TypeIndex
lowerTypeUnion(const DICompositeType
*Ty
);
460 /// Symbol records should point to complete types, but type records should
461 /// always point to incomplete types to avoid cycles in the type graph. Only
462 /// use this entry point when generating symbol records. The complete and
463 /// incomplete type indices only differ for record types. All other types use
465 codeview::TypeIndex
getCompleteTypeIndex(const DIType
*Ty
);
467 codeview::TypeIndex
lowerCompleteTypeClass(const DICompositeType
*Ty
);
468 codeview::TypeIndex
lowerCompleteTypeUnion(const DICompositeType
*Ty
);
470 struct TypeLoweringScope
;
472 void emitDeferredCompleteTypes();
474 void collectMemberInfo(ClassInfo
&Info
, const DIDerivedType
*DDTy
);
475 ClassInfo
collectClassInfo(const DICompositeType
*Ty
);
477 /// Common record member lowering functionality for record types, which are
478 /// structs, classes, and unions. Returns the field list index and the member
480 std::tuple
<codeview::TypeIndex
, codeview::TypeIndex
, unsigned, bool>
481 lowerRecordFieldList(const DICompositeType
*Ty
);
483 /// Inserts {{Node, ClassTy}, TI} into TypeIndices and checks for duplicates.
484 codeview::TypeIndex
recordTypeIndexForDINode(const DINode
*Node
,
485 codeview::TypeIndex TI
,
486 const DIType
*ClassTy
= nullptr);
488 /// Collect the names of parent scopes, innermost to outermost. Return the
489 /// innermost subprogram scope if present. Ensure that parent type scopes are
490 /// inserted into the type table.
492 collectParentScopeNames(const DIScope
*Scope
,
493 SmallVectorImpl
<StringRef
> &ParentScopeNames
);
494 std::string
getFullyQualifiedName(const DIScope
*Scope
, StringRef Name
);
495 std::string
getFullyQualifiedName(const DIScope
*Scope
);
497 unsigned getPointerSizeInBytes();
499 void discoverJumpTableBranches(const MachineFunction
*MF
, bool isThumb
);
500 void collectDebugInfoForJumpTables(const MachineFunction
*MF
, bool isThumb
);
501 void emitDebugInfoForJumpTables(const FunctionInfo
&FI
);
504 /// Gather pre-function debug information.
505 void beginFunctionImpl(const MachineFunction
*MF
) override
;
507 /// Gather post-function debug information.
508 void endFunctionImpl(const MachineFunction
*) override
;
510 /// Check if the current module is in Fortran.
511 bool moduleIsInFortran() {
512 return CurrentSourceLanguage
== codeview::SourceLanguage::Fortran
;
516 CodeViewDebug(AsmPrinter
*AP
);
518 void beginModule(Module
*M
) override
;
520 void setSymbolSize(const MCSymbol
*, uint64_t) override
{}
522 /// Emit the COFF section that holds the line table information.
523 void endModule() override
;
525 /// Process beginning of an instruction.
526 void beginInstruction(const MachineInstr
*MI
) override
;
529 template <> struct DenseMapInfo
<CodeViewDebug::LocalVarDef
> {
531 static inline CodeViewDebug::LocalVarDef
getEmptyKey() {
532 return CodeViewDebug::LocalVarDef::createFromOpaqueValue(~0ULL);
535 static inline CodeViewDebug::LocalVarDef
getTombstoneKey() {
536 return CodeViewDebug::LocalVarDef::createFromOpaqueValue(~0ULL - 1ULL);
539 static unsigned getHashValue(const CodeViewDebug::LocalVarDef
&DR
) {
540 return CodeViewDebug::LocalVarDef::toOpaqueValue(DR
) * 37ULL;
543 static bool isEqual(const CodeViewDebug::LocalVarDef
&LHS
,
544 const CodeViewDebug::LocalVarDef
&RHS
) {
545 return CodeViewDebug::LocalVarDef::toOpaqueValue(LHS
) ==
546 CodeViewDebug::LocalVarDef::toOpaqueValue(RHS
);
550 } // end namespace llvm
552 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H