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