1//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
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#include "CodeViewDebug.h"
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallBitVector.h"
17#include "llvm/ADT/SmallString.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/TinyPtrVector.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/BinaryFormat/COFF.h"
22#include "llvm/BinaryFormat/Dwarf.h"
23#include "llvm/CodeGen/AsmPrinter.h"
24#include "llvm/CodeGen/LexicalScopes.h"
25#include "llvm/CodeGen/MachineFrameInfo.h"
26#include "llvm/CodeGen/MachineFunction.h"
27#include "llvm/CodeGen/MachineInstr.h"
28#include "llvm/CodeGen/MachineModuleInfo.h"
29#include "llvm/CodeGen/TargetFrameLowering.h"
30#include "llvm/CodeGen/TargetLowering.h"
31#include "llvm/CodeGen/TargetRegisterInfo.h"
32#include "llvm/CodeGen/TargetSubtargetInfo.h"
33#include "llvm/Config/llvm-config.h"
34#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
35#include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h"
36#include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
37#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
38#include "llvm/DebugInfo/CodeView/EnumTables.h"
39#include "llvm/DebugInfo/CodeView/Line.h"
40#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
41#include "llvm/DebugInfo/CodeView/TypeRecord.h"
42#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
43#include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h"
44#include "llvm/IR/Constants.h"
45#include "llvm/IR/DataLayout.h"
46#include "llvm/IR/DebugInfoMetadata.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/GlobalValue.h"
49#include "llvm/IR/GlobalVariable.h"
50#include "llvm/IR/Metadata.h"
51#include "llvm/IR/Module.h"
52#include "llvm/MC/MCAsmInfo.h"
53#include "llvm/MC/MCContext.h"
54#include "llvm/MC/MCSectionCOFF.h"
55#include "llvm/MC/MCStreamer.h"
56#include "llvm/MC/MCSymbol.h"
57#include "llvm/Support/BinaryStreamWriter.h"
58#include "llvm/Support/Casting.h"
59#include "llvm/Support/Error.h"
60#include "llvm/Support/ErrorHandling.h"
61#include "llvm/Support/FormatVariadic.h"
62#include "llvm/Support/Path.h"
63#include "llvm/Support/SMLoc.h"
64#include "llvm/Support/ScopedPrinter.h"
65#include "llvm/Target/TargetLoweringObjectFile.h"
66#include "llvm/Target/TargetMachine.h"
67#include "llvm/TargetParser/Triple.h"
68#include <algorithm>
69#include <cassert>
70#include <cctype>
71#include <cstddef>
72#include <limits>
73
74using namespace llvm;
75using namespace llvm::codeview;
76
77static cl::opt<bool> UseTagRecord2(
78 "use-codeview-tagrecord2", cl::Hidden,
79 cl::desc(
80 "Use the *2 versions for tag records in CodeView (LF_CLASS2, etc.)"),
81 cl::init(Val: false));
82
83namespace {
84class CVMCAdapter : public CodeViewRecordStreamer {
85public:
86 CVMCAdapter(MCStreamer &OS, TypeCollection &TypeTable)
87 : OS(&OS), TypeTable(TypeTable) {}
88
89 void emitBytes(StringRef Data) override { OS->emitBytes(Data); }
90
91 void emitIntValue(uint64_t Value, unsigned Size) override {
92 OS->emitIntValueInHex(Value, Size);
93 }
94
95 void emitBinaryData(StringRef Data) override { OS->emitBinaryData(Data); }
96
97 void AddComment(const Twine &T) override { OS->AddComment(T); }
98
99 void AddRawComment(const Twine &T) override { OS->emitRawComment(T); }
100
101 bool isVerboseAsm() override { return OS->isVerboseAsm(); }
102
103 std::string getTypeName(TypeIndex TI) override {
104 std::string TypeName;
105 if (!TI.isNoneType()) {
106 if (TI.isSimple())
107 TypeName = std::string(TypeIndex::simpleTypeName(TI));
108 else
109 TypeName = std::string(TypeTable.getTypeName(Index: TI));
110 }
111 return TypeName;
112 }
113
114private:
115 MCStreamer *OS = nullptr;
116 TypeCollection &TypeTable;
117};
118} // namespace
119
120static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
121 switch (Type) {
122 case Triple::ArchType::x86:
123 return CPUType::Pentium3;
124 case Triple::ArchType::x86_64:
125 return CPUType::X64;
126 case Triple::ArchType::thumb:
127 // LLVM currently doesn't support Windows CE and so thumb
128 // here is indiscriminately mapped to ARMNT specifically.
129 return CPUType::ARMNT;
130 case Triple::ArchType::aarch64:
131 return CPUType::ARM64;
132 case Triple::ArchType::mipsel:
133 return CPUType::MIPS;
134 case Triple::ArchType::UnknownArch:
135 return CPUType::Unknown;
136 default:
137 report_fatal_error(reason: "target architecture doesn't map to a CodeView CPUType");
138 }
139}
140
141CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
142 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {}
143
144StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
145 std::string &Filepath = FileToFilepathMap[File];
146 if (!Filepath.empty())
147 return Filepath;
148
149 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
150
151 // If this is a Unix-style path, just use it as is. Don't try to canonicalize
152 // it textually because one of the path components could be a symlink.
153 if (Dir.starts_with(Prefix: "/") || Filename.starts_with(Prefix: "/")) {
154 if (llvm::sys::path::is_absolute(path: Filename, style: llvm::sys::path::Style::posix))
155 return Filename;
156 Filepath = std::string(Dir);
157 if (Dir.back() != '/')
158 Filepath += '/';
159 Filepath += Filename;
160 return Filepath;
161 }
162
163 // Clang emits directory and relative filename info into the IR, but CodeView
164 // operates on full paths. We could change Clang to emit full paths too, but
165 // that would increase the IR size and probably not needed for other users.
166 // For now, just concatenate and canonicalize the path here.
167 if (Filename.find(C: ':') == 1)
168 Filepath = std::string(Filename);
169 else
170 Filepath = (Dir + "\\" + Filename).str();
171
172 // Canonicalize the path. We have to do it textually because we may no longer
173 // have access the file in the filesystem.
174 // First, replace all slashes with backslashes.
175 llvm::replace(Range&: Filepath, OldValue: '/', NewValue: '\\');
176
177 // Remove all "\.\" with "\".
178 size_t Cursor = 0;
179 while ((Cursor = Filepath.find(s: "\\.\\", pos: Cursor)) != std::string::npos)
180 Filepath.erase(pos: Cursor, n: 2);
181
182 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
183 // path should be well-formatted, e.g. start with a drive letter, etc.
184 Cursor = 0;
185 while ((Cursor = Filepath.find(s: "\\..\\", pos: Cursor)) != std::string::npos) {
186 // Something's wrong if the path starts with "\..\", abort.
187 if (Cursor == 0)
188 break;
189
190 size_t PrevSlash = Filepath.rfind(c: '\\', pos: Cursor - 1);
191 if (PrevSlash == std::string::npos)
192 // Something's wrong, abort.
193 break;
194
195 Filepath.erase(pos: PrevSlash, n: Cursor + 3 - PrevSlash);
196 // The next ".." might be following the one we've just erased.
197 Cursor = PrevSlash;
198 }
199
200 // Remove all duplicate backslashes.
201 Cursor = 0;
202 while ((Cursor = Filepath.find(s: "\\\\", pos: Cursor)) != std::string::npos)
203 Filepath.erase(pos: Cursor, n: 1);
204
205 return Filepath;
206}
207
208unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
209 StringRef FullPath = getFullFilepath(File: F);
210 unsigned NextId = FileIdMap.size() + 1;
211 auto Insertion = FileIdMap.insert(KV: std::make_pair(x&: FullPath, y&: NextId));
212 if (Insertion.second) {
213 // We have to compute the full filepath and emit a .cv_file directive.
214 ArrayRef<uint8_t> ChecksumAsBytes;
215 FileChecksumKind CSKind = FileChecksumKind::None;
216 if (F->getChecksum()) {
217 std::string Checksum = fromHex(Input: F->getChecksum()->Value);
218 void *CKMem = OS.getContext().allocate(Size: Checksum.size(), Align: 1);
219 memcpy(dest: CKMem, src: Checksum.data(), n: Checksum.size());
220 ChecksumAsBytes = ArrayRef<uint8_t>(
221 reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
222 switch (F->getChecksum()->Kind) {
223 case DIFile::CSK_MD5:
224 CSKind = FileChecksumKind::MD5;
225 break;
226 case DIFile::CSK_SHA1:
227 CSKind = FileChecksumKind::SHA1;
228 break;
229 case DIFile::CSK_SHA256:
230 CSKind = FileChecksumKind::SHA256;
231 break;
232 }
233 }
234 bool Success = OS.emitCVFileDirective(FileNo: NextId, Filename: FullPath, Checksum: ChecksumAsBytes,
235 ChecksumKind: static_cast<unsigned>(CSKind));
236 (void)Success;
237 assert(Success && ".cv_file directive failed");
238 }
239 return Insertion.first->second;
240}
241
242CodeViewDebug::InlineSite &
243CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
244 const DISubprogram *Inlinee) {
245 auto SiteInsertion = CurFn->InlineSites.try_emplace(k: InlinedAt);
246 InlineSite *Site = &SiteInsertion.first->second;
247 if (SiteInsertion.second) {
248 unsigned ParentFuncId = CurFn->FuncId;
249 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
250 ParentFuncId =
251 getInlineSite(InlinedAt: OuterIA, Inlinee: InlinedAt->getScope()->getSubprogram())
252 .SiteFuncId;
253
254 Site->SiteFuncId = NextFuncId++;
255 OS.emitCVInlineSiteIdDirective(
256 FunctionId: Site->SiteFuncId, IAFunc: ParentFuncId, IAFile: maybeRecordFile(F: InlinedAt->getFile()),
257 IALine: InlinedAt->getLine(), IACol: InlinedAt->getColumn(), Loc: SMLoc());
258 Site->Inlinee = Inlinee;
259 InlinedSubprograms.insert(X: Inlinee);
260 auto InlineeIdx = getFuncIdForSubprogram(SP: Inlinee);
261
262 if (InlinedAt->getInlinedAt() == nullptr)
263 CurFn->Inlinees.insert(V: InlineeIdx);
264 }
265 return *Site;
266}
267
268static StringRef getPrettyScopeName(const DIScope *Scope) {
269 StringRef ScopeName = Scope->getName();
270 if (!ScopeName.empty())
271 return ScopeName;
272
273 switch (Scope->getTag()) {
274 case dwarf::DW_TAG_enumeration_type:
275 case dwarf::DW_TAG_class_type:
276 case dwarf::DW_TAG_structure_type:
277 case dwarf::DW_TAG_union_type:
278 return "<unnamed-tag>";
279 case dwarf::DW_TAG_namespace:
280 return "`anonymous namespace'";
281 default:
282 return StringRef();
283 }
284}
285
286const DISubprogram *CodeViewDebug::collectParentScopeNames(
287 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
288 const DISubprogram *ClosestSubprogram = nullptr;
289 while (Scope != nullptr) {
290 if (ClosestSubprogram == nullptr)
291 ClosestSubprogram = dyn_cast<DISubprogram>(Val: Scope);
292
293 // If a type appears in a scope chain, make sure it gets emitted. The
294 // frontend will be responsible for deciding if this should be a forward
295 // declaration or a complete type.
296 if (const auto *Ty = dyn_cast<DICompositeType>(Val: Scope))
297 DeferredCompleteTypes.push_back(Elt: Ty);
298
299 StringRef ScopeName = getPrettyScopeName(Scope);
300 if (!ScopeName.empty())
301 QualifiedNameComponents.push_back(Elt: ScopeName);
302 Scope = Scope->getScope();
303 }
304 return ClosestSubprogram;
305}
306
307static std::string formatNestedName(ArrayRef<StringRef> QualifiedNameComponents,
308 StringRef TypeName) {
309 std::string FullyQualifiedName;
310 for (StringRef QualifiedNameComponent :
311 llvm::reverse(C&: QualifiedNameComponents)) {
312 FullyQualifiedName.append(str: std::string(QualifiedNameComponent));
313 FullyQualifiedName.append(s: "::");
314 }
315 FullyQualifiedName.append(str: std::string(TypeName));
316 return FullyQualifiedName;
317}
318
319struct CodeViewDebug::TypeLoweringScope {
320 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
321 ~TypeLoweringScope() {
322 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
323 // inner TypeLoweringScopes don't attempt to emit deferred types.
324 if (CVD.TypeEmissionLevel == 1)
325 CVD.emitDeferredCompleteTypes();
326 --CVD.TypeEmissionLevel;
327 }
328 CodeViewDebug &CVD;
329};
330
331std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Scope,
332 StringRef Name) {
333 // Ensure types in the scope chain are emitted as soon as possible.
334 // This can create otherwise a situation where S_UDTs are emitted while
335 // looping in emitDebugInfoForUDTs.
336 TypeLoweringScope S(*this);
337 SmallVector<StringRef, 5> QualifiedNameComponents;
338 collectParentScopeNames(Scope, QualifiedNameComponents);
339 return formatNestedName(QualifiedNameComponents, TypeName: Name);
340}
341
342std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Ty) {
343 const DIScope *Scope = Ty->getScope();
344 return getFullyQualifiedName(Scope, Name: getPrettyScopeName(Scope: Ty));
345}
346
347TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
348 // No scope means global scope and that uses the zero index.
349 //
350 // We also use zero index when the scope is a DISubprogram
351 // to suppress the emission of LF_STRING_ID for the function,
352 // which can trigger a link-time error with the linker in
353 // VS2019 version 16.11.2 or newer.
354 // Note, however, skipping the debug info emission for the DISubprogram
355 // is a temporary fix. The root issue here is that we need to figure out
356 // the proper way to encode a function nested in another function
357 // (as introduced by the Fortran 'contains' keyword) in CodeView.
358 if (!Scope || isa<DIFile>(Val: Scope) || isa<DISubprogram>(Val: Scope))
359 return TypeIndex();
360
361 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
362
363 // Check if we've already translated this scope.
364 auto I = TypeIndices.find(Val: {Scope, nullptr});
365 if (I != TypeIndices.end())
366 return I->second;
367
368 // Build the fully qualified name of the scope.
369 std::string ScopeName = getFullyQualifiedName(Ty: Scope);
370 StringIdRecord SID(TypeIndex(), ScopeName);
371 auto TI = TypeTable.writeLeafType(Record&: SID);
372 return recordTypeIndexForDINode(Node: Scope, TI);
373}
374
375static StringRef removeTemplateArgs(StringRef Name) {
376 // Remove template args from the display name. Assume that the template args
377 // are the last thing in the name.
378 if (Name.empty() || Name.back() != '>')
379 return Name;
380
381 int OpenBrackets = 0;
382 for (int i = Name.size() - 1; i >= 0; --i) {
383 if (Name[i] == '>')
384 ++OpenBrackets;
385 else if (Name[i] == '<') {
386 --OpenBrackets;
387 if (OpenBrackets == 0)
388 return Name.substr(Start: 0, N: i);
389 }
390 }
391 return Name;
392}
393
394TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
395 assert(SP);
396
397 // Check if we've already translated this subprogram.
398 auto I = TypeIndices.find(Val: {SP, nullptr});
399 if (I != TypeIndices.end())
400 return I->second;
401
402 // The display name includes function template arguments. Drop them to match
403 // MSVC. We need to have the template arguments in the DISubprogram name
404 // because they are used in other symbol records, such as S_GPROC32_IDs.
405 StringRef DisplayName = removeTemplateArgs(Name: SP->getName());
406
407 const DIScope *Scope = SP->getScope();
408 TypeIndex TI;
409 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Val: Scope)) {
410 // If the scope is a DICompositeType, then this must be a method. Member
411 // function types take some special handling, and require access to the
412 // subprogram.
413 TypeIndex ClassType = getTypeIndex(Ty: Class);
414 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
415 DisplayName);
416 TI = TypeTable.writeLeafType(Record&: MFuncId);
417 } else {
418 // Otherwise, this must be a free function.
419 TypeIndex ParentScope = getScopeIndex(Scope);
420 FuncIdRecord FuncId(ParentScope, getTypeIndex(Ty: SP->getType()), DisplayName);
421 TI = TypeTable.writeLeafType(Record&: FuncId);
422 }
423
424 return recordTypeIndexForDINode(Node: SP, TI);
425}
426
427static bool isNonTrivial(const DICompositeType *DCTy) {
428 return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
429}
430
431static FunctionOptions
432getFunctionOptions(const DISubroutineType *Ty,
433 const DICompositeType *ClassTy = nullptr,
434 StringRef SPName = StringRef("")) {
435 FunctionOptions FO = FunctionOptions::None;
436 const DIType *ReturnTy = nullptr;
437 if (auto TypeArray = Ty->getTypeArray()) {
438 if (TypeArray.size())
439 ReturnTy = TypeArray[0];
440 }
441
442 // Add CxxReturnUdt option to functions that return nontrivial record types
443 // or methods that return record types.
444 if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(Val: ReturnTy))
445 if (isNonTrivial(DCTy: ReturnDCTy) || ClassTy)
446 FO |= FunctionOptions::CxxReturnUdt;
447
448 // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
449 if (ClassTy && isNonTrivial(DCTy: ClassTy) && SPName == ClassTy->getName()) {
450 FO |= FunctionOptions::Constructor;
451
452 // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
453
454 }
455 return FO;
456}
457
458TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
459 const DICompositeType *Class) {
460 // Always use the method declaration as the key for the function type. The
461 // method declaration contains the this adjustment.
462 if (SP->getDeclaration())
463 SP = SP->getDeclaration();
464 assert(!SP->getDeclaration() && "should use declaration as key");
465
466 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
467 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
468 auto I = TypeIndices.find(Val: {SP, Class});
469 if (I != TypeIndices.end())
470 return I->second;
471
472 // Make sure complete type info for the class is emitted *after* the member
473 // function type, as the complete class type is likely to reference this
474 // member function type.
475 TypeLoweringScope S(*this);
476 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
477
478 FunctionOptions FO = getFunctionOptions(Ty: SP->getType(), ClassTy: Class, SPName: SP->getName());
479 TypeIndex TI = lowerTypeMemberFunction(
480 Ty: SP->getType(), ClassTy: Class, ThisAdjustment: SP->getThisAdjustment(), IsStaticMethod, FO);
481 return recordTypeIndexForDINode(Node: SP, TI, ClassTy: Class);
482}
483
484TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
485 TypeIndex TI,
486 const DIType *ClassTy) {
487 auto InsertResult = TypeIndices.insert(KV: {{Node, ClassTy}, TI});
488 (void)InsertResult;
489 assert(InsertResult.second && "DINode was already assigned a type index");
490 return TI;
491}
492
493unsigned CodeViewDebug::getPointerSizeInBytes() {
494 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
495}
496
497void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
498 const LexicalScope *LS) {
499 if (const DILocation *InlinedAt = LS->getInlinedAt()) {
500 // This variable was inlined. Associate it with the InlineSite.
501 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
502 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
503 Site.InlinedLocals.emplace_back(Args: std::move(Var));
504 } else {
505 // This variable goes into the corresponding lexical scope.
506 ScopeVariables[LS].emplace_back(Args: std::move(Var));
507 }
508}
509
510static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
511 const DILocation *Loc) {
512 if (!llvm::is_contained(Range&: Locs, Element: Loc))
513 Locs.push_back(Elt: Loc);
514}
515
516void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
517 const MachineFunction *MF) {
518 // Skip this instruction if it has the same location as the previous one.
519 if (!DL || DL == PrevInstLoc)
520 return;
521
522 const DIScope *Scope = DL->getScope();
523 if (!Scope)
524 return;
525
526 // Skip this line if it is longer than the maximum we can record.
527 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
528 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
529 LI.isNeverStepInto())
530 return;
531
532 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
533 if (CI.getStartColumn() != DL.getCol())
534 return;
535
536 if (!CurFn->HaveLineInfo)
537 CurFn->HaveLineInfo = true;
538 unsigned FileId = 0;
539 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
540 FileId = CurFn->LastFileId;
541 else
542 FileId = CurFn->LastFileId = maybeRecordFile(F: DL->getFile());
543 PrevInstLoc = DL;
544
545 unsigned FuncId = CurFn->FuncId;
546 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
547 const DILocation *Loc = DL.get();
548
549 // If this location was actually inlined from somewhere else, give it the ID
550 // of the inline call site.
551 FuncId =
552 getInlineSite(InlinedAt: SiteLoc, Inlinee: Loc->getScope()->getSubprogram()).SiteFuncId;
553
554 // Ensure we have links in the tree of inline call sites.
555 bool FirstLoc = true;
556 while ((SiteLoc = Loc->getInlinedAt())) {
557 InlineSite &Site =
558 getInlineSite(InlinedAt: SiteLoc, Inlinee: Loc->getScope()->getSubprogram());
559 if (!FirstLoc)
560 addLocIfNotPresent(Locs&: Site.ChildSites, Loc);
561 FirstLoc = false;
562 Loc = SiteLoc;
563 }
564 addLocIfNotPresent(Locs&: CurFn->ChildSites, Loc);
565 }
566
567 OS.emitCVLocDirective(FunctionId: FuncId, FileNo: FileId, Line: DL.getLine(), Column: DL.getCol(),
568 /*PrologueEnd=*/false, /*IsStmt=*/false,
569 FileName: DL->getFilename(), Loc: SMLoc());
570}
571
572void CodeViewDebug::emitCodeViewMagicVersion() {
573 OS.emitValueToAlignment(Alignment: Align(4));
574 OS.AddComment(T: "Debug section magic");
575 OS.emitInt32(Value: COFF::DEBUG_SECTION_MAGIC);
576}
577
578static SourceLanguage
579MapDWARFLanguageToCVLang(dwarf::SourceLanguageName DWLName) {
580 switch (DWLName) {
581 case dwarf::DW_LNAME_C:
582 return SourceLanguage::C;
583 case dwarf::DW_LNAME_C_plus_plus:
584 return SourceLanguage::Cpp;
585 case dwarf::DW_LNAME_Fortran:
586 return SourceLanguage::Fortran;
587 case dwarf::DW_LNAME_Pascal:
588 return SourceLanguage::Pascal;
589 case dwarf::DW_LNAME_Cobol:
590 return SourceLanguage::Cobol;
591 case dwarf::DW_LNAME_Java:
592 return SourceLanguage::Java;
593 case dwarf::DW_LNAME_D:
594 return SourceLanguage::D;
595 case dwarf::DW_LNAME_Swift:
596 return SourceLanguage::Swift;
597 case dwarf::DW_LNAME_Rust:
598 return SourceLanguage::Rust;
599 case dwarf::DW_LNAME_ObjC:
600 return SourceLanguage::ObjC;
601 case dwarf::DW_LNAME_ObjC_plus_plus:
602 return SourceLanguage::ObjCpp;
603 default:
604 // There's no CodeView representation for this language, and CV doesn't
605 // have an "unknown" option for the language field, so we'll use MASM,
606 // as it's very low level.
607 return SourceLanguage::Masm;
608 }
609}
610
611static SourceLanguage MapDWARFLanguageToCVLang(dwarf::SourceLanguage DWLang) {
612 auto MaybeLName = dwarf::toDW_LNAME(language: DWLang);
613 if (!MaybeLName)
614 return MapDWARFLanguageToCVLang(DWLName: static_cast<dwarf::SourceLanguageName>(0));
615
616 return MapDWARFLanguageToCVLang(DWLName: MaybeLName->first);
617}
618
619void CodeViewDebug::beginModule(Module *M) {
620 // If COFF debug section is not available, skip any debug info related stuff.
621 if (!Asm->getObjFileLowering().getCOFFDebugSymbolsSection()) {
622 Asm = nullptr;
623 return;
624 }
625
626 CompilerInfoAsm = Asm;
627 TheCPU = mapArchToCVCPUType(Type: M->getTargetTriple().getArch());
628
629 // Get the current source language.
630 const MDNode *Node;
631 if (Asm->hasDebugInfo()) {
632 Node = *M->debug_compile_units_begin();
633 } else {
634 // When emitting only compiler information, we may have only NoDebug CUs,
635 // which would be skipped by debug_compile_units_begin.
636 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata(Name: "llvm.dbg.cu");
637 if (CUs->operands().empty()) {
638 Asm = nullptr;
639 return;
640 }
641 Node = *CUs->operands().begin();
642 }
643
644 TheCU = cast<DICompileUnit>(Val: Node);
645 DISourceLanguageName Lang = TheCU->getSourceLanguage();
646 CurrentSourceLanguage =
647 Lang.hasVersionedName()
648 ? MapDWARFLanguageToCVLang(
649 DWLName: static_cast<dwarf::SourceLanguageName>(Lang.getName()))
650 : MapDWARFLanguageToCVLang(
651 DWLang: static_cast<dwarf::SourceLanguage>(Lang.getName()));
652 if (!M->getCodeViewFlag() ||
653 TheCU->getEmissionKind() == DICompileUnit::NoDebug) {
654 Asm = nullptr;
655 return;
656 }
657
658 collectGlobalVariableInfo();
659
660 // Check if we should emit type record hashes.
661 ConstantInt *GH =
662 mdconst::extract_or_null<ConstantInt>(MD: M->getModuleFlag(Key: "CodeViewGHash"));
663 EmitDebugGlobalHashes = GH && !GH->isZero();
664}
665
666void CodeViewDebug::endModule() {
667 if (!CompilerInfoAsm)
668 return;
669
670 // The COFF .debug$S section consists of several subsections, each starting
671 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
672 // of the payload followed by the payload itself. The subsections are 4-byte
673 // aligned.
674
675 // Use the generic .debug$S section, and make a subsection for all the inlined
676 // subprograms.
677 switchToDebugSectionForSymbol(GVSym: nullptr);
678
679 MCSymbol *CompilerInfo = beginCVSubsection(Kind: DebugSubsectionKind::Symbols);
680 emitObjName();
681 emitCompilerInformation();
682 endCVSubsection(EndLabel: CompilerInfo);
683 if (!Asm)
684 return;
685
686 emitSecureHotPatchInformation();
687
688 emitInlineeLinesSubsection();
689
690 // Emit per-function debug information.
691 for (auto &P : FnDebugInfo)
692 if (!P.first->isDeclarationForLinker())
693 emitDebugInfoForFunction(GV: P.first, FI&: *P.second);
694
695 // Get types used by globals without emitting anything.
696 // This is meant to collect all static const data members so they can be
697 // emitted as globals.
698 collectDebugInfoForGlobals();
699
700 // Emit retained types.
701 emitDebugInfoForRetainedTypes();
702
703 // Emit global variable debug information.
704 setCurrentSubprogram(nullptr);
705 emitDebugInfoForGlobals();
706
707 // Switch back to the generic .debug$S section after potentially processing
708 // comdat symbol sections.
709 switchToDebugSectionForSymbol(GVSym: nullptr);
710
711 // Emit UDT records for any types used by global variables.
712 if (!GlobalUDTs.empty()) {
713 MCSymbol *SymbolsEnd = beginCVSubsection(Kind: DebugSubsectionKind::Symbols);
714 emitDebugInfoForUDTs(UDTs: GlobalUDTs);
715 endCVSubsection(EndLabel: SymbolsEnd);
716 }
717
718 // This subsection holds a file index to offset in string table table.
719 OS.AddComment(T: "File index to string table offset subsection");
720 OS.emitCVFileChecksumsDirective();
721
722 // This subsection holds the string table.
723 OS.AddComment(T: "String table");
724 OS.emitCVStringTableDirective();
725
726 // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
727 // subsection in the generic .debug$S section at the end. There is no
728 // particular reason for this ordering other than to match MSVC.
729 emitBuildInfo();
730
731 // Emit type information and hashes last, so that any types we translate while
732 // emitting function info are included.
733 emitTypeInformation();
734
735 if (EmitDebugGlobalHashes)
736 emitTypeGlobalHashes();
737
738 clear();
739}
740
741static void
742emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
743 unsigned MaxFixedRecordLength = 0xF00) {
744 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
745 // after a fixed length portion of the record. The fixed length portion should
746 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
747 // overall record size is less than the maximum allowed.
748 SmallString<32> NullTerminatedString(
749 S.take_front(N: MaxRecordLength - MaxFixedRecordLength - 1));
750 NullTerminatedString.push_back(Elt: '\0');
751 OS.emitBytes(Data: NullTerminatedString);
752}
753
754void CodeViewDebug::emitTypeInformation() {
755 if (TypeTable.empty())
756 return;
757
758 // Start the .debug$T or .debug$P section with 0x4.
759 OS.switchSection(Section: Asm->getObjFileLowering().getCOFFDebugTypesSection());
760 emitCodeViewMagicVersion();
761
762 TypeTableCollection Table(TypeTable.records());
763 TypeVisitorCallbackPipeline Pipeline;
764
765 // To emit type record using Codeview MCStreamer adapter
766 CVMCAdapter CVMCOS(OS, Table);
767 TypeRecordMapping typeMapping(CVMCOS);
768 Pipeline.addCallbackToPipeline(Callbacks&: typeMapping);
769
770 std::optional<TypeIndex> B = Table.getFirst();
771 while (B) {
772 // This will fail if the record data is invalid.
773 CVType Record = Table.getType(Index: *B);
774
775 Error E = codeview::visitTypeRecord(Record, Index: *B, Callbacks&: Pipeline);
776
777 if (E) {
778 logAllUnhandledErrors(E: std::move(E), OS&: errs(), ErrorBanner: "error: ");
779 llvm_unreachable("produced malformed type record");
780 }
781
782 B = Table.getNext(Prev: *B);
783 }
784}
785
786void CodeViewDebug::emitTypeGlobalHashes() {
787 if (TypeTable.empty())
788 return;
789
790 // Start the .debug$H section with the version and hash algorithm, currently
791 // hardcoded to version 0, SHA1.
792 OS.switchSection(Section: Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
793
794 OS.emitValueToAlignment(Alignment: Align(4));
795 OS.AddComment(T: "Magic");
796 OS.emitInt32(Value: COFF::DEBUG_HASHES_SECTION_MAGIC);
797 OS.AddComment(T: "Section Version");
798 OS.emitInt16(Value: 0);
799 OS.AddComment(T: "Hash Algorithm");
800 OS.emitInt16(Value: uint16_t(GlobalTypeHashAlg::BLAKE3));
801
802 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
803 for (const auto &GHR : TypeTable.hashes()) {
804 if (OS.isVerboseAsm()) {
805 // Emit an EOL-comment describing which TypeIndex this hash corresponds
806 // to, as well as the stringified SHA1 hash.
807 SmallString<32> Comment;
808 raw_svector_ostream CommentOS(Comment);
809 CommentOS << formatv(Fmt: "{0:X+} [{1}]", Vals: TI.getIndex(), Vals: GHR);
810 OS.AddComment(T: Comment);
811 ++TI;
812 }
813 assert(GHR.Hash.size() == 8);
814 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
815 GHR.Hash.size());
816 OS.emitBinaryData(Data: S);
817 }
818}
819
820void CodeViewDebug::emitObjName() {
821 MCSymbol *CompilerEnd = beginSymbolRecord(Kind: SymbolKind::S_OBJNAME);
822
823 StringRef PathRef(CompilerInfoAsm->TM.Options.ObjectFilenameForDebug);
824 llvm::SmallString<256> PathStore(PathRef);
825
826 if (PathRef.empty() || PathRef == "-") {
827 // Don't emit the filename if we're writing to stdout or to /dev/null.
828 PathRef = {};
829 } else {
830 PathRef = PathStore;
831 }
832
833 OS.AddComment(T: "Signature");
834 OS.emitIntValue(Value: 0, Size: 4);
835
836 OS.AddComment(T: "Object name");
837 emitNullTerminatedSymbolName(OS, S: PathRef);
838
839 endSymbolRecord(SymEnd: CompilerEnd);
840}
841
842void CodeViewDebug::emitSecureHotPatchInformation() {
843 MCSymbol *hotPatchInfo = nullptr;
844
845 for (const auto &F : MMI->getModule()->functions()) {
846 if (!F.isDeclarationForLinker() &&
847 F.hasFnAttribute(Kind: "marked_for_windows_hot_patching")) {
848 if (hotPatchInfo == nullptr)
849 hotPatchInfo = beginCVSubsection(Kind: DebugSubsectionKind::Symbols);
850 MCSymbol *HotPatchEnd = beginSymbolRecord(Kind: SymbolKind::S_HOTPATCHFUNC);
851 auto *SP = F.getSubprogram();
852 OS.AddComment(T: "Function");
853 OS.emitInt32(Value: getFuncIdForSubprogram(SP).getIndex());
854 OS.AddComment(T: "Name");
855 emitNullTerminatedSymbolName(OS, S: F.getName());
856 endSymbolRecord(SymEnd: HotPatchEnd);
857 }
858 }
859
860 if (hotPatchInfo != nullptr)
861 endCVSubsection(EndLabel: hotPatchInfo);
862}
863
864namespace {
865struct Version {
866 int Part[4];
867};
868} // end anonymous namespace
869
870// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
871// the version number.
872static Version parseVersion(StringRef Name) {
873 Version V = {.Part: {0}};
874 int N = 0;
875 for (const char C : Name) {
876 if (isdigit(C)) {
877 V.Part[N] *= 10;
878 V.Part[N] += C - '0';
879 V.Part[N] =
880 std::min<int>(a: V.Part[N], b: std::numeric_limits<uint16_t>::max());
881 } else if (C == '.') {
882 ++N;
883 if (N >= 4)
884 return V;
885 } else if (N > 0)
886 return V;
887 }
888 return V;
889}
890
891void CodeViewDebug::emitCompilerInformation() {
892 MCSymbol *CompilerEnd = beginSymbolRecord(Kind: SymbolKind::S_COMPILE3);
893 uint32_t Flags = 0;
894
895 // The low byte of the flags indicates the source language.
896 Flags = CurrentSourceLanguage;
897 // TODO: Figure out which other flags need to be set.
898 if (MMI->getModule()->getProfileSummary(/*IsCS*/ false) != nullptr) {
899 Flags |= static_cast<uint32_t>(CompileSym3Flags::PGO);
900 }
901 using ArchType = llvm::Triple::ArchType;
902 const Module *M = MMI->getModule();
903 ArchType Arch = M->getTargetTriple().getArch();
904 // The module flag survives LTO, and is reset to 0 if any merged module lacks
905 // it.
906 auto *HotpatchFlag =
907 mdconst::extract_or_null<ConstantInt>(MD: M->getModuleFlag(Key: "ms-hotpatch"));
908 if ((HotpatchFlag && HotpatchFlag->isOne()) || Arch == ArchType::thumb ||
909 Arch == ArchType::aarch64) {
910 Flags |= static_cast<uint32_t>(CompileSym3Flags::HotPatch);
911 }
912
913 OS.AddComment(T: "Flags and language");
914 OS.emitInt32(Value: Flags);
915
916 OS.AddComment(T: "CPUType");
917 OS.emitInt16(Value: static_cast<uint64_t>(TheCPU));
918
919 StringRef CompilerVersion = "0";
920 if (TheCU)
921 CompilerVersion = TheCU->getProducer();
922
923 Version FrontVer = parseVersion(Name: CompilerVersion);
924 OS.AddComment(T: "Frontend version");
925 for (int N : FrontVer.Part) {
926 OS.emitInt16(Value: N);
927 }
928
929 // Some Microsoft tools, like Binscope, expect a backend version number of at
930 // least 8.something, so we'll coerce the LLVM version into a form that
931 // guarantees it'll be big enough without really lying about the version.
932 int Major = 1000 * LLVM_VERSION_MAJOR +
933 10 * LLVM_VERSION_MINOR +
934 LLVM_VERSION_PATCH;
935 // Clamp it for builds that use unusually large version numbers.
936 Major = std::min<int>(a: Major, b: std::numeric_limits<uint16_t>::max());
937 Version BackVer = {.Part: { Major, 0, 0, 0 }};
938 OS.AddComment(T: "Backend version");
939 for (int N : BackVer.Part)
940 OS.emitInt16(Value: N);
941
942 OS.AddComment(T: "Null-terminated compiler version string");
943 emitNullTerminatedSymbolName(OS, S: CompilerVersion);
944
945 endSymbolRecord(SymEnd: CompilerEnd);
946}
947
948static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
949 StringRef S) {
950 StringIdRecord SIR(TypeIndex(0x0), S);
951 return TypeTable.writeLeafType(Record&: SIR);
952}
953
954void CodeViewDebug::emitBuildInfo() {
955 // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
956 // build info. The known prefix is:
957 // - Absolute path of current directory
958 // - Compiler path
959 // - Main source file path, relative to CWD or absolute
960 // - Type server PDB file
961 // - Canonical compiler command line
962 // If frontend and backend compilation are separated (think llc or LTO), it's
963 // not clear if the compiler path should refer to the executable for the
964 // frontend or the backend. Leave it blank for now.
965 TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
966 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata(Name: "llvm.dbg.cu");
967 const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
968 const auto *CU = cast<DICompileUnit>(Val: Node);
969 const DIFile *MainSourceFile = CU->getFile();
970 BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
971 getStringIdTypeIdx(TypeTable, S: MainSourceFile->getDirectory());
972 BuildInfoArgs[BuildInfoRecord::SourceFile] =
973 getStringIdTypeIdx(TypeTable, S: MainSourceFile->getFilename());
974 // FIXME: PDB is intentionally blank unless we implement /Zi type servers.
975 BuildInfoArgs[BuildInfoRecord::TypeServerPDB] =
976 getStringIdTypeIdx(TypeTable, S: "");
977 BuildInfoArgs[BuildInfoRecord::BuildTool] =
978 getStringIdTypeIdx(TypeTable, S: Asm->TM.Options.MCOptions.Argv0);
979 BuildInfoArgs[BuildInfoRecord::CommandLine] = getStringIdTypeIdx(
980 TypeTable, S: Asm->TM.Options.MCOptions.CommandlineArgs);
981
982 BuildInfoRecord BIR(BuildInfoArgs);
983 TypeIndex BuildInfoIndex = TypeTable.writeLeafType(Record&: BIR);
984
985 // Make a new .debug$S subsection for the S_BUILDINFO record, which points
986 // from the module symbols into the type stream.
987 MCSymbol *BISubsecEnd = beginCVSubsection(Kind: DebugSubsectionKind::Symbols);
988 MCSymbol *BIEnd = beginSymbolRecord(Kind: SymbolKind::S_BUILDINFO);
989 OS.AddComment(T: "LF_BUILDINFO index");
990 OS.emitInt32(Value: BuildInfoIndex.getIndex());
991 endSymbolRecord(SymEnd: BIEnd);
992 endCVSubsection(EndLabel: BISubsecEnd);
993}
994
995void CodeViewDebug::emitInlineeLinesSubsection() {
996 if (InlinedSubprograms.empty())
997 return;
998
999 OS.AddComment(T: "Inlinee lines subsection");
1000 MCSymbol *InlineEnd = beginCVSubsection(Kind: DebugSubsectionKind::InlineeLines);
1001
1002 // We emit the checksum info for files. This is used by debuggers to
1003 // determine if a pdb matches the source before loading it. Visual Studio,
1004 // for instance, will display a warning that the breakpoints are not valid if
1005 // the pdb does not match the source.
1006 OS.AddComment(T: "Inlinee lines signature");
1007 OS.emitInt32(Value: unsigned(InlineeLinesSignature::Normal));
1008
1009 for (const DISubprogram *SP : InlinedSubprograms) {
1010 assert(TypeIndices.count({SP, nullptr}));
1011 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
1012
1013 OS.addBlankLine();
1014 unsigned FileId = maybeRecordFile(F: SP->getFile());
1015 OS.AddComment(T: "Inlined function " + SP->getName() + " starts at " +
1016 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
1017 OS.addBlankLine();
1018 OS.AddComment(T: "Type index of inlined function");
1019 OS.emitInt32(Value: InlineeIdx.getIndex());
1020 OS.AddComment(T: "Offset into filechecksum table");
1021 OS.emitCVFileChecksumOffsetDirective(FileNo: FileId);
1022 OS.AddComment(T: "Starting line number");
1023 OS.emitInt32(Value: SP->getLine());
1024 }
1025
1026 endCVSubsection(EndLabel: InlineEnd);
1027}
1028
1029void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
1030 const DILocation *InlinedAt,
1031 const InlineSite &Site) {
1032 assert(TypeIndices.count({Site.Inlinee, nullptr}));
1033 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
1034
1035 // SymbolRecord
1036 MCSymbol *InlineEnd = beginSymbolRecord(Kind: SymbolKind::S_INLINESITE);
1037
1038 OS.AddComment(T: "PtrParent");
1039 OS.emitInt32(Value: 0);
1040 OS.AddComment(T: "PtrEnd");
1041 OS.emitInt32(Value: 0);
1042 OS.AddComment(T: "Inlinee type index");
1043 OS.emitInt32(Value: InlineeIdx.getIndex());
1044
1045 unsigned FileId = maybeRecordFile(F: Site.Inlinee->getFile());
1046 unsigned StartLineNum = Site.Inlinee->getLine();
1047
1048 OS.emitCVInlineLinetableDirective(PrimaryFunctionId: Site.SiteFuncId, SourceFileId: FileId, SourceLineNum: StartLineNum,
1049 FnStartSym: FI.Begin, FnEndSym: FI.End);
1050
1051 endSymbolRecord(SymEnd: InlineEnd);
1052
1053 emitLocalVariableList(FI, Locals: Site.InlinedLocals);
1054
1055 // Recurse on child inlined call sites before closing the scope.
1056 for (const DILocation *ChildSite : Site.ChildSites) {
1057 auto I = FI.InlineSites.find(x: ChildSite);
1058 assert(I != FI.InlineSites.end() &&
1059 "child site not in function inline site map");
1060 emitInlinedCallSite(FI, InlinedAt: ChildSite, Site: I->second);
1061 }
1062
1063 // Close the scope.
1064 emitEndSymbolRecord(EndKind: SymbolKind::S_INLINESITE_END);
1065}
1066
1067void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
1068 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
1069 // comdat key. A section may be comdat because of -ffunction-sections or
1070 // because it is comdat in the IR.
1071 MCSectionCOFF *GVSec =
1072 GVSym ? static_cast<MCSectionCOFF *>(&GVSym->getSection()) : nullptr;
1073 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
1074
1075 auto *DebugSec = static_cast<MCSectionCOFF *>(
1076 CompilerInfoAsm->getObjFileLowering().getCOFFDebugSymbolsSection());
1077 DebugSec = OS.getContext().getAssociativeCOFFSection(Sec: DebugSec, KeySym);
1078
1079 OS.switchSection(Section: DebugSec);
1080
1081 // Emit the magic version number if this is the first time we've switched to
1082 // this section.
1083 if (ComdatDebugSections.insert(V: DebugSec).second)
1084 emitCodeViewMagicVersion();
1085}
1086
1087// Emit an S_THUNK32/S_END symbol pair for a thunk routine.
1088// The only supported thunk ordinal is currently the standard type.
1089void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
1090 FunctionInfo &FI,
1091 const MCSymbol *Fn) {
1092 std::string FuncName =
1093 std::string(GlobalValue::dropLLVMManglingEscape(Name: GV->getName()));
1094 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
1095
1096 OS.AddComment(T: "Symbol subsection for " + Twine(FuncName));
1097 MCSymbol *SymbolsEnd = beginCVSubsection(Kind: DebugSubsectionKind::Symbols);
1098
1099 // Emit S_THUNK32
1100 MCSymbol *ThunkRecordEnd = beginSymbolRecord(Kind: SymbolKind::S_THUNK32);
1101 OS.AddComment(T: "PtrParent");
1102 OS.emitInt32(Value: 0);
1103 OS.AddComment(T: "PtrEnd");
1104 OS.emitInt32(Value: 0);
1105 OS.AddComment(T: "PtrNext");
1106 OS.emitInt32(Value: 0);
1107 OS.AddComment(T: "Thunk section relative address");
1108 OS.emitCOFFSecRel32(Symbol: Fn, /*Offset=*/0);
1109 OS.AddComment(T: "Thunk section index");
1110 OS.emitCOFFSectionIndex(Symbol: Fn);
1111 OS.AddComment(T: "Code size");
1112 OS.emitAbsoluteSymbolDiff(Hi: FI.End, Lo: Fn, Size: 2);
1113 OS.AddComment(T: "Ordinal");
1114 OS.emitInt8(Value: unsigned(ordinal));
1115 OS.AddComment(T: "Function name");
1116 emitNullTerminatedSymbolName(OS, S: FuncName);
1117 // Additional fields specific to the thunk ordinal would go here.
1118 endSymbolRecord(SymEnd: ThunkRecordEnd);
1119
1120 // Local variables/inlined routines are purposely omitted here. The point of
1121 // marking this as a thunk is so Visual Studio will NOT stop in this routine.
1122
1123 // Emit S_PROC_ID_END
1124 emitEndSymbolRecord(EndKind: SymbolKind::S_PROC_ID_END);
1125
1126 endCVSubsection(EndLabel: SymbolsEnd);
1127}
1128
1129void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
1130 FunctionInfo &FI) {
1131 // For each function there is a separate subsection which holds the PC to
1132 // file:line table.
1133 const MCSymbol *Fn = Asm->getSymbol(GV);
1134 assert(Fn);
1135
1136 // Switch to the to a comdat section, if appropriate.
1137 switchToDebugSectionForSymbol(GVSym: Fn);
1138
1139 std::string FuncName;
1140 auto *SP = GV->getSubprogram();
1141 assert(SP);
1142 setCurrentSubprogram(SP);
1143
1144 if (SP->isThunk()) {
1145 emitDebugInfoForThunk(GV, FI, Fn);
1146 return;
1147 }
1148
1149 // If we have a display name, build the fully qualified name by walking the
1150 // chain of scopes.
1151 if (!SP->getName().empty())
1152 FuncName = getFullyQualifiedName(Scope: SP->getScope(), Name: SP->getName());
1153
1154 // If our DISubprogram name is empty, use the mangled name.
1155 if (FuncName.empty())
1156 FuncName = std::string(GlobalValue::dropLLVMManglingEscape(Name: GV->getName()));
1157
1158 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
1159 if (MMI->getModule()->getTargetTriple().getArch() == Triple::x86)
1160 OS.emitCVFPOData(ProcSym: Fn);
1161
1162 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
1163 OS.AddComment(T: "Symbol subsection for " + Twine(FuncName));
1164 MCSymbol *SymbolsEnd = beginCVSubsection(Kind: DebugSubsectionKind::Symbols);
1165 {
1166 SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
1167 : SymbolKind::S_GPROC32_ID;
1168 MCSymbol *ProcRecordEnd = beginSymbolRecord(Kind: ProcKind);
1169
1170 // These fields are filled in by tools like CVPACK which run after the fact.
1171 OS.AddComment(T: "PtrParent");
1172 OS.emitInt32(Value: 0);
1173 OS.AddComment(T: "PtrEnd");
1174 OS.emitInt32(Value: 0);
1175 OS.AddComment(T: "PtrNext");
1176 OS.emitInt32(Value: 0);
1177 // This is the important bit that tells the debugger where the function
1178 // code is located and what's its size:
1179 OS.AddComment(T: "Code size");
1180 OS.emitAbsoluteSymbolDiff(Hi: FI.End, Lo: Fn, Size: 4);
1181 OS.AddComment(T: "Offset after prologue");
1182 OS.emitInt32(Value: 0);
1183 OS.AddComment(T: "Offset before epilogue");
1184 OS.emitInt32(Value: 0);
1185 OS.AddComment(T: "Function type index");
1186 OS.emitInt32(Value: getFuncIdForSubprogram(SP: GV->getSubprogram()).getIndex());
1187 OS.AddComment(T: "Function section relative address");
1188 OS.emitCOFFSecRel32(Symbol: Fn, /*Offset=*/0);
1189 OS.AddComment(T: "Function section index");
1190 OS.emitCOFFSectionIndex(Symbol: Fn);
1191 OS.AddComment(T: "Flags");
1192 ProcSymFlags ProcFlags = ProcSymFlags::HasOptimizedDebugInfo;
1193 if (FI.HasFramePointer)
1194 ProcFlags |= ProcSymFlags::HasFP;
1195 if (GV->hasFnAttribute(Kind: Attribute::NoReturn))
1196 ProcFlags |= ProcSymFlags::IsNoReturn;
1197 if (GV->hasFnAttribute(Kind: Attribute::NoInline))
1198 ProcFlags |= ProcSymFlags::IsNoInline;
1199 OS.emitInt8(Value: static_cast<uint8_t>(ProcFlags));
1200 // Emit the function display name as a null-terminated string.
1201 OS.AddComment(T: "Function name");
1202 // Truncate the name so we won't overflow the record length field.
1203 emitNullTerminatedSymbolName(OS, S: FuncName);
1204 endSymbolRecord(SymEnd: ProcRecordEnd);
1205
1206 MCSymbol *FrameProcEnd = beginSymbolRecord(Kind: SymbolKind::S_FRAMEPROC);
1207 // Subtract out the CSR size since MSVC excludes that and we include it.
1208 OS.AddComment(T: "FrameSize");
1209 OS.emitInt32(Value: FI.FrameSize - FI.CSRSize);
1210 OS.AddComment(T: "Padding");
1211 OS.emitInt32(Value: 0);
1212 OS.AddComment(T: "Offset of padding");
1213 OS.emitInt32(Value: 0);
1214 OS.AddComment(T: "Bytes of callee saved registers");
1215 OS.emitInt32(Value: FI.CSRSize);
1216 OS.AddComment(T: "Exception handler offset");
1217 OS.emitInt32(Value: 0);
1218 OS.AddComment(T: "Exception handler section");
1219 OS.emitInt16(Value: 0);
1220 OS.AddComment(T: "Flags (defines frame register)");
1221 OS.emitInt32(Value: uint32_t(FI.FrameProcOpts));
1222 endSymbolRecord(SymEnd: FrameProcEnd);
1223
1224 emitInlinees(Inlinees: FI.Inlinees);
1225 emitLocalVariableList(FI, Locals: FI.Locals);
1226 emitGlobalVariableList(Globals: FI.Globals);
1227 emitLexicalBlockList(Blocks: FI.ChildBlocks, FI);
1228
1229 // Emit inlined call site information. Only emit functions inlined directly
1230 // into the parent function. We'll emit the other sites recursively as part
1231 // of their parent inline site.
1232 for (const DILocation *InlinedAt : FI.ChildSites) {
1233 auto I = FI.InlineSites.find(x: InlinedAt);
1234 assert(I != FI.InlineSites.end() &&
1235 "child site not in function inline site map");
1236 emitInlinedCallSite(FI, InlinedAt, Site: I->second);
1237 }
1238
1239 for (auto Annot : FI.Annotations) {
1240 MCSymbol *Label = Annot.first;
1241 MDTuple *Strs = cast<MDTuple>(Val: Annot.second);
1242 MCSymbol *AnnotEnd = beginSymbolRecord(Kind: SymbolKind::S_ANNOTATION);
1243 OS.emitCOFFSecRel32(Symbol: Label, /*Offset=*/0);
1244 // FIXME: Make sure we don't overflow the max record size.
1245 OS.emitCOFFSectionIndex(Symbol: Label);
1246 OS.emitInt16(Value: Strs->getNumOperands());
1247 for (Metadata *MD : Strs->operands()) {
1248 // MDStrings are null terminated, so we can do EmitBytes and get the
1249 // nice .asciz directive.
1250 StringRef Str = cast<MDString>(Val: MD)->getString();
1251 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1252 OS.emitBytes(Data: StringRef(Str.data(), Str.size() + 1));
1253 }
1254 endSymbolRecord(SymEnd: AnnotEnd);
1255 }
1256
1257 for (auto HeapAllocSite : FI.HeapAllocSites) {
1258 const MCSymbol *BeginLabel = std::get<0>(t&: HeapAllocSite);
1259 const MCSymbol *EndLabel = std::get<1>(t&: HeapAllocSite);
1260 const DIType *DITy = std::get<2>(t&: HeapAllocSite);
1261 MCSymbol *HeapAllocEnd = beginSymbolRecord(Kind: SymbolKind::S_HEAPALLOCSITE);
1262 OS.AddComment(T: "Call site offset");
1263 OS.emitCOFFSecRel32(Symbol: BeginLabel, /*Offset=*/0);
1264 OS.AddComment(T: "Call site section index");
1265 OS.emitCOFFSectionIndex(Symbol: BeginLabel);
1266 OS.AddComment(T: "Call instruction length");
1267 OS.emitAbsoluteSymbolDiff(Hi: EndLabel, Lo: BeginLabel, Size: 2);
1268 OS.AddComment(T: "Type index");
1269 OS.emitInt32(Value: getCompleteTypeIndex(Ty: DITy).getIndex());
1270 endSymbolRecord(SymEnd: HeapAllocEnd);
1271 }
1272
1273 if (SP != nullptr)
1274 emitDebugInfoForUDTs(UDTs: LocalUDTs);
1275
1276 emitDebugInfoForJumpTables(FI);
1277
1278 // We're done with this function.
1279 emitEndSymbolRecord(EndKind: SymbolKind::S_PROC_ID_END);
1280 }
1281 endCVSubsection(EndLabel: SymbolsEnd);
1282
1283 // We have an assembler directive that takes care of the whole line table.
1284 OS.emitCVLinetableDirective(FunctionId: FI.FuncId, FnStart: Fn, FnEnd: FI.End);
1285}
1286
1287CodeViewDebug::LocalVarDef
1288CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset,
1289 int32_t DerefOffset) {
1290 LocalVarDef DR;
1291 DR.InMemory = -1;
1292 DR.DataOffset = Offset;
1293 assert(DR.DataOffset == Offset && "truncation");
1294 DR.IsSubfield = 0;
1295 DR.StructOffset = 0;
1296 DR.CVRegister = CVRegister;
1297 DR.DerefOffset = DerefOffset;
1298 return DR;
1299}
1300
1301void CodeViewDebug::collectVariableInfoFromMFTable(
1302 DenseSet<InlinedEntity> &Processed) {
1303 const MachineFunction &MF = *Asm->MF;
1304 const TargetSubtargetInfo &TSI = MF.getSubtarget();
1305 const TargetFrameLowering *TFI = TSI.getFrameLowering();
1306 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1307
1308 for (const MachineFunction::VariableDbgInfo &VI :
1309 MF.getInStackSlotVariableDbgInfo()) {
1310 if (!VI.Var)
1311 continue;
1312 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1313 "Expected inlined-at fields to agree");
1314
1315 Processed.insert(V: InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
1316 LexicalScope *Scope = LScopes.findLexicalScope(DL: VI.Loc);
1317
1318 // If variable scope is not found then skip this variable.
1319 if (!Scope)
1320 continue;
1321
1322 // If the variable has an attached offset expression, extract it.
1323 int64_t ExprOffset = 0;
1324 int64_t DerefOffset = LocalVarDef::NoDeref;
1325 if (VI.Expr) {
1326 SmallVector<uint64_t, 2> FirstRemaining;
1327 if (!VI.Expr->extractLeadingOffset(OffsetInBytes&: ExprOffset, RemainingOps&: FirstRemaining))
1328 continue;
1329 if (!FirstRemaining.empty()) {
1330 if (FirstRemaining.front() != dwarf::DW_OP_deref)
1331 continue;
1332 SmallVector<uint64_t, 1> LastRemaining;
1333 if (!DIExpression::extractLeadingOffset(
1334 Ops: ArrayRef(FirstRemaining).drop_front(), OffsetInBytes&: DerefOffset,
1335 RemainingOps&: LastRemaining))
1336 continue;
1337 if (!LastRemaining.empty())
1338 continue;
1339 }
1340 }
1341
1342 // Get the frame register used and the offset.
1343 Register FrameReg;
1344 StackOffset FrameOffset =
1345 TFI->getFrameIndexReference(MF: *Asm->MF, FI: VI.getStackSlot(), FrameReg);
1346 uint16_t CVReg = TRI->getCodeViewRegNum(Reg: FrameReg);
1347
1348 if (FrameOffset.getScalable()) {
1349 // No encoding currently exists for scalable offsets; bail out.
1350 continue;
1351 }
1352 if (DerefOffset < INT32_MIN || DerefOffset > INT32_MAX)
1353 continue;
1354
1355 // Calculate the label ranges.
1356 LocalVarDef DefRange =
1357 createDefRangeMem(CVRegister: CVReg, Offset: FrameOffset.getFixed() + ExprOffset,
1358 DerefOffset: static_cast<int32_t>(DerefOffset));
1359
1360 LocalVariable Var;
1361 Var.DIVar = VI.Var;
1362
1363 for (const InsnRange &Range : Scope->getRanges()) {
1364 const MCSymbol *Begin = getLabelBeforeInsn(MI: Range.first);
1365 const MCSymbol *End = getLabelAfterInsn(MI: Range.second);
1366 End = End ? End : Asm->getFunctionEnd();
1367 Var.DefRanges[DefRange].emplace_back(Args&: Begin, Args&: End);
1368 }
1369
1370 recordLocalVariable(Var: std::move(Var), LS: Scope);
1371 }
1372}
1373
1374void CodeViewDebug::calculateRanges(
1375 LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
1376 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1377
1378 // Calculate the definition ranges.
1379 for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
1380 const auto &Entry = *I;
1381 if (!Entry.isDbgValue())
1382 continue;
1383 const MachineInstr *DVInst = Entry.getInstr();
1384 assert(DVInst->isDebugValue() && "Invalid History entry");
1385 // FIXME: Find a way to represent constant variables, since they are
1386 // relatively common.
1387 std::optional<DbgVariableLocation> Location =
1388 DbgVariableLocation::extractFromMachineInstruction(Instruction: *DVInst);
1389 if (!Location)
1390 {
1391 // When we don't have a location this is usually because LLVM has
1392 // transformed it into a constant and we only have an llvm.dbg.value. We
1393 // can't represent these well in CodeView since S_LOCAL only works on
1394 // registers and memory locations. Instead, we will pretend this to be a
1395 // constant value to at least have it show up in the debugger.
1396 auto Op = DVInst->getDebugOperand(Index: 0);
1397 if (Op.isImm())
1398 Var.ConstantValue = APSInt(APInt(64, Op.getImm()), false);
1399 continue;
1400 }
1401
1402 // We can only handle a register, an offsetted load of a register, or an
1403 // indirect offsetted load.
1404 if (!Location->Register || Location->LoadChain.size() > 2)
1405 continue;
1406
1407 // Codeview can only express byte-aligned offsets, ensure that we have a
1408 // byte-boundaried location.
1409 if (Location->FragmentInfo)
1410 if (Location->FragmentInfo->OffsetInBits % 8)
1411 continue;
1412
1413 if (TRI->isIgnoredCVReg(LLVMReg: Location->Register)) {
1414 // No encoding currently exists for this register; bail out.
1415 continue;
1416 }
1417
1418 LocalVarDef DR;
1419 DR.CVRegister = TRI->getCodeViewRegNum(Reg: Location->Register);
1420 DR.InMemory = !Location->LoadChain.empty();
1421 DR.DataOffset = 0;
1422 DR.DerefOffset = LocalVarDef::NoDeref;
1423 if (!Location->LoadChain.empty()) {
1424 DR.DataOffset = Location->LoadChain[0];
1425 if (Location->LoadChain.size() >= 2)
1426 DR.DerefOffset = Location->LoadChain[1];
1427 }
1428 if (Location->FragmentInfo) {
1429 DR.IsSubfield = true;
1430 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
1431 } else {
1432 DR.IsSubfield = false;
1433 DR.StructOffset = 0;
1434 }
1435
1436 // Compute the label range.
1437 const MCSymbol *Begin = getLabelBeforeInsn(MI: Entry.getInstr());
1438 const MCSymbol *End;
1439 if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
1440 auto &EndingEntry = Entries[Entry.getEndIndex()];
1441 End = EndingEntry.isDbgValue()
1442 ? getLabelBeforeInsn(MI: EndingEntry.getInstr())
1443 : getLabelAfterInsn(MI: EndingEntry.getInstr());
1444 } else
1445 End = Asm->getFunctionEnd();
1446
1447 // If the last range end is our begin, just extend the last range.
1448 // Otherwise make a new range.
1449 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1450 Var.DefRanges[DR];
1451 if (!R.empty() && R.back().second == Begin)
1452 R.back().second = End;
1453 else
1454 R.emplace_back(Args&: Begin, Args&: End);
1455
1456 // FIXME: Do more range combining.
1457 }
1458}
1459
1460void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1461 DenseSet<InlinedEntity> Processed;
1462 // Grab the variable info that was squirreled away in the MMI side-table.
1463 collectVariableInfoFromMFTable(Processed);
1464
1465 for (const MDNode *N : SP->getRetainedNodes())
1466 if (const auto *GVE = dyn_cast<DIGlobalVariableExpression>(Val: N))
1467 collectGlobalOrStaticLocalVariableInfo(GVE);
1468
1469 for (const auto &I : DbgValues) {
1470 InlinedEntity IV = I.first;
1471 if (Processed.count(V: IV))
1472 continue;
1473 const DILocalVariable *DIVar = cast<DILocalVariable>(Val: IV.first);
1474 const DILocation *InlinedAt = IV.second;
1475
1476 // Instruction ranges, specifying where IV is accessible.
1477 const auto &Entries = I.second;
1478
1479 LexicalScope *Scope = nullptr;
1480 if (InlinedAt)
1481 Scope = LScopes.findInlinedScope(N: DIVar->getScope(), IA: InlinedAt);
1482 else
1483 Scope = LScopes.findLexicalScope(N: DIVar->getScope());
1484 // If variable scope is not found then skip this variable.
1485 if (!Scope)
1486 continue;
1487
1488 LocalVariable Var;
1489 Var.DIVar = DIVar;
1490
1491 calculateRanges(Var, Entries);
1492 recordLocalVariable(Var: std::move(Var), LS: Scope);
1493 }
1494}
1495
1496void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
1497 const TargetSubtargetInfo &TSI = MF->getSubtarget();
1498 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1499 const MachineFrameInfo &MFI = MF->getFrameInfo();
1500 const Function &GV = MF->getFunction();
1501 auto Insertion = FnDebugInfo.insert(KV: {&GV, std::make_unique<FunctionInfo>()});
1502 assert(Insertion.second && "function already has info");
1503 CurFn = Insertion.first->second.get();
1504 CurFn->FuncId = NextFuncId++;
1505 CurFn->Begin = Asm->getFunctionBegin();
1506
1507 // The S_FRAMEPROC record reports the stack size, and how many bytes of
1508 // callee-saved registers were used. For targets that don't use a PUSH
1509 // instruction (AArch64), this will be zero.
1510 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1511 CurFn->FrameSize = MFI.getStackSize();
1512 CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1513 CurFn->HasStackRealignment = TRI->hasStackRealignment(MF: *MF);
1514
1515 // For this function S_FRAMEPROC record, figure out which codeview register
1516 // will be the frame pointer.
1517 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1518 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1519 if (CurFn->FrameSize > 0) {
1520 if (!TSI.getFrameLowering()->hasFP(MF: *MF)) {
1521 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1522 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1523 } else {
1524 CurFn->HasFramePointer = true;
1525 // If there is an FP, parameters are always relative to it.
1526 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1527 if (CurFn->HasStackRealignment) {
1528 // If the stack needs realignment, locals are relative to SP or VFRAME.
1529 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1530 } else {
1531 // Otherwise, locals are relative to EBP, and we probably have VLAs or
1532 // other stack adjustments.
1533 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1534 }
1535 }
1536 }
1537
1538 // Compute other frame procedure options.
1539 FrameProcedureOptions FPO = FrameProcedureOptions::None;
1540 if (MFI.hasVarSizedObjects())
1541 FPO |= FrameProcedureOptions::HasAlloca;
1542 if (MF->exposesReturnsTwice())
1543 FPO |= FrameProcedureOptions::HasSetJmp;
1544 // FIXME: Set HasLongJmp if we ever track that info.
1545 if (MF->hasInlineAsm())
1546 FPO |= FrameProcedureOptions::HasInlineAssembly;
1547 if (GV.hasPersonalityFn()) {
1548 if (isAsynchronousEHPersonality(
1549 Pers: classifyEHPersonality(Pers: GV.getPersonalityFn())))
1550 FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1551 else
1552 FPO |= FrameProcedureOptions::HasExceptionHandling;
1553 }
1554 if (GV.hasFnAttribute(Kind: Attribute::InlineHint))
1555 FPO |= FrameProcedureOptions::MarkedInline;
1556 if (GV.hasFnAttribute(Kind: Attribute::Naked))
1557 FPO |= FrameProcedureOptions::Naked;
1558 if (MFI.hasStackProtectorIndex()) {
1559 FPO |= FrameProcedureOptions::SecurityChecks;
1560 if (GV.hasFnAttribute(Kind: Attribute::StackProtectStrong) ||
1561 GV.hasFnAttribute(Kind: Attribute::StackProtectReq)) {
1562 FPO |= FrameProcedureOptions::StrictSecurityChecks;
1563 }
1564 } else if (!GV.hasStackProtectorFnAttr()) {
1565 // __declspec(safebuffers) disables stack guards.
1566 FPO |= FrameProcedureOptions::SafeBuffers;
1567 }
1568 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1569 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1570 if (Asm->TM.getOptLevel() != CodeGenOptLevel::None && !GV.hasOptSize() &&
1571 !GV.hasOptNone())
1572 FPO |= FrameProcedureOptions::OptimizedForSpeed;
1573 if (GV.hasProfileData()) {
1574 FPO |= FrameProcedureOptions::ValidProfileCounts;
1575 FPO |= FrameProcedureOptions::ProfileGuidedOptimization;
1576 }
1577 // FIXME: Set GuardCfg when it is implemented.
1578 CurFn->FrameProcOpts = FPO;
1579
1580 OS.emitCVFuncIdDirective(FunctionId: CurFn->FuncId);
1581
1582 // Find the end of the function prolog. First known non-DBG_VALUE and
1583 // non-frame setup location marks the beginning of the function body.
1584 // FIXME: is there a simpler a way to do this? Can we just search
1585 // for the first instruction of the function, not the last of the prolog?
1586 DebugLoc PrologEndLoc;
1587 bool EmptyPrologue = true;
1588 for (const auto &MBB : *MF) {
1589 for (const auto &MI : MBB) {
1590 if (!MI.isMetaInstruction() && !MI.getFlag(Flag: MachineInstr::FrameSetup) &&
1591 MI.getDebugLoc()) {
1592 PrologEndLoc = MI.getDebugLoc();
1593 break;
1594 } else if (!MI.isMetaInstruction()) {
1595 EmptyPrologue = false;
1596 }
1597 }
1598 }
1599
1600 // Record beginning of function if we have a non-empty prologue.
1601 if (PrologEndLoc && !EmptyPrologue) {
1602 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1603 maybeRecordLocation(DL: FnStartDL, MF);
1604 }
1605
1606 // Find heap alloc sites and emit labels around them.
1607 for (const auto &MBB : *MF) {
1608 for (const auto &MI : MBB) {
1609 if (MI.getHeapAllocMarker()) {
1610 requestLabelBeforeInsn(MI: &MI);
1611 requestLabelAfterInsn(MI: &MI);
1612 }
1613 }
1614 }
1615
1616 // Mark branches that may potentially be using jump tables with labels.
1617 bool isThumb = MMI->getModule()->getTargetTriple().getArch() ==
1618 llvm::Triple::ArchType::thumb;
1619 discoverJumpTableBranches(MF, isThumb);
1620}
1621
1622static bool shouldEmitUdt(const DIType *T) {
1623 if (!T)
1624 return false;
1625
1626 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1627 if (T->getTag() == dwarf::DW_TAG_typedef) {
1628 if (DIScope *Scope = T->getScope()) {
1629 switch (Scope->getTag()) {
1630 case dwarf::DW_TAG_structure_type:
1631 case dwarf::DW_TAG_class_type:
1632 case dwarf::DW_TAG_union_type:
1633 return false;
1634 default:
1635 // do nothing.
1636 ;
1637 }
1638 }
1639 }
1640
1641 while (true) {
1642 if (!T || T->isForwardDecl())
1643 return false;
1644
1645 const DIDerivedType *DT = dyn_cast<DIDerivedType>(Val: T);
1646 if (!DT)
1647 return true;
1648 T = DT->getBaseType();
1649 }
1650 return true;
1651}
1652
1653void CodeViewDebug::addToUDTs(const DIType *Ty) {
1654 // Don't record empty UDTs.
1655 if (Ty->getName().empty())
1656 return;
1657 if (!shouldEmitUdt(T: Ty))
1658 return;
1659
1660 SmallVector<StringRef, 5> ParentScopeNames;
1661 const DISubprogram *ClosestSubprogram =
1662 collectParentScopeNames(Scope: Ty->getScope(), QualifiedNameComponents&: ParentScopeNames);
1663
1664 std::string FullyQualifiedName =
1665 formatNestedName(QualifiedNameComponents: ParentScopeNames, TypeName: getPrettyScopeName(Scope: Ty));
1666
1667 if (ClosestSubprogram == nullptr) {
1668 GlobalUDTs.emplace_back(args: std::move(FullyQualifiedName), args&: Ty);
1669 } else if (ClosestSubprogram == CurrentSubprogram) {
1670 LocalUDTs.emplace_back(args: std::move(FullyQualifiedName), args&: Ty);
1671 }
1672
1673 // TODO: What if the ClosestSubprogram is neither null or the current
1674 // subprogram? Currently, the UDT just gets dropped on the floor.
1675 //
1676 // The current behavior is not desirable. To get maximal fidelity, we would
1677 // need to perform all type translation before beginning emission of .debug$S
1678 // and then make LocalUDTs a member of FunctionInfo
1679}
1680
1681TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1682 // Generic dispatch for lowering an unknown type.
1683 switch (Ty->getTag()) {
1684 case dwarf::DW_TAG_array_type:
1685 return lowerTypeArray(Ty: cast<DICompositeType>(Val: Ty));
1686 case dwarf::DW_TAG_typedef:
1687 return lowerTypeAlias(Ty: cast<DIDerivedType>(Val: Ty));
1688 case dwarf::DW_TAG_base_type:
1689 return lowerTypeBasic(Ty: cast<DIBasicType>(Val: Ty));
1690 case dwarf::DW_TAG_pointer_type:
1691 if (cast<DIDerivedType>(Val: Ty)->getName() == "__vtbl_ptr_type")
1692 return lowerTypeVFTableShape(Ty: cast<DIDerivedType>(Val: Ty));
1693 [[fallthrough]];
1694 case dwarf::DW_TAG_reference_type:
1695 case dwarf::DW_TAG_rvalue_reference_type:
1696 return lowerTypePointer(Ty: cast<DIDerivedType>(Val: Ty));
1697 case dwarf::DW_TAG_ptr_to_member_type:
1698 return lowerTypeMemberPointer(Ty: cast<DIDerivedType>(Val: Ty));
1699 case dwarf::DW_TAG_restrict_type:
1700 case dwarf::DW_TAG_const_type:
1701 case dwarf::DW_TAG_volatile_type:
1702 // TODO: add support for DW_TAG_atomic_type here
1703 return lowerTypeModifier(Ty: cast<DIDerivedType>(Val: Ty));
1704 case dwarf::DW_TAG_subroutine_type:
1705 if (ClassTy) {
1706 // The member function type of a member function pointer has no
1707 // ThisAdjustment.
1708 return lowerTypeMemberFunction(Ty: cast<DISubroutineType>(Val: Ty), ClassTy,
1709 /*ThisAdjustment=*/0,
1710 /*IsStaticMethod=*/false);
1711 }
1712 return lowerTypeFunction(Ty: cast<DISubroutineType>(Val: Ty));
1713 case dwarf::DW_TAG_enumeration_type:
1714 return lowerTypeEnum(Ty: cast<DICompositeType>(Val: Ty));
1715 case dwarf::DW_TAG_class_type:
1716 case dwarf::DW_TAG_structure_type:
1717 return lowerTypeClass(Ty: cast<DICompositeType>(Val: Ty));
1718 case dwarf::DW_TAG_union_type:
1719 return lowerTypeUnion(Ty: cast<DICompositeType>(Val: Ty));
1720 case dwarf::DW_TAG_string_type:
1721 return lowerTypeString(Ty: cast<DIStringType>(Val: Ty));
1722 case dwarf::DW_TAG_unspecified_type:
1723 if (Ty->getName() == "decltype(nullptr)")
1724 return TypeIndex::NullptrT();
1725 return TypeIndex::None();
1726 default:
1727 // Use the null type index.
1728 return TypeIndex();
1729 }
1730}
1731
1732TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1733 TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty: Ty->getBaseType());
1734 StringRef TypeName = Ty->getName();
1735
1736 addToUDTs(Ty);
1737
1738 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1739 TypeName == "HRESULT")
1740 return TypeIndex(SimpleTypeKind::HResult);
1741 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1742 TypeName == "wchar_t")
1743 return TypeIndex(SimpleTypeKind::WideCharacter);
1744
1745 return UnderlyingTypeIndex;
1746}
1747
1748TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1749 const DIType *ElementType = Ty->getBaseType();
1750 TypeIndex ElementTypeIndex = getTypeIndex(Ty: ElementType);
1751 // IndexType is size_t, which depends on the bitness of the target.
1752 TypeIndex IndexType = getPointerSizeInBytes() == 8
1753 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1754 : TypeIndex(SimpleTypeKind::UInt32Long);
1755
1756 uint64_t ElementSize = getBaseTypeSize(Ty: ElementType) / 8;
1757
1758 // Add subranges to array type.
1759 DINodeArray Elements = Ty->getElements();
1760 for (int i = Elements.size() - 1; i >= 0; --i) {
1761 const DINode *Element = Elements[i];
1762 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1763
1764 const DISubrange *Subrange = cast<DISubrange>(Val: Element);
1765 int64_t Count = -1;
1766
1767 // If Subrange has a Count field, use it.
1768 // Otherwise, if it has an upperboud, use (upperbound - lowerbound + 1),
1769 // where lowerbound is from the LowerBound field of the Subrange,
1770 // or the language default lowerbound if that field is unspecified.
1771 if (auto *CI = dyn_cast_if_present<ConstantInt *>(Val: Subrange->getCount()))
1772 Count = CI->getSExtValue();
1773 else if (auto *UI = dyn_cast_if_present<ConstantInt *>(
1774 Val: Subrange->getUpperBound())) {
1775 // Fortran uses 1 as the default lowerbound; other languages use 0.
1776 int64_t Lowerbound = (moduleIsInFortran()) ? 1 : 0;
1777 auto *LI = dyn_cast_if_present<ConstantInt *>(Val: Subrange->getLowerBound());
1778 Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound;
1779 Count = UI->getSExtValue() - Lowerbound + 1;
1780 }
1781
1782 // Forward declarations of arrays without a size and VLAs use a count of -1.
1783 // Emit a count of zero in these cases to match what MSVC does for arrays
1784 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1785 // should do for them even if we could distinguish them.
1786 if (Count == -1)
1787 Count = 0;
1788
1789 // Update the element size and element type index for subsequent subranges.
1790 ElementSize *= Count;
1791
1792 // If this is the outermost array, use the size from the array. It will be
1793 // more accurate if we had a VLA or an incomplete element type size.
1794 uint64_t ArraySize =
1795 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1796
1797 StringRef Name = (i == 0) ? Ty->getName() : "";
1798 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1799 ElementTypeIndex = TypeTable.writeLeafType(Record&: AR);
1800 }
1801
1802 return ElementTypeIndex;
1803}
1804
1805// This function lowers a Fortran character type (DIStringType).
1806// Note that it handles only the character*n variant (using SizeInBits
1807// field in DIString to describe the type size) at the moment.
1808// Other variants (leveraging the StringLength and StringLengthExp
1809// fields in DIStringType) remain TBD.
1810TypeIndex CodeViewDebug::lowerTypeString(const DIStringType *Ty) {
1811 TypeIndex CharType = TypeIndex(SimpleTypeKind::NarrowCharacter);
1812 uint64_t ArraySize = Ty->getSizeInBits() >> 3;
1813 StringRef Name = Ty->getName();
1814 // IndexType is size_t, which depends on the bitness of the target.
1815 TypeIndex IndexType = getPointerSizeInBytes() == 8
1816 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1817 : TypeIndex(SimpleTypeKind::UInt32Long);
1818
1819 // Create a type of character array of ArraySize.
1820 ArrayRecord AR(CharType, IndexType, ArraySize, Name);
1821
1822 return TypeTable.writeLeafType(Record&: AR);
1823}
1824
1825TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1826 TypeIndex Index;
1827 dwarf::TypeKind Kind;
1828 uint32_t ByteSize;
1829
1830 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1831 ByteSize = Ty->getSizeInBits() / 8;
1832
1833 SimpleTypeKind STK = SimpleTypeKind::None;
1834 switch (Kind) {
1835 case dwarf::DW_ATE_address:
1836 // FIXME: Translate
1837 break;
1838 case dwarf::DW_ATE_boolean:
1839 switch (ByteSize) {
1840 case 1: STK = SimpleTypeKind::Boolean8; break;
1841 case 2: STK = SimpleTypeKind::Boolean16; break;
1842 case 4: STK = SimpleTypeKind::Boolean32; break;
1843 case 8: STK = SimpleTypeKind::Boolean64; break;
1844 case 16: STK = SimpleTypeKind::Boolean128; break;
1845 }
1846 break;
1847 case dwarf::DW_ATE_complex_float:
1848 // The CodeView size for a complex represents the size of
1849 // an individual component.
1850 switch (ByteSize) {
1851 case 4: STK = SimpleTypeKind::Complex16; break;
1852 case 8: STK = SimpleTypeKind::Complex32; break;
1853 case 16: STK = SimpleTypeKind::Complex64; break;
1854 case 20: STK = SimpleTypeKind::Complex80; break;
1855 case 32: STK = SimpleTypeKind::Complex128; break;
1856 }
1857 break;
1858 case dwarf::DW_ATE_float:
1859 switch (ByteSize) {
1860 case 2: STK = SimpleTypeKind::Float16; break;
1861 case 4: STK = SimpleTypeKind::Float32; break;
1862 case 6: STK = SimpleTypeKind::Float48; break;
1863 case 8: STK = SimpleTypeKind::Float64; break;
1864 case 10: STK = SimpleTypeKind::Float80; break;
1865 case 16: STK = SimpleTypeKind::Float128; break;
1866 }
1867 break;
1868 case dwarf::DW_ATE_signed:
1869 switch (ByteSize) {
1870 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1871 case 2: STK = SimpleTypeKind::Int16Short; break;
1872 case 4: STK = SimpleTypeKind::Int32; break;
1873 case 8: STK = SimpleTypeKind::Int64Quad; break;
1874 case 16: STK = SimpleTypeKind::Int128Oct; break;
1875 }
1876 break;
1877 case dwarf::DW_ATE_unsigned:
1878 switch (ByteSize) {
1879 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1880 case 2: STK = SimpleTypeKind::UInt16Short; break;
1881 case 4: STK = SimpleTypeKind::UInt32; break;
1882 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1883 case 16: STK = SimpleTypeKind::UInt128Oct; break;
1884 }
1885 break;
1886 case dwarf::DW_ATE_UTF:
1887 switch (ByteSize) {
1888 case 1: STK = SimpleTypeKind::Character8; break;
1889 case 2: STK = SimpleTypeKind::Character16; break;
1890 case 4: STK = SimpleTypeKind::Character32; break;
1891 }
1892 break;
1893 case dwarf::DW_ATE_signed_char:
1894 if (ByteSize == 1)
1895 STK = SimpleTypeKind::SignedCharacter;
1896 break;
1897 case dwarf::DW_ATE_unsigned_char:
1898 if (ByteSize == 1)
1899 STK = SimpleTypeKind::UnsignedCharacter;
1900 break;
1901 default:
1902 break;
1903 }
1904
1905 // Apply some fixups based on the source-level type name.
1906 // Include some amount of canonicalization from an old naming scheme Clang
1907 // used to use for integer types (in an outdated effort to be compatible with
1908 // GCC's debug info/GDB's behavior, which has since been addressed).
1909 if (STK == SimpleTypeKind::Int32 &&
1910 (Ty->getName() == "long int" || Ty->getName() == "long"))
1911 STK = SimpleTypeKind::Int32Long;
1912 if (STK == SimpleTypeKind::UInt32 && (Ty->getName() == "long unsigned int" ||
1913 Ty->getName() == "unsigned long"))
1914 STK = SimpleTypeKind::UInt32Long;
1915 if (STK == SimpleTypeKind::UInt16Short &&
1916 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1917 STK = SimpleTypeKind::WideCharacter;
1918 if ((STK == SimpleTypeKind::SignedCharacter ||
1919 STK == SimpleTypeKind::UnsignedCharacter) &&
1920 Ty->getName() == "char")
1921 STK = SimpleTypeKind::NarrowCharacter;
1922
1923 return TypeIndex(STK);
1924}
1925
1926TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1927 PointerOptions PO) {
1928 TypeIndex PointeeTI = getTypeIndex(Ty: Ty->getBaseType());
1929
1930 // Pointers to simple types without any options can use SimpleTypeMode, rather
1931 // than having a dedicated pointer type record.
1932 if (PointeeTI.isSimple() && PO == PointerOptions::None &&
1933 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1934 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1935 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1936 ? SimpleTypeMode::NearPointer64
1937 : SimpleTypeMode::NearPointer32;
1938 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1939 }
1940
1941 PointerKind PK =
1942 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1943 PointerMode PM = PointerMode::Pointer;
1944 switch (Ty->getTag()) {
1945 default: llvm_unreachable("not a pointer tag type");
1946 case dwarf::DW_TAG_pointer_type:
1947 PM = PointerMode::Pointer;
1948 break;
1949 case dwarf::DW_TAG_reference_type:
1950 PM = PointerMode::LValueReference;
1951 break;
1952 case dwarf::DW_TAG_rvalue_reference_type:
1953 PM = PointerMode::RValueReference;
1954 break;
1955 }
1956
1957 if (Ty->isObjectPointer())
1958 PO |= PointerOptions::Const;
1959
1960 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1961 return TypeTable.writeLeafType(Record&: PR);
1962}
1963
1964static PointerToMemberRepresentation
1965translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1966 // SizeInBytes being zero generally implies that the member pointer type was
1967 // incomplete, which can happen if it is part of a function prototype. In this
1968 // case, use the unknown model instead of the general model.
1969 if (IsPMF) {
1970 switch (Flags & DINode::FlagPtrToMemberRep) {
1971 case 0:
1972 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1973 : PointerToMemberRepresentation::GeneralFunction;
1974 case DINode::FlagSingleInheritance:
1975 return PointerToMemberRepresentation::SingleInheritanceFunction;
1976 case DINode::FlagMultipleInheritance:
1977 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1978 case DINode::FlagVirtualInheritance:
1979 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1980 }
1981 } else {
1982 switch (Flags & DINode::FlagPtrToMemberRep) {
1983 case 0:
1984 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1985 : PointerToMemberRepresentation::GeneralData;
1986 case DINode::FlagSingleInheritance:
1987 return PointerToMemberRepresentation::SingleInheritanceData;
1988 case DINode::FlagMultipleInheritance:
1989 return PointerToMemberRepresentation::MultipleInheritanceData;
1990 case DINode::FlagVirtualInheritance:
1991 return PointerToMemberRepresentation::VirtualInheritanceData;
1992 }
1993 }
1994 llvm_unreachable("invalid ptr to member representation");
1995}
1996
1997TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1998 PointerOptions PO) {
1999 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
2000 bool IsPMF = isa<DISubroutineType>(Val: Ty->getBaseType());
2001 TypeIndex ClassTI = getTypeIndex(Ty: Ty->getClassType());
2002 TypeIndex PointeeTI =
2003 getTypeIndex(Ty: Ty->getBaseType(), ClassTy: IsPMF ? Ty->getClassType() : nullptr);
2004 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2005 : PointerKind::Near32;
2006 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
2007 : PointerMode::PointerToDataMember;
2008
2009 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
2010 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
2011 MemberPointerInfo MPI(
2012 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Flags: Ty->getFlags()));
2013 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
2014 return TypeTable.writeLeafType(Record&: PR);
2015}
2016
2017/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
2018/// have a translation, use the NearC convention.
2019static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
2020 switch (DwarfCC) {
2021 case dwarf::DW_CC_normal: return CallingConvention::NearC;
2022 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
2023 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
2024 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
2025 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
2026 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
2027 }
2028 return CallingConvention::NearC;
2029}
2030
2031TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
2032 ModifierOptions Mods = ModifierOptions::None;
2033 PointerOptions PO = PointerOptions::None;
2034 bool IsModifier = true;
2035 const DIType *BaseTy = Ty;
2036 while (IsModifier && BaseTy) {
2037 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
2038 switch (BaseTy->getTag()) {
2039 case dwarf::DW_TAG_const_type:
2040 Mods |= ModifierOptions::Const;
2041 PO |= PointerOptions::Const;
2042 break;
2043 case dwarf::DW_TAG_volatile_type:
2044 Mods |= ModifierOptions::Volatile;
2045 PO |= PointerOptions::Volatile;
2046 break;
2047 case dwarf::DW_TAG_restrict_type:
2048 // Only pointer types be marked with __restrict. There is no known flag
2049 // for __restrict in LF_MODIFIER records.
2050 PO |= PointerOptions::Restrict;
2051 break;
2052 default:
2053 IsModifier = false;
2054 break;
2055 }
2056 if (IsModifier)
2057 BaseTy = cast<DIDerivedType>(Val: BaseTy)->getBaseType();
2058 }
2059
2060 // Check if the inner type will use an LF_POINTER record. If so, the
2061 // qualifiers will go in the LF_POINTER record. This comes up for types like
2062 // 'int *const' and 'int *__restrict', not the more common cases like 'const
2063 // char *'.
2064 if (BaseTy) {
2065 switch (BaseTy->getTag()) {
2066 case dwarf::DW_TAG_pointer_type:
2067 case dwarf::DW_TAG_reference_type:
2068 case dwarf::DW_TAG_rvalue_reference_type:
2069 return lowerTypePointer(Ty: cast<DIDerivedType>(Val: BaseTy), PO);
2070 case dwarf::DW_TAG_ptr_to_member_type:
2071 return lowerTypeMemberPointer(Ty: cast<DIDerivedType>(Val: BaseTy), PO);
2072 default:
2073 break;
2074 }
2075 }
2076
2077 TypeIndex ModifiedTI = getTypeIndex(Ty: BaseTy);
2078
2079 // Return the base type index if there aren't any modifiers. For example, the
2080 // metadata could contain restrict wrappers around non-pointer types.
2081 if (Mods == ModifierOptions::None)
2082 return ModifiedTI;
2083
2084 ModifierRecord MR(ModifiedTI, Mods);
2085 return TypeTable.writeLeafType(Record&: MR);
2086}
2087
2088TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
2089 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
2090 for (const DIType *ArgType : Ty->getTypeArray())
2091 ReturnAndArgTypeIndices.push_back(Elt: getTypeIndex(Ty: ArgType));
2092
2093 // MSVC uses type none for variadic argument.
2094 if (ReturnAndArgTypeIndices.size() > 1 &&
2095 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
2096 ReturnAndArgTypeIndices.back() = TypeIndex::None();
2097 }
2098 TypeIndex ReturnTypeIndex = TypeIndex::Void();
2099 ArrayRef<TypeIndex> ArgTypeIndices = {};
2100 if (!ReturnAndArgTypeIndices.empty()) {
2101 auto ReturnAndArgTypesRef = ArrayRef(ReturnAndArgTypeIndices);
2102 ReturnTypeIndex = ReturnAndArgTypesRef.consume_front();
2103 ArgTypeIndices = ReturnAndArgTypesRef;
2104 }
2105
2106 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2107 TypeIndex ArgListIndex = TypeTable.writeLeafType(Record&: ArgListRec);
2108
2109 CallingConvention CC = dwarfCCToCodeView(DwarfCC: Ty->getCC());
2110
2111 FunctionOptions FO = getFunctionOptions(Ty);
2112 ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
2113 ArgListIndex);
2114 return TypeTable.writeLeafType(Record&: Procedure);
2115}
2116
2117TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
2118 const DIType *ClassTy,
2119 int ThisAdjustment,
2120 bool IsStaticMethod,
2121 FunctionOptions FO) {
2122 // Lower the containing class type.
2123 TypeIndex ClassType = getTypeIndex(Ty: ClassTy);
2124
2125 DITypeArray ReturnAndArgs = Ty->getTypeArray();
2126
2127 unsigned Index = 0;
2128 SmallVector<TypeIndex, 8> ArgTypeIndices;
2129 TypeIndex ReturnTypeIndex = TypeIndex::Void();
2130 if (ReturnAndArgs.size() > Index) {
2131 ReturnTypeIndex = getTypeIndex(Ty: ReturnAndArgs[Index++]);
2132 }
2133
2134 // If the first argument is a pointer type and this isn't a static method,
2135 // treat it as the special 'this' parameter, which is encoded separately from
2136 // the arguments.
2137 TypeIndex ThisTypeIndex;
2138 if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
2139 if (const DIDerivedType *PtrTy =
2140 dyn_cast_or_null<DIDerivedType>(Val: ReturnAndArgs[Index])) {
2141 if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
2142 ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, SubroutineTy: Ty);
2143 Index++;
2144 }
2145 }
2146 }
2147
2148 while (Index < ReturnAndArgs.size())
2149 ArgTypeIndices.push_back(Elt: getTypeIndex(Ty: ReturnAndArgs[Index++]));
2150
2151 // MSVC uses type none for variadic argument.
2152 if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
2153 ArgTypeIndices.back() = TypeIndex::None();
2154
2155 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2156 TypeIndex ArgListIndex = TypeTable.writeLeafType(Record&: ArgListRec);
2157
2158 CallingConvention CC = dwarfCCToCodeView(DwarfCC: Ty->getCC());
2159
2160 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
2161 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
2162 return TypeTable.writeLeafType(Record&: MFR);
2163}
2164
2165TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
2166 unsigned VSlotCount =
2167 Ty->getSizeInBits() / (8 * Asm->MAI.getCodePointerSize());
2168 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
2169
2170 VFTableShapeRecord VFTSR(Slots);
2171 return TypeTable.writeLeafType(Record&: VFTSR);
2172}
2173
2174static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
2175 switch (Flags & DINode::FlagAccessibility) {
2176 case DINode::FlagPrivate: return MemberAccess::Private;
2177 case DINode::FlagPublic: return MemberAccess::Public;
2178 case DINode::FlagProtected: return MemberAccess::Protected;
2179 case 0:
2180 // If there was no explicit access control, provide the default for the tag.
2181 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
2182 : MemberAccess::Public;
2183 }
2184 llvm_unreachable("access flags are exclusive");
2185}
2186
2187static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
2188 if (SP->isArtificial())
2189 return MethodOptions::CompilerGenerated;
2190
2191 // FIXME: Handle other MethodOptions.
2192
2193 return MethodOptions::None;
2194}
2195
2196static MethodKind translateMethodKindFlags(const DISubprogram *SP,
2197 bool Introduced) {
2198 if (SP->getFlags() & DINode::FlagStaticMember)
2199 return MethodKind::Static;
2200
2201 switch (SP->getVirtuality()) {
2202 case dwarf::DW_VIRTUALITY_none:
2203 break;
2204 case dwarf::DW_VIRTUALITY_virtual:
2205 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
2206 case dwarf::DW_VIRTUALITY_pure_virtual:
2207 return Introduced ? MethodKind::PureIntroducingVirtual
2208 : MethodKind::PureVirtual;
2209 default:
2210 llvm_unreachable("unhandled virtuality case");
2211 }
2212
2213 return MethodKind::Vanilla;
2214}
2215
2216static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
2217 switch (Ty->getTag()) {
2218 case dwarf::DW_TAG_class_type:
2219 return UseTagRecord2 ? TypeRecordKind::Class2 : TypeRecordKind::Class;
2220 case dwarf::DW_TAG_structure_type:
2221 return UseTagRecord2 ? TypeRecordKind::Struct2 : TypeRecordKind::Struct;
2222 default:
2223 llvm_unreachable("unexpected tag");
2224 }
2225}
2226
2227/// Return ClassOptions that should be present on both the forward declaration
2228/// and the defintion of a tag type.
2229static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
2230 ClassOptions CO = ClassOptions::None;
2231
2232 // MSVC always sets this flag, even for local types. Clang doesn't always
2233 // appear to give every type a linkage name, which may be problematic for us.
2234 // FIXME: Investigate the consequences of not following them here.
2235 if (!Ty->getIdentifier().empty())
2236 CO |= ClassOptions::HasUniqueName;
2237
2238 // Put the Nested flag on a type if it appears immediately inside a tag type.
2239 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
2240 // here. That flag is only set on definitions, and not forward declarations.
2241 const DIScope *ImmediateScope = Ty->getScope();
2242 if (ImmediateScope && isa<DICompositeType>(Val: ImmediateScope))
2243 CO |= ClassOptions::Nested;
2244
2245 // Put the Scoped flag on function-local types. MSVC puts this flag for enum
2246 // type only when it has an immediate function scope. Clang never puts enums
2247 // inside DILexicalBlock scopes. Enum types, as generated by clang, are
2248 // always in function, class, or file scopes.
2249 if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
2250 if (ImmediateScope && isa<DISubprogram>(Val: ImmediateScope))
2251 CO |= ClassOptions::Scoped;
2252 } else {
2253 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
2254 Scope = Scope->getScope()) {
2255 if (isa<DISubprogram>(Val: Scope)) {
2256 CO |= ClassOptions::Scoped;
2257 break;
2258 }
2259 }
2260 }
2261
2262 return CO;
2263}
2264
2265void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
2266 switch (Ty->getTag()) {
2267 case dwarf::DW_TAG_class_type:
2268 case dwarf::DW_TAG_structure_type:
2269 case dwarf::DW_TAG_union_type:
2270 case dwarf::DW_TAG_enumeration_type:
2271 break;
2272 default:
2273 return;
2274 }
2275
2276 if (const auto *File = Ty->getFile()) {
2277 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2278 TypeIndex SIDI = TypeTable.writeLeafType(Record&: SIDR);
2279
2280 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2281 TypeTable.writeLeafType(Record&: USLR);
2282 }
2283}
2284
2285TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
2286 ClassOptions CO = getCommonClassOptions(Ty);
2287 TypeIndex FTI;
2288 unsigned EnumeratorCount = 0;
2289
2290 if (Ty->isForwardDecl()) {
2291 CO |= ClassOptions::ForwardReference;
2292 } else {
2293 ContinuationRecordBuilder ContinuationBuilder;
2294 ContinuationBuilder.begin(RecordKind: ContinuationRecordKind::FieldList);
2295 for (const DINode *Element : Ty->getElements()) {
2296 // We assume that the frontend provides all members in source declaration
2297 // order, which is what MSVC does.
2298 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Val: Element)) {
2299 EnumeratorRecord ER(
2300 MemberAccess::Public,
2301 APSInt(Enumerator->getValue(), Enumerator->isUnsigned()),
2302 Enumerator->getName());
2303 ContinuationBuilder.writeMemberType(Record&: ER);
2304 EnumeratorCount++;
2305 }
2306 }
2307 FTI = TypeTable.insertRecord(Builder&: ContinuationBuilder);
2308 }
2309
2310 std::string FullName = getFullyQualifiedName(Ty);
2311
2312 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2313 getTypeIndex(Ty: Ty->getBaseType()));
2314 TypeIndex EnumTI = TypeTable.writeLeafType(Record&: ER);
2315
2316 addUDTSrcLine(Ty, TI: EnumTI);
2317
2318 return EnumTI;
2319}
2320
2321//===----------------------------------------------------------------------===//
2322// ClassInfo
2323//===----------------------------------------------------------------------===//
2324
2325struct llvm::ClassInfo {
2326 struct MemberInfo {
2327 const DIDerivedType *MemberTypeNode;
2328 uint64_t BaseOffset;
2329 };
2330 // [MemberInfo]
2331 using MemberList = std::vector<MemberInfo>;
2332
2333 using MethodsList = TinyPtrVector<const DISubprogram *>;
2334 // MethodName -> MethodsList
2335 using MethodsMap = MapVector<MDString *, MethodsList>;
2336
2337 /// Base classes.
2338 std::vector<const DIDerivedType *> Inheritance;
2339
2340 /// Direct members.
2341 MemberList Members;
2342 // Direct overloaded methods gathered by name.
2343 MethodsMap Methods;
2344
2345 TypeIndex VShapeTI;
2346
2347 std::vector<const DIType *> NestedTypes;
2348};
2349
2350void CodeViewDebug::clear() {
2351 assert(CurFn == nullptr);
2352 FileIdMap.clear();
2353 FnDebugInfo.clear();
2354 FileToFilepathMap.clear();
2355 LocalUDTs.clear();
2356 GlobalUDTs.clear();
2357 TypeIndices.clear();
2358 CompleteTypeIndices.clear();
2359 ScopeGlobals.clear();
2360 CVGlobalVariableOffsets.clear();
2361}
2362
2363void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2364 const DIDerivedType *DDTy) {
2365 if (!DDTy->getName().empty()) {
2366 Info.Members.push_back(x: {.MemberTypeNode: DDTy, .BaseOffset: 0});
2367
2368 // Collect static const data members with values.
2369 if ((DDTy->getFlags() & DINode::FlagStaticMember) ==
2370 DINode::FlagStaticMember) {
2371 if (DDTy->getConstant() && (isa<ConstantInt>(Val: DDTy->getConstant()) ||
2372 isa<ConstantFP>(Val: DDTy->getConstant())))
2373 StaticConstMembers.push_back(Elt: DDTy);
2374 }
2375
2376 return;
2377 }
2378
2379 // An unnamed member may represent a nested struct or union. Attempt to
2380 // interpret the unnamed member as a DICompositeType possibly wrapped in
2381 // qualifier types. Add all the indirect fields to the current record if that
2382 // succeeds, and drop the member if that fails.
2383 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
2384 uint64_t Offset = DDTy->getOffsetInBits();
2385 const DIType *Ty = DDTy->getBaseType();
2386 bool FullyResolved = false;
2387 while (!FullyResolved) {
2388 switch (Ty->getTag()) {
2389 case dwarf::DW_TAG_const_type:
2390 case dwarf::DW_TAG_volatile_type:
2391 // FIXME: we should apply the qualifier types to the indirect fields
2392 // rather than dropping them.
2393 Ty = cast<DIDerivedType>(Val: Ty)->getBaseType();
2394 break;
2395 default:
2396 FullyResolved = true;
2397 break;
2398 }
2399 }
2400
2401 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Val: Ty);
2402 if (!DCTy)
2403 return;
2404
2405 ClassInfo NestedInfo = collectClassInfo(Ty: DCTy);
2406 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
2407 Info.Members.push_back(
2408 x: {.MemberTypeNode: IndirectField.MemberTypeNode, .BaseOffset: IndirectField.BaseOffset + Offset});
2409}
2410
2411ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2412 ClassInfo Info;
2413 // Add elements to structure type.
2414 DINodeArray Elements = Ty->getElements();
2415 for (auto *Element : Elements) {
2416 // We assume that the frontend provides all members in source declaration
2417 // order, which is what MSVC does.
2418 if (!Element)
2419 continue;
2420 if (auto *SP = dyn_cast<DISubprogram>(Val: Element)) {
2421 Info.Methods[SP->getRawName()].push_back(NewVal: SP);
2422 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Val: Element)) {
2423 if (DDTy->getTag() == dwarf::DW_TAG_member) {
2424 collectMemberInfo(Info, DDTy);
2425 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2426 Info.Inheritance.push_back(x: DDTy);
2427 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2428 DDTy->getName() == "__vtbl_ptr_type") {
2429 Info.VShapeTI = getTypeIndex(Ty: DDTy);
2430 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2431 Info.NestedTypes.push_back(x: DDTy);
2432 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2433 // Ignore friend members. It appears that MSVC emitted info about
2434 // friends in the past, but modern versions do not.
2435 }
2436 } else if (auto *Composite = dyn_cast<DICompositeType>(Val: Element)) {
2437 Info.NestedTypes.push_back(x: Composite);
2438 }
2439 // Skip other unrecognized kinds of elements.
2440 }
2441 return Info;
2442}
2443
2444static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2445 // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2446 // if a complete type should be emitted instead of a forward reference.
2447 return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2448 !Ty->isForwardDecl();
2449}
2450
2451TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
2452 // Emit the complete type for unnamed structs. C++ classes with methods
2453 // which have a circular reference back to the class type are expected to
2454 // be named by the front-end and should not be "unnamed". C unnamed
2455 // structs should not have circular references.
2456 if (shouldAlwaysEmitCompleteClassType(Ty)) {
2457 // If this unnamed complete type is already in the process of being defined
2458 // then the description of the type is malformed and cannot be emitted
2459 // into CodeView correctly so report a fatal error.
2460 auto I = CompleteTypeIndices.find(Val: Ty);
2461 if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2462 report_fatal_error(reason: "cannot debug circular reference to unnamed type");
2463 return getCompleteTypeIndex(Ty);
2464 }
2465
2466 // First, construct the forward decl. Don't look into Ty to compute the
2467 // forward decl options, since it might not be available in all TUs.
2468 TypeRecordKind Kind = getRecordKind(Ty);
2469 ClassOptions CO =
2470 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2471 std::string FullName = getFullyQualifiedName(Ty);
2472 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2473 FullName, Ty->getIdentifier());
2474 TypeIndex FwdDeclTI = TypeTable.writeLeafType(Record&: CR);
2475 if (!Ty->isForwardDecl())
2476 DeferredCompleteTypes.push_back(Elt: Ty);
2477 return FwdDeclTI;
2478}
2479
2480TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2481 // Construct the field list and complete type record.
2482 TypeRecordKind Kind = getRecordKind(Ty);
2483 ClassOptions CO = getCommonClassOptions(Ty);
2484 TypeIndex FieldTI;
2485 TypeIndex VShapeTI;
2486 unsigned FieldCount;
2487 bool ContainsNestedClass;
2488 std::tie(args&: FieldTI, args&: VShapeTI, args&: FieldCount, args&: ContainsNestedClass) =
2489 lowerRecordFieldList(Ty);
2490
2491 if (ContainsNestedClass)
2492 CO |= ClassOptions::ContainsNestedClass;
2493
2494 // MSVC appears to set this flag by searching any destructor or method with
2495 // FunctionOptions::Constructor among the emitted members. Clang AST has all
2496 // the members, however special member functions are not yet emitted into
2497 // debug information. For now checking a class's non-triviality seems enough.
2498 // FIXME: not true for a nested unnamed struct.
2499 if (isNonTrivial(DCTy: Ty))
2500 CO |= ClassOptions::HasConstructorOrDestructor;
2501
2502 std::string FullName = getFullyQualifiedName(Ty);
2503
2504 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2505
2506 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2507 SizeInBytes, FullName, Ty->getIdentifier());
2508 TypeIndex ClassTI = TypeTable.writeLeafType(Record&: CR);
2509
2510 addUDTSrcLine(Ty, TI: ClassTI);
2511
2512 addToUDTs(Ty);
2513
2514 return ClassTI;
2515}
2516
2517TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
2518 // Emit the complete type for unnamed unions.
2519 if (shouldAlwaysEmitCompleteClassType(Ty))
2520 return getCompleteTypeIndex(Ty);
2521
2522 ClassOptions CO =
2523 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2524 std::string FullName = getFullyQualifiedName(Ty);
2525 TypeRecordKind Kind =
2526 UseTagRecord2 ? TypeRecordKind::Union2 : TypeRecordKind::Union;
2527 UnionRecord UR(Kind, 0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
2528 TypeIndex FwdDeclTI = TypeTable.writeLeafType(Record&: UR);
2529 if (!Ty->isForwardDecl())
2530 DeferredCompleteTypes.push_back(Elt: Ty);
2531 return FwdDeclTI;
2532}
2533
2534TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
2535 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
2536 TypeIndex FieldTI;
2537 unsigned FieldCount;
2538 bool ContainsNestedClass;
2539 std::tie(args&: FieldTI, args: std::ignore, args&: FieldCount, args&: ContainsNestedClass) =
2540 lowerRecordFieldList(Ty);
2541
2542 if (ContainsNestedClass)
2543 CO |= ClassOptions::ContainsNestedClass;
2544
2545 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2546 std::string FullName = getFullyQualifiedName(Ty);
2547
2548 TypeRecordKind Kind =
2549 UseTagRecord2 ? TypeRecordKind::Union2 : TypeRecordKind::Union;
2550 UnionRecord UR(Kind, FieldCount, CO, FieldTI, SizeInBytes, FullName,
2551 Ty->getIdentifier());
2552 TypeIndex UnionTI = TypeTable.writeLeafType(Record&: UR);
2553
2554 addUDTSrcLine(Ty, TI: UnionTI);
2555
2556 addToUDTs(Ty);
2557
2558 return UnionTI;
2559}
2560
2561std::tuple<TypeIndex, TypeIndex, unsigned, bool>
2562CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2563 // Manually count members. MSVC appears to count everything that generates a
2564 // field list record. Each individual overload in a method overload group
2565 // contributes to this count, even though the overload group is a single field
2566 // list record.
2567 unsigned MemberCount = 0;
2568 ClassInfo Info = collectClassInfo(Ty);
2569 ContinuationRecordBuilder ContinuationBuilder;
2570 ContinuationBuilder.begin(RecordKind: ContinuationRecordKind::FieldList);
2571
2572 // Create base classes.
2573 for (const DIDerivedType *I : Info.Inheritance) {
2574 if (I->getFlags() & DINode::FlagVirtual) {
2575 // Virtual base.
2576 unsigned VBPtrOffset = I->getVBPtrOffset();
2577 // FIXME: Despite the accessor name, the offset is really in bytes.
2578 unsigned VBTableIndex = I->getOffsetInBits() / 4;
2579 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2580 ? TypeRecordKind::IndirectVirtualBaseClass
2581 : TypeRecordKind::VirtualBaseClass;
2582 VirtualBaseClassRecord VBCR(
2583 RecordKind, translateAccessFlags(RecordTag: Ty->getTag(), Flags: I->getFlags()),
2584 getTypeIndex(Ty: I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
2585 VBTableIndex);
2586
2587 ContinuationBuilder.writeMemberType(Record&: VBCR);
2588 MemberCount++;
2589 } else {
2590 assert(I->getOffsetInBits() % 8 == 0 &&
2591 "bases must be on byte boundaries");
2592 BaseClassRecord BCR(translateAccessFlags(RecordTag: Ty->getTag(), Flags: I->getFlags()),
2593 getTypeIndex(Ty: I->getBaseType()),
2594 I->getOffsetInBits() / 8);
2595 ContinuationBuilder.writeMemberType(Record&: BCR);
2596 MemberCount++;
2597 }
2598 }
2599
2600 // Create members.
2601 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2602 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2603 TypeIndex MemberBaseType = getTypeIndex(Ty: Member->getBaseType());
2604 StringRef MemberName = Member->getName();
2605 MemberAccess Access =
2606 translateAccessFlags(RecordTag: Ty->getTag(), Flags: Member->getFlags());
2607
2608 if (Member->isStaticMember()) {
2609 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
2610 ContinuationBuilder.writeMemberType(Record&: SDMR);
2611 MemberCount++;
2612 continue;
2613 }
2614
2615 // Virtual function pointer member.
2616 if ((Member->getFlags() & DINode::FlagArtificial) &&
2617 Member->getName().starts_with(Prefix: "_vptr$")) {
2618 VFPtrRecord VFPR(getTypeIndex(Ty: Member->getBaseType()));
2619 ContinuationBuilder.writeMemberType(Record&: VFPR);
2620 MemberCount++;
2621 continue;
2622 }
2623
2624 // Data member.
2625 uint64_t MemberOffsetInBits =
2626 Member->getOffsetInBits() + MemberInfo.BaseOffset;
2627 if (Member->isBitField()) {
2628 uint64_t StartBitOffset = MemberOffsetInBits;
2629 if (const auto *CI =
2630 dyn_cast_or_null<ConstantInt>(Val: Member->getStorageOffsetInBits())) {
2631 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2632 }
2633 StartBitOffset -= MemberOffsetInBits;
2634 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2635 StartBitOffset);
2636 MemberBaseType = TypeTable.writeLeafType(Record&: BFR);
2637 }
2638 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2639 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2640 MemberName);
2641 ContinuationBuilder.writeMemberType(Record&: DMR);
2642 MemberCount++;
2643 }
2644
2645 // Create methods
2646 for (auto &MethodItr : Info.Methods) {
2647 StringRef Name = MethodItr.first->getString();
2648
2649 std::vector<OneMethodRecord> Methods;
2650 for (const DISubprogram *SP : MethodItr.second) {
2651 TypeIndex MethodType = getMemberFunctionType(SP, Class: Ty);
2652 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2653
2654 unsigned VFTableOffset = -1;
2655 if (Introduced)
2656 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2657
2658 Methods.push_back(x: OneMethodRecord(
2659 MethodType, translateAccessFlags(RecordTag: Ty->getTag(), Flags: SP->getFlags()),
2660 translateMethodKindFlags(SP, Introduced),
2661 translateMethodOptionFlags(SP), VFTableOffset, Name));
2662 MemberCount++;
2663 }
2664 assert(!Methods.empty() && "Empty methods map entry");
2665 if (Methods.size() == 1)
2666 ContinuationBuilder.writeMemberType(Record&: Methods[0]);
2667 else {
2668 // FIXME: Make this use its own ContinuationBuilder so that
2669 // MethodOverloadList can be split correctly.
2670 MethodOverloadListRecord MOLR(Methods);
2671 TypeIndex MethodList = TypeTable.writeLeafType(Record&: MOLR);
2672
2673 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2674 ContinuationBuilder.writeMemberType(Record&: OMR);
2675 }
2676 }
2677
2678 // Create nested classes.
2679 for (const DIType *Nested : Info.NestedTypes) {
2680 NestedTypeRecord R(getTypeIndex(Ty: Nested), Nested->getName());
2681 ContinuationBuilder.writeMemberType(Record&: R);
2682 MemberCount++;
2683 }
2684
2685 TypeIndex FieldTI = TypeTable.insertRecord(Builder&: ContinuationBuilder);
2686 return std::make_tuple(args&: FieldTI, args&: Info.VShapeTI, args&: MemberCount,
2687 args: !Info.NestedTypes.empty());
2688}
2689
2690TypeIndex CodeViewDebug::getVBPTypeIndex() {
2691 if (!VBPType.getIndex()) {
2692 // Make a 'const int *' type.
2693 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2694 TypeIndex ModifiedTI = TypeTable.writeLeafType(Record&: MR);
2695
2696 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2697 : PointerKind::Near32;
2698 PointerMode PM = PointerMode::Pointer;
2699 PointerOptions PO = PointerOptions::None;
2700 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2701 VBPType = TypeTable.writeLeafType(Record&: PR);
2702 }
2703
2704 return VBPType;
2705}
2706
2707TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
2708 // The null DIType is the void type. Don't try to hash it.
2709 if (!Ty)
2710 return TypeIndex::Void();
2711
2712 // Check if we've already translated this type. Don't try to do a
2713 // get-or-create style insertion that caches the hash lookup across the
2714 // lowerType call. It will update the TypeIndices map.
2715 auto I = TypeIndices.find(Val: {Ty, ClassTy});
2716 if (I != TypeIndices.end())
2717 return I->second;
2718
2719 TypeLoweringScope S(*this);
2720 TypeIndex TI = lowerType(Ty, ClassTy);
2721 return recordTypeIndexForDINode(Node: Ty, TI, ClassTy);
2722}
2723
2724codeview::TypeIndex
2725CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
2726 const DISubroutineType *SubroutineTy) {
2727 assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2728 "this type must be a pointer type");
2729
2730 PointerOptions Options = PointerOptions::None;
2731 if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2732 Options = PointerOptions::LValueRefThisPointer;
2733 else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2734 Options = PointerOptions::RValueRefThisPointer;
2735
2736 // Check if we've already translated this type. If there is no ref qualifier
2737 // on the function then we look up this pointer type with no associated class
2738 // so that the TypeIndex for the this pointer can be shared with the type
2739 // index for other pointers to this class type. If there is a ref qualifier
2740 // then we lookup the pointer using the subroutine as the parent type.
2741 auto I = TypeIndices.find(Val: {PtrTy, SubroutineTy});
2742 if (I != TypeIndices.end())
2743 return I->second;
2744
2745 TypeLoweringScope S(*this);
2746 TypeIndex TI = lowerTypePointer(Ty: PtrTy, PO: Options);
2747 return recordTypeIndexForDINode(Node: PtrTy, TI, ClassTy: SubroutineTy);
2748}
2749
2750TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
2751 // The null DIType is the void type. Don't try to hash it.
2752 if (!Ty)
2753 return TypeIndex::Void();
2754
2755 // Look through typedefs when getting the complete type index. Call
2756 // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2757 // emitted only once.
2758 if (Ty->getTag() == dwarf::DW_TAG_typedef)
2759 (void)getTypeIndex(Ty);
2760 while (Ty->getTag() == dwarf::DW_TAG_typedef)
2761 Ty = cast<DIDerivedType>(Val: Ty)->getBaseType();
2762
2763 // If this is a non-record type, the complete type index is the same as the
2764 // normal type index. Just call getTypeIndex.
2765 switch (Ty->getTag()) {
2766 case dwarf::DW_TAG_class_type:
2767 case dwarf::DW_TAG_structure_type:
2768 case dwarf::DW_TAG_union_type:
2769 break;
2770 default:
2771 return getTypeIndex(Ty);
2772 }
2773
2774 const auto *CTy = cast<DICompositeType>(Val: Ty);
2775
2776 TypeLoweringScope S(*this);
2777
2778 // Make sure the forward declaration is emitted first. It's unclear if this
2779 // is necessary, but MSVC does it, and we should follow suit until we can show
2780 // otherwise.
2781 // We only emit a forward declaration for named types.
2782 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2783 TypeIndex FwdDeclTI = getTypeIndex(Ty: CTy);
2784
2785 // Just use the forward decl if we don't have complete type info. This
2786 // might happen if the frontend is using modules and expects the complete
2787 // definition to be emitted elsewhere.
2788 if (CTy->isForwardDecl())
2789 return FwdDeclTI;
2790 }
2791
2792 // Check if we've already translated the complete record type.
2793 // Insert the type with a null TypeIndex to signify that the type is currently
2794 // being lowered.
2795 auto InsertResult = CompleteTypeIndices.try_emplace(Key: CTy);
2796 if (!InsertResult.second)
2797 return InsertResult.first->second;
2798
2799 TypeIndex TI;
2800 switch (CTy->getTag()) {
2801 case dwarf::DW_TAG_class_type:
2802 case dwarf::DW_TAG_structure_type:
2803 TI = lowerCompleteTypeClass(Ty: CTy);
2804 break;
2805 case dwarf::DW_TAG_union_type:
2806 TI = lowerCompleteTypeUnion(Ty: CTy);
2807 break;
2808 default:
2809 llvm_unreachable("not a record");
2810 }
2811
2812 // Update the type index associated with this CompositeType. This cannot
2813 // use the 'InsertResult' iterator above because it is potentially
2814 // invalidated by map insertions which can occur while lowering the class
2815 // type above.
2816 CompleteTypeIndices[CTy] = TI;
2817 return TI;
2818}
2819
2820/// Emit all the deferred complete record types. Try to do this in FIFO order,
2821/// and do this until fixpoint, as each complete record type typically
2822/// references
2823/// many other record types.
2824void CodeViewDebug::emitDeferredCompleteTypes() {
2825 SmallVector<const DICompositeType *, 4> TypesToEmit;
2826 while (!DeferredCompleteTypes.empty()) {
2827 std::swap(LHS&: DeferredCompleteTypes, RHS&: TypesToEmit);
2828 for (const DICompositeType *RecordTy : TypesToEmit)
2829 getCompleteTypeIndex(Ty: RecordTy);
2830 TypesToEmit.clear();
2831 }
2832}
2833
2834void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2835 ArrayRef<LocalVariable> Locals) {
2836 // Get the sorted list of parameters and emit them first.
2837 SmallVector<const LocalVariable *, 6> Params;
2838 for (const LocalVariable &L : Locals)
2839 if (L.DIVar->isParameter())
2840 Params.push_back(Elt: &L);
2841 llvm::sort(C&: Params, Comp: [](const LocalVariable *L, const LocalVariable *R) {
2842 return L->DIVar->getArg() < R->DIVar->getArg();
2843 });
2844 for (const LocalVariable *L : Params)
2845 emitLocalVariable(FI, Var: *L);
2846
2847 // Next emit all non-parameters in the order that we found them.
2848 for (const LocalVariable &L : Locals) {
2849 if (!L.DIVar->isParameter()) {
2850 if (L.ConstantValue) {
2851 // If ConstantValue is set we will emit it as a S_CONSTANT instead of a
2852 // S_LOCAL in order to be able to represent it at all.
2853 const DIType *Ty = L.DIVar->getType();
2854 APSInt Val(*L.ConstantValue);
2855 emitConstantSymbolRecord(DTy: Ty, Value&: Val, QualifiedName: std::string(L.DIVar->getName()));
2856 } else {
2857 emitLocalVariable(FI, Var: L);
2858 }
2859 }
2860 }
2861}
2862
2863void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2864 const LocalVariable &Var) {
2865 // LocalSym record, see SymbolRecord.h for more info.
2866 MCSymbol *LocalEnd = beginSymbolRecord(Kind: SymbolKind::S_LOCAL);
2867
2868 LocalSymFlags Flags = LocalSymFlags::None;
2869 if (Var.DIVar->isParameter())
2870 Flags |= LocalSymFlags::IsParameter;
2871 if (Var.DefRanges.empty())
2872 Flags |= LocalSymFlags::IsOptimizedOut;
2873
2874 OS.AddComment(T: "TypeIndex");
2875 TypeIndex TI = getCompleteTypeIndex(Ty: Var.DIVar->getType());
2876 OS.emitInt32(Value: TI.getIndex());
2877 OS.AddComment(T: "Flags");
2878 OS.emitInt16(Value: static_cast<uint16_t>(Flags));
2879 // Truncate the name so we won't overflow the record length field.
2880 emitNullTerminatedSymbolName(OS, S: Var.DIVar->getName());
2881 endSymbolRecord(SymEnd: LocalEnd);
2882
2883 // Calculate the on disk prefix of the appropriate def range record. The
2884 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2885 // should be big enough to hold all forms without memory allocation.
2886 SmallString<20> BytePrefix;
2887 for (const auto &Pair : Var.DefRanges) {
2888 LocalVarDef DefRange = Pair.first;
2889 const auto &Ranges = Pair.second;
2890 BytePrefix.clear();
2891 if (DefRange.InMemory) {
2892 int Offset = DefRange.DataOffset;
2893 unsigned Reg = DefRange.CVRegister;
2894
2895 // 32-bit x86 call sequences often use PUSH instructions, which disrupt
2896 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
2897 // instead. In frames without stack realignment, $T0 will be the CFA.
2898 if (RegisterId(Reg) == RegisterId::ESP) {
2899 Reg = unsigned(RegisterId::VFRAME);
2900 Offset += FI.OffsetAdjustment;
2901 }
2902
2903 EncodedFramePtrReg EncFP = encodeFramePtrReg(Reg: RegisterId(Reg), CPU: TheCPU);
2904
2905 if (DefRange.DerefOffset != LocalVarDef::NoDeref) {
2906 uint16_t RegRelFlags = 0;
2907 if (DefRange.IsSubfield) {
2908 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2909 (DefRange.StructOffset
2910 << DefRangeRegisterRelSym::OffsetInParentShift);
2911 }
2912 DefRangeRegisterRelIndirHeader DRHdr;
2913 DRHdr.Register = Reg;
2914 DRHdr.Flags = RegRelFlags;
2915 DRHdr.BasePointerOffset = Offset;
2916 DRHdr.OffsetInUdt = DefRange.DerefOffset;
2917 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2918 } else if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2919 (bool(Flags & LocalSymFlags::IsParameter)
2920 ? (EncFP == FI.EncodedParamFramePtrReg)
2921 : (EncFP == FI.EncodedLocalFramePtrReg))) {
2922 // If we can use the chosen frame pointer for the frame and this isn't a
2923 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2924 // Otherwise, use S_DEFRANGE_REGISTER_REL.
2925 DefRangeFramePointerRelHeader DRHdr;
2926 DRHdr.Offset = Offset;
2927 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2928 } else {
2929 uint16_t RegRelFlags = 0;
2930 if (DefRange.IsSubfield) {
2931 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2932 (DefRange.StructOffset
2933 << DefRangeRegisterRelSym::OffsetInParentShift);
2934 }
2935 DefRangeRegisterRelHeader DRHdr;
2936 DRHdr.Register = Reg;
2937 DRHdr.Flags = RegRelFlags;
2938 DRHdr.BasePointerOffset = Offset;
2939 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2940 }
2941 } else {
2942 assert(DefRange.DataOffset == 0 &&
2943 DefRange.DerefOffset == LocalVarDef::NoDeref &&
2944 "unexpected offset into register");
2945 if (DefRange.IsSubfield) {
2946 DefRangeSubfieldRegisterHeader DRHdr;
2947 DRHdr.Register = DefRange.CVRegister;
2948 DRHdr.MayHaveNoName = 0;
2949 DRHdr.OffsetInParent = DefRange.StructOffset;
2950 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2951 } else {
2952 DefRangeRegisterHeader DRHdr;
2953 DRHdr.Register = DefRange.CVRegister;
2954 DRHdr.MayHaveNoName = 0;
2955 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2956 }
2957 }
2958 }
2959}
2960
2961void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2962 const FunctionInfo& FI) {
2963 for (LexicalBlock *Block : Blocks)
2964 emitLexicalBlock(Block: *Block, FI);
2965}
2966
2967/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2968/// lexical block scope.
2969void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2970 const FunctionInfo& FI) {
2971 MCSymbol *RecordEnd = beginSymbolRecord(Kind: SymbolKind::S_BLOCK32);
2972 OS.AddComment(T: "PtrParent");
2973 OS.emitInt32(Value: 0); // PtrParent
2974 OS.AddComment(T: "PtrEnd");
2975 OS.emitInt32(Value: 0); // PtrEnd
2976 OS.AddComment(T: "Code size");
2977 OS.emitAbsoluteSymbolDiff(Hi: Block.End, Lo: Block.Begin, Size: 4); // Code Size
2978 OS.AddComment(T: "Function section relative address");
2979 OS.emitCOFFSecRel32(Symbol: Block.Begin, /*Offset=*/0); // Func Offset
2980 OS.AddComment(T: "Function section index");
2981 OS.emitCOFFSectionIndex(Symbol: FI.Begin); // Func Symbol
2982 OS.AddComment(T: "Lexical block name");
2983 emitNullTerminatedSymbolName(OS, S: Block.Name); // Name
2984 endSymbolRecord(SymEnd: RecordEnd);
2985
2986 // Emit variables local to this lexical block.
2987 emitLocalVariableList(FI, Locals: Block.Locals);
2988 emitGlobalVariableList(Globals: Block.Globals);
2989
2990 // Emit lexical blocks contained within this block.
2991 emitLexicalBlockList(Blocks: Block.Children, FI);
2992
2993 // Close the lexical block scope.
2994 emitEndSymbolRecord(EndKind: SymbolKind::S_END);
2995}
2996
2997/// Convenience routine for collecting lexical block information for a list
2998/// of lexical scopes.
2999void CodeViewDebug::collectLexicalBlockInfo(
3000 SmallVectorImpl<LexicalScope *> &Scopes,
3001 SmallVectorImpl<LexicalBlock *> &Blocks,
3002 SmallVectorImpl<LocalVariable> &Locals,
3003 SmallVectorImpl<CVGlobalVariable> &Globals) {
3004 for (LexicalScope *Scope : Scopes)
3005 collectLexicalBlockInfo(Scope&: *Scope, ParentBlocks&: Blocks, ParentLocals&: Locals, ParentGlobals&: Globals);
3006}
3007
3008/// Populate the lexical blocks and local variable lists of the parent with
3009/// information about the specified lexical scope.
3010void CodeViewDebug::collectLexicalBlockInfo(
3011 LexicalScope &Scope,
3012 SmallVectorImpl<LexicalBlock *> &ParentBlocks,
3013 SmallVectorImpl<LocalVariable> &ParentLocals,
3014 SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
3015 if (Scope.isAbstractScope())
3016 return;
3017
3018 // Gather information about the lexical scope including local variables,
3019 // global variables, and address ranges.
3020 bool IgnoreScope = false;
3021 auto LI = ScopeVariables.find(Val: &Scope);
3022 SmallVectorImpl<LocalVariable> *Locals =
3023 LI != ScopeVariables.end() ? &LI->second : nullptr;
3024 auto GI = ScopeGlobals.find(Val: Scope.getScopeNode());
3025 SmallVectorImpl<CVGlobalVariable> *Globals =
3026 GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
3027 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Val: Scope.getScopeNode());
3028 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
3029
3030 // Ignore lexical scopes which do not contain variables.
3031 if (!Locals && !Globals)
3032 IgnoreScope = true;
3033
3034 // Ignore lexical scopes which are not lexical blocks.
3035 if (!DILB)
3036 IgnoreScope = true;
3037
3038 // Ignore scopes which have too many address ranges to represent in the
3039 // current CodeView format or do not have a valid address range.
3040 //
3041 // For lexical scopes with multiple address ranges you may be tempted to
3042 // construct a single range covering every instruction where the block is
3043 // live and everything in between. Unfortunately, Visual Studio only
3044 // displays variables from the first matching lexical block scope. If the
3045 // first lexical block contains exception handling code or cold code which
3046 // is moved to the bottom of the routine creating a single range covering
3047 // nearly the entire routine, then it will hide all other lexical blocks
3048 // and the variables they contain.
3049 if (Ranges.size() != 1 || !getLabelAfterInsn(MI: Ranges.front().second))
3050 IgnoreScope = true;
3051
3052 if (IgnoreScope) {
3053 // This scope can be safely ignored and eliminating it will reduce the
3054 // size of the debug information. Be sure to collect any variable and scope
3055 // information from the this scope or any of its children and collapse them
3056 // into the parent scope.
3057 if (Locals)
3058 ParentLocals.append(in_start: Locals->begin(), in_end: Locals->end());
3059 if (Globals)
3060 ParentGlobals.append(in_start: Globals->begin(), in_end: Globals->end());
3061 collectLexicalBlockInfo(Scopes&: Scope.getChildren(),
3062 Blocks&: ParentBlocks,
3063 Locals&: ParentLocals,
3064 Globals&: ParentGlobals);
3065 return;
3066 }
3067
3068 // Create a new CodeView lexical block for this lexical scope. If we've
3069 // seen this DILexicalBlock before then the scope tree is malformed and
3070 // we can handle this gracefully by not processing it a second time.
3071 auto BlockInsertion = CurFn->LexicalBlocks.try_emplace(k: DILB);
3072 if (!BlockInsertion.second)
3073 return;
3074
3075 // Create a lexical block containing the variables and collect the
3076 // lexical block information for the children.
3077 const InsnRange &Range = Ranges.front();
3078 assert(Range.first && Range.second);
3079 LexicalBlock &Block = BlockInsertion.first->second;
3080 Block.Begin = getLabelBeforeInsn(MI: Range.first);
3081 Block.End = getLabelAfterInsn(MI: Range.second);
3082 assert(Block.Begin && "missing label for scope begin");
3083 assert(Block.End && "missing label for scope end");
3084 Block.Name = DILB->getName();
3085 if (Locals)
3086 Block.Locals = std::move(*Locals);
3087 if (Globals)
3088 Block.Globals = std::move(*Globals);
3089 ParentBlocks.push_back(Elt: &Block);
3090 collectLexicalBlockInfo(Scopes&: Scope.getChildren(),
3091 Blocks&: Block.Children,
3092 Locals&: Block.Locals,
3093 Globals&: Block.Globals);
3094}
3095
3096void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
3097 const Function &GV = MF->getFunction();
3098 assert(FnDebugInfo.count(&GV));
3099 assert(CurFn == FnDebugInfo[&GV].get());
3100
3101 collectVariableInfo(SP: GV.getSubprogram());
3102
3103 // Build the lexical block structure to emit for this routine.
3104 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
3105 collectLexicalBlockInfo(Scope&: *CFS,
3106 ParentBlocks&: CurFn->ChildBlocks,
3107 ParentLocals&: CurFn->Locals,
3108 ParentGlobals&: CurFn->Globals);
3109
3110 // Clear the scope and variable information from the map which will not be
3111 // valid after we have finished processing this routine. This also prepares
3112 // the map for the subsequent routine.
3113 ScopeVariables.clear();
3114
3115 // Don't emit anything if we don't have any line tables.
3116 // Thunks are compiler-generated and probably won't have source correlation.
3117 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
3118 FnDebugInfo.erase(Key: &GV);
3119 CurFn = nullptr;
3120 return;
3121 }
3122
3123 // Find heap alloc sites and add to list.
3124 for (const auto &MBB : *MF) {
3125 for (const auto &MI : MBB) {
3126 if (MDNode *MD = MI.getHeapAllocMarker()) {
3127 CurFn->HeapAllocSites.push_back(x: std::make_tuple(args: getLabelBeforeInsn(MI: &MI),
3128 args: getLabelAfterInsn(MI: &MI),
3129 args: dyn_cast<DIType>(Val: MD)));
3130 }
3131 }
3132 }
3133
3134 bool isThumb = MMI->getModule()->getTargetTriple().getArch() ==
3135 llvm::Triple::ArchType::thumb;
3136 collectDebugInfoForJumpTables(MF, isThumb);
3137
3138 CurFn->Annotations = MF->getCodeViewAnnotations();
3139
3140 CurFn->End = Asm->getFunctionEnd();
3141
3142 CurFn = nullptr;
3143}
3144
3145// Usable locations are valid with non-zero line numbers, or artificial
3146// subprograms because they are associated to the corresponding line within the
3147// inlined callee.
3148//
3149// A line number of zero corresponds to optimized code that doesn't have a
3150// distinct source location.
3151//
3152// In this case, we try to use the previous or next source location depending on
3153// the context.
3154static bool isUsableDebugLoc(DebugLoc DL) {
3155 if (!DL)
3156 return false;
3157 if (DL.getLine() != 0)
3158 return true;
3159 if (const DILocalScope *Scope = DL->getScope())
3160 return Scope->getSubprogram()->isArtificial();
3161 return false;
3162}
3163
3164void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
3165 DebugHandlerBase::beginInstruction(MI);
3166
3167 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
3168 if (!Asm || !CurFn || MI->isDebugInstr() ||
3169 MI->getFlag(Flag: MachineInstr::FrameSetup))
3170 return;
3171
3172 // If the first instruction of a new MBB has no location, find the first
3173 // instruction with a location and use that.
3174 DebugLoc DL = MI->getDebugLoc();
3175 if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) {
3176 for (const auto &NextMI : *MI->getParent()) {
3177 if (NextMI.isDebugInstr())
3178 continue;
3179 DL = NextMI.getDebugLoc();
3180 if (isUsableDebugLoc(DL))
3181 break;
3182 }
3183 // FIXME: Handle the case where the BB has no valid locations. This would
3184 // probably require doing a real dataflow analysis.
3185 }
3186 PrevInstBB = MI->getParent();
3187
3188 // If we still don't have a debug location, don't record a location.
3189 if (!isUsableDebugLoc(DL))
3190 return;
3191
3192 maybeRecordLocation(DL, MF: Asm->MF);
3193}
3194
3195MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
3196 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
3197 *EndLabel = MMI->getContext().createTempSymbol();
3198 OS.emitInt32(Value: unsigned(Kind));
3199 OS.AddComment(T: "Subsection size");
3200 OS.emitAbsoluteSymbolDiff(Hi: EndLabel, Lo: BeginLabel, Size: 4);
3201 OS.emitLabel(Symbol: BeginLabel);
3202 return EndLabel;
3203}
3204
3205void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
3206 OS.emitLabel(Symbol: EndLabel);
3207 // Every subsection must be aligned to a 4-byte boundary.
3208 OS.emitValueToAlignment(Alignment: Align(4));
3209}
3210
3211MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
3212 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
3213 *EndLabel = MMI->getContext().createTempSymbol();
3214 OS.AddComment(T: "Record length");
3215 OS.emitAbsoluteSymbolDiff(Hi: EndLabel, Lo: BeginLabel, Size: 2);
3216 OS.emitLabel(Symbol: BeginLabel);
3217 if (OS.isVerboseAsm())
3218 OS.AddComment(T: "Record kind: " + getSymbolTypeNames().toString(Value: SymKind));
3219 OS.emitInt16(Value: unsigned(SymKind));
3220 return EndLabel;
3221}
3222
3223void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
3224 // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
3225 // an extra copy of every symbol record in LLD. This increases object file
3226 // size by less than 1% in the clang build, and is compatible with the Visual
3227 // C++ linker.
3228 OS.emitValueToAlignment(Alignment: Align(4));
3229 OS.emitLabel(Symbol: SymEnd);
3230}
3231
3232void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
3233 OS.AddComment(T: "Record length");
3234 OS.emitInt16(Value: 2);
3235 if (OS.isVerboseAsm())
3236 OS.AddComment(T: "Record kind: " + getSymbolTypeNames().toString(Value: EndKind));
3237 OS.emitInt16(Value: uint16_t(EndKind)); // Record Kind
3238}
3239
3240void CodeViewDebug::emitDebugInfoForUDTs(
3241 const std::vector<std::pair<std::string, const DIType *>> &UDTs) {
3242#ifndef NDEBUG
3243 size_t OriginalSize = UDTs.size();
3244#endif
3245 for (const auto &UDT : UDTs) {
3246 const DIType *T = UDT.second;
3247 assert(shouldEmitUdt(T));
3248 MCSymbol *UDTRecordEnd = beginSymbolRecord(SymKind: SymbolKind::S_UDT);
3249 OS.AddComment(T: "Type");
3250 OS.emitInt32(Value: getCompleteTypeIndex(Ty: T).getIndex());
3251 assert(OriginalSize == UDTs.size() &&
3252 "getCompleteTypeIndex found new UDTs!");
3253 emitNullTerminatedSymbolName(OS, S: UDT.first);
3254 endSymbolRecord(SymEnd: UDTRecordEnd);
3255 }
3256}
3257
3258void CodeViewDebug::collectGlobalOrStaticLocalVariableInfo(
3259 const DIGlobalVariableExpression *GVE) {
3260 const DIGlobalVariable *DIGV = GVE->getVariable();
3261 const DIExpression *DIE = GVE->getExpression();
3262 // Don't emit string literals in CodeView, as the only useful parts are
3263 // generally the filename and line number, which isn't possible to output
3264 // in CodeView. String literals should be the only unnamed GlobalVariable
3265 // with debug info.
3266 if (DIGV->getName().empty())
3267 return;
3268
3269 if ((DIE->getNumElements() == 2) &&
3270 (DIE->getElement(I: 0) == dwarf::DW_OP_plus_uconst))
3271 // Record the constant offset for the variable.
3272 //
3273 // A Fortran common block uses this idiom to encode the offset
3274 // of a variable from the common block's starting address.
3275 CVGlobalVariableOffsets.insert(KV: std::make_pair(x&: DIGV, y: DIE->getElement(I: 1)));
3276
3277 // Emit constant global variables in a global symbol section.
3278 if (!GlobalMap.count(Val: GVE) && DIE->isConstant())
3279 GlobalVariables.emplace_back(Args: CVGlobalVariable{.DIGV: DIGV, .GVInfo: DIE});
3280
3281 const auto *GV = GlobalMap.lookup(Val: GVE);
3282 if (!GV || GV->isDeclarationForLinker())
3283 return;
3284
3285 DIScope *Scope = DIGV->getScope();
3286 SmallVector<CVGlobalVariable, 1> *VariableList;
3287 if (Scope && isa<DILocalScope>(Val: Scope)) {
3288 // Locate a global variable list for this scope, creating one if
3289 // necessary.
3290 auto Insertion =
3291 ScopeGlobals.insert(KV: {Scope, std::unique_ptr<GlobalVariableList>()});
3292 if (Insertion.second)
3293 Insertion.first->second = std::make_unique<GlobalVariableList>();
3294 VariableList = Insertion.first->second.get();
3295 } else if (GV->hasComdat()) {
3296 // Emit this global variable into a COMDAT section.
3297 VariableList = &ComdatVariables;
3298 } else {
3299 // Emit this global variable in a single global symbol section.
3300 VariableList = &GlobalVariables;
3301 }
3302 VariableList->emplace_back(Args: CVGlobalVariable{.DIGV: DIGV, .GVInfo: GV});
3303}
3304
3305void CodeViewDebug::collectGlobalVariableInfo() {
3306 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
3307 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
3308 GV.getDebugInfo(GVs&: GVEs);
3309 for (const auto *GVE : GVEs)
3310 GlobalMap[GVE] = &GV;
3311 }
3312
3313 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata(Name: "llvm.dbg.cu");
3314 for (const MDNode *Node : CUs->operands()) {
3315 const auto *CU = cast<DICompileUnit>(Val: Node);
3316 for (const auto *GVE : CU->getGlobalVariables()) {
3317 collectGlobalOrStaticLocalVariableInfo(GVE);
3318 }
3319 }
3320}
3321
3322void CodeViewDebug::collectDebugInfoForGlobals() {
3323 for (const CVGlobalVariable &CVGV : GlobalVariables) {
3324 const DIGlobalVariable *DIGV = CVGV.DIGV;
3325 const DIScope *Scope = DIGV->getScope();
3326 getCompleteTypeIndex(Ty: DIGV->getType());
3327 getFullyQualifiedName(Scope, Name: DIGV->getName());
3328 }
3329
3330 for (const CVGlobalVariable &CVGV : ComdatVariables) {
3331 const DIGlobalVariable *DIGV = CVGV.DIGV;
3332 const DIScope *Scope = DIGV->getScope();
3333 getCompleteTypeIndex(Ty: DIGV->getType());
3334 getFullyQualifiedName(Scope, Name: DIGV->getName());
3335 }
3336}
3337
3338void CodeViewDebug::emitDebugInfoForGlobals() {
3339 // First, emit all globals that are not in a comdat in a single symbol
3340 // substream. MSVC doesn't like it if the substream is empty, so only open
3341 // it if we have at least one global to emit.
3342 switchToDebugSectionForSymbol(GVSym: nullptr);
3343 if (!GlobalVariables.empty() || !StaticConstMembers.empty()) {
3344 OS.AddComment(T: "Symbol subsection for globals");
3345 MCSymbol *EndLabel = beginCVSubsection(Kind: DebugSubsectionKind::Symbols);
3346 emitGlobalVariableList(Globals: GlobalVariables);
3347 emitStaticConstMemberList();
3348 endCVSubsection(EndLabel);
3349 }
3350
3351 // Second, emit each global that is in a comdat into its own .debug$S
3352 // section along with its own symbol substream.
3353 for (const CVGlobalVariable &CVGV : ComdatVariables) {
3354 const GlobalVariable *GV = cast<const GlobalVariable *>(Val: CVGV.GVInfo);
3355 MCSymbol *GVSym = Asm->getSymbol(GV);
3356 OS.AddComment(T: "Symbol subsection for " +
3357 Twine(GlobalValue::dropLLVMManglingEscape(Name: GV->getName())));
3358 switchToDebugSectionForSymbol(GVSym);
3359 MCSymbol *EndLabel = beginCVSubsection(Kind: DebugSubsectionKind::Symbols);
3360 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3361 emitDebugInfoForGlobal(CVGV);
3362 endCVSubsection(EndLabel);
3363 }
3364}
3365
3366void CodeViewDebug::emitDebugInfoForRetainedTypes() {
3367 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata(Name: "llvm.dbg.cu");
3368 for (const MDNode *Node : CUs->operands()) {
3369 for (auto *Ty : cast<DICompileUnit>(Val: Node)->getRetainedTypes()) {
3370 if (DIType *RT = dyn_cast<DIType>(Val: Ty)) {
3371 getTypeIndex(Ty: RT);
3372 // FIXME: Add to global/local DTU list.
3373 }
3374 }
3375 }
3376}
3377
3378// Emit each global variable in the specified array.
3379void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
3380 for (const CVGlobalVariable &CVGV : Globals) {
3381 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3382 emitDebugInfoForGlobal(CVGV);
3383 }
3384}
3385
3386void CodeViewDebug::emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,
3387 const std::string &QualifiedName) {
3388 MCSymbol *SConstantEnd = beginSymbolRecord(SymKind: SymbolKind::S_CONSTANT);
3389 OS.AddComment(T: "Type");
3390 OS.emitInt32(Value: getTypeIndex(Ty: DTy).getIndex());
3391
3392 OS.AddComment(T: "Value");
3393
3394 // Encoded integers shouldn't need more than 10 bytes.
3395 uint8_t Data[10];
3396 BinaryStreamWriter Writer(Data, llvm::endianness::little);
3397 CodeViewRecordIO IO(Writer);
3398 cantFail(Err: IO.mapEncodedInteger(Value));
3399 StringRef SRef((char *)Data, Writer.getOffset());
3400 OS.emitBinaryData(Data: SRef);
3401
3402 OS.AddComment(T: "Name");
3403 emitNullTerminatedSymbolName(OS, S: QualifiedName);
3404 endSymbolRecord(SymEnd: SConstantEnd);
3405}
3406
3407void CodeViewDebug::emitStaticConstMemberList() {
3408 for (const DIDerivedType *DTy : StaticConstMembers) {
3409 const DIScope *Scope = DTy->getScope();
3410
3411 APSInt Value;
3412 if (const ConstantInt *CI =
3413 dyn_cast_or_null<ConstantInt>(Val: DTy->getConstant()))
3414 Value = APSInt(CI->getValue(),
3415 DebugHandlerBase::isUnsignedDIType(Ty: DTy->getBaseType()));
3416 else if (const ConstantFP *CFP =
3417 dyn_cast_or_null<ConstantFP>(Val: DTy->getConstant()))
3418 Value = APSInt(CFP->getValueAPF().bitcastToAPInt(), true);
3419 else
3420 llvm_unreachable("cannot emit a constant without a value");
3421
3422 emitConstantSymbolRecord(DTy: DTy->getBaseType(), Value,
3423 QualifiedName: getFullyQualifiedName(Scope, Name: DTy->getName()));
3424 }
3425}
3426
3427static bool isFloatDIType(const DIType *Ty) {
3428 if (isa<DICompositeType>(Val: Ty))
3429 return false;
3430
3431 if (auto *DTy = dyn_cast<DIDerivedType>(Val: Ty)) {
3432 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
3433 if (T == dwarf::DW_TAG_pointer_type ||
3434 T == dwarf::DW_TAG_ptr_to_member_type ||
3435 T == dwarf::DW_TAG_reference_type ||
3436 T == dwarf::DW_TAG_rvalue_reference_type)
3437 return false;
3438 assert(DTy->getBaseType() && "Expected valid base type");
3439 return isFloatDIType(Ty: DTy->getBaseType());
3440 }
3441
3442 auto *BTy = cast<DIBasicType>(Val: Ty);
3443 return (BTy->getEncoding() == dwarf::DW_ATE_float);
3444}
3445
3446void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
3447 const DIGlobalVariable *DIGV = CVGV.DIGV;
3448
3449 const DIScope *Scope = DIGV->getScope();
3450 // For static data members, get the scope from the declaration.
3451 if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
3452 Val: DIGV->getRawStaticDataMemberDeclaration()))
3453 Scope = MemberDecl->getScope();
3454 // For static local variables and Fortran, the scoping portion is elided
3455 // in its name so that we can reference the variable in the command line
3456 // of the VS debugger.
3457 std::string QualifiedName =
3458 (moduleIsInFortran() || (Scope && isa<DILocalScope>(Val: Scope)))
3459 ? std::string(DIGV->getName())
3460 : getFullyQualifiedName(Scope, Name: DIGV->getName());
3461
3462 if (const GlobalVariable *GV =
3463 dyn_cast_if_present<const GlobalVariable *>(Val: CVGV.GVInfo)) {
3464 // DataSym record, see SymbolRecord.h for more info. Thread local data
3465 // happens to have the same format as global data.
3466 MCSymbol *GVSym = Asm->getSymbol(GV);
3467 SymbolKind DataSym = GV->isThreadLocal()
3468 ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3469 : SymbolKind::S_GTHREAD32)
3470 : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
3471 : SymbolKind::S_GDATA32);
3472 MCSymbol *DataEnd = beginSymbolRecord(SymKind: DataSym);
3473 OS.AddComment(T: "Type");
3474 OS.emitInt32(Value: getCompleteTypeIndex(Ty: DIGV->getType()).getIndex());
3475 OS.AddComment(T: "DataOffset");
3476
3477 // Use the offset seen while collecting info on globals.
3478 uint64_t Offset = CVGlobalVariableOffsets.lookup(Val: DIGV);
3479 OS.emitCOFFSecRel32(Symbol: GVSym, Offset);
3480
3481 OS.AddComment(T: "Segment");
3482 OS.emitCOFFSectionIndex(Symbol: GVSym);
3483 OS.AddComment(T: "Name");
3484 const unsigned LengthOfDataRecord = 12;
3485 emitNullTerminatedSymbolName(OS, S: QualifiedName, MaxFixedRecordLength: LengthOfDataRecord);
3486 endSymbolRecord(SymEnd: DataEnd);
3487 } else {
3488 const DIExpression *DIE = cast<const DIExpression *>(Val: CVGV.GVInfo);
3489 assert(DIE->isConstant() &&
3490 "Global constant variables must contain a constant expression.");
3491
3492 // Use unsigned for floats.
3493 bool isUnsigned = isFloatDIType(Ty: DIGV->getType())
3494 ? true
3495 : DebugHandlerBase::isUnsignedDIType(Ty: DIGV->getType());
3496 APSInt Value(APInt(/*BitWidth=*/64, DIE->getElement(I: 1)), isUnsigned);
3497 emitConstantSymbolRecord(DTy: DIGV->getType(), Value, QualifiedName);
3498 }
3499}
3500
3501void forEachJumpTableBranch(
3502 const MachineFunction *MF, bool isThumb,
3503 const std::function<void(const MachineJumpTableInfo &, const MachineInstr &,
3504 int64_t)> &Callback) {
3505 auto JTI = MF->getJumpTableInfo();
3506 if (JTI && !JTI->isEmpty()) {
3507#ifndef NDEBUG
3508 auto UsedJTs = llvm::SmallBitVector(JTI->getJumpTables().size());
3509#endif
3510 for (const auto &MBB : *MF) {
3511 // Search for indirect branches...
3512 const auto LastMI = MBB.getFirstTerminator();
3513 if (LastMI != MBB.end() && LastMI->isIndirectBranch()) {
3514 if (isThumb) {
3515 // ... that directly use jump table operands.
3516 // NOTE: ARM uses pattern matching to lower its BR_JT SDNode to
3517 // machine instructions, hence inserting a JUMP_TABLE_DEBUG_INFO node
3518 // interferes with this process *but* the resulting pseudo-instruction
3519 // uses a Jump Table operand, so extract the jump table index directly
3520 // from that.
3521 for (const auto &MO : LastMI->operands()) {
3522 if (MO.isJTI()) {
3523 unsigned Index = MO.getIndex();
3524#ifndef NDEBUG
3525 UsedJTs.set(Index);
3526#endif
3527 Callback(*JTI, *LastMI, Index);
3528 break;
3529 }
3530 }
3531 } else {
3532 // ... that have jump table debug info.
3533 // NOTE: The debug info is inserted as a JUMP_TABLE_DEBUG_INFO node
3534 // when lowering the BR_JT SDNode to an indirect branch.
3535 for (auto I = MBB.instr_rbegin(), E = MBB.instr_rend(); I != E; ++I) {
3536 if (I->isJumpTableDebugInfo()) {
3537 unsigned Index = I->getOperand(i: 0).getImm();
3538#ifndef NDEBUG
3539 UsedJTs.set(Index);
3540#endif
3541 Callback(*JTI, *LastMI, Index);
3542 break;
3543 }
3544 }
3545 }
3546 }
3547 }
3548#ifndef NDEBUG
3549 assert(UsedJTs.all() &&
3550 "Some of jump tables were not used in a debug info instruction");
3551#endif
3552 }
3553}
3554
3555void CodeViewDebug::discoverJumpTableBranches(const MachineFunction *MF,
3556 bool isThumb) {
3557 forEachJumpTableBranch(
3558 MF, isThumb,
3559 Callback: [this](const MachineJumpTableInfo &, const MachineInstr &BranchMI,
3560 int64_t) { requestLabelBeforeInsn(MI: &BranchMI); });
3561}
3562
3563void CodeViewDebug::collectDebugInfoForJumpTables(const MachineFunction *MF,
3564 bool isThumb) {
3565 forEachJumpTableBranch(
3566 MF, isThumb,
3567 Callback: [this, MF](const MachineJumpTableInfo &JTI, const MachineInstr &BranchMI,
3568 int64_t JumpTableIndex) {
3569 // For label-difference jump tables, find the base expression.
3570 // Otherwise the jump table uses an absolute address (so no base
3571 // is required).
3572 const MCSymbol *Base;
3573 uint64_t BaseOffset = 0;
3574 const MCSymbol *Branch = getLabelBeforeInsn(MI: &BranchMI);
3575 JumpTableEntrySize EntrySize;
3576 switch (JTI.getEntryKind()) {
3577 case MachineJumpTableInfo::EK_Custom32:
3578 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
3579 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
3580 llvm_unreachable(
3581 "EK_Custom32, EK_GPRel32BlockAddress, and "
3582 "EK_GPRel64BlockAddress should never be emitted for COFF");
3583 case MachineJumpTableInfo::EK_BlockAddress:
3584 // Each entry is an absolute address.
3585 EntrySize = JumpTableEntrySize::Pointer;
3586 Base = nullptr;
3587 break;
3588 case MachineJumpTableInfo::EK_Inline:
3589 case MachineJumpTableInfo::EK_LabelDifference32:
3590 case MachineJumpTableInfo::EK_LabelDifference64:
3591 // Ask the AsmPrinter.
3592 std::tie(args&: Base, args&: BaseOffset, args&: Branch, args&: EntrySize) =
3593 Asm->getCodeViewJumpTableInfo(JTI: JumpTableIndex, BranchInstr: &BranchMI, BranchLabel: Branch);
3594 break;
3595 }
3596
3597 const MachineJumpTableEntry &JTE = JTI.getJumpTables()[JumpTableIndex];
3598 JumpTableInfo CVJTI{.EntrySize: EntrySize,
3599 .Base: Base,
3600 .BaseOffset: BaseOffset,
3601 .Branch: Branch,
3602 .Table: MF->getJTISymbol(JTI: JumpTableIndex, Ctx&: MMI->getContext()),
3603 .TableSize: JTE.MBBs.size(),
3604 .Cases: {}};
3605 for (const auto &MBB : JTE.MBBs)
3606 CVJTI.Cases.push_back(x: MBB->getSymbol());
3607 CurFn->JumpTables.push_back(x: std::move(CVJTI));
3608 });
3609}
3610
3611void CodeViewDebug::emitDebugInfoForJumpTables(const FunctionInfo &FI) {
3612 // Emit S_LABEL32 records for each jump target
3613 for (const auto &JumpTable : FI.JumpTables) {
3614 for (const auto &CaseSym : JumpTable.Cases) {
3615 MCSymbol *LabelEnd = beginSymbolRecord(SymKind: SymbolKind::S_LABEL32);
3616 OS.AddComment(T: "Offset and segment");
3617 OS.emitCOFFSecRel32(Symbol: CaseSym, Offset: 0);
3618 OS.AddComment(T: "Flags");
3619 OS.emitInt8(Value: 0);
3620 emitNullTerminatedSymbolName(OS, S: CaseSym->getName());
3621 endSymbolRecord(SymEnd: LabelEnd);
3622 }
3623 }
3624
3625 for (const auto &JumpTable : FI.JumpTables) {
3626 MCSymbol *JumpTableEnd = beginSymbolRecord(SymKind: SymbolKind::S_ARMSWITCHTABLE);
3627 if (JumpTable.Base) {
3628 OS.AddComment(T: "Base offset");
3629 OS.emitCOFFSecRel32(Symbol: JumpTable.Base, Offset: JumpTable.BaseOffset);
3630 OS.AddComment(T: "Base section index");
3631 OS.emitCOFFSectionIndex(Symbol: JumpTable.Base);
3632 } else {
3633 OS.AddComment(T: "Base offset");
3634 OS.emitInt32(Value: 0);
3635 OS.AddComment(T: "Base section index");
3636 OS.emitInt16(Value: 0);
3637 }
3638 OS.AddComment(T: "Switch type");
3639 OS.emitInt16(Value: static_cast<uint16_t>(JumpTable.EntrySize));
3640 OS.AddComment(T: "Branch offset");
3641 OS.emitCOFFSecRel32(Symbol: JumpTable.Branch, /*Offset=*/0);
3642 OS.AddComment(T: "Table offset");
3643 OS.emitCOFFSecRel32(Symbol: JumpTable.Table, /*Offset=*/0);
3644 OS.AddComment(T: "Branch section index");
3645 OS.emitCOFFSectionIndex(Symbol: JumpTable.Branch);
3646 OS.AddComment(T: "Table section index");
3647 OS.emitCOFFSectionIndex(Symbol: JumpTable.Table);
3648 OS.AddComment(T: "Entries count");
3649 OS.emitInt32(Value: JumpTable.TableSize);
3650 endSymbolRecord(SymEnd: JumpTableEnd);
3651 }
3652}
3653
3654void CodeViewDebug::emitInlinees(
3655 const SmallSet<codeview::TypeIndex, 1> &Inlinees) {
3656 // Divide the list of inlinees into chunks such that each chunk fits within
3657 // one record.
3658 constexpr size_t ChunkSize =
3659 (MaxRecordLength - sizeof(SymbolKind) - sizeof(uint32_t)) /
3660 sizeof(uint32_t);
3661
3662 SmallVector<TypeIndex> SortedInlinees{Inlinees.begin(), Inlinees.end()};
3663 llvm::sort(C&: SortedInlinees);
3664
3665 size_t CurrentIndex = 0;
3666 while (CurrentIndex < SortedInlinees.size()) {
3667 auto Symbol = beginSymbolRecord(SymKind: SymbolKind::S_INLINEES);
3668 auto CurrentChunkSize =
3669 std::min(a: ChunkSize, b: SortedInlinees.size() - CurrentIndex);
3670 OS.AddComment(T: "Count");
3671 OS.emitInt32(Value: CurrentChunkSize);
3672
3673 const size_t CurrentChunkEnd = CurrentIndex + CurrentChunkSize;
3674 for (; CurrentIndex < CurrentChunkEnd; ++CurrentIndex) {
3675 OS.AddComment(T: "Inlinee");
3676 OS.emitInt32(Value: SortedInlinees[CurrentIndex].getIndex());
3677 }
3678 endSymbolRecord(SymEnd: Symbol);
3679 }
3680}
3681