1 //===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing Microsoft CodeView debug info.
12 //===----------------------------------------------------------------------===//
14 #include "CodeViewDebug.h"
15 #include "llvm/ADT/TinyPtrVector.h"
16 #include "llvm/DebugInfo/CodeView/CVTypeDumper.h"
17 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
18 #include "llvm/DebugInfo/CodeView/CodeView.h"
19 #include "llvm/DebugInfo/CodeView/Line.h"
20 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
21 #include "llvm/DebugInfo/CodeView/TypeDatabase.h"
22 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
23 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
24 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
25 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
26 #include "llvm/DebugInfo/MSF/ByteStream.h"
27 #include "llvm/DebugInfo/MSF/StreamReader.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCSectionCOFF.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Support/COFF.h"
34 #include "llvm/Support/ScopedPrinter.h"
35 #include "llvm/Target/TargetFrameLowering.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
40 using namespace llvm::codeview;
41 using namespace llvm::msf;
43 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
44 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), Allocator(),
45 TypeTable(Allocator), CurFn(nullptr) {
46 // If module doesn't have named metadata anchors or COFF debug section
47 // is not available, skip any debug info related stuff.
48 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
49 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
54 // Tell MMI that we have debug info.
55 MMI->setDebugInfoAvailability(true);
58 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
59 std::string &Filepath = FileToFilepathMap[File];
60 if (!Filepath.empty())
63 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
65 // Clang emits directory and relative filename info into the IR, but CodeView
66 // operates on full paths. We could change Clang to emit full paths too, but
67 // that would increase the IR size and probably not needed for other users.
68 // For now, just concatenate and canonicalize the path here.
69 if (Filename.find(':') == 1)
72 Filepath = (Dir + "\\" + Filename).str();
74 // Canonicalize the path. We have to do it textually because we may no longer
75 // have access the file in the filesystem.
76 // First, replace all slashes with backslashes.
77 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
79 // Remove all "\.\" with "\".
81 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
82 Filepath.erase(Cursor, 2);
84 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
85 // path should be well-formatted, e.g. start with a drive letter, etc.
87 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
88 // Something's wrong if the path starts with "\..\", abort.
92 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
93 if (PrevSlash == std::string::npos)
94 // Something's wrong, abort.
97 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
98 // The next ".." might be following the one we've just erased.
102 // Remove all duplicate backslashes.
104 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
105 Filepath.erase(Cursor, 1);
110 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
111 unsigned NextId = FileIdMap.size() + 1;
112 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
113 if (Insertion.second) {
114 // We have to compute the full filepath and emit a .cv_file directive.
115 StringRef FullPath = getFullFilepath(F);
116 bool Success = OS.EmitCVFileDirective(NextId, FullPath);
118 assert(Success && ".cv_file directive failed");
120 return Insertion.first->second;
123 CodeViewDebug::InlineSite &
124 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
125 const DISubprogram *Inlinee) {
126 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
127 InlineSite *Site = &SiteInsertion.first->second;
128 if (SiteInsertion.second) {
129 unsigned ParentFuncId = CurFn->FuncId;
130 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
132 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
135 Site->SiteFuncId = NextFuncId++;
136 OS.EmitCVInlineSiteIdDirective(
137 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
138 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
139 Site->Inlinee = Inlinee;
140 InlinedSubprograms.insert(Inlinee);
141 getFuncIdForSubprogram(Inlinee);
146 static StringRef getPrettyScopeName(const DIScope *Scope) {
147 StringRef ScopeName = Scope->getName();
148 if (!ScopeName.empty())
151 switch (Scope->getTag()) {
152 case dwarf::DW_TAG_enumeration_type:
153 case dwarf::DW_TAG_class_type:
154 case dwarf::DW_TAG_structure_type:
155 case dwarf::DW_TAG_union_type:
156 return "<unnamed-tag>";
157 case dwarf::DW_TAG_namespace:
158 return "`anonymous namespace'";
164 static const DISubprogram *getQualifiedNameComponents(
165 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
166 const DISubprogram *ClosestSubprogram = nullptr;
167 while (Scope != nullptr) {
168 if (ClosestSubprogram == nullptr)
169 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
170 StringRef ScopeName = getPrettyScopeName(Scope);
171 if (!ScopeName.empty())
172 QualifiedNameComponents.push_back(ScopeName);
173 Scope = Scope->getScope().resolve();
175 return ClosestSubprogram;
178 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
179 StringRef TypeName) {
180 std::string FullyQualifiedName;
181 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
182 FullyQualifiedName.append(QualifiedNameComponent);
183 FullyQualifiedName.append("::");
185 FullyQualifiedName.append(TypeName);
186 return FullyQualifiedName;
189 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
190 SmallVector<StringRef, 5> QualifiedNameComponents;
191 getQualifiedNameComponents(Scope, QualifiedNameComponents);
192 return getQualifiedName(QualifiedNameComponents, Name);
195 struct CodeViewDebug::TypeLoweringScope {
196 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
197 ~TypeLoweringScope() {
198 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
199 // inner TypeLoweringScopes don't attempt to emit deferred types.
200 if (CVD.TypeEmissionLevel == 1)
201 CVD.emitDeferredCompleteTypes();
202 --CVD.TypeEmissionLevel;
207 static std::string getFullyQualifiedName(const DIScope *Ty) {
208 const DIScope *Scope = Ty->getScope().resolve();
209 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
212 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
213 // No scope means global scope and that uses the zero index.
214 if (!Scope || isa<DIFile>(Scope))
217 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
219 // Check if we've already translated this scope.
220 auto I = TypeIndices.find({Scope, nullptr});
221 if (I != TypeIndices.end())
224 // Build the fully qualified name of the scope.
225 std::string ScopeName = getFullyQualifiedName(Scope);
226 StringIdRecord SID(TypeIndex(), ScopeName);
227 auto TI = TypeTable.writeKnownType(SID);
228 return recordTypeIndexForDINode(Scope, TI);
231 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
234 // Check if we've already translated this subprogram.
235 auto I = TypeIndices.find({SP, nullptr});
236 if (I != TypeIndices.end())
239 // The display name includes function template arguments. Drop them to match
241 StringRef DisplayName = SP->getDisplayName().split('<').first;
243 const DIScope *Scope = SP->getScope().resolve();
245 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
246 // If the scope is a DICompositeType, then this must be a method. Member
247 // function types take some special handling, and require access to the
249 TypeIndex ClassType = getTypeIndex(Class);
250 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
252 TI = TypeTable.writeKnownType(MFuncId);
254 // Otherwise, this must be a free function.
255 TypeIndex ParentScope = getScopeIndex(Scope);
256 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
257 TI = TypeTable.writeKnownType(FuncId);
260 return recordTypeIndexForDINode(SP, TI);
263 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
264 const DICompositeType *Class) {
265 // Always use the method declaration as the key for the function type. The
266 // method declaration contains the this adjustment.
267 if (SP->getDeclaration())
268 SP = SP->getDeclaration();
269 assert(!SP->getDeclaration() && "should use declaration as key");
271 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
272 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
273 auto I = TypeIndices.find({SP, Class});
274 if (I != TypeIndices.end())
277 // Make sure complete type info for the class is emitted *after* the member
278 // function type, as the complete class type is likely to reference this
279 // member function type.
280 TypeLoweringScope S(*this);
282 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
283 return recordTypeIndexForDINode(SP, TI, Class);
286 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
288 const DIType *ClassTy) {
289 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
291 assert(InsertResult.second && "DINode was already assigned a type index");
295 unsigned CodeViewDebug::getPointerSizeInBytes() {
296 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
299 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
300 const DILocation *InlinedAt) {
302 // This variable was inlined. Associate it with the InlineSite.
303 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
304 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
305 Site.InlinedLocals.emplace_back(Var);
307 // This variable goes in the main ProcSym.
308 CurFn->Locals.emplace_back(Var);
312 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
313 const DILocation *Loc) {
314 auto B = Locs.begin(), E = Locs.end();
315 if (std::find(B, E, Loc) == E)
319 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
320 const MachineFunction *MF) {
321 // Skip this instruction if it has the same location as the previous one.
322 if (DL == CurFn->LastLoc)
325 const DIScope *Scope = DL.get()->getScope();
329 // Skip this line if it is longer than the maximum we can record.
330 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
331 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
332 LI.isNeverStepInto())
335 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
336 if (CI.getStartColumn() != DL.getCol())
339 if (!CurFn->HaveLineInfo)
340 CurFn->HaveLineInfo = true;
342 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
343 FileId = CurFn->LastFileId;
345 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
348 unsigned FuncId = CurFn->FuncId;
349 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
350 const DILocation *Loc = DL.get();
352 // If this location was actually inlined from somewhere else, give it the ID
353 // of the inline call site.
355 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
357 // Ensure we have links in the tree of inline call sites.
358 bool FirstLoc = true;
359 while ((SiteLoc = Loc->getInlinedAt())) {
361 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
363 addLocIfNotPresent(Site.ChildSites, Loc);
367 addLocIfNotPresent(CurFn->ChildSites, Loc);
370 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
371 /*PrologueEnd=*/false, /*IsStmt=*/false,
372 DL->getFilename(), SMLoc());
375 void CodeViewDebug::emitCodeViewMagicVersion() {
376 OS.EmitValueToAlignment(4);
377 OS.AddComment("Debug section magic");
378 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
381 void CodeViewDebug::endModule() {
382 if (!Asm || !MMI->hasDebugInfo())
385 assert(Asm != nullptr);
387 // The COFF .debug$S section consists of several subsections, each starting
388 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
389 // of the payload followed by the payload itself. The subsections are 4-byte
392 // Use the generic .debug$S section, and make a subsection for all the inlined
394 switchToDebugSectionForSymbol(nullptr);
396 MCSymbol *CompilerInfo = beginCVSubsection(ModuleSubstreamKind::Symbols);
397 emitCompilerInformation();
398 endCVSubsection(CompilerInfo);
400 emitInlineeLinesSubsection();
402 // Emit per-function debug information.
403 for (auto &P : FnDebugInfo)
404 if (!P.first->isDeclarationForLinker())
405 emitDebugInfoForFunction(P.first, P.second);
407 // Emit global variable debug information.
408 setCurrentSubprogram(nullptr);
409 emitDebugInfoForGlobals();
411 // Emit retained types.
412 emitDebugInfoForRetainedTypes();
414 // Switch back to the generic .debug$S section after potentially processing
415 // comdat symbol sections.
416 switchToDebugSectionForSymbol(nullptr);
418 // Emit UDT records for any types used by global variables.
419 if (!GlobalUDTs.empty()) {
420 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
421 emitDebugInfoForUDTs(GlobalUDTs);
422 endCVSubsection(SymbolsEnd);
425 // This subsection holds a file index to offset in string table table.
426 OS.AddComment("File index to string table offset subsection");
427 OS.EmitCVFileChecksumsDirective();
429 // This subsection holds the string table.
430 OS.AddComment("String table");
431 OS.EmitCVStringTableDirective();
433 // Emit type information last, so that any types we translate while emitting
434 // function info are included.
435 emitTypeInformation();
440 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
441 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
442 // after a fixed length portion of the record. The fixed length portion should
443 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
444 // overall record size is less than the maximum allowed.
445 unsigned MaxFixedRecordLength = 0xF00;
446 SmallString<32> NullTerminatedString(
447 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
448 NullTerminatedString.push_back('\0');
449 OS.EmitBytes(NullTerminatedString);
452 void CodeViewDebug::emitTypeInformation() {
453 // Do nothing if we have no debug info or if no non-trivial types were emitted
454 // to TypeTable during codegen.
455 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
458 if (TypeTable.empty())
461 // Start the .debug$T section with 0x4.
462 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
463 emitCodeViewMagicVersion();
465 SmallString<8> CommentPrefix;
466 if (OS.isVerboseAsm()) {
467 CommentPrefix += '\t';
468 CommentPrefix += Asm->MAI->getCommentString();
469 CommentPrefix += ' ';
473 CVTypeDumper CVTD(TypeDB);
474 TypeTable.ForEachRecord([&](TypeIndex Index, ArrayRef<uint8_t> Record) {
475 if (OS.isVerboseAsm()) {
476 // Emit a block comment describing the type record for readability.
477 SmallString<512> CommentBlock;
478 raw_svector_ostream CommentOS(CommentBlock);
479 ScopedPrinter SP(CommentOS);
480 SP.setPrefix(CommentPrefix);
481 TypeDumpVisitor TDV(TypeDB, &SP, false);
482 Error E = CVTD.dump(Record, TDV);
484 logAllUnhandledErrors(std::move(E), errs(), "error: ");
485 llvm_unreachable("produced malformed type record");
487 // emitRawComment will insert its own tab and comment string before
488 // the first line, so strip off our first one. It also prints its own
491 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
494 // Assert that the type data is valid even if we aren't dumping
495 // comments. The MSVC linker doesn't do much type record validation,
496 // so the first link of an invalid type record can succeed while
497 // subsequent links will fail with LNK1285.
498 ByteStream Stream(Record);
500 StreamReader Reader(Stream);
501 Error E = Reader.readArray(Types, Reader.getLength());
503 TypeVisitorCallbacks C;
504 E = CVTypeVisitor(C).visitTypeStream(Types);
507 logAllUnhandledErrors(std::move(E), errs(), "error: ");
508 llvm_unreachable("produced malformed type record");
512 StringRef S(reinterpret_cast<const char *>(Record.data()), Record.size());
513 OS.EmitBinaryData(S);
519 static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
521 case dwarf::DW_LANG_C:
522 case dwarf::DW_LANG_C89:
523 case dwarf::DW_LANG_C99:
524 case dwarf::DW_LANG_C11:
525 case dwarf::DW_LANG_ObjC:
526 return SourceLanguage::C;
527 case dwarf::DW_LANG_C_plus_plus:
528 case dwarf::DW_LANG_C_plus_plus_03:
529 case dwarf::DW_LANG_C_plus_plus_11:
530 case dwarf::DW_LANG_C_plus_plus_14:
531 return SourceLanguage::Cpp;
532 case dwarf::DW_LANG_Fortran77:
533 case dwarf::DW_LANG_Fortran90:
534 case dwarf::DW_LANG_Fortran03:
535 case dwarf::DW_LANG_Fortran08:
536 return SourceLanguage::Fortran;
537 case dwarf::DW_LANG_Pascal83:
538 return SourceLanguage::Pascal;
539 case dwarf::DW_LANG_Cobol74:
540 case dwarf::DW_LANG_Cobol85:
541 return SourceLanguage::Cobol;
542 case dwarf::DW_LANG_Java:
543 return SourceLanguage::Java;
545 // There's no CodeView representation for this language, and CV doesn't
546 // have an "unknown" option for the language field, so we'll use MASM,
547 // as it's very low level.
548 return SourceLanguage::Masm;
556 // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
557 // the version number.
558 static Version parseVersion(StringRef Name) {
561 for (const char C : Name) {
564 V.Part[N] += C - '0';
565 } else if (C == '.') {
575 static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
577 case Triple::ArchType::x86:
578 return CPUType::Pentium3;
579 case Triple::ArchType::x86_64:
581 case Triple::ArchType::thumb:
582 return CPUType::Thumb;
584 report_fatal_error("target architecture doesn't map to a CodeView "
589 } // anonymous namespace
591 void CodeViewDebug::emitCompilerInformation() {
592 MCContext &Context = MMI->getContext();
593 MCSymbol *CompilerBegin = Context.createTempSymbol(),
594 *CompilerEnd = Context.createTempSymbol();
595 OS.AddComment("Record length");
596 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
597 OS.EmitLabel(CompilerBegin);
598 OS.AddComment("Record kind: S_COMPILE3");
599 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
602 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
603 const MDNode *Node = *CUs->operands().begin();
604 const auto *CU = cast<DICompileUnit>(Node);
606 // The low byte of the flags indicates the source language.
607 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
608 // TODO: Figure out which other flags need to be set.
610 OS.AddComment("Flags and language");
611 OS.EmitIntValue(Flags, 4);
613 OS.AddComment("CPUType");
615 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
616 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
618 StringRef CompilerVersion = CU->getProducer();
619 Version FrontVer = parseVersion(CompilerVersion);
620 OS.AddComment("Frontend version");
621 for (int N = 0; N < 4; ++N)
622 OS.EmitIntValue(FrontVer.Part[N], 2);
624 // Some Microsoft tools, like Binscope, expect a backend version number of at
625 // least 8.something, so we'll coerce the LLVM version into a form that
626 // guarantees it'll be big enough without really lying about the version.
627 int Major = 1000 * LLVM_VERSION_MAJOR +
628 10 * LLVM_VERSION_MINOR +
630 // Clamp it for builds that use unusually large version numbers.
631 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
632 Version BackVer = {{ Major, 0, 0, 0 }};
633 OS.AddComment("Backend version");
634 for (int N = 0; N < 4; ++N)
635 OS.EmitIntValue(BackVer.Part[N], 2);
637 OS.AddComment("Null-terminated compiler version string");
638 emitNullTerminatedSymbolName(OS, CompilerVersion);
640 OS.EmitLabel(CompilerEnd);
643 void CodeViewDebug::emitInlineeLinesSubsection() {
644 if (InlinedSubprograms.empty())
647 OS.AddComment("Inlinee lines subsection");
648 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
650 // We don't provide any extra file info.
651 // FIXME: Find out if debuggers use this info.
652 OS.AddComment("Inlinee lines signature");
653 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
655 for (const DISubprogram *SP : InlinedSubprograms) {
656 assert(TypeIndices.count({SP, nullptr}));
657 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
660 unsigned FileId = maybeRecordFile(SP->getFile());
661 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
662 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
664 // The filechecksum table uses 8 byte entries for now, and file ids start at
666 unsigned FileOffset = (FileId - 1) * 8;
667 OS.AddComment("Type index of inlined function");
668 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
669 OS.AddComment("Offset into filechecksum table");
670 OS.EmitIntValue(FileOffset, 4);
671 OS.AddComment("Starting line number");
672 OS.EmitIntValue(SP->getLine(), 4);
675 endCVSubsection(InlineEnd);
678 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
679 const DILocation *InlinedAt,
680 const InlineSite &Site) {
681 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
682 *InlineEnd = MMI->getContext().createTempSymbol();
684 assert(TypeIndices.count({Site.Inlinee, nullptr}));
685 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
688 OS.AddComment("Record length");
689 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
690 OS.EmitLabel(InlineBegin);
691 OS.AddComment("Record kind: S_INLINESITE");
692 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
694 OS.AddComment("PtrParent");
695 OS.EmitIntValue(0, 4);
696 OS.AddComment("PtrEnd");
697 OS.EmitIntValue(0, 4);
698 OS.AddComment("Inlinee type index");
699 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
701 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
702 unsigned StartLineNum = Site.Inlinee->getLine();
704 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
707 OS.EmitLabel(InlineEnd);
709 emitLocalVariableList(Site.InlinedLocals);
711 // Recurse on child inlined call sites before closing the scope.
712 for (const DILocation *ChildSite : Site.ChildSites) {
713 auto I = FI.InlineSites.find(ChildSite);
714 assert(I != FI.InlineSites.end() &&
715 "child site not in function inline site map");
716 emitInlinedCallSite(FI, ChildSite, I->second);
720 OS.AddComment("Record length");
721 OS.EmitIntValue(2, 2); // RecordLength
722 OS.AddComment("Record kind: S_INLINESITE_END");
723 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
726 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
727 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
728 // comdat key. A section may be comdat because of -ffunction-sections or
729 // because it is comdat in the IR.
730 MCSectionCOFF *GVSec =
731 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
732 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
734 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
735 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
736 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
738 OS.SwitchSection(DebugSec);
740 // Emit the magic version number if this is the first time we've switched to
742 if (ComdatDebugSections.insert(DebugSec).second)
743 emitCodeViewMagicVersion();
746 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
748 // For each function there is a separate subsection
749 // which holds the PC to file:line table.
750 const MCSymbol *Fn = Asm->getSymbol(GV);
753 // Switch to the to a comdat section, if appropriate.
754 switchToDebugSectionForSymbol(Fn);
756 std::string FuncName;
757 auto *SP = GV->getSubprogram();
759 setCurrentSubprogram(SP);
761 // If we have a display name, build the fully qualified name by walking the
763 if (!SP->getDisplayName().empty())
765 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
767 // If our DISubprogram name is empty, use the mangled name.
768 if (FuncName.empty())
769 FuncName = GlobalValue::getRealLinkageName(GV->getName());
771 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
772 OS.AddComment("Symbol subsection for " + Twine(FuncName));
773 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
775 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
776 *ProcRecordEnd = MMI->getContext().createTempSymbol();
777 OS.AddComment("Record length");
778 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
779 OS.EmitLabel(ProcRecordBegin);
781 if (GV->hasLocalLinkage()) {
782 OS.AddComment("Record kind: S_LPROC32_ID");
783 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
785 OS.AddComment("Record kind: S_GPROC32_ID");
786 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
789 // These fields are filled in by tools like CVPACK which run after the fact.
790 OS.AddComment("PtrParent");
791 OS.EmitIntValue(0, 4);
792 OS.AddComment("PtrEnd");
793 OS.EmitIntValue(0, 4);
794 OS.AddComment("PtrNext");
795 OS.EmitIntValue(0, 4);
796 // This is the important bit that tells the debugger where the function
797 // code is located and what's its size:
798 OS.AddComment("Code size");
799 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
800 OS.AddComment("Offset after prologue");
801 OS.EmitIntValue(0, 4);
802 OS.AddComment("Offset before epilogue");
803 OS.EmitIntValue(0, 4);
804 OS.AddComment("Function type index");
805 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
806 OS.AddComment("Function section relative address");
807 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
808 OS.AddComment("Function section index");
809 OS.EmitCOFFSectionIndex(Fn);
810 OS.AddComment("Flags");
811 OS.EmitIntValue(0, 1);
812 // Emit the function display name as a null-terminated string.
813 OS.AddComment("Function name");
814 // Truncate the name so we won't overflow the record length field.
815 emitNullTerminatedSymbolName(OS, FuncName);
816 OS.EmitLabel(ProcRecordEnd);
818 emitLocalVariableList(FI.Locals);
820 // Emit inlined call site information. Only emit functions inlined directly
821 // into the parent function. We'll emit the other sites recursively as part
822 // of their parent inline site.
823 for (const DILocation *InlinedAt : FI.ChildSites) {
824 auto I = FI.InlineSites.find(InlinedAt);
825 assert(I != FI.InlineSites.end() &&
826 "child site not in function inline site map");
827 emitInlinedCallSite(FI, InlinedAt, I->second);
831 emitDebugInfoForUDTs(LocalUDTs);
833 // We're done with this function.
834 OS.AddComment("Record length");
835 OS.EmitIntValue(0x0002, 2);
836 OS.AddComment("Record kind: S_PROC_ID_END");
837 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
839 endCVSubsection(SymbolsEnd);
841 // We have an assembler directive that takes care of the whole line table.
842 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
845 CodeViewDebug::LocalVarDefRange
846 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
849 DR.DataOffset = Offset;
850 assert(DR.DataOffset == Offset && "truncation");
853 DR.CVRegister = CVRegister;
857 CodeViewDebug::LocalVarDefRange
858 CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
859 int Offset, bool IsSubfield,
860 uint16_t StructOffset) {
862 DR.InMemory = InMemory;
863 DR.DataOffset = Offset;
864 DR.IsSubfield = IsSubfield;
865 DR.StructOffset = StructOffset;
866 DR.CVRegister = CVRegister;
870 void CodeViewDebug::collectVariableInfoFromMFTable(
871 DenseSet<InlinedVariable> &Processed) {
872 const MachineFunction &MF = *Asm->MF;
873 const TargetSubtargetInfo &TSI = MF.getSubtarget();
874 const TargetFrameLowering *TFI = TSI.getFrameLowering();
875 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
877 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
880 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
881 "Expected inlined-at fields to agree");
883 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
884 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
886 // If variable scope is not found then skip this variable.
890 // Get the frame register used and the offset.
891 unsigned FrameReg = 0;
892 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
893 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
895 // Calculate the label ranges.
896 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
897 for (const InsnRange &Range : Scope->getRanges()) {
898 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
899 const MCSymbol *End = getLabelAfterInsn(Range.second);
900 End = End ? End : Asm->getFunctionEnd();
901 DefRange.Ranges.emplace_back(Begin, End);
906 Var.DefRanges.emplace_back(std::move(DefRange));
907 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
911 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
912 DenseSet<InlinedVariable> Processed;
913 // Grab the variable info that was squirreled away in the MMI side-table.
914 collectVariableInfoFromMFTable(Processed);
916 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
918 for (const auto &I : DbgValues) {
919 InlinedVariable IV = I.first;
920 if (Processed.count(IV))
922 const DILocalVariable *DIVar = IV.first;
923 const DILocation *InlinedAt = IV.second;
925 // Instruction ranges, specifying where IV is accessible.
926 const auto &Ranges = I.second;
928 LexicalScope *Scope = nullptr;
930 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
932 Scope = LScopes.findLexicalScope(DIVar->getScope());
933 // If variable scope is not found then skip this variable.
940 // Calculate the definition ranges.
941 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
942 const InsnRange &Range = *I;
943 const MachineInstr *DVInst = Range.first;
944 assert(DVInst->isDebugValue() && "Invalid History entry");
945 const DIExpression *DIExpr = DVInst->getDebugExpression();
946 bool IsSubfield = false;
947 unsigned StructOffset = 0;
950 auto Fragment = DIExpr->getFragmentInfo();
951 if (DIExpr && Fragment) {
953 StructOffset = Fragment->OffsetInBits / 8;
954 } else if (DIExpr && DIExpr->getNumElements() > 0) {
955 continue; // Ignore unrecognized exprs.
958 // Bail if operand 0 is not a valid register. This means the variable is a
959 // simple constant, or is described by a complex expression.
960 // FIXME: Find a way to represent constant variables, since they are
961 // relatively common.
963 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
967 // Handle the two cases we can handle: indirect in memory and in register.
968 unsigned CVReg = TRI->getCodeViewRegNum(Reg);
969 bool InMemory = DVInst->getOperand(1).isImm();
970 int Offset = InMemory ? DVInst->getOperand(1).getImm() : 0;
973 DR.CVRegister = CVReg;
974 DR.InMemory = InMemory;
975 DR.DataOffset = Offset;
976 DR.IsSubfield = IsSubfield;
977 DR.StructOffset = StructOffset;
979 if (Var.DefRanges.empty() ||
980 Var.DefRanges.back().isDifferentLocation(DR)) {
981 Var.DefRanges.emplace_back(std::move(DR));
985 // Compute the label range.
986 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
987 const MCSymbol *End = getLabelAfterInsn(Range.second);
989 // This range is valid until the next overlapping bitpiece. In the
990 // common case, ranges will not be bitpieces, so they will overlap.
991 auto J = std::next(I);
993 !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
996 End = getLabelBeforeInsn(J->first);
998 End = Asm->getFunctionEnd();
1001 // If the last range end is our begin, just extend the last range.
1002 // Otherwise make a new range.
1003 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
1004 Var.DefRanges.back().Ranges;
1005 if (!Ranges.empty() && Ranges.back().second == Begin)
1006 Ranges.back().second = End;
1008 Ranges.emplace_back(Begin, End);
1010 // FIXME: Do more range combining.
1013 recordLocalVariable(std::move(Var), InlinedAt);
1017 void CodeViewDebug::beginFunction(const MachineFunction *MF) {
1018 assert(!CurFn && "Can't process two functions at once!");
1020 if (!Asm || !MMI->hasDebugInfo() || !MF->getFunction()->getSubprogram())
1023 DebugHandlerBase::beginFunction(MF);
1025 const Function *GV = MF->getFunction();
1026 assert(FnDebugInfo.count(GV) == false);
1027 CurFn = &FnDebugInfo[GV];
1028 CurFn->FuncId = NextFuncId++;
1029 CurFn->Begin = Asm->getFunctionBegin();
1031 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1033 // Find the end of the function prolog. First known non-DBG_VALUE and
1034 // non-frame setup location marks the beginning of the function body.
1035 // FIXME: is there a simpler a way to do this? Can we just search
1036 // for the first instruction of the function, not the last of the prolog?
1037 DebugLoc PrologEndLoc;
1038 bool EmptyPrologue = true;
1039 for (const auto &MBB : *MF) {
1040 for (const auto &MI : MBB) {
1041 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1043 PrologEndLoc = MI.getDebugLoc();
1045 } else if (!MI.isDebugValue()) {
1046 EmptyPrologue = false;
1051 // Record beginning of function if we have a non-empty prologue.
1052 if (PrologEndLoc && !EmptyPrologue) {
1053 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1054 maybeRecordLocation(FnStartDL, MF);
1058 void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
1059 // Don't record empty UDTs.
1060 if (Ty->getName().empty())
1063 SmallVector<StringRef, 5> QualifiedNameComponents;
1064 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1065 Ty->getScope().resolve(), QualifiedNameComponents);
1067 std::string FullyQualifiedName =
1068 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
1070 if (ClosestSubprogram == nullptr)
1071 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1072 else if (ClosestSubprogram == CurrentSubprogram)
1073 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1075 // TODO: What if the ClosestSubprogram is neither null or the current
1076 // subprogram? Currently, the UDT just gets dropped on the floor.
1078 // The current behavior is not desirable. To get maximal fidelity, we would
1079 // need to perform all type translation before beginning emission of .debug$S
1080 // and then make LocalUDTs a member of FunctionInfo
1083 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1084 // Generic dispatch for lowering an unknown type.
1085 switch (Ty->getTag()) {
1086 case dwarf::DW_TAG_array_type:
1087 return lowerTypeArray(cast<DICompositeType>(Ty));
1088 case dwarf::DW_TAG_typedef:
1089 return lowerTypeAlias(cast<DIDerivedType>(Ty));
1090 case dwarf::DW_TAG_base_type:
1091 return lowerTypeBasic(cast<DIBasicType>(Ty));
1092 case dwarf::DW_TAG_pointer_type:
1093 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1094 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1096 case dwarf::DW_TAG_reference_type:
1097 case dwarf::DW_TAG_rvalue_reference_type:
1098 return lowerTypePointer(cast<DIDerivedType>(Ty));
1099 case dwarf::DW_TAG_ptr_to_member_type:
1100 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1101 case dwarf::DW_TAG_const_type:
1102 case dwarf::DW_TAG_volatile_type:
1103 // TODO: add support for DW_TAG_atomic_type here
1104 return lowerTypeModifier(cast<DIDerivedType>(Ty));
1105 case dwarf::DW_TAG_subroutine_type:
1107 // The member function type of a member function pointer has no
1109 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1110 /*ThisAdjustment=*/0);
1112 return lowerTypeFunction(cast<DISubroutineType>(Ty));
1113 case dwarf::DW_TAG_enumeration_type:
1114 return lowerTypeEnum(cast<DICompositeType>(Ty));
1115 case dwarf::DW_TAG_class_type:
1116 case dwarf::DW_TAG_structure_type:
1117 return lowerTypeClass(cast<DICompositeType>(Ty));
1118 case dwarf::DW_TAG_union_type:
1119 return lowerTypeUnion(cast<DICompositeType>(Ty));
1121 // Use the null type index.
1126 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1127 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1128 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
1129 StringRef TypeName = Ty->getName();
1131 addToUDTs(Ty, UnderlyingTypeIndex);
1133 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1134 TypeName == "HRESULT")
1135 return TypeIndex(SimpleTypeKind::HResult);
1136 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1137 TypeName == "wchar_t")
1138 return TypeIndex(SimpleTypeKind::WideCharacter);
1140 return UnderlyingTypeIndex;
1143 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1144 DITypeRef ElementTypeRef = Ty->getBaseType();
1145 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1146 // IndexType is size_t, which depends on the bitness of the target.
1147 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
1148 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1149 : TypeIndex(SimpleTypeKind::UInt32Long);
1151 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1154 // We want to assert that the element type multiplied by the array lengths
1155 // match the size of the overall array. However, if we don't have complete
1156 // type information for the base type, we can't make this assertion. This
1157 // happens if limited debug info is enabled in this case:
1158 // struct VTableOptzn { VTableOptzn(); virtual ~VTableOptzn(); };
1159 // VTableOptzn array[3];
1160 // The DICompositeType of VTableOptzn will have size zero, and the array will
1161 // have size 3 * sizeof(void*), and we should avoid asserting.
1163 // There is a related bug in the front-end where an array of a structure,
1164 // which was declared as incomplete structure first, ends up not getting a
1165 // size assigned to it. (PR28303)
1168 // struct A { int f; } a[3];
1169 bool PartiallyIncomplete = false;
1170 if (Ty->getSizeInBits() == 0 || ElementSize == 0) {
1171 PartiallyIncomplete = true;
1174 // Add subranges to array type.
1175 DINodeArray Elements = Ty->getElements();
1176 for (int i = Elements.size() - 1; i >= 0; --i) {
1177 const DINode *Element = Elements[i];
1178 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1180 const DISubrange *Subrange = cast<DISubrange>(Element);
1181 assert(Subrange->getLowerBound() == 0 &&
1182 "codeview doesn't support subranges with lower bounds");
1183 int64_t Count = Subrange->getCount();
1185 // Variable Length Array (VLA) has Count equal to '-1'.
1186 // Replace with Count '1', assume it is the minimum VLA length.
1187 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
1190 PartiallyIncomplete = true;
1193 // Update the element size and element type index for subsequent subranges.
1194 ElementSize *= Count;
1196 // If this is the outermost array, use the size from the array. It will be
1197 // more accurate if PartiallyIncomplete is true.
1198 uint64_t ArraySize =
1199 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1201 StringRef Name = (i == 0) ? Ty->getName() : "";
1202 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1203 ElementTypeIndex = TypeTable.writeKnownType(AR);
1206 (void)PartiallyIncomplete;
1207 assert(PartiallyIncomplete || ElementSize == (Ty->getSizeInBits() / 8));
1209 return ElementTypeIndex;
1212 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1214 dwarf::TypeKind Kind;
1217 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1218 ByteSize = Ty->getSizeInBits() / 8;
1220 SimpleTypeKind STK = SimpleTypeKind::None;
1222 case dwarf::DW_ATE_address:
1225 case dwarf::DW_ATE_boolean:
1227 case 1: STK = SimpleTypeKind::Boolean8; break;
1228 case 2: STK = SimpleTypeKind::Boolean16; break;
1229 case 4: STK = SimpleTypeKind::Boolean32; break;
1230 case 8: STK = SimpleTypeKind::Boolean64; break;
1231 case 16: STK = SimpleTypeKind::Boolean128; break;
1234 case dwarf::DW_ATE_complex_float:
1236 case 2: STK = SimpleTypeKind::Complex16; break;
1237 case 4: STK = SimpleTypeKind::Complex32; break;
1238 case 8: STK = SimpleTypeKind::Complex64; break;
1239 case 10: STK = SimpleTypeKind::Complex80; break;
1240 case 16: STK = SimpleTypeKind::Complex128; break;
1243 case dwarf::DW_ATE_float:
1245 case 2: STK = SimpleTypeKind::Float16; break;
1246 case 4: STK = SimpleTypeKind::Float32; break;
1247 case 6: STK = SimpleTypeKind::Float48; break;
1248 case 8: STK = SimpleTypeKind::Float64; break;
1249 case 10: STK = SimpleTypeKind::Float80; break;
1250 case 16: STK = SimpleTypeKind::Float128; break;
1253 case dwarf::DW_ATE_signed:
1255 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1256 case 2: STK = SimpleTypeKind::Int16Short; break;
1257 case 4: STK = SimpleTypeKind::Int32; break;
1258 case 8: STK = SimpleTypeKind::Int64Quad; break;
1259 case 16: STK = SimpleTypeKind::Int128Oct; break;
1262 case dwarf::DW_ATE_unsigned:
1264 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1265 case 2: STK = SimpleTypeKind::UInt16Short; break;
1266 case 4: STK = SimpleTypeKind::UInt32; break;
1267 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1268 case 16: STK = SimpleTypeKind::UInt128Oct; break;
1271 case dwarf::DW_ATE_UTF:
1273 case 2: STK = SimpleTypeKind::Character16; break;
1274 case 4: STK = SimpleTypeKind::Character32; break;
1277 case dwarf::DW_ATE_signed_char:
1279 STK = SimpleTypeKind::SignedCharacter;
1281 case dwarf::DW_ATE_unsigned_char:
1283 STK = SimpleTypeKind::UnsignedCharacter;
1289 // Apply some fixups based on the source-level type name.
1290 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1291 STK = SimpleTypeKind::Int32Long;
1292 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1293 STK = SimpleTypeKind::UInt32Long;
1294 if (STK == SimpleTypeKind::UInt16Short &&
1295 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1296 STK = SimpleTypeKind::WideCharacter;
1297 if ((STK == SimpleTypeKind::SignedCharacter ||
1298 STK == SimpleTypeKind::UnsignedCharacter) &&
1299 Ty->getName() == "char")
1300 STK = SimpleTypeKind::NarrowCharacter;
1302 return TypeIndex(STK);
1305 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1306 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1308 // Pointers to simple types can use SimpleTypeMode, rather than having a
1309 // dedicated pointer type record.
1310 if (PointeeTI.isSimple() &&
1311 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1312 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1313 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1314 ? SimpleTypeMode::NearPointer64
1315 : SimpleTypeMode::NearPointer32;
1316 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1320 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1321 PointerMode PM = PointerMode::Pointer;
1322 switch (Ty->getTag()) {
1323 default: llvm_unreachable("not a pointer tag type");
1324 case dwarf::DW_TAG_pointer_type:
1325 PM = PointerMode::Pointer;
1327 case dwarf::DW_TAG_reference_type:
1328 PM = PointerMode::LValueReference;
1330 case dwarf::DW_TAG_rvalue_reference_type:
1331 PM = PointerMode::RValueReference;
1334 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1335 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1337 PointerOptions PO = PointerOptions::None;
1338 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1339 return TypeTable.writeKnownType(PR);
1342 static PointerToMemberRepresentation
1343 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1344 // SizeInBytes being zero generally implies that the member pointer type was
1345 // incomplete, which can happen if it is part of a function prototype. In this
1346 // case, use the unknown model instead of the general model.
1348 switch (Flags & DINode::FlagPtrToMemberRep) {
1350 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1351 : PointerToMemberRepresentation::GeneralFunction;
1352 case DINode::FlagSingleInheritance:
1353 return PointerToMemberRepresentation::SingleInheritanceFunction;
1354 case DINode::FlagMultipleInheritance:
1355 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1356 case DINode::FlagVirtualInheritance:
1357 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1360 switch (Flags & DINode::FlagPtrToMemberRep) {
1362 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1363 : PointerToMemberRepresentation::GeneralData;
1364 case DINode::FlagSingleInheritance:
1365 return PointerToMemberRepresentation::SingleInheritanceData;
1366 case DINode::FlagMultipleInheritance:
1367 return PointerToMemberRepresentation::MultipleInheritanceData;
1368 case DINode::FlagVirtualInheritance:
1369 return PointerToMemberRepresentation::VirtualInheritanceData;
1372 llvm_unreachable("invalid ptr to member representation");
1375 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1376 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1377 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1378 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1379 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1380 : PointerKind::Near32;
1381 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1382 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1383 : PointerMode::PointerToDataMember;
1384 PointerOptions PO = PointerOptions::None; // FIXME
1385 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1386 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1387 MemberPointerInfo MPI(
1388 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1389 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1390 return TypeTable.writeKnownType(PR);
1393 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1394 /// have a translation, use the NearC convention.
1395 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1397 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1398 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1399 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1400 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1401 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1402 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1404 return CallingConvention::NearC;
1407 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1408 ModifierOptions Mods = ModifierOptions::None;
1409 bool IsModifier = true;
1410 const DIType *BaseTy = Ty;
1411 while (IsModifier && BaseTy) {
1412 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1413 switch (BaseTy->getTag()) {
1414 case dwarf::DW_TAG_const_type:
1415 Mods |= ModifierOptions::Const;
1417 case dwarf::DW_TAG_volatile_type:
1418 Mods |= ModifierOptions::Volatile;
1425 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1427 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1428 ModifierRecord MR(ModifiedTI, Mods);
1429 return TypeTable.writeKnownType(MR);
1432 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1433 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1434 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1435 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1437 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1438 ArrayRef<TypeIndex> ArgTypeIndices = None;
1439 if (!ReturnAndArgTypeIndices.empty()) {
1440 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1441 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1442 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1445 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1446 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
1448 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1450 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1451 ArgTypeIndices.size(), ArgListIndex);
1452 return TypeTable.writeKnownType(Procedure);
1455 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1456 const DIType *ClassTy,
1457 int ThisAdjustment) {
1458 // Lower the containing class type.
1459 TypeIndex ClassType = getTypeIndex(ClassTy);
1461 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1462 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1463 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1465 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1466 ArrayRef<TypeIndex> ArgTypeIndices = None;
1467 if (!ReturnAndArgTypeIndices.empty()) {
1468 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1469 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1470 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1472 TypeIndex ThisTypeIndex = TypeIndex::Void();
1473 if (!ArgTypeIndices.empty()) {
1474 ThisTypeIndex = ArgTypeIndices.front();
1475 ArgTypeIndices = ArgTypeIndices.drop_front();
1478 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1479 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
1481 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1483 // TODO: Need to use the correct values for:
1485 // ThisPointerAdjustment.
1486 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1487 FunctionOptions::None, ArgTypeIndices.size(),
1488 ArgListIndex, ThisAdjustment);
1489 TypeIndex TI = TypeTable.writeKnownType(MFR);
1494 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1495 unsigned VSlotCount = Ty->getSizeInBits() / (8 * Asm->MAI->getPointerSize());
1496 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1498 VFTableShapeRecord VFTSR(Slots);
1499 return TypeTable.writeKnownType(VFTSR);
1502 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1503 switch (Flags & DINode::FlagAccessibility) {
1504 case DINode::FlagPrivate: return MemberAccess::Private;
1505 case DINode::FlagPublic: return MemberAccess::Public;
1506 case DINode::FlagProtected: return MemberAccess::Protected;
1508 // If there was no explicit access control, provide the default for the tag.
1509 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1510 : MemberAccess::Public;
1512 llvm_unreachable("access flags are exclusive");
1515 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1516 if (SP->isArtificial())
1517 return MethodOptions::CompilerGenerated;
1519 // FIXME: Handle other MethodOptions.
1521 return MethodOptions::None;
1524 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1526 switch (SP->getVirtuality()) {
1527 case dwarf::DW_VIRTUALITY_none:
1529 case dwarf::DW_VIRTUALITY_virtual:
1530 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1531 case dwarf::DW_VIRTUALITY_pure_virtual:
1532 return Introduced ? MethodKind::PureIntroducingVirtual
1533 : MethodKind::PureVirtual;
1535 llvm_unreachable("unhandled virtuality case");
1538 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1540 return MethodKind::Vanilla;
1543 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1544 switch (Ty->getTag()) {
1545 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1546 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1548 llvm_unreachable("unexpected tag");
1551 /// Return ClassOptions that should be present on both the forward declaration
1552 /// and the defintion of a tag type.
1553 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1554 ClassOptions CO = ClassOptions::None;
1556 // MSVC always sets this flag, even for local types. Clang doesn't always
1557 // appear to give every type a linkage name, which may be problematic for us.
1558 // FIXME: Investigate the consequences of not following them here.
1559 if (!Ty->getIdentifier().empty())
1560 CO |= ClassOptions::HasUniqueName;
1562 // Put the Nested flag on a type if it appears immediately inside a tag type.
1563 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1564 // here. That flag is only set on definitions, and not forward declarations.
1565 const DIScope *ImmediateScope = Ty->getScope().resolve();
1566 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1567 CO |= ClassOptions::Nested;
1569 // Put the Scoped flag on function-local types.
1570 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1571 Scope = Scope->getScope().resolve()) {
1572 if (isa<DISubprogram>(Scope)) {
1573 CO |= ClassOptions::Scoped;
1581 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
1582 ClassOptions CO = getCommonClassOptions(Ty);
1584 unsigned EnumeratorCount = 0;
1586 if (Ty->isForwardDecl()) {
1587 CO |= ClassOptions::ForwardReference;
1589 FieldListRecordBuilder FLRB(TypeTable);
1592 for (const DINode *Element : Ty->getElements()) {
1593 // We assume that the frontend provides all members in source declaration
1594 // order, which is what MSVC does.
1595 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1596 EnumeratorRecord ER(MemberAccess::Public,
1597 APSInt::getUnsigned(Enumerator->getValue()),
1598 Enumerator->getName());
1599 FLRB.writeMemberType(ER);
1606 std::string FullName = getFullyQualifiedName(Ty);
1608 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1609 getTypeIndex(Ty->getBaseType()));
1610 return TypeTable.writeKnownType(ER);
1613 //===----------------------------------------------------------------------===//
1615 //===----------------------------------------------------------------------===//
1617 struct llvm::ClassInfo {
1619 const DIDerivedType *MemberTypeNode;
1620 uint64_t BaseOffset;
1623 typedef std::vector<MemberInfo> MemberList;
1625 typedef TinyPtrVector<const DISubprogram *> MethodsList;
1626 // MethodName -> MethodsList
1627 typedef MapVector<MDString *, MethodsList> MethodsMap;
1630 std::vector<const DIDerivedType *> Inheritance;
1634 // Direct overloaded methods gathered by name.
1639 std::vector<const DICompositeType *> NestedClasses;
1642 void CodeViewDebug::clear() {
1643 assert(CurFn == nullptr);
1645 FnDebugInfo.clear();
1646 FileToFilepathMap.clear();
1649 TypeIndices.clear();
1650 CompleteTypeIndices.clear();
1653 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1654 const DIDerivedType *DDTy) {
1655 if (!DDTy->getName().empty()) {
1656 Info.Members.push_back({DDTy, 0});
1659 // An unnamed member must represent a nested struct or union. Add all the
1660 // indirect fields to the current record.
1661 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
1662 uint64_t Offset = DDTy->getOffsetInBits();
1663 const DIType *Ty = DDTy->getBaseType().resolve();
1664 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
1665 ClassInfo NestedInfo = collectClassInfo(DCTy);
1666 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
1667 Info.Members.push_back(
1668 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
1671 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1673 // Add elements to structure type.
1674 DINodeArray Elements = Ty->getElements();
1675 for (auto *Element : Elements) {
1676 // We assume that the frontend provides all members in source declaration
1677 // order, which is what MSVC does.
1680 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1681 Info.Methods[SP->getRawName()].push_back(SP);
1682 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
1683 if (DDTy->getTag() == dwarf::DW_TAG_member) {
1684 collectMemberInfo(Info, DDTy);
1685 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1686 Info.Inheritance.push_back(DDTy);
1687 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1688 DDTy->getName() == "__vtbl_ptr_type") {
1689 Info.VShapeTI = getTypeIndex(DDTy);
1690 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1691 // Ignore friend members. It appears that MSVC emitted info about
1692 // friends in the past, but modern versions do not.
1694 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1695 Info.NestedClasses.push_back(Composite);
1697 // Skip other unrecognized kinds of elements.
1702 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1703 // First, construct the forward decl. Don't look into Ty to compute the
1704 // forward decl options, since it might not be available in all TUs.
1705 TypeRecordKind Kind = getRecordKind(Ty);
1707 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
1708 std::string FullName = getFullyQualifiedName(Ty);
1709 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1710 FullName, Ty->getIdentifier());
1711 TypeIndex FwdDeclTI = TypeTable.writeKnownType(CR);
1712 if (!Ty->isForwardDecl())
1713 DeferredCompleteTypes.push_back(Ty);
1717 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1718 // Construct the field list and complete type record.
1719 TypeRecordKind Kind = getRecordKind(Ty);
1720 ClassOptions CO = getCommonClassOptions(Ty);
1723 unsigned FieldCount;
1724 bool ContainsNestedClass;
1725 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1726 lowerRecordFieldList(Ty);
1728 if (ContainsNestedClass)
1729 CO |= ClassOptions::ContainsNestedClass;
1731 std::string FullName = getFullyQualifiedName(Ty);
1733 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1735 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1736 SizeInBytes, FullName, Ty->getIdentifier());
1737 TypeIndex ClassTI = TypeTable.writeKnownType(CR);
1739 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1740 TypeIndex SIDI = TypeTable.writeKnownType(SIDR);
1741 UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
1742 TypeTable.writeKnownType(USLR);
1744 addToUDTs(Ty, ClassTI);
1749 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1751 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
1752 std::string FullName = getFullyQualifiedName(Ty);
1753 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
1754 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UR);
1755 if (!Ty->isForwardDecl())
1756 DeferredCompleteTypes.push_back(Ty);
1760 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1761 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
1763 unsigned FieldCount;
1764 bool ContainsNestedClass;
1765 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1766 lowerRecordFieldList(Ty);
1768 if (ContainsNestedClass)
1769 CO |= ClassOptions::ContainsNestedClass;
1771 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1772 std::string FullName = getFullyQualifiedName(Ty);
1774 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1775 Ty->getIdentifier());
1776 TypeIndex UnionTI = TypeTable.writeKnownType(UR);
1778 StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1779 TypeIndex SIRI = TypeTable.writeKnownType(SIR);
1780 UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
1781 TypeTable.writeKnownType(USLR);
1783 addToUDTs(Ty, UnionTI);
1788 std::tuple<TypeIndex, TypeIndex, unsigned, bool>
1789 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1790 // Manually count members. MSVC appears to count everything that generates a
1791 // field list record. Each individual overload in a method overload group
1792 // contributes to this count, even though the overload group is a single field
1794 unsigned MemberCount = 0;
1795 ClassInfo Info = collectClassInfo(Ty);
1796 FieldListRecordBuilder FLBR(TypeTable);
1799 // Create base classes.
1800 for (const DIDerivedType *I : Info.Inheritance) {
1801 if (I->getFlags() & DINode::FlagVirtual) {
1803 // FIXME: Emit VBPtrOffset when the frontend provides it.
1804 unsigned VBPtrOffset = 0;
1805 // FIXME: Despite the accessor name, the offset is really in bytes.
1806 unsigned VBTableIndex = I->getOffsetInBits() / 4;
1807 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1808 ? TypeRecordKind::IndirectVirtualBaseClass
1809 : TypeRecordKind::VirtualBaseClass;
1810 VirtualBaseClassRecord VBCR(
1811 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
1812 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1815 FLBR.writeMemberType(VBCR);
1817 assert(I->getOffsetInBits() % 8 == 0 &&
1818 "bases must be on byte boundaries");
1819 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1820 getTypeIndex(I->getBaseType()),
1821 I->getOffsetInBits() / 8);
1822 FLBR.writeMemberType(BCR);
1827 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1828 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1829 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
1830 StringRef MemberName = Member->getName();
1831 MemberAccess Access =
1832 translateAccessFlags(Ty->getTag(), Member->getFlags());
1834 if (Member->isStaticMember()) {
1835 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
1836 FLBR.writeMemberType(SDMR);
1841 // Virtual function pointer member.
1842 if ((Member->getFlags() & DINode::FlagArtificial) &&
1843 Member->getName().startswith("_vptr$")) {
1844 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
1845 FLBR.writeMemberType(VFPR);
1851 uint64_t MemberOffsetInBits =
1852 Member->getOffsetInBits() + MemberInfo.BaseOffset;
1853 if (Member->isBitField()) {
1854 uint64_t StartBitOffset = MemberOffsetInBits;
1855 if (const auto *CI =
1856 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
1857 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
1859 StartBitOffset -= MemberOffsetInBits;
1860 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
1862 MemberBaseType = TypeTable.writeKnownType(BFR);
1864 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
1865 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
1867 FLBR.writeMemberType(DMR);
1872 for (auto &MethodItr : Info.Methods) {
1873 StringRef Name = MethodItr.first->getString();
1875 std::vector<OneMethodRecord> Methods;
1876 for (const DISubprogram *SP : MethodItr.second) {
1877 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1878 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
1880 unsigned VFTableOffset = -1;
1882 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1884 Methods.push_back(OneMethodRecord(
1885 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
1886 translateMethodKindFlags(SP, Introduced),
1887 translateMethodOptionFlags(SP), VFTableOffset, Name));
1890 assert(Methods.size() > 0 && "Empty methods map entry");
1891 if (Methods.size() == 1)
1892 FLBR.writeMemberType(Methods[0]);
1894 MethodOverloadListRecord MOLR(Methods);
1895 TypeIndex MethodList = TypeTable.writeKnownType(MOLR);
1896 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
1897 FLBR.writeMemberType(OMR);
1901 // Create nested classes.
1902 for (const DICompositeType *Nested : Info.NestedClasses) {
1903 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
1904 FLBR.writeMemberType(R);
1908 TypeIndex FieldTI = FLBR.end();
1909 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
1910 !Info.NestedClasses.empty());
1913 TypeIndex CodeViewDebug::getVBPTypeIndex() {
1914 if (!VBPType.getIndex()) {
1915 // Make a 'const int *' type.
1916 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
1917 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
1919 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1920 : PointerKind::Near32;
1921 PointerMode PM = PointerMode::Pointer;
1922 PointerOptions PO = PointerOptions::None;
1923 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1925 VBPType = TypeTable.writeKnownType(PR);
1931 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
1932 const DIType *Ty = TypeRef.resolve();
1933 const DIType *ClassTy = ClassTyRef.resolve();
1935 // The null DIType is the void type. Don't try to hash it.
1937 return TypeIndex::Void();
1939 // Check if we've already translated this type. Don't try to do a
1940 // get-or-create style insertion that caches the hash lookup across the
1941 // lowerType call. It will update the TypeIndices map.
1942 auto I = TypeIndices.find({Ty, ClassTy});
1943 if (I != TypeIndices.end())
1946 TypeLoweringScope S(*this);
1947 TypeIndex TI = lowerType(Ty, ClassTy);
1948 return recordTypeIndexForDINode(Ty, TI, ClassTy);
1951 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1952 const DIType *Ty = TypeRef.resolve();
1954 // The null DIType is the void type. Don't try to hash it.
1956 return TypeIndex::Void();
1958 // If this is a non-record type, the complete type index is the same as the
1959 // normal type index. Just call getTypeIndex.
1960 switch (Ty->getTag()) {
1961 case dwarf::DW_TAG_class_type:
1962 case dwarf::DW_TAG_structure_type:
1963 case dwarf::DW_TAG_union_type:
1966 return getTypeIndex(Ty);
1969 // Check if we've already translated the complete record type. Lowering a
1970 // complete type should never trigger lowering another complete type, so we
1971 // can reuse the hash table lookup result.
1972 const auto *CTy = cast<DICompositeType>(Ty);
1973 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1974 if (!InsertResult.second)
1975 return InsertResult.first->second;
1977 TypeLoweringScope S(*this);
1979 // Make sure the forward declaration is emitted first. It's unclear if this
1980 // is necessary, but MSVC does it, and we should follow suit until we can show
1982 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1984 // Just use the forward decl if we don't have complete type info. This might
1985 // happen if the frontend is using modules and expects the complete definition
1986 // to be emitted elsewhere.
1987 if (CTy->isForwardDecl())
1991 switch (CTy->getTag()) {
1992 case dwarf::DW_TAG_class_type:
1993 case dwarf::DW_TAG_structure_type:
1994 TI = lowerCompleteTypeClass(CTy);
1996 case dwarf::DW_TAG_union_type:
1997 TI = lowerCompleteTypeUnion(CTy);
2000 llvm_unreachable("not a record");
2003 InsertResult.first->second = TI;
2007 /// Emit all the deferred complete record types. Try to do this in FIFO order,
2008 /// and do this until fixpoint, as each complete record type typically
2010 /// many other record types.
2011 void CodeViewDebug::emitDeferredCompleteTypes() {
2012 SmallVector<const DICompositeType *, 4> TypesToEmit;
2013 while (!DeferredCompleteTypes.empty()) {
2014 std::swap(DeferredCompleteTypes, TypesToEmit);
2015 for (const DICompositeType *RecordTy : TypesToEmit)
2016 getCompleteTypeIndex(RecordTy);
2017 TypesToEmit.clear();
2021 void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
2022 // Get the sorted list of parameters and emit them first.
2023 SmallVector<const LocalVariable *, 6> Params;
2024 for (const LocalVariable &L : Locals)
2025 if (L.DIVar->isParameter())
2026 Params.push_back(&L);
2027 std::sort(Params.begin(), Params.end(),
2028 [](const LocalVariable *L, const LocalVariable *R) {
2029 return L->DIVar->getArg() < R->DIVar->getArg();
2031 for (const LocalVariable *L : Params)
2032 emitLocalVariable(*L);
2034 // Next emit all non-parameters in the order that we found them.
2035 for (const LocalVariable &L : Locals)
2036 if (!L.DIVar->isParameter())
2037 emitLocalVariable(L);
2040 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2041 // LocalSym record, see SymbolRecord.h for more info.
2042 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2043 *LocalEnd = MMI->getContext().createTempSymbol();
2044 OS.AddComment("Record length");
2045 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2046 OS.EmitLabel(LocalBegin);
2048 OS.AddComment("Record kind: S_LOCAL");
2049 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
2051 LocalSymFlags Flags = LocalSymFlags::None;
2052 if (Var.DIVar->isParameter())
2053 Flags |= LocalSymFlags::IsParameter;
2054 if (Var.DefRanges.empty())
2055 Flags |= LocalSymFlags::IsOptimizedOut;
2057 OS.AddComment("TypeIndex");
2058 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
2059 OS.EmitIntValue(TI.getIndex(), 4);
2060 OS.AddComment("Flags");
2061 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
2062 // Truncate the name so we won't overflow the record length field.
2063 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2064 OS.EmitLabel(LocalEnd);
2066 // Calculate the on disk prefix of the appropriate def range record. The
2067 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2068 // should be big enough to hold all forms without memory allocation.
2069 SmallString<20> BytePrefix;
2070 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2072 if (DefRange.InMemory) {
2073 uint16_t RegRelFlags = 0;
2074 if (DefRange.IsSubfield) {
2075 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2076 (DefRange.StructOffset
2077 << DefRangeRegisterRelSym::OffsetInParentShift);
2079 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2080 Sym.Hdr.Register = DefRange.CVRegister;
2081 Sym.Hdr.Flags = RegRelFlags;
2082 Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
2083 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
2085 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
2087 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
2089 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
2090 if (DefRange.IsSubfield) {
2091 // Unclear what matters here.
2092 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2093 Sym.Hdr.Register = DefRange.CVRegister;
2094 Sym.Hdr.MayHaveNoName = 0;
2095 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2097 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2098 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2100 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2103 // Unclear what matters here.
2104 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2105 Sym.Hdr.Register = DefRange.CVRegister;
2106 Sym.Hdr.MayHaveNoName = 0;
2107 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2108 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2110 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2114 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2118 void CodeViewDebug::endFunction(const MachineFunction *MF) {
2119 if (!Asm || !CurFn) // We haven't created any debug info for this function.
2122 const Function *GV = MF->getFunction();
2123 assert(FnDebugInfo.count(GV));
2124 assert(CurFn == &FnDebugInfo[GV]);
2126 collectVariableInfo(GV->getSubprogram());
2128 DebugHandlerBase::endFunction(MF);
2130 // Don't emit anything if we don't have any line tables.
2131 if (!CurFn->HaveLineInfo) {
2132 FnDebugInfo.erase(GV);
2137 CurFn->End = Asm->getFunctionEnd();
2142 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
2143 DebugHandlerBase::beginInstruction(MI);
2145 // Ignore DBG_VALUE locations and function prologue.
2146 if (!Asm || !CurFn || MI->isDebugValue() ||
2147 MI->getFlag(MachineInstr::FrameSetup))
2149 DebugLoc DL = MI->getDebugLoc();
2150 if (DL == PrevInstLoc || !DL)
2152 maybeRecordLocation(DL, Asm->MF);
2155 MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
2156 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2157 *EndLabel = MMI->getContext().createTempSymbol();
2158 OS.EmitIntValue(unsigned(Kind), 4);
2159 OS.AddComment("Subsection size");
2160 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2161 OS.EmitLabel(BeginLabel);
2165 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2166 OS.EmitLabel(EndLabel);
2167 // Every subsection must be aligned to a 4-byte boundary.
2168 OS.EmitValueToAlignment(4);
2171 void CodeViewDebug::emitDebugInfoForUDTs(
2172 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
2173 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
2174 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2175 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2176 OS.AddComment("Record length");
2177 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2178 OS.EmitLabel(UDTRecordBegin);
2180 OS.AddComment("Record kind: S_UDT");
2181 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2183 OS.AddComment("Type");
2184 OS.EmitIntValue(UDT.second.getIndex(), 4);
2186 emitNullTerminatedSymbolName(OS, UDT.first);
2187 OS.EmitLabel(UDTRecordEnd);
2191 void CodeViewDebug::emitDebugInfoForGlobals() {
2192 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2194 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
2195 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2196 GV.getDebugInfo(GVEs);
2197 for (const auto *GVE : GVEs)
2198 GlobalMap[GVE] = &GV;
2201 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2202 for (const MDNode *Node : CUs->operands()) {
2203 const auto *CU = cast<DICompileUnit>(Node);
2205 // First, emit all globals that are not in a comdat in a single symbol
2206 // substream. MSVC doesn't like it if the substream is empty, so only open
2207 // it if we have at least one global to emit.
2208 switchToDebugSectionForSymbol(nullptr);
2209 MCSymbol *EndLabel = nullptr;
2210 for (const auto *GVE : CU->getGlobalVariables()) {
2211 if (const auto *GV = GlobalMap.lookup(GVE))
2212 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
2214 OS.AddComment("Symbol subsection for globals");
2215 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
2217 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2218 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
2222 endCVSubsection(EndLabel);
2224 // Second, emit each global that is in a comdat into its own .debug$S
2225 // section along with its own symbol substream.
2226 for (const auto *GVE : CU->getGlobalVariables()) {
2227 if (const auto *GV = GlobalMap.lookup(GVE)) {
2228 if (GV->hasComdat()) {
2229 MCSymbol *GVSym = Asm->getSymbol(GV);
2230 OS.AddComment("Symbol subsection for " +
2231 Twine(GlobalValue::getRealLinkageName(GV->getName())));
2232 switchToDebugSectionForSymbol(GVSym);
2233 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
2234 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2235 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
2236 endCVSubsection(EndLabel);
2243 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2244 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2245 for (const MDNode *Node : CUs->operands()) {
2246 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2247 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2249 // FIXME: Add to global/local DTU list.
2255 void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
2256 const GlobalVariable *GV,
2258 // DataSym record, see SymbolRecord.h for more info.
2259 // FIXME: Thread local data, etc
2260 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2261 *DataEnd = MMI->getContext().createTempSymbol();
2262 OS.AddComment("Record length");
2263 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2264 OS.EmitLabel(DataBegin);
2265 if (DIGV->isLocalToUnit()) {
2266 if (GV->isThreadLocal()) {
2267 OS.AddComment("Record kind: S_LTHREAD32");
2268 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2270 OS.AddComment("Record kind: S_LDATA32");
2271 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2274 if (GV->isThreadLocal()) {
2275 OS.AddComment("Record kind: S_GTHREAD32");
2276 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2278 OS.AddComment("Record kind: S_GDATA32");
2279 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2282 OS.AddComment("Type");
2283 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2284 OS.AddComment("DataOffset");
2285 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
2286 OS.AddComment("Segment");
2287 OS.EmitCOFFSectionIndex(GVSym);
2288 OS.AddComment("Name");
2289 emitNullTerminatedSymbolName(OS, DIGV->getName());
2290 OS.EmitLabel(DataEnd);