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/CVTypeVisitor.h"
17 #include "llvm/DebugInfo/CodeView/CodeView.h"
18 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.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/TypeTableCollection.h"
26 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCSectionCOFF.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Support/BinaryByteStream.h"
33 #include "llvm/Support/BinaryStreamReader.h"
34 #include "llvm/Support/COFF.h"
35 #include "llvm/Support/ScopedPrinter.h"
36 #include "llvm/Target/TargetFrameLowering.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
41 using namespace llvm::codeview;
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->getName().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(DebugSubsectionKind::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(DebugSubsectionKind::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 += ' ';
472 TypeTableCollection Table(TypeTable.records());
473 Optional<TypeIndex> B = Table.getFirst();
475 // This will fail if the record data is invalid.
476 CVType Record = Table.getType(*B);
478 if (OS.isVerboseAsm()) {
479 // Emit a block comment describing the type record for readability.
480 SmallString<512> CommentBlock;
481 raw_svector_ostream CommentOS(CommentBlock);
482 ScopedPrinter SP(CommentOS);
483 SP.setPrefix(CommentPrefix);
484 TypeDumpVisitor TDV(Table, &SP, false);
486 Error E = codeview::visitTypeRecord(Record, *B, TDV);
488 logAllUnhandledErrors(std::move(E), errs(), "error: ");
489 llvm_unreachable("produced malformed type record");
491 // emitRawComment will insert its own tab and comment string before
492 // the first line, so strip off our first one. It also prints its own
495 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
497 OS.EmitBinaryData(Record.str_data());
498 B = Table.getNext(*B);
504 static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
506 case dwarf::DW_LANG_C:
507 case dwarf::DW_LANG_C89:
508 case dwarf::DW_LANG_C99:
509 case dwarf::DW_LANG_C11:
510 case dwarf::DW_LANG_ObjC:
511 return SourceLanguage::C;
512 case dwarf::DW_LANG_C_plus_plus:
513 case dwarf::DW_LANG_C_plus_plus_03:
514 case dwarf::DW_LANG_C_plus_plus_11:
515 case dwarf::DW_LANG_C_plus_plus_14:
516 return SourceLanguage::Cpp;
517 case dwarf::DW_LANG_Fortran77:
518 case dwarf::DW_LANG_Fortran90:
519 case dwarf::DW_LANG_Fortran03:
520 case dwarf::DW_LANG_Fortran08:
521 return SourceLanguage::Fortran;
522 case dwarf::DW_LANG_Pascal83:
523 return SourceLanguage::Pascal;
524 case dwarf::DW_LANG_Cobol74:
525 case dwarf::DW_LANG_Cobol85:
526 return SourceLanguage::Cobol;
527 case dwarf::DW_LANG_Java:
528 return SourceLanguage::Java;
530 // There's no CodeView representation for this language, and CV doesn't
531 // have an "unknown" option for the language field, so we'll use MASM,
532 // as it's very low level.
533 return SourceLanguage::Masm;
541 // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
542 // the version number.
543 static Version parseVersion(StringRef Name) {
546 for (const char C : Name) {
549 V.Part[N] += C - '0';
550 } else if (C == '.') {
560 static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
562 case Triple::ArchType::x86:
563 return CPUType::Pentium3;
564 case Triple::ArchType::x86_64:
566 case Triple::ArchType::thumb:
567 return CPUType::Thumb;
569 report_fatal_error("target architecture doesn't map to a CodeView "
574 } // anonymous namespace
576 void CodeViewDebug::emitCompilerInformation() {
577 MCContext &Context = MMI->getContext();
578 MCSymbol *CompilerBegin = Context.createTempSymbol(),
579 *CompilerEnd = Context.createTempSymbol();
580 OS.AddComment("Record length");
581 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
582 OS.EmitLabel(CompilerBegin);
583 OS.AddComment("Record kind: S_COMPILE3");
584 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
587 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
588 const MDNode *Node = *CUs->operands().begin();
589 const auto *CU = cast<DICompileUnit>(Node);
591 // The low byte of the flags indicates the source language.
592 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
593 // TODO: Figure out which other flags need to be set.
595 OS.AddComment("Flags and language");
596 OS.EmitIntValue(Flags, 4);
598 OS.AddComment("CPUType");
600 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
601 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
603 StringRef CompilerVersion = CU->getProducer();
604 Version FrontVer = parseVersion(CompilerVersion);
605 OS.AddComment("Frontend version");
606 for (int N = 0; N < 4; ++N)
607 OS.EmitIntValue(FrontVer.Part[N], 2);
609 // Some Microsoft tools, like Binscope, expect a backend version number of at
610 // least 8.something, so we'll coerce the LLVM version into a form that
611 // guarantees it'll be big enough without really lying about the version.
612 int Major = 1000 * LLVM_VERSION_MAJOR +
613 10 * LLVM_VERSION_MINOR +
615 // Clamp it for builds that use unusually large version numbers.
616 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
617 Version BackVer = {{ Major, 0, 0, 0 }};
618 OS.AddComment("Backend version");
619 for (int N = 0; N < 4; ++N)
620 OS.EmitIntValue(BackVer.Part[N], 2);
622 OS.AddComment("Null-terminated compiler version string");
623 emitNullTerminatedSymbolName(OS, CompilerVersion);
625 OS.EmitLabel(CompilerEnd);
628 void CodeViewDebug::emitInlineeLinesSubsection() {
629 if (InlinedSubprograms.empty())
632 OS.AddComment("Inlinee lines subsection");
633 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
635 // We don't provide any extra file info.
636 // FIXME: Find out if debuggers use this info.
637 OS.AddComment("Inlinee lines signature");
638 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
640 for (const DISubprogram *SP : InlinedSubprograms) {
641 assert(TypeIndices.count({SP, nullptr}));
642 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
645 unsigned FileId = maybeRecordFile(SP->getFile());
646 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
647 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
649 // The filechecksum table uses 8 byte entries for now, and file ids start at
651 unsigned FileOffset = (FileId - 1) * 8;
652 OS.AddComment("Type index of inlined function");
653 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
654 OS.AddComment("Offset into filechecksum table");
655 OS.EmitIntValue(FileOffset, 4);
656 OS.AddComment("Starting line number");
657 OS.EmitIntValue(SP->getLine(), 4);
660 endCVSubsection(InlineEnd);
663 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
664 const DILocation *InlinedAt,
665 const InlineSite &Site) {
666 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
667 *InlineEnd = MMI->getContext().createTempSymbol();
669 assert(TypeIndices.count({Site.Inlinee, nullptr}));
670 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
673 OS.AddComment("Record length");
674 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
675 OS.EmitLabel(InlineBegin);
676 OS.AddComment("Record kind: S_INLINESITE");
677 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
679 OS.AddComment("PtrParent");
680 OS.EmitIntValue(0, 4);
681 OS.AddComment("PtrEnd");
682 OS.EmitIntValue(0, 4);
683 OS.AddComment("Inlinee type index");
684 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
686 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
687 unsigned StartLineNum = Site.Inlinee->getLine();
689 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
692 OS.EmitLabel(InlineEnd);
694 emitLocalVariableList(Site.InlinedLocals);
696 // Recurse on child inlined call sites before closing the scope.
697 for (const DILocation *ChildSite : Site.ChildSites) {
698 auto I = FI.InlineSites.find(ChildSite);
699 assert(I != FI.InlineSites.end() &&
700 "child site not in function inline site map");
701 emitInlinedCallSite(FI, ChildSite, I->second);
705 OS.AddComment("Record length");
706 OS.EmitIntValue(2, 2); // RecordLength
707 OS.AddComment("Record kind: S_INLINESITE_END");
708 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
711 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
712 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
713 // comdat key. A section may be comdat because of -ffunction-sections or
714 // because it is comdat in the IR.
715 MCSectionCOFF *GVSec =
716 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
717 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
719 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
720 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
721 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
723 OS.SwitchSection(DebugSec);
725 // Emit the magic version number if this is the first time we've switched to
727 if (ComdatDebugSections.insert(DebugSec).second)
728 emitCodeViewMagicVersion();
731 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
733 // For each function there is a separate subsection
734 // which holds the PC to file:line table.
735 const MCSymbol *Fn = Asm->getSymbol(GV);
738 // Switch to the to a comdat section, if appropriate.
739 switchToDebugSectionForSymbol(Fn);
741 std::string FuncName;
742 auto *SP = GV->getSubprogram();
744 setCurrentSubprogram(SP);
746 // If we have a display name, build the fully qualified name by walking the
748 if (!SP->getName().empty())
750 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
752 // If our DISubprogram name is empty, use the mangled name.
753 if (FuncName.empty())
754 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
756 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
757 OS.AddComment("Symbol subsection for " + Twine(FuncName));
758 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
760 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
761 *ProcRecordEnd = MMI->getContext().createTempSymbol();
762 OS.AddComment("Record length");
763 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
764 OS.EmitLabel(ProcRecordBegin);
766 if (GV->hasLocalLinkage()) {
767 OS.AddComment("Record kind: S_LPROC32_ID");
768 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
770 OS.AddComment("Record kind: S_GPROC32_ID");
771 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
774 // These fields are filled in by tools like CVPACK which run after the fact.
775 OS.AddComment("PtrParent");
776 OS.EmitIntValue(0, 4);
777 OS.AddComment("PtrEnd");
778 OS.EmitIntValue(0, 4);
779 OS.AddComment("PtrNext");
780 OS.EmitIntValue(0, 4);
781 // This is the important bit that tells the debugger where the function
782 // code is located and what's its size:
783 OS.AddComment("Code size");
784 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
785 OS.AddComment("Offset after prologue");
786 OS.EmitIntValue(0, 4);
787 OS.AddComment("Offset before epilogue");
788 OS.EmitIntValue(0, 4);
789 OS.AddComment("Function type index");
790 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
791 OS.AddComment("Function section relative address");
792 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
793 OS.AddComment("Function section index");
794 OS.EmitCOFFSectionIndex(Fn);
795 OS.AddComment("Flags");
796 OS.EmitIntValue(0, 1);
797 // Emit the function display name as a null-terminated string.
798 OS.AddComment("Function name");
799 // Truncate the name so we won't overflow the record length field.
800 emitNullTerminatedSymbolName(OS, FuncName);
801 OS.EmitLabel(ProcRecordEnd);
803 emitLocalVariableList(FI.Locals);
805 // Emit inlined call site information. Only emit functions inlined directly
806 // into the parent function. We'll emit the other sites recursively as part
807 // of their parent inline site.
808 for (const DILocation *InlinedAt : FI.ChildSites) {
809 auto I = FI.InlineSites.find(InlinedAt);
810 assert(I != FI.InlineSites.end() &&
811 "child site not in function inline site map");
812 emitInlinedCallSite(FI, InlinedAt, I->second);
816 emitDebugInfoForUDTs(LocalUDTs);
818 // We're done with this function.
819 OS.AddComment("Record length");
820 OS.EmitIntValue(0x0002, 2);
821 OS.AddComment("Record kind: S_PROC_ID_END");
822 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
824 endCVSubsection(SymbolsEnd);
826 // We have an assembler directive that takes care of the whole line table.
827 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
830 CodeViewDebug::LocalVarDefRange
831 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
834 DR.DataOffset = Offset;
835 assert(DR.DataOffset == Offset && "truncation");
838 DR.CVRegister = CVRegister;
842 CodeViewDebug::LocalVarDefRange
843 CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
844 int Offset, bool IsSubfield,
845 uint16_t StructOffset) {
847 DR.InMemory = InMemory;
848 DR.DataOffset = Offset;
849 DR.IsSubfield = IsSubfield;
850 DR.StructOffset = StructOffset;
851 DR.CVRegister = CVRegister;
855 void CodeViewDebug::collectVariableInfoFromMFTable(
856 DenseSet<InlinedVariable> &Processed) {
857 const MachineFunction &MF = *Asm->MF;
858 const TargetSubtargetInfo &TSI = MF.getSubtarget();
859 const TargetFrameLowering *TFI = TSI.getFrameLowering();
860 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
862 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
865 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
866 "Expected inlined-at fields to agree");
868 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
869 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
871 // If variable scope is not found then skip this variable.
875 // If the variable has an attached offset expression, extract it.
876 // FIXME: Try to handle DW_OP_deref as well.
877 int64_t ExprOffset = 0;
879 if (!VI.Expr->extractIfOffset(ExprOffset))
882 // Get the frame register used and the offset.
883 unsigned FrameReg = 0;
884 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
885 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
887 // Calculate the label ranges.
888 LocalVarDefRange DefRange =
889 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
890 for (const InsnRange &Range : Scope->getRanges()) {
891 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
892 const MCSymbol *End = getLabelAfterInsn(Range.second);
893 End = End ? End : Asm->getFunctionEnd();
894 DefRange.Ranges.emplace_back(Begin, End);
899 Var.DefRanges.emplace_back(std::move(DefRange));
900 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
904 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
905 DenseSet<InlinedVariable> Processed;
906 // Grab the variable info that was squirreled away in the MMI side-table.
907 collectVariableInfoFromMFTable(Processed);
909 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
911 for (const auto &I : DbgValues) {
912 InlinedVariable IV = I.first;
913 if (Processed.count(IV))
915 const DILocalVariable *DIVar = IV.first;
916 const DILocation *InlinedAt = IV.second;
918 // Instruction ranges, specifying where IV is accessible.
919 const auto &Ranges = I.second;
921 LexicalScope *Scope = nullptr;
923 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
925 Scope = LScopes.findLexicalScope(DIVar->getScope());
926 // If variable scope is not found then skip this variable.
933 // Calculate the definition ranges.
934 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
935 const InsnRange &Range = *I;
936 const MachineInstr *DVInst = Range.first;
937 assert(DVInst->isDebugValue() && "Invalid History entry");
938 const DIExpression *DIExpr = DVInst->getDebugExpression();
939 bool IsSubfield = false;
940 unsigned StructOffset = 0;
943 auto Fragment = DIExpr->getFragmentInfo();
946 StructOffset = Fragment->OffsetInBits / 8;
947 } else if (DIExpr->getNumElements() > 0) {
948 continue; // Ignore unrecognized exprs.
951 // Bail if operand 0 is not a valid register. This means the variable is a
952 // simple constant, or is described by a complex expression.
953 // FIXME: Find a way to represent constant variables, since they are
954 // relatively common.
956 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
960 // Handle the two cases we can handle: indirect in memory and in register.
961 unsigned CVReg = TRI->getCodeViewRegNum(Reg);
962 bool InMemory = DVInst->getOperand(1).isImm();
963 int Offset = InMemory ? DVInst->getOperand(1).getImm() : 0;
966 DR.CVRegister = CVReg;
967 DR.InMemory = InMemory;
968 DR.DataOffset = Offset;
969 DR.IsSubfield = IsSubfield;
970 DR.StructOffset = StructOffset;
972 if (Var.DefRanges.empty() ||
973 Var.DefRanges.back().isDifferentLocation(DR)) {
974 Var.DefRanges.emplace_back(std::move(DR));
978 // Compute the label range.
979 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
980 const MCSymbol *End = getLabelAfterInsn(Range.second);
982 // This range is valid until the next overlapping bitpiece. In the
983 // common case, ranges will not be bitpieces, so they will overlap.
984 auto J = std::next(I);
986 !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
989 End = getLabelBeforeInsn(J->first);
991 End = Asm->getFunctionEnd();
994 // If the last range end is our begin, just extend the last range.
995 // Otherwise make a new range.
996 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
997 Var.DefRanges.back().Ranges;
998 if (!Ranges.empty() && Ranges.back().second == Begin)
999 Ranges.back().second = End;
1001 Ranges.emplace_back(Begin, End);
1003 // FIXME: Do more range combining.
1006 recordLocalVariable(std::move(Var), InlinedAt);
1010 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
1011 const Function *GV = MF->getFunction();
1012 assert(FnDebugInfo.count(GV) == false);
1013 CurFn = &FnDebugInfo[GV];
1014 CurFn->FuncId = NextFuncId++;
1015 CurFn->Begin = Asm->getFunctionBegin();
1017 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1019 // Find the end of the function prolog. First known non-DBG_VALUE and
1020 // non-frame setup location marks the beginning of the function body.
1021 // FIXME: is there a simpler a way to do this? Can we just search
1022 // for the first instruction of the function, not the last of the prolog?
1023 DebugLoc PrologEndLoc;
1024 bool EmptyPrologue = true;
1025 for (const auto &MBB : *MF) {
1026 for (const auto &MI : MBB) {
1027 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1029 PrologEndLoc = MI.getDebugLoc();
1031 } else if (!MI.isMetaInstruction()) {
1032 EmptyPrologue = false;
1037 // Record beginning of function if we have a non-empty prologue.
1038 if (PrologEndLoc && !EmptyPrologue) {
1039 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1040 maybeRecordLocation(FnStartDL, MF);
1044 void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
1045 // Don't record empty UDTs.
1046 if (Ty->getName().empty())
1049 SmallVector<StringRef, 5> QualifiedNameComponents;
1050 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1051 Ty->getScope().resolve(), QualifiedNameComponents);
1053 std::string FullyQualifiedName =
1054 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
1056 if (ClosestSubprogram == nullptr)
1057 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1058 else if (ClosestSubprogram == CurrentSubprogram)
1059 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1061 // TODO: What if the ClosestSubprogram is neither null or the current
1062 // subprogram? Currently, the UDT just gets dropped on the floor.
1064 // The current behavior is not desirable. To get maximal fidelity, we would
1065 // need to perform all type translation before beginning emission of .debug$S
1066 // and then make LocalUDTs a member of FunctionInfo
1069 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1070 // Generic dispatch for lowering an unknown type.
1071 switch (Ty->getTag()) {
1072 case dwarf::DW_TAG_array_type:
1073 return lowerTypeArray(cast<DICompositeType>(Ty));
1074 case dwarf::DW_TAG_typedef:
1075 return lowerTypeAlias(cast<DIDerivedType>(Ty));
1076 case dwarf::DW_TAG_base_type:
1077 return lowerTypeBasic(cast<DIBasicType>(Ty));
1078 case dwarf::DW_TAG_pointer_type:
1079 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1080 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1082 case dwarf::DW_TAG_reference_type:
1083 case dwarf::DW_TAG_rvalue_reference_type:
1084 return lowerTypePointer(cast<DIDerivedType>(Ty));
1085 case dwarf::DW_TAG_ptr_to_member_type:
1086 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1087 case dwarf::DW_TAG_const_type:
1088 case dwarf::DW_TAG_volatile_type:
1089 // TODO: add support for DW_TAG_atomic_type here
1090 return lowerTypeModifier(cast<DIDerivedType>(Ty));
1091 case dwarf::DW_TAG_subroutine_type:
1093 // The member function type of a member function pointer has no
1095 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1096 /*ThisAdjustment=*/0);
1098 return lowerTypeFunction(cast<DISubroutineType>(Ty));
1099 case dwarf::DW_TAG_enumeration_type:
1100 return lowerTypeEnum(cast<DICompositeType>(Ty));
1101 case dwarf::DW_TAG_class_type:
1102 case dwarf::DW_TAG_structure_type:
1103 return lowerTypeClass(cast<DICompositeType>(Ty));
1104 case dwarf::DW_TAG_union_type:
1105 return lowerTypeUnion(cast<DICompositeType>(Ty));
1107 // Use the null type index.
1112 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1113 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1114 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
1115 StringRef TypeName = Ty->getName();
1117 addToUDTs(Ty, UnderlyingTypeIndex);
1119 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1120 TypeName == "HRESULT")
1121 return TypeIndex(SimpleTypeKind::HResult);
1122 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1123 TypeName == "wchar_t")
1124 return TypeIndex(SimpleTypeKind::WideCharacter);
1126 return UnderlyingTypeIndex;
1129 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1130 DITypeRef ElementTypeRef = Ty->getBaseType();
1131 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1132 // IndexType is size_t, which depends on the bitness of the target.
1133 TypeIndex IndexType = Asm->TM.getPointerSize() == 8
1134 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1135 : TypeIndex(SimpleTypeKind::UInt32Long);
1137 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1139 // Add subranges to array type.
1140 DINodeArray Elements = Ty->getElements();
1141 for (int i = Elements.size() - 1; i >= 0; --i) {
1142 const DINode *Element = Elements[i];
1143 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1145 const DISubrange *Subrange = cast<DISubrange>(Element);
1146 assert(Subrange->getLowerBound() == 0 &&
1147 "codeview doesn't support subranges with lower bounds");
1148 int64_t Count = Subrange->getCount();
1150 // Variable Length Array (VLA) has Count equal to '-1'.
1151 // Replace with Count '1', assume it is the minimum VLA length.
1152 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
1156 // Update the element size and element type index for subsequent subranges.
1157 ElementSize *= Count;
1159 // If this is the outermost array, use the size from the array. It will be
1160 // more accurate if we had a VLA or an incomplete element type size.
1161 uint64_t ArraySize =
1162 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1164 StringRef Name = (i == 0) ? Ty->getName() : "";
1165 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1166 ElementTypeIndex = TypeTable.writeKnownType(AR);
1169 return ElementTypeIndex;
1172 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1174 dwarf::TypeKind Kind;
1177 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1178 ByteSize = Ty->getSizeInBits() / 8;
1180 SimpleTypeKind STK = SimpleTypeKind::None;
1182 case dwarf::DW_ATE_address:
1185 case dwarf::DW_ATE_boolean:
1187 case 1: STK = SimpleTypeKind::Boolean8; break;
1188 case 2: STK = SimpleTypeKind::Boolean16; break;
1189 case 4: STK = SimpleTypeKind::Boolean32; break;
1190 case 8: STK = SimpleTypeKind::Boolean64; break;
1191 case 16: STK = SimpleTypeKind::Boolean128; break;
1194 case dwarf::DW_ATE_complex_float:
1196 case 2: STK = SimpleTypeKind::Complex16; break;
1197 case 4: STK = SimpleTypeKind::Complex32; break;
1198 case 8: STK = SimpleTypeKind::Complex64; break;
1199 case 10: STK = SimpleTypeKind::Complex80; break;
1200 case 16: STK = SimpleTypeKind::Complex128; break;
1203 case dwarf::DW_ATE_float:
1205 case 2: STK = SimpleTypeKind::Float16; break;
1206 case 4: STK = SimpleTypeKind::Float32; break;
1207 case 6: STK = SimpleTypeKind::Float48; break;
1208 case 8: STK = SimpleTypeKind::Float64; break;
1209 case 10: STK = SimpleTypeKind::Float80; break;
1210 case 16: STK = SimpleTypeKind::Float128; break;
1213 case dwarf::DW_ATE_signed:
1215 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1216 case 2: STK = SimpleTypeKind::Int16Short; break;
1217 case 4: STK = SimpleTypeKind::Int32; break;
1218 case 8: STK = SimpleTypeKind::Int64Quad; break;
1219 case 16: STK = SimpleTypeKind::Int128Oct; break;
1222 case dwarf::DW_ATE_unsigned:
1224 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1225 case 2: STK = SimpleTypeKind::UInt16Short; break;
1226 case 4: STK = SimpleTypeKind::UInt32; break;
1227 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1228 case 16: STK = SimpleTypeKind::UInt128Oct; break;
1231 case dwarf::DW_ATE_UTF:
1233 case 2: STK = SimpleTypeKind::Character16; break;
1234 case 4: STK = SimpleTypeKind::Character32; break;
1237 case dwarf::DW_ATE_signed_char:
1239 STK = SimpleTypeKind::SignedCharacter;
1241 case dwarf::DW_ATE_unsigned_char:
1243 STK = SimpleTypeKind::UnsignedCharacter;
1249 // Apply some fixups based on the source-level type name.
1250 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1251 STK = SimpleTypeKind::Int32Long;
1252 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1253 STK = SimpleTypeKind::UInt32Long;
1254 if (STK == SimpleTypeKind::UInt16Short &&
1255 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1256 STK = SimpleTypeKind::WideCharacter;
1257 if ((STK == SimpleTypeKind::SignedCharacter ||
1258 STK == SimpleTypeKind::UnsignedCharacter) &&
1259 Ty->getName() == "char")
1260 STK = SimpleTypeKind::NarrowCharacter;
1262 return TypeIndex(STK);
1265 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1266 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1268 // Pointers to simple types can use SimpleTypeMode, rather than having a
1269 // dedicated pointer type record.
1270 if (PointeeTI.isSimple() &&
1271 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1272 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1273 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1274 ? SimpleTypeMode::NearPointer64
1275 : SimpleTypeMode::NearPointer32;
1276 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1280 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1281 PointerMode PM = PointerMode::Pointer;
1282 switch (Ty->getTag()) {
1283 default: llvm_unreachable("not a pointer tag type");
1284 case dwarf::DW_TAG_pointer_type:
1285 PM = PointerMode::Pointer;
1287 case dwarf::DW_TAG_reference_type:
1288 PM = PointerMode::LValueReference;
1290 case dwarf::DW_TAG_rvalue_reference_type:
1291 PM = PointerMode::RValueReference;
1294 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1295 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1297 PointerOptions PO = PointerOptions::None;
1298 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1299 return TypeTable.writeKnownType(PR);
1302 static PointerToMemberRepresentation
1303 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1304 // SizeInBytes being zero generally implies that the member pointer type was
1305 // incomplete, which can happen if it is part of a function prototype. In this
1306 // case, use the unknown model instead of the general model.
1308 switch (Flags & DINode::FlagPtrToMemberRep) {
1310 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1311 : PointerToMemberRepresentation::GeneralFunction;
1312 case DINode::FlagSingleInheritance:
1313 return PointerToMemberRepresentation::SingleInheritanceFunction;
1314 case DINode::FlagMultipleInheritance:
1315 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1316 case DINode::FlagVirtualInheritance:
1317 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1320 switch (Flags & DINode::FlagPtrToMemberRep) {
1322 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1323 : PointerToMemberRepresentation::GeneralData;
1324 case DINode::FlagSingleInheritance:
1325 return PointerToMemberRepresentation::SingleInheritanceData;
1326 case DINode::FlagMultipleInheritance:
1327 return PointerToMemberRepresentation::MultipleInheritanceData;
1328 case DINode::FlagVirtualInheritance:
1329 return PointerToMemberRepresentation::VirtualInheritanceData;
1332 llvm_unreachable("invalid ptr to member representation");
1335 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1336 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1337 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1338 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1339 PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
1340 : PointerKind::Near32;
1341 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1342 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1343 : PointerMode::PointerToDataMember;
1344 PointerOptions PO = PointerOptions::None; // FIXME
1345 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1346 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1347 MemberPointerInfo MPI(
1348 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1349 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1350 return TypeTable.writeKnownType(PR);
1353 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1354 /// have a translation, use the NearC convention.
1355 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1357 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1358 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1359 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1360 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1361 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1362 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1364 return CallingConvention::NearC;
1367 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1368 ModifierOptions Mods = ModifierOptions::None;
1369 bool IsModifier = true;
1370 const DIType *BaseTy = Ty;
1371 while (IsModifier && BaseTy) {
1372 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1373 switch (BaseTy->getTag()) {
1374 case dwarf::DW_TAG_const_type:
1375 Mods |= ModifierOptions::Const;
1377 case dwarf::DW_TAG_volatile_type:
1378 Mods |= ModifierOptions::Volatile;
1385 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1387 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1388 ModifierRecord MR(ModifiedTI, Mods);
1389 return TypeTable.writeKnownType(MR);
1392 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1393 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1394 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1395 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1397 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1398 ArrayRef<TypeIndex> ArgTypeIndices = None;
1399 if (!ReturnAndArgTypeIndices.empty()) {
1400 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1401 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1402 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1405 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1406 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
1408 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1410 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1411 ArgTypeIndices.size(), ArgListIndex);
1412 return TypeTable.writeKnownType(Procedure);
1415 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1416 const DIType *ClassTy,
1417 int ThisAdjustment) {
1418 // Lower the containing class type.
1419 TypeIndex ClassType = getTypeIndex(ClassTy);
1421 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1422 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1423 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1425 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1426 ArrayRef<TypeIndex> ArgTypeIndices = None;
1427 if (!ReturnAndArgTypeIndices.empty()) {
1428 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1429 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1430 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1432 TypeIndex ThisTypeIndex = TypeIndex::Void();
1433 if (!ArgTypeIndices.empty()) {
1434 ThisTypeIndex = ArgTypeIndices.front();
1435 ArgTypeIndices = ArgTypeIndices.drop_front();
1438 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1439 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
1441 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1443 // TODO: Need to use the correct values for:
1445 // ThisPointerAdjustment.
1446 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1447 FunctionOptions::None, ArgTypeIndices.size(),
1448 ArgListIndex, ThisAdjustment);
1449 TypeIndex TI = TypeTable.writeKnownType(MFR);
1454 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1455 unsigned VSlotCount =
1456 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
1457 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1459 VFTableShapeRecord VFTSR(Slots);
1460 return TypeTable.writeKnownType(VFTSR);
1463 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1464 switch (Flags & DINode::FlagAccessibility) {
1465 case DINode::FlagPrivate: return MemberAccess::Private;
1466 case DINode::FlagPublic: return MemberAccess::Public;
1467 case DINode::FlagProtected: return MemberAccess::Protected;
1469 // If there was no explicit access control, provide the default for the tag.
1470 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1471 : MemberAccess::Public;
1473 llvm_unreachable("access flags are exclusive");
1476 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1477 if (SP->isArtificial())
1478 return MethodOptions::CompilerGenerated;
1480 // FIXME: Handle other MethodOptions.
1482 return MethodOptions::None;
1485 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1487 switch (SP->getVirtuality()) {
1488 case dwarf::DW_VIRTUALITY_none:
1490 case dwarf::DW_VIRTUALITY_virtual:
1491 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1492 case dwarf::DW_VIRTUALITY_pure_virtual:
1493 return Introduced ? MethodKind::PureIntroducingVirtual
1494 : MethodKind::PureVirtual;
1496 llvm_unreachable("unhandled virtuality case");
1499 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1501 return MethodKind::Vanilla;
1504 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1505 switch (Ty->getTag()) {
1506 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1507 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1509 llvm_unreachable("unexpected tag");
1512 /// Return ClassOptions that should be present on both the forward declaration
1513 /// and the defintion of a tag type.
1514 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1515 ClassOptions CO = ClassOptions::None;
1517 // MSVC always sets this flag, even for local types. Clang doesn't always
1518 // appear to give every type a linkage name, which may be problematic for us.
1519 // FIXME: Investigate the consequences of not following them here.
1520 if (!Ty->getIdentifier().empty())
1521 CO |= ClassOptions::HasUniqueName;
1523 // Put the Nested flag on a type if it appears immediately inside a tag type.
1524 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1525 // here. That flag is only set on definitions, and not forward declarations.
1526 const DIScope *ImmediateScope = Ty->getScope().resolve();
1527 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1528 CO |= ClassOptions::Nested;
1530 // Put the Scoped flag on function-local types.
1531 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1532 Scope = Scope->getScope().resolve()) {
1533 if (isa<DISubprogram>(Scope)) {
1534 CO |= ClassOptions::Scoped;
1542 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
1543 ClassOptions CO = getCommonClassOptions(Ty);
1545 unsigned EnumeratorCount = 0;
1547 if (Ty->isForwardDecl()) {
1548 CO |= ClassOptions::ForwardReference;
1550 FieldListRecordBuilder FLRB(TypeTable);
1553 for (const DINode *Element : Ty->getElements()) {
1554 // We assume that the frontend provides all members in source declaration
1555 // order, which is what MSVC does.
1556 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1557 EnumeratorRecord ER(MemberAccess::Public,
1558 APSInt::getUnsigned(Enumerator->getValue()),
1559 Enumerator->getName());
1560 FLRB.writeMemberType(ER);
1564 FTI = FLRB.end(true);
1567 std::string FullName = getFullyQualifiedName(Ty);
1569 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1570 getTypeIndex(Ty->getBaseType()));
1571 return TypeTable.writeKnownType(ER);
1574 //===----------------------------------------------------------------------===//
1576 //===----------------------------------------------------------------------===//
1578 struct llvm::ClassInfo {
1580 const DIDerivedType *MemberTypeNode;
1581 uint64_t BaseOffset;
1584 typedef std::vector<MemberInfo> MemberList;
1586 typedef TinyPtrVector<const DISubprogram *> MethodsList;
1587 // MethodName -> MethodsList
1588 typedef MapVector<MDString *, MethodsList> MethodsMap;
1591 std::vector<const DIDerivedType *> Inheritance;
1595 // Direct overloaded methods gathered by name.
1600 std::vector<const DICompositeType *> NestedClasses;
1603 void CodeViewDebug::clear() {
1604 assert(CurFn == nullptr);
1606 FnDebugInfo.clear();
1607 FileToFilepathMap.clear();
1610 TypeIndices.clear();
1611 CompleteTypeIndices.clear();
1614 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1615 const DIDerivedType *DDTy) {
1616 if (!DDTy->getName().empty()) {
1617 Info.Members.push_back({DDTy, 0});
1620 // An unnamed member must represent a nested struct or union. Add all the
1621 // indirect fields to the current record.
1622 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
1623 uint64_t Offset = DDTy->getOffsetInBits();
1624 const DIType *Ty = DDTy->getBaseType().resolve();
1625 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
1626 ClassInfo NestedInfo = collectClassInfo(DCTy);
1627 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
1628 Info.Members.push_back(
1629 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
1632 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1634 // Add elements to structure type.
1635 DINodeArray Elements = Ty->getElements();
1636 for (auto *Element : Elements) {
1637 // We assume that the frontend provides all members in source declaration
1638 // order, which is what MSVC does.
1641 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1642 Info.Methods[SP->getRawName()].push_back(SP);
1643 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
1644 if (DDTy->getTag() == dwarf::DW_TAG_member) {
1645 collectMemberInfo(Info, DDTy);
1646 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1647 Info.Inheritance.push_back(DDTy);
1648 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1649 DDTy->getName() == "__vtbl_ptr_type") {
1650 Info.VShapeTI = getTypeIndex(DDTy);
1651 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1652 // Ignore friend members. It appears that MSVC emitted info about
1653 // friends in the past, but modern versions do not.
1655 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1656 Info.NestedClasses.push_back(Composite);
1658 // Skip other unrecognized kinds of elements.
1663 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1664 // First, construct the forward decl. Don't look into Ty to compute the
1665 // forward decl options, since it might not be available in all TUs.
1666 TypeRecordKind Kind = getRecordKind(Ty);
1668 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
1669 std::string FullName = getFullyQualifiedName(Ty);
1670 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1671 FullName, Ty->getIdentifier());
1672 TypeIndex FwdDeclTI = TypeTable.writeKnownType(CR);
1673 if (!Ty->isForwardDecl())
1674 DeferredCompleteTypes.push_back(Ty);
1678 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1679 // Construct the field list and complete type record.
1680 TypeRecordKind Kind = getRecordKind(Ty);
1681 ClassOptions CO = getCommonClassOptions(Ty);
1684 unsigned FieldCount;
1685 bool ContainsNestedClass;
1686 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1687 lowerRecordFieldList(Ty);
1689 if (ContainsNestedClass)
1690 CO |= ClassOptions::ContainsNestedClass;
1692 std::string FullName = getFullyQualifiedName(Ty);
1694 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1696 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1697 SizeInBytes, FullName, Ty->getIdentifier());
1698 TypeIndex ClassTI = TypeTable.writeKnownType(CR);
1700 if (const auto *File = Ty->getFile()) {
1701 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1702 TypeIndex SIDI = TypeTable.writeKnownType(SIDR);
1703 UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
1704 TypeTable.writeKnownType(USLR);
1707 addToUDTs(Ty, ClassTI);
1712 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1714 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
1715 std::string FullName = getFullyQualifiedName(Ty);
1716 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
1717 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UR);
1718 if (!Ty->isForwardDecl())
1719 DeferredCompleteTypes.push_back(Ty);
1723 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1724 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
1726 unsigned FieldCount;
1727 bool ContainsNestedClass;
1728 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1729 lowerRecordFieldList(Ty);
1731 if (ContainsNestedClass)
1732 CO |= ClassOptions::ContainsNestedClass;
1734 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1735 std::string FullName = getFullyQualifiedName(Ty);
1737 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1738 Ty->getIdentifier());
1739 TypeIndex UnionTI = TypeTable.writeKnownType(UR);
1741 StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1742 TypeIndex SIRI = TypeTable.writeKnownType(SIR);
1743 UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
1744 TypeTable.writeKnownType(USLR);
1746 addToUDTs(Ty, UnionTI);
1751 std::tuple<TypeIndex, TypeIndex, unsigned, bool>
1752 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1753 // Manually count members. MSVC appears to count everything that generates a
1754 // field list record. Each individual overload in a method overload group
1755 // contributes to this count, even though the overload group is a single field
1757 unsigned MemberCount = 0;
1758 ClassInfo Info = collectClassInfo(Ty);
1759 FieldListRecordBuilder FLBR(TypeTable);
1762 // Create base classes.
1763 for (const DIDerivedType *I : Info.Inheritance) {
1764 if (I->getFlags() & DINode::FlagVirtual) {
1766 // FIXME: Emit VBPtrOffset when the frontend provides it.
1767 unsigned VBPtrOffset = 0;
1768 // FIXME: Despite the accessor name, the offset is really in bytes.
1769 unsigned VBTableIndex = I->getOffsetInBits() / 4;
1770 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1771 ? TypeRecordKind::IndirectVirtualBaseClass
1772 : TypeRecordKind::VirtualBaseClass;
1773 VirtualBaseClassRecord VBCR(
1774 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
1775 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1778 FLBR.writeMemberType(VBCR);
1780 assert(I->getOffsetInBits() % 8 == 0 &&
1781 "bases must be on byte boundaries");
1782 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1783 getTypeIndex(I->getBaseType()),
1784 I->getOffsetInBits() / 8);
1785 FLBR.writeMemberType(BCR);
1790 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1791 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1792 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
1793 StringRef MemberName = Member->getName();
1794 MemberAccess Access =
1795 translateAccessFlags(Ty->getTag(), Member->getFlags());
1797 if (Member->isStaticMember()) {
1798 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
1799 FLBR.writeMemberType(SDMR);
1804 // Virtual function pointer member.
1805 if ((Member->getFlags() & DINode::FlagArtificial) &&
1806 Member->getName().startswith("_vptr$")) {
1807 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
1808 FLBR.writeMemberType(VFPR);
1814 uint64_t MemberOffsetInBits =
1815 Member->getOffsetInBits() + MemberInfo.BaseOffset;
1816 if (Member->isBitField()) {
1817 uint64_t StartBitOffset = MemberOffsetInBits;
1818 if (const auto *CI =
1819 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
1820 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
1822 StartBitOffset -= MemberOffsetInBits;
1823 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
1825 MemberBaseType = TypeTable.writeKnownType(BFR);
1827 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
1828 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
1830 FLBR.writeMemberType(DMR);
1835 for (auto &MethodItr : Info.Methods) {
1836 StringRef Name = MethodItr.first->getString();
1838 std::vector<OneMethodRecord> Methods;
1839 for (const DISubprogram *SP : MethodItr.second) {
1840 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1841 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
1843 unsigned VFTableOffset = -1;
1845 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1847 Methods.push_back(OneMethodRecord(
1848 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
1849 translateMethodKindFlags(SP, Introduced),
1850 translateMethodOptionFlags(SP), VFTableOffset, Name));
1853 assert(Methods.size() > 0 && "Empty methods map entry");
1854 if (Methods.size() == 1)
1855 FLBR.writeMemberType(Methods[0]);
1857 MethodOverloadListRecord MOLR(Methods);
1858 TypeIndex MethodList = TypeTable.writeKnownType(MOLR);
1859 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
1860 FLBR.writeMemberType(OMR);
1864 // Create nested classes.
1865 for (const DICompositeType *Nested : Info.NestedClasses) {
1866 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
1867 FLBR.writeMemberType(R);
1871 TypeIndex FieldTI = FLBR.end(true);
1872 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
1873 !Info.NestedClasses.empty());
1876 TypeIndex CodeViewDebug::getVBPTypeIndex() {
1877 if (!VBPType.getIndex()) {
1878 // Make a 'const int *' type.
1879 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
1880 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
1882 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1883 : PointerKind::Near32;
1884 PointerMode PM = PointerMode::Pointer;
1885 PointerOptions PO = PointerOptions::None;
1886 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1888 VBPType = TypeTable.writeKnownType(PR);
1894 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
1895 const DIType *Ty = TypeRef.resolve();
1896 const DIType *ClassTy = ClassTyRef.resolve();
1898 // The null DIType is the void type. Don't try to hash it.
1900 return TypeIndex::Void();
1902 // Check if we've already translated this type. Don't try to do a
1903 // get-or-create style insertion that caches the hash lookup across the
1904 // lowerType call. It will update the TypeIndices map.
1905 auto I = TypeIndices.find({Ty, ClassTy});
1906 if (I != TypeIndices.end())
1909 TypeLoweringScope S(*this);
1910 TypeIndex TI = lowerType(Ty, ClassTy);
1911 return recordTypeIndexForDINode(Ty, TI, ClassTy);
1914 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1915 const DIType *Ty = TypeRef.resolve();
1917 // The null DIType is the void type. Don't try to hash it.
1919 return TypeIndex::Void();
1921 // If this is a non-record type, the complete type index is the same as the
1922 // normal type index. Just call getTypeIndex.
1923 switch (Ty->getTag()) {
1924 case dwarf::DW_TAG_class_type:
1925 case dwarf::DW_TAG_structure_type:
1926 case dwarf::DW_TAG_union_type:
1929 return getTypeIndex(Ty);
1932 // Check if we've already translated the complete record type. Lowering a
1933 // complete type should never trigger lowering another complete type, so we
1934 // can reuse the hash table lookup result.
1935 const auto *CTy = cast<DICompositeType>(Ty);
1936 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1937 if (!InsertResult.second)
1938 return InsertResult.first->second;
1940 TypeLoweringScope S(*this);
1942 // Make sure the forward declaration is emitted first. It's unclear if this
1943 // is necessary, but MSVC does it, and we should follow suit until we can show
1945 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1947 // Just use the forward decl if we don't have complete type info. This might
1948 // happen if the frontend is using modules and expects the complete definition
1949 // to be emitted elsewhere.
1950 if (CTy->isForwardDecl())
1954 switch (CTy->getTag()) {
1955 case dwarf::DW_TAG_class_type:
1956 case dwarf::DW_TAG_structure_type:
1957 TI = lowerCompleteTypeClass(CTy);
1959 case dwarf::DW_TAG_union_type:
1960 TI = lowerCompleteTypeUnion(CTy);
1963 llvm_unreachable("not a record");
1966 InsertResult.first->second = TI;
1970 /// Emit all the deferred complete record types. Try to do this in FIFO order,
1971 /// and do this until fixpoint, as each complete record type typically
1973 /// many other record types.
1974 void CodeViewDebug::emitDeferredCompleteTypes() {
1975 SmallVector<const DICompositeType *, 4> TypesToEmit;
1976 while (!DeferredCompleteTypes.empty()) {
1977 std::swap(DeferredCompleteTypes, TypesToEmit);
1978 for (const DICompositeType *RecordTy : TypesToEmit)
1979 getCompleteTypeIndex(RecordTy);
1980 TypesToEmit.clear();
1984 void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
1985 // Get the sorted list of parameters and emit them first.
1986 SmallVector<const LocalVariable *, 6> Params;
1987 for (const LocalVariable &L : Locals)
1988 if (L.DIVar->isParameter())
1989 Params.push_back(&L);
1990 std::sort(Params.begin(), Params.end(),
1991 [](const LocalVariable *L, const LocalVariable *R) {
1992 return L->DIVar->getArg() < R->DIVar->getArg();
1994 for (const LocalVariable *L : Params)
1995 emitLocalVariable(*L);
1997 // Next emit all non-parameters in the order that we found them.
1998 for (const LocalVariable &L : Locals)
1999 if (!L.DIVar->isParameter())
2000 emitLocalVariable(L);
2003 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2004 // LocalSym record, see SymbolRecord.h for more info.
2005 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2006 *LocalEnd = MMI->getContext().createTempSymbol();
2007 OS.AddComment("Record length");
2008 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2009 OS.EmitLabel(LocalBegin);
2011 OS.AddComment("Record kind: S_LOCAL");
2012 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
2014 LocalSymFlags Flags = LocalSymFlags::None;
2015 if (Var.DIVar->isParameter())
2016 Flags |= LocalSymFlags::IsParameter;
2017 if (Var.DefRanges.empty())
2018 Flags |= LocalSymFlags::IsOptimizedOut;
2020 OS.AddComment("TypeIndex");
2021 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
2022 OS.EmitIntValue(TI.getIndex(), 4);
2023 OS.AddComment("Flags");
2024 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
2025 // Truncate the name so we won't overflow the record length field.
2026 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2027 OS.EmitLabel(LocalEnd);
2029 // Calculate the on disk prefix of the appropriate def range record. The
2030 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2031 // should be big enough to hold all forms without memory allocation.
2032 SmallString<20> BytePrefix;
2033 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2035 if (DefRange.InMemory) {
2036 uint16_t RegRelFlags = 0;
2037 if (DefRange.IsSubfield) {
2038 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2039 (DefRange.StructOffset
2040 << DefRangeRegisterRelSym::OffsetInParentShift);
2042 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2043 Sym.Hdr.Register = DefRange.CVRegister;
2044 Sym.Hdr.Flags = RegRelFlags;
2045 Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
2046 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
2048 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
2050 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
2052 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
2053 if (DefRange.IsSubfield) {
2054 // Unclear what matters here.
2055 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2056 Sym.Hdr.Register = DefRange.CVRegister;
2057 Sym.Hdr.MayHaveNoName = 0;
2058 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2060 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2061 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2063 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2066 // Unclear what matters here.
2067 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2068 Sym.Hdr.Register = DefRange.CVRegister;
2069 Sym.Hdr.MayHaveNoName = 0;
2070 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2071 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2073 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2077 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2081 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
2082 const Function *GV = MF->getFunction();
2083 assert(FnDebugInfo.count(GV));
2084 assert(CurFn == &FnDebugInfo[GV]);
2086 collectVariableInfo(GV->getSubprogram());
2088 // Don't emit anything if we don't have any line tables.
2089 if (!CurFn->HaveLineInfo) {
2090 FnDebugInfo.erase(GV);
2095 CurFn->End = Asm->getFunctionEnd();
2100 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
2101 DebugHandlerBase::beginInstruction(MI);
2103 // Ignore DBG_VALUE locations and function prologue.
2104 if (!Asm || !CurFn || MI->isDebugValue() ||
2105 MI->getFlag(MachineInstr::FrameSetup))
2107 DebugLoc DL = MI->getDebugLoc();
2108 if (DL == PrevInstLoc || !DL)
2110 maybeRecordLocation(DL, Asm->MF);
2113 MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
2114 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2115 *EndLabel = MMI->getContext().createTempSymbol();
2116 OS.EmitIntValue(unsigned(Kind), 4);
2117 OS.AddComment("Subsection size");
2118 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2119 OS.EmitLabel(BeginLabel);
2123 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2124 OS.EmitLabel(EndLabel);
2125 // Every subsection must be aligned to a 4-byte boundary.
2126 OS.EmitValueToAlignment(4);
2129 void CodeViewDebug::emitDebugInfoForUDTs(
2130 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
2131 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
2132 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2133 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2134 OS.AddComment("Record length");
2135 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2136 OS.EmitLabel(UDTRecordBegin);
2138 OS.AddComment("Record kind: S_UDT");
2139 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2141 OS.AddComment("Type");
2142 OS.EmitIntValue(UDT.second.getIndex(), 4);
2144 emitNullTerminatedSymbolName(OS, UDT.first);
2145 OS.EmitLabel(UDTRecordEnd);
2149 void CodeViewDebug::emitDebugInfoForGlobals() {
2150 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2152 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
2153 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2154 GV.getDebugInfo(GVEs);
2155 for (const auto *GVE : GVEs)
2156 GlobalMap[GVE] = &GV;
2159 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2160 for (const MDNode *Node : CUs->operands()) {
2161 const auto *CU = cast<DICompileUnit>(Node);
2163 // First, emit all globals that are not in a comdat in a single symbol
2164 // substream. MSVC doesn't like it if the substream is empty, so only open
2165 // it if we have at least one global to emit.
2166 switchToDebugSectionForSymbol(nullptr);
2167 MCSymbol *EndLabel = nullptr;
2168 for (const auto *GVE : CU->getGlobalVariables()) {
2169 if (const auto *GV = GlobalMap.lookup(GVE))
2170 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
2172 OS.AddComment("Symbol subsection for globals");
2173 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
2175 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2176 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
2180 endCVSubsection(EndLabel);
2182 // Second, emit each global that is in a comdat into its own .debug$S
2183 // section along with its own symbol substream.
2184 for (const auto *GVE : CU->getGlobalVariables()) {
2185 if (const auto *GV = GlobalMap.lookup(GVE)) {
2186 if (GV->hasComdat()) {
2187 MCSymbol *GVSym = Asm->getSymbol(GV);
2188 OS.AddComment("Symbol subsection for " +
2189 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
2190 switchToDebugSectionForSymbol(GVSym);
2191 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
2192 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2193 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
2194 endCVSubsection(EndLabel);
2201 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2202 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2203 for (const MDNode *Node : CUs->operands()) {
2204 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2205 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2207 // FIXME: Add to global/local DTU list.
2213 void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
2214 const GlobalVariable *GV,
2216 // DataSym record, see SymbolRecord.h for more info.
2217 // FIXME: Thread local data, etc
2218 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2219 *DataEnd = MMI->getContext().createTempSymbol();
2220 OS.AddComment("Record length");
2221 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2222 OS.EmitLabel(DataBegin);
2223 if (DIGV->isLocalToUnit()) {
2224 if (GV->isThreadLocal()) {
2225 OS.AddComment("Record kind: S_LTHREAD32");
2226 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2228 OS.AddComment("Record kind: S_LDATA32");
2229 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2232 if (GV->isThreadLocal()) {
2233 OS.AddComment("Record kind: S_GTHREAD32");
2234 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2236 OS.AddComment("Record kind: S_GDATA32");
2237 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2240 OS.AddComment("Type");
2241 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2242 OS.AddComment("DataOffset");
2243 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
2244 OS.AddComment("Segment");
2245 OS.EmitCOFFSectionIndex(GVSym);
2246 OS.AddComment("Name");
2247 emitNullTerminatedSymbolName(OS, DIGV->getName());
2248 OS.EmitLabel(DataEnd);