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/ByteStream.h"
17 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
18 #include "llvm/DebugInfo/CodeView/CodeView.h"
19 #include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h"
20 #include "llvm/DebugInfo/CodeView/Line.h"
21 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
22 #include "llvm/DebugInfo/CodeView/TypeDumper.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/IR/Constants.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCSectionCOFF.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Support/COFF.h"
31 #include "llvm/Support/ScopedPrinter.h"
32 #include "llvm/Target/TargetFrameLowering.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
37 using namespace llvm::codeview;
39 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
40 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
41 // If module doesn't have named metadata anchors or COFF debug section
42 // is not available, skip any debug info related stuff.
43 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
44 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
49 // Tell MMI that we have debug info.
50 MMI->setDebugInfoAvailability(true);
53 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
54 std::string &Filepath = FileToFilepathMap[File];
55 if (!Filepath.empty())
58 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
60 // Clang emits directory and relative filename info into the IR, but CodeView
61 // operates on full paths. We could change Clang to emit full paths too, but
62 // that would increase the IR size and probably not needed for other users.
63 // For now, just concatenate and canonicalize the path here.
64 if (Filename.find(':') == 1)
67 Filepath = (Dir + "\\" + Filename).str();
69 // Canonicalize the path. We have to do it textually because we may no longer
70 // have access the file in the filesystem.
71 // First, replace all slashes with backslashes.
72 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
74 // Remove all "\.\" with "\".
76 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
77 Filepath.erase(Cursor, 2);
79 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
80 // path should be well-formatted, e.g. start with a drive letter, etc.
82 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
83 // Something's wrong if the path starts with "\..\", abort.
87 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
88 if (PrevSlash == std::string::npos)
89 // Something's wrong, abort.
92 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
93 // The next ".." might be following the one we've just erased.
97 // Remove all duplicate backslashes.
99 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
100 Filepath.erase(Cursor, 1);
105 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
106 unsigned NextId = FileIdMap.size() + 1;
107 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
108 if (Insertion.second) {
109 // We have to compute the full filepath and emit a .cv_file directive.
110 StringRef FullPath = getFullFilepath(F);
111 NextId = OS.EmitCVFileDirective(NextId, FullPath);
112 assert(NextId == FileIdMap.size() && ".cv_file directive failed");
114 return Insertion.first->second;
117 CodeViewDebug::InlineSite &
118 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
119 const DISubprogram *Inlinee) {
120 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
121 InlineSite *Site = &SiteInsertion.first->second;
122 if (SiteInsertion.second) {
123 Site->SiteFuncId = NextFuncId++;
124 Site->Inlinee = Inlinee;
125 InlinedSubprograms.insert(Inlinee);
126 getFuncIdForSubprogram(Inlinee);
131 static StringRef getPrettyScopeName(const DIScope *Scope) {
132 StringRef ScopeName = Scope->getName();
133 if (!ScopeName.empty())
136 switch (Scope->getTag()) {
137 case dwarf::DW_TAG_enumeration_type:
138 case dwarf::DW_TAG_class_type:
139 case dwarf::DW_TAG_structure_type:
140 case dwarf::DW_TAG_union_type:
141 return "<unnamed-tag>";
142 case dwarf::DW_TAG_namespace:
143 return "`anonymous namespace'";
149 static const DISubprogram *getQualifiedNameComponents(
150 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
151 const DISubprogram *ClosestSubprogram = nullptr;
152 while (Scope != nullptr) {
153 if (ClosestSubprogram == nullptr)
154 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
155 StringRef ScopeName = getPrettyScopeName(Scope);
156 if (!ScopeName.empty())
157 QualifiedNameComponents.push_back(ScopeName);
158 Scope = Scope->getScope().resolve();
160 return ClosestSubprogram;
163 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
164 StringRef TypeName) {
165 std::string FullyQualifiedName;
166 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
167 FullyQualifiedName.append(QualifiedNameComponent);
168 FullyQualifiedName.append("::");
170 FullyQualifiedName.append(TypeName);
171 return FullyQualifiedName;
174 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
175 SmallVector<StringRef, 5> QualifiedNameComponents;
176 getQualifiedNameComponents(Scope, QualifiedNameComponents);
177 return getQualifiedName(QualifiedNameComponents, Name);
180 struct CodeViewDebug::TypeLoweringScope {
181 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
182 ~TypeLoweringScope() {
183 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
184 // inner TypeLoweringScopes don't attempt to emit deferred types.
185 if (CVD.TypeEmissionLevel == 1)
186 CVD.emitDeferredCompleteTypes();
187 --CVD.TypeEmissionLevel;
192 static std::string getFullyQualifiedName(const DIScope *Ty) {
193 const DIScope *Scope = Ty->getScope().resolve();
194 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
197 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
198 // No scope means global scope and that uses the zero index.
199 if (!Scope || isa<DIFile>(Scope))
202 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
204 // Check if we've already translated this scope.
205 auto I = TypeIndices.find({Scope, nullptr});
206 if (I != TypeIndices.end())
209 // Build the fully qualified name of the scope.
210 std::string ScopeName = getFullyQualifiedName(Scope);
212 TypeTable.writeStringId(StringIdRecord(TypeIndex(), ScopeName));
213 return recordTypeIndexForDINode(Scope, TI);
216 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
219 // Check if we've already translated this subprogram.
220 auto I = TypeIndices.find({SP, nullptr});
221 if (I != TypeIndices.end())
224 // The display name includes function template arguments. Drop them to match
226 StringRef DisplayName = SP->getDisplayName().split('<').first;
228 const DIScope *Scope = SP->getScope().resolve();
230 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
231 // If the scope is a DICompositeType, then this must be a method. Member
232 // function types take some special handling, and require access to the
234 TypeIndex ClassType = getTypeIndex(Class);
235 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
237 TI = TypeTable.writeMemberFuncId(MFuncId);
239 // Otherwise, this must be a free function.
240 TypeIndex ParentScope = getScopeIndex(Scope);
241 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
242 TI = TypeTable.writeFuncId(FuncId);
245 return recordTypeIndexForDINode(SP, TI);
248 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
249 const DICompositeType *Class) {
250 // Always use the method declaration as the key for the function type. The
251 // method declaration contains the this adjustment.
252 if (SP->getDeclaration())
253 SP = SP->getDeclaration();
254 assert(!SP->getDeclaration() && "should use declaration as key");
256 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
257 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
258 auto I = TypeIndices.find({SP, Class});
259 if (I != TypeIndices.end())
262 // Make sure complete type info for the class is emitted *after* the member
263 // function type, as the complete class type is likely to reference this
264 // member function type.
265 TypeLoweringScope S(*this);
267 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
268 return recordTypeIndexForDINode(SP, TI, Class);
271 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
273 const DIType *ClassTy) {
274 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
276 assert(InsertResult.second && "DINode was already assigned a type index");
280 unsigned CodeViewDebug::getPointerSizeInBytes() {
281 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
284 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
285 const DILocation *InlinedAt) {
287 // This variable was inlined. Associate it with the InlineSite.
288 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
289 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
290 Site.InlinedLocals.emplace_back(Var);
292 // This variable goes in the main ProcSym.
293 CurFn->Locals.emplace_back(Var);
297 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
298 const DILocation *Loc) {
299 auto B = Locs.begin(), E = Locs.end();
300 if (std::find(B, E, Loc) == E)
304 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
305 const MachineFunction *MF) {
306 // Skip this instruction if it has the same location as the previous one.
307 if (DL == CurFn->LastLoc)
310 const DIScope *Scope = DL.get()->getScope();
314 // Skip this line if it is longer than the maximum we can record.
315 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
316 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
317 LI.isNeverStepInto())
320 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
321 if (CI.getStartColumn() != DL.getCol())
324 if (!CurFn->HaveLineInfo)
325 CurFn->HaveLineInfo = true;
327 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
328 FileId = CurFn->LastFileId;
330 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
333 unsigned FuncId = CurFn->FuncId;
334 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
335 const DILocation *Loc = DL.get();
337 // If this location was actually inlined from somewhere else, give it the ID
338 // of the inline call site.
340 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
342 // Ensure we have links in the tree of inline call sites.
343 bool FirstLoc = true;
344 while ((SiteLoc = Loc->getInlinedAt())) {
346 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
348 addLocIfNotPresent(Site.ChildSites, Loc);
352 addLocIfNotPresent(CurFn->ChildSites, Loc);
355 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
356 /*PrologueEnd=*/false,
357 /*IsStmt=*/false, DL->getFilename());
360 void CodeViewDebug::emitCodeViewMagicVersion() {
361 OS.EmitValueToAlignment(4);
362 OS.AddComment("Debug section magic");
363 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
366 void CodeViewDebug::endModule() {
367 if (!Asm || !MMI->hasDebugInfo())
370 assert(Asm != nullptr);
372 // The COFF .debug$S section consists of several subsections, each starting
373 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
374 // of the payload followed by the payload itself. The subsections are 4-byte
377 // Use the generic .debug$S section, and make a subsection for all the inlined
379 switchToDebugSectionForSymbol(nullptr);
380 emitInlineeLinesSubsection();
382 // Emit per-function debug information.
383 for (auto &P : FnDebugInfo)
384 if (!P.first->isDeclarationForLinker())
385 emitDebugInfoForFunction(P.first, P.second);
387 // Emit global variable debug information.
388 setCurrentSubprogram(nullptr);
389 emitDebugInfoForGlobals();
391 // Emit retained types.
392 emitDebugInfoForRetainedTypes();
394 // Switch back to the generic .debug$S section after potentially processing
395 // comdat symbol sections.
396 switchToDebugSectionForSymbol(nullptr);
398 // Emit UDT records for any types used by global variables.
399 if (!GlobalUDTs.empty()) {
400 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
401 emitDebugInfoForUDTs(GlobalUDTs);
402 endCVSubsection(SymbolsEnd);
405 // This subsection holds a file index to offset in string table table.
406 OS.AddComment("File index to string table offset subsection");
407 OS.EmitCVFileChecksumsDirective();
409 // This subsection holds the string table.
410 OS.AddComment("String table");
411 OS.EmitCVStringTableDirective();
413 // Emit type information last, so that any types we translate while emitting
414 // function info are included.
415 emitTypeInformation();
420 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
421 // Microsoft's linker seems to have trouble with symbol names longer than
423 S = S.substr(0, 0xffd8);
424 SmallString<32> NullTerminatedString(S);
425 NullTerminatedString.push_back('\0');
426 OS.EmitBytes(NullTerminatedString);
429 void CodeViewDebug::emitTypeInformation() {
430 // Do nothing if we have no debug info or if no non-trivial types were emitted
431 // to TypeTable during codegen.
432 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
435 if (TypeTable.empty())
438 // Start the .debug$T section with 0x4.
439 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
440 emitCodeViewMagicVersion();
442 SmallString<8> CommentPrefix;
443 if (OS.isVerboseAsm()) {
444 CommentPrefix += '\t';
445 CommentPrefix += Asm->MAI->getCommentString();
446 CommentPrefix += ' ';
449 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
450 TypeTable.ForEachRecord(
451 [&](TypeIndex Index, StringRef Record) {
452 if (OS.isVerboseAsm()) {
453 // Emit a block comment describing the type record for readability.
454 SmallString<512> CommentBlock;
455 raw_svector_ostream CommentOS(CommentBlock);
456 ScopedPrinter SP(CommentOS);
457 SP.setPrefix(CommentPrefix);
458 CVTD.setPrinter(&SP);
459 Error E = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
461 logAllUnhandledErrors(std::move(E), errs(), "error: ");
462 llvm_unreachable("produced malformed type record");
464 // emitRawComment will insert its own tab and comment string before
465 // the first line, so strip off our first one. It also prints its own
468 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
471 // Assert that the type data is valid even if we aren't dumping
472 // comments. The MSVC linker doesn't do much type record validation,
473 // so the first link of an invalid type record can succeed while
474 // subsequent links will fail with LNK1285.
475 ByteStream<> Stream({Record.bytes_begin(), Record.bytes_end()});
477 StreamReader Reader(Stream);
478 Error E = Reader.readArray(Types, Reader.getLength());
480 TypeVisitorCallbacks C;
481 E = CVTypeVisitor(C).visitTypeStream(Types);
484 logAllUnhandledErrors(std::move(E), errs(), "error: ");
485 llvm_unreachable("produced malformed type record");
489 OS.EmitBinaryData(Record);
493 void CodeViewDebug::emitInlineeLinesSubsection() {
494 if (InlinedSubprograms.empty())
497 OS.AddComment("Inlinee lines subsection");
498 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
500 // We don't provide any extra file info.
501 // FIXME: Find out if debuggers use this info.
502 OS.AddComment("Inlinee lines signature");
503 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
505 for (const DISubprogram *SP : InlinedSubprograms) {
506 assert(TypeIndices.count({SP, nullptr}));
507 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
510 unsigned FileId = maybeRecordFile(SP->getFile());
511 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
512 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
514 // The filechecksum table uses 8 byte entries for now, and file ids start at
516 unsigned FileOffset = (FileId - 1) * 8;
517 OS.AddComment("Type index of inlined function");
518 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
519 OS.AddComment("Offset into filechecksum table");
520 OS.EmitIntValue(FileOffset, 4);
521 OS.AddComment("Starting line number");
522 OS.EmitIntValue(SP->getLine(), 4);
525 endCVSubsection(InlineEnd);
528 void CodeViewDebug::collectInlineSiteChildren(
529 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
530 const InlineSite &Site) {
531 for (const DILocation *ChildSiteLoc : Site.ChildSites) {
532 auto I = FI.InlineSites.find(ChildSiteLoc);
533 const InlineSite &ChildSite = I->second;
534 Children.push_back(ChildSite.SiteFuncId);
535 collectInlineSiteChildren(Children, FI, ChildSite);
539 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
540 const DILocation *InlinedAt,
541 const InlineSite &Site) {
542 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
543 *InlineEnd = MMI->getContext().createTempSymbol();
545 assert(TypeIndices.count({Site.Inlinee, nullptr}));
546 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
549 OS.AddComment("Record length");
550 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
551 OS.EmitLabel(InlineBegin);
552 OS.AddComment("Record kind: S_INLINESITE");
553 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
555 OS.AddComment("PtrParent");
556 OS.EmitIntValue(0, 4);
557 OS.AddComment("PtrEnd");
558 OS.EmitIntValue(0, 4);
559 OS.AddComment("Inlinee type index");
560 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
562 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
563 unsigned StartLineNum = Site.Inlinee->getLine();
564 SmallVector<unsigned, 3> SecondaryFuncIds;
565 collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
567 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
568 FI.Begin, FI.End, SecondaryFuncIds);
570 OS.EmitLabel(InlineEnd);
572 emitLocalVariableList(Site.InlinedLocals);
574 // Recurse on child inlined call sites before closing the scope.
575 for (const DILocation *ChildSite : Site.ChildSites) {
576 auto I = FI.InlineSites.find(ChildSite);
577 assert(I != FI.InlineSites.end() &&
578 "child site not in function inline site map");
579 emitInlinedCallSite(FI, ChildSite, I->second);
583 OS.AddComment("Record length");
584 OS.EmitIntValue(2, 2); // RecordLength
585 OS.AddComment("Record kind: S_INLINESITE_END");
586 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
589 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
590 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
591 // comdat key. A section may be comdat because of -ffunction-sections or
592 // because it is comdat in the IR.
593 MCSectionCOFF *GVSec =
594 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
595 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
597 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
598 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
599 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
601 OS.SwitchSection(DebugSec);
603 // Emit the magic version number if this is the first time we've switched to
605 if (ComdatDebugSections.insert(DebugSec).second)
606 emitCodeViewMagicVersion();
609 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
611 // For each function there is a separate subsection
612 // which holds the PC to file:line table.
613 const MCSymbol *Fn = Asm->getSymbol(GV);
616 // Switch to the to a comdat section, if appropriate.
617 switchToDebugSectionForSymbol(Fn);
619 std::string FuncName;
620 auto *SP = GV->getSubprogram();
622 setCurrentSubprogram(SP);
624 // If we have a display name, build the fully qualified name by walking the
626 if (!SP->getDisplayName().empty())
628 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
630 // If our DISubprogram name is empty, use the mangled name.
631 if (FuncName.empty())
632 FuncName = GlobalValue::getRealLinkageName(GV->getName());
634 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
635 OS.AddComment("Symbol subsection for " + Twine(FuncName));
636 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
638 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
639 *ProcRecordEnd = MMI->getContext().createTempSymbol();
640 OS.AddComment("Record length");
641 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
642 OS.EmitLabel(ProcRecordBegin);
644 if (GV->hasLocalLinkage()) {
645 OS.AddComment("Record kind: S_LPROC32_ID");
646 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
648 OS.AddComment("Record kind: S_GPROC32_ID");
649 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
652 // These fields are filled in by tools like CVPACK which run after the fact.
653 OS.AddComment("PtrParent");
654 OS.EmitIntValue(0, 4);
655 OS.AddComment("PtrEnd");
656 OS.EmitIntValue(0, 4);
657 OS.AddComment("PtrNext");
658 OS.EmitIntValue(0, 4);
659 // This is the important bit that tells the debugger where the function
660 // code is located and what's its size:
661 OS.AddComment("Code size");
662 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
663 OS.AddComment("Offset after prologue");
664 OS.EmitIntValue(0, 4);
665 OS.AddComment("Offset before epilogue");
666 OS.EmitIntValue(0, 4);
667 OS.AddComment("Function type index");
668 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
669 OS.AddComment("Function section relative address");
670 OS.EmitCOFFSecRel32(Fn);
671 OS.AddComment("Function section index");
672 OS.EmitCOFFSectionIndex(Fn);
673 OS.AddComment("Flags");
674 OS.EmitIntValue(0, 1);
675 // Emit the function display name as a null-terminated string.
676 OS.AddComment("Function name");
677 // Truncate the name so we won't overflow the record length field.
678 emitNullTerminatedSymbolName(OS, FuncName);
679 OS.EmitLabel(ProcRecordEnd);
681 emitLocalVariableList(FI.Locals);
683 // Emit inlined call site information. Only emit functions inlined directly
684 // into the parent function. We'll emit the other sites recursively as part
685 // of their parent inline site.
686 for (const DILocation *InlinedAt : FI.ChildSites) {
687 auto I = FI.InlineSites.find(InlinedAt);
688 assert(I != FI.InlineSites.end() &&
689 "child site not in function inline site map");
690 emitInlinedCallSite(FI, InlinedAt, I->second);
694 emitDebugInfoForUDTs(LocalUDTs);
696 // We're done with this function.
697 OS.AddComment("Record length");
698 OS.EmitIntValue(0x0002, 2);
699 OS.AddComment("Record kind: S_PROC_ID_END");
700 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
702 endCVSubsection(SymbolsEnd);
704 // We have an assembler directive that takes care of the whole line table.
705 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
708 CodeViewDebug::LocalVarDefRange
709 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
712 DR.DataOffset = Offset;
713 assert(DR.DataOffset == Offset && "truncation");
715 DR.CVRegister = CVRegister;
719 CodeViewDebug::LocalVarDefRange
720 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
725 DR.CVRegister = CVRegister;
729 void CodeViewDebug::collectVariableInfoFromMMITable(
730 DenseSet<InlinedVariable> &Processed) {
731 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
732 const TargetFrameLowering *TFI = TSI.getFrameLowering();
733 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
735 for (const MachineModuleInfo::VariableDbgInfo &VI :
736 MMI->getVariableDbgInfo()) {
739 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
740 "Expected inlined-at fields to agree");
742 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
743 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
745 // If variable scope is not found then skip this variable.
749 // Get the frame register used and the offset.
750 unsigned FrameReg = 0;
751 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
752 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
754 // Calculate the label ranges.
755 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
756 for (const InsnRange &Range : Scope->getRanges()) {
757 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
758 const MCSymbol *End = getLabelAfterInsn(Range.second);
759 End = End ? End : Asm->getFunctionEnd();
760 DefRange.Ranges.emplace_back(Begin, End);
765 Var.DefRanges.emplace_back(std::move(DefRange));
766 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
770 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
771 DenseSet<InlinedVariable> Processed;
772 // Grab the variable info that was squirreled away in the MMI side-table.
773 collectVariableInfoFromMMITable(Processed);
775 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
777 for (const auto &I : DbgValues) {
778 InlinedVariable IV = I.first;
779 if (Processed.count(IV))
781 const DILocalVariable *DIVar = IV.first;
782 const DILocation *InlinedAt = IV.second;
784 // Instruction ranges, specifying where IV is accessible.
785 const auto &Ranges = I.second;
787 LexicalScope *Scope = nullptr;
789 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
791 Scope = LScopes.findLexicalScope(DIVar->getScope());
792 // If variable scope is not found then skip this variable.
799 // Calculate the definition ranges.
800 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
801 const InsnRange &Range = *I;
802 const MachineInstr *DVInst = Range.first;
803 assert(DVInst->isDebugValue() && "Invalid History entry");
804 const DIExpression *DIExpr = DVInst->getDebugExpression();
806 // Bail if there is a complex DWARF expression for now.
807 if (DIExpr && DIExpr->getNumElements() > 0)
810 // Bail if operand 0 is not a valid register. This means the variable is a
811 // simple constant, or is described by a complex expression.
812 // FIXME: Find a way to represent constant variables, since they are
813 // relatively common.
815 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
819 // Handle the two cases we can handle: indirect in memory and in register.
820 bool IsIndirect = DVInst->getOperand(1).isImm();
821 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
823 LocalVarDefRange DefRange;
825 int64_t Offset = DVInst->getOperand(1).getImm();
826 DefRange = createDefRangeMem(CVReg, Offset);
828 DefRange = createDefRangeReg(CVReg);
830 if (Var.DefRanges.empty() ||
831 Var.DefRanges.back().isDifferentLocation(DefRange)) {
832 Var.DefRanges.emplace_back(std::move(DefRange));
836 // Compute the label range.
837 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
838 const MCSymbol *End = getLabelAfterInsn(Range.second);
840 if (std::next(I) != E)
841 End = getLabelBeforeInsn(std::next(I)->first);
843 End = Asm->getFunctionEnd();
846 // If the last range end is our begin, just extend the last range.
847 // Otherwise make a new range.
848 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
849 Var.DefRanges.back().Ranges;
850 if (!Ranges.empty() && Ranges.back().second == Begin)
851 Ranges.back().second = End;
853 Ranges.emplace_back(Begin, End);
855 // FIXME: Do more range combining.
858 recordLocalVariable(std::move(Var), InlinedAt);
862 void CodeViewDebug::beginFunction(const MachineFunction *MF) {
863 assert(!CurFn && "Can't process two functions at once!");
865 if (!Asm || !MMI->hasDebugInfo() || !MF->getFunction()->getSubprogram())
868 DebugHandlerBase::beginFunction(MF);
870 const Function *GV = MF->getFunction();
871 assert(FnDebugInfo.count(GV) == false);
872 CurFn = &FnDebugInfo[GV];
873 CurFn->FuncId = NextFuncId++;
874 CurFn->Begin = Asm->getFunctionBegin();
876 // Find the end of the function prolog. First known non-DBG_VALUE and
877 // non-frame setup location marks the beginning of the function body.
878 // FIXME: is there a simpler a way to do this? Can we just search
879 // for the first instruction of the function, not the last of the prolog?
880 DebugLoc PrologEndLoc;
881 bool EmptyPrologue = true;
882 for (const auto &MBB : *MF) {
883 for (const auto &MI : MBB) {
884 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
886 PrologEndLoc = MI.getDebugLoc();
888 } else if (!MI.isDebugValue()) {
889 EmptyPrologue = false;
894 // Record beginning of function if we have a non-empty prologue.
895 if (PrologEndLoc && !EmptyPrologue) {
896 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
897 maybeRecordLocation(FnStartDL, MF);
901 void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
902 // Don't record empty UDTs.
903 if (Ty->getName().empty())
906 SmallVector<StringRef, 5> QualifiedNameComponents;
907 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
908 Ty->getScope().resolve(), QualifiedNameComponents);
910 std::string FullyQualifiedName =
911 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
913 if (ClosestSubprogram == nullptr)
914 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
915 else if (ClosestSubprogram == CurrentSubprogram)
916 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
918 // TODO: What if the ClosestSubprogram is neither null or the current
919 // subprogram? Currently, the UDT just gets dropped on the floor.
921 // The current behavior is not desirable. To get maximal fidelity, we would
922 // need to perform all type translation before beginning emission of .debug$S
923 // and then make LocalUDTs a member of FunctionInfo
926 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
927 // Generic dispatch for lowering an unknown type.
928 switch (Ty->getTag()) {
929 case dwarf::DW_TAG_array_type:
930 return lowerTypeArray(cast<DICompositeType>(Ty));
931 case dwarf::DW_TAG_typedef:
932 return lowerTypeAlias(cast<DIDerivedType>(Ty));
933 case dwarf::DW_TAG_base_type:
934 return lowerTypeBasic(cast<DIBasicType>(Ty));
935 case dwarf::DW_TAG_pointer_type:
936 case dwarf::DW_TAG_reference_type:
937 case dwarf::DW_TAG_rvalue_reference_type:
938 return lowerTypePointer(cast<DIDerivedType>(Ty));
939 case dwarf::DW_TAG_ptr_to_member_type:
940 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
941 case dwarf::DW_TAG_const_type:
942 case dwarf::DW_TAG_volatile_type:
943 return lowerTypeModifier(cast<DIDerivedType>(Ty));
944 case dwarf::DW_TAG_subroutine_type:
946 // The member function type of a member function pointer has no
948 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
949 /*ThisAdjustment=*/0);
951 return lowerTypeFunction(cast<DISubroutineType>(Ty));
952 case dwarf::DW_TAG_enumeration_type:
953 return lowerTypeEnum(cast<DICompositeType>(Ty));
954 case dwarf::DW_TAG_class_type:
955 case dwarf::DW_TAG_structure_type:
956 return lowerTypeClass(cast<DICompositeType>(Ty));
957 case dwarf::DW_TAG_union_type:
958 return lowerTypeUnion(cast<DICompositeType>(Ty));
960 // Use the null type index.
965 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
966 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
967 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
968 StringRef TypeName = Ty->getName();
970 addToUDTs(Ty, UnderlyingTypeIndex);
972 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
973 TypeName == "HRESULT")
974 return TypeIndex(SimpleTypeKind::HResult);
975 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
976 TypeName == "wchar_t")
977 return TypeIndex(SimpleTypeKind::WideCharacter);
979 return UnderlyingTypeIndex;
982 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
983 DITypeRef ElementTypeRef = Ty->getBaseType();
984 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
985 // IndexType is size_t, which depends on the bitness of the target.
986 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
987 ? TypeIndex(SimpleTypeKind::UInt64Quad)
988 : TypeIndex(SimpleTypeKind::UInt32Long);
990 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
992 bool UndefinedSubrange = false;
995 // There is a bug in the front-end where an array of a structure, which was
996 // declared as incomplete structure first, ends up not getting a size assigned
1000 // struct A { int f; } a[3];
1002 // This needs to be fixed in the front-end, but in the meantime we don't want
1003 // to trigger an assertion because of this.
1004 if (Ty->getSizeInBits() == 0) {
1005 UndefinedSubrange = true;
1008 // Add subranges to array type.
1009 DINodeArray Elements = Ty->getElements();
1010 for (int i = Elements.size() - 1; i >= 0; --i) {
1011 const DINode *Element = Elements[i];
1012 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1014 const DISubrange *Subrange = cast<DISubrange>(Element);
1015 assert(Subrange->getLowerBound() == 0 &&
1016 "codeview doesn't support subranges with lower bounds");
1017 int64_t Count = Subrange->getCount();
1019 // Variable Length Array (VLA) has Count equal to '-1'.
1020 // Replace with Count '1', assume it is the minimum VLA length.
1021 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
1024 UndefinedSubrange = true;
1027 StringRef Name = (i == 0) ? Ty->getName() : "";
1028 // Update the element size and element type index for subsequent subranges.
1029 ElementSize *= Count;
1030 ElementTypeIndex = TypeTable.writeArray(
1031 ArrayRecord(ElementTypeIndex, IndexType, ElementSize, Name));
1034 (void)UndefinedSubrange;
1035 assert(UndefinedSubrange || ElementSize == (Ty->getSizeInBits() / 8));
1037 return ElementTypeIndex;
1040 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1042 dwarf::TypeKind Kind;
1045 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1046 ByteSize = Ty->getSizeInBits() / 8;
1048 SimpleTypeKind STK = SimpleTypeKind::None;
1050 case dwarf::DW_ATE_address:
1053 case dwarf::DW_ATE_boolean:
1055 case 1: STK = SimpleTypeKind::Boolean8; break;
1056 case 2: STK = SimpleTypeKind::Boolean16; break;
1057 case 4: STK = SimpleTypeKind::Boolean32; break;
1058 case 8: STK = SimpleTypeKind::Boolean64; break;
1059 case 16: STK = SimpleTypeKind::Boolean128; break;
1062 case dwarf::DW_ATE_complex_float:
1064 case 2: STK = SimpleTypeKind::Complex16; break;
1065 case 4: STK = SimpleTypeKind::Complex32; break;
1066 case 8: STK = SimpleTypeKind::Complex64; break;
1067 case 10: STK = SimpleTypeKind::Complex80; break;
1068 case 16: STK = SimpleTypeKind::Complex128; break;
1071 case dwarf::DW_ATE_float:
1073 case 2: STK = SimpleTypeKind::Float16; break;
1074 case 4: STK = SimpleTypeKind::Float32; break;
1075 case 6: STK = SimpleTypeKind::Float48; break;
1076 case 8: STK = SimpleTypeKind::Float64; break;
1077 case 10: STK = SimpleTypeKind::Float80; break;
1078 case 16: STK = SimpleTypeKind::Float128; break;
1081 case dwarf::DW_ATE_signed:
1083 case 1: STK = SimpleTypeKind::SByte; break;
1084 case 2: STK = SimpleTypeKind::Int16Short; break;
1085 case 4: STK = SimpleTypeKind::Int32; break;
1086 case 8: STK = SimpleTypeKind::Int64Quad; break;
1087 case 16: STK = SimpleTypeKind::Int128Oct; break;
1090 case dwarf::DW_ATE_unsigned:
1092 case 1: STK = SimpleTypeKind::Byte; break;
1093 case 2: STK = SimpleTypeKind::UInt16Short; break;
1094 case 4: STK = SimpleTypeKind::UInt32; break;
1095 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1096 case 16: STK = SimpleTypeKind::UInt128Oct; break;
1099 case dwarf::DW_ATE_UTF:
1101 case 2: STK = SimpleTypeKind::Character16; break;
1102 case 4: STK = SimpleTypeKind::Character32; break;
1105 case dwarf::DW_ATE_signed_char:
1107 STK = SimpleTypeKind::SignedCharacter;
1109 case dwarf::DW_ATE_unsigned_char:
1111 STK = SimpleTypeKind::UnsignedCharacter;
1117 // Apply some fixups based on the source-level type name.
1118 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1119 STK = SimpleTypeKind::Int32Long;
1120 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1121 STK = SimpleTypeKind::UInt32Long;
1122 if (STK == SimpleTypeKind::UInt16Short &&
1123 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1124 STK = SimpleTypeKind::WideCharacter;
1125 if ((STK == SimpleTypeKind::SignedCharacter ||
1126 STK == SimpleTypeKind::UnsignedCharacter) &&
1127 Ty->getName() == "char")
1128 STK = SimpleTypeKind::NarrowCharacter;
1130 return TypeIndex(STK);
1133 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1134 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1136 // While processing the type being pointed to it is possible we already
1137 // created this pointer type. If so, we check here and return the existing
1139 auto I = TypeIndices.find({Ty, nullptr});
1140 if (I != TypeIndices.end())
1143 // Pointers to simple types can use SimpleTypeMode, rather than having a
1144 // dedicated pointer type record.
1145 if (PointeeTI.isSimple() &&
1146 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1147 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1148 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1149 ? SimpleTypeMode::NearPointer64
1150 : SimpleTypeMode::NearPointer32;
1151 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1155 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1156 PointerMode PM = PointerMode::Pointer;
1157 switch (Ty->getTag()) {
1158 default: llvm_unreachable("not a pointer tag type");
1159 case dwarf::DW_TAG_pointer_type:
1160 PM = PointerMode::Pointer;
1162 case dwarf::DW_TAG_reference_type:
1163 PM = PointerMode::LValueReference;
1165 case dwarf::DW_TAG_rvalue_reference_type:
1166 PM = PointerMode::RValueReference;
1169 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1170 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1172 PointerOptions PO = PointerOptions::None;
1173 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1174 return TypeTable.writePointer(PR);
1177 static PointerToMemberRepresentation
1178 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1179 // SizeInBytes being zero generally implies that the member pointer type was
1180 // incomplete, which can happen if it is part of a function prototype. In this
1181 // case, use the unknown model instead of the general model.
1183 switch (Flags & DINode::FlagPtrToMemberRep) {
1185 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1186 : PointerToMemberRepresentation::GeneralFunction;
1187 case DINode::FlagSingleInheritance:
1188 return PointerToMemberRepresentation::SingleInheritanceFunction;
1189 case DINode::FlagMultipleInheritance:
1190 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1191 case DINode::FlagVirtualInheritance:
1192 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1195 switch (Flags & DINode::FlagPtrToMemberRep) {
1197 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1198 : PointerToMemberRepresentation::GeneralData;
1199 case DINode::FlagSingleInheritance:
1200 return PointerToMemberRepresentation::SingleInheritanceData;
1201 case DINode::FlagMultipleInheritance:
1202 return PointerToMemberRepresentation::MultipleInheritanceData;
1203 case DINode::FlagVirtualInheritance:
1204 return PointerToMemberRepresentation::VirtualInheritanceData;
1207 llvm_unreachable("invalid ptr to member representation");
1210 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1211 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1212 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1213 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1214 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1215 : PointerKind::Near32;
1216 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1217 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1218 : PointerMode::PointerToDataMember;
1219 PointerOptions PO = PointerOptions::None; // FIXME
1220 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1221 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1222 MemberPointerInfo MPI(
1223 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1224 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1225 return TypeTable.writePointer(PR);
1228 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1229 /// have a translation, use the NearC convention.
1230 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1232 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1233 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1234 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1235 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1236 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1237 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1239 return CallingConvention::NearC;
1242 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1243 ModifierOptions Mods = ModifierOptions::None;
1244 bool IsModifier = true;
1245 const DIType *BaseTy = Ty;
1246 while (IsModifier && BaseTy) {
1247 // FIXME: Need to add DWARF tag for __unaligned.
1248 switch (BaseTy->getTag()) {
1249 case dwarf::DW_TAG_const_type:
1250 Mods |= ModifierOptions::Const;
1252 case dwarf::DW_TAG_volatile_type:
1253 Mods |= ModifierOptions::Volatile;
1260 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1262 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1264 // While processing the type being pointed to, it is possible we already
1265 // created this modifier type. If so, we check here and return the existing
1267 auto I = TypeIndices.find({Ty, nullptr});
1268 if (I != TypeIndices.end())
1271 ModifierRecord MR(ModifiedTI, Mods);
1272 return TypeTable.writeModifier(MR);
1275 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1276 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1277 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1278 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1280 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1281 ArrayRef<TypeIndex> ArgTypeIndices = None;
1282 if (!ReturnAndArgTypeIndices.empty()) {
1283 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1284 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1285 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1288 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1289 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1291 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1293 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1294 ArgTypeIndices.size(), ArgListIndex);
1295 return TypeTable.writeProcedure(Procedure);
1298 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1299 const DIType *ClassTy,
1300 int ThisAdjustment) {
1301 // Lower the containing class type.
1302 TypeIndex ClassType = getTypeIndex(ClassTy);
1304 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1305 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1306 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1308 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1309 ArrayRef<TypeIndex> ArgTypeIndices = None;
1310 if (!ReturnAndArgTypeIndices.empty()) {
1311 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1312 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1313 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1315 TypeIndex ThisTypeIndex = TypeIndex::Void();
1316 if (!ArgTypeIndices.empty()) {
1317 ThisTypeIndex = ArgTypeIndices.front();
1318 ArgTypeIndices = ArgTypeIndices.drop_front();
1321 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1322 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1324 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1326 // TODO: Need to use the correct values for:
1328 // ThisPointerAdjustment.
1329 TypeIndex TI = TypeTable.writeMemberFunction(MemberFunctionRecord(
1330 ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
1331 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
1336 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1337 switch (Flags & DINode::FlagAccessibility) {
1338 case DINode::FlagPrivate: return MemberAccess::Private;
1339 case DINode::FlagPublic: return MemberAccess::Public;
1340 case DINode::FlagProtected: return MemberAccess::Protected;
1342 // If there was no explicit access control, provide the default for the tag.
1343 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1344 : MemberAccess::Public;
1346 llvm_unreachable("access flags are exclusive");
1349 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1350 if (SP->isArtificial())
1351 return MethodOptions::CompilerGenerated;
1353 // FIXME: Handle other MethodOptions.
1355 return MethodOptions::None;
1358 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1360 switch (SP->getVirtuality()) {
1361 case dwarf::DW_VIRTUALITY_none:
1363 case dwarf::DW_VIRTUALITY_virtual:
1364 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1365 case dwarf::DW_VIRTUALITY_pure_virtual:
1366 return Introduced ? MethodKind::PureIntroducingVirtual
1367 : MethodKind::PureVirtual;
1369 llvm_unreachable("unhandled virtuality case");
1372 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1374 return MethodKind::Vanilla;
1377 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1378 switch (Ty->getTag()) {
1379 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1380 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1382 llvm_unreachable("unexpected tag");
1385 /// Return ClassOptions that should be present on both the forward declaration
1386 /// and the defintion of a tag type.
1387 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1388 ClassOptions CO = ClassOptions::None;
1390 // MSVC always sets this flag, even for local types. Clang doesn't always
1391 // appear to give every type a linkage name, which may be problematic for us.
1392 // FIXME: Investigate the consequences of not following them here.
1393 if (!Ty->getIdentifier().empty())
1394 CO |= ClassOptions::HasUniqueName;
1396 // Put the Nested flag on a type if it appears immediately inside a tag type.
1397 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1398 // here. That flag is only set on definitions, and not forward declarations.
1399 const DIScope *ImmediateScope = Ty->getScope().resolve();
1400 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1401 CO |= ClassOptions::Nested;
1403 // Put the Scoped flag on function-local types.
1404 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1405 Scope = Scope->getScope().resolve()) {
1406 if (isa<DISubprogram>(Scope)) {
1407 CO |= ClassOptions::Scoped;
1415 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
1416 ClassOptions CO = getCommonClassOptions(Ty);
1418 unsigned EnumeratorCount = 0;
1420 if (Ty->isForwardDecl()) {
1421 CO |= ClassOptions::ForwardReference;
1423 FieldListRecordBuilder Fields;
1424 for (const DINode *Element : Ty->getElements()) {
1425 // We assume that the frontend provides all members in source declaration
1426 // order, which is what MSVC does.
1427 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1428 Fields.writeEnumerator(EnumeratorRecord(
1429 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
1430 Enumerator->getName()));
1434 FTI = TypeTable.writeFieldList(Fields);
1437 std::string FullName = getFullyQualifiedName(Ty);
1439 return TypeTable.writeEnum(EnumRecord(EnumeratorCount, CO, FTI, FullName,
1440 Ty->getIdentifier(),
1441 getTypeIndex(Ty->getBaseType())));
1444 //===----------------------------------------------------------------------===//
1446 //===----------------------------------------------------------------------===//
1448 struct llvm::ClassInfo {
1450 const DIDerivedType *MemberTypeNode;
1451 uint64_t BaseOffset;
1454 typedef std::vector<MemberInfo> MemberList;
1456 typedef TinyPtrVector<const DISubprogram *> MethodsList;
1457 // MethodName -> MethodsList
1458 typedef MapVector<MDString *, MethodsList> MethodsMap;
1461 std::vector<const DIDerivedType *> Inheritance;
1465 // Direct overloaded methods gathered by name.
1468 std::vector<const DICompositeType *> NestedClasses;
1471 void CodeViewDebug::clear() {
1472 assert(CurFn == nullptr);
1474 FnDebugInfo.clear();
1475 FileToFilepathMap.clear();
1478 TypeIndices.clear();
1479 CompleteTypeIndices.clear();
1482 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1483 const DIDerivedType *DDTy) {
1484 if (!DDTy->getName().empty()) {
1485 Info.Members.push_back({DDTy, 0});
1488 // An unnamed member must represent a nested struct or union. Add all the
1489 // indirect fields to the current record.
1490 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
1491 uint64_t Offset = DDTy->getOffsetInBits();
1492 const DIType *Ty = DDTy->getBaseType().resolve();
1493 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
1494 ClassInfo NestedInfo = collectClassInfo(DCTy);
1495 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
1496 Info.Members.push_back(
1497 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
1500 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1502 // Add elements to structure type.
1503 DINodeArray Elements = Ty->getElements();
1504 for (auto *Element : Elements) {
1505 // We assume that the frontend provides all members in source declaration
1506 // order, which is what MSVC does.
1509 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1510 Info.Methods[SP->getRawName()].push_back(SP);
1511 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
1512 if (DDTy->getTag() == dwarf::DW_TAG_member) {
1513 collectMemberInfo(Info, DDTy);
1514 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1515 Info.Inheritance.push_back(DDTy);
1516 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1517 // Ignore friend members. It appears that MSVC emitted info about
1518 // friends in the past, but modern versions do not.
1520 // FIXME: Get Clang to emit function virtual table here and handle it.
1521 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1522 Info.NestedClasses.push_back(Composite);
1524 // Skip other unrecognized kinds of elements.
1529 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1530 // First, construct the forward decl. Don't look into Ty to compute the
1531 // forward decl options, since it might not be available in all TUs.
1532 TypeRecordKind Kind = getRecordKind(Ty);
1534 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
1535 std::string FullName = getFullyQualifiedName(Ty);
1536 TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord(
1537 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
1538 TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()));
1539 if (!Ty->isForwardDecl())
1540 DeferredCompleteTypes.push_back(Ty);
1544 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1545 // Construct the field list and complete type record.
1546 TypeRecordKind Kind = getRecordKind(Ty);
1547 ClassOptions CO = getCommonClassOptions(Ty);
1550 unsigned FieldCount;
1551 bool ContainsNestedClass;
1552 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1553 lowerRecordFieldList(Ty);
1555 if (ContainsNestedClass)
1556 CO |= ClassOptions::ContainsNestedClass;
1558 std::string FullName = getFullyQualifiedName(Ty);
1560 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1562 TypeIndex ClassTI = TypeTable.writeClass(ClassRecord(
1563 Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI,
1564 TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()));
1566 TypeTable.writeUdtSourceLine(UdtSourceLineRecord(
1567 ClassTI, TypeTable.writeStringId(StringIdRecord(
1568 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1571 addToUDTs(Ty, ClassTI);
1576 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1578 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
1579 std::string FullName = getFullyQualifiedName(Ty);
1580 TypeIndex FwdDeclTI =
1581 TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0,
1582 FullName, Ty->getIdentifier()));
1583 if (!Ty->isForwardDecl())
1584 DeferredCompleteTypes.push_back(Ty);
1588 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1589 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
1591 unsigned FieldCount;
1592 bool ContainsNestedClass;
1593 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1594 lowerRecordFieldList(Ty);
1596 if (ContainsNestedClass)
1597 CO |= ClassOptions::ContainsNestedClass;
1599 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1600 std::string FullName = getFullyQualifiedName(Ty);
1602 TypeIndex UnionTI = TypeTable.writeUnion(
1603 UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName,
1604 Ty->getIdentifier()));
1606 TypeTable.writeUdtSourceLine(UdtSourceLineRecord(
1607 UnionTI, TypeTable.writeStringId(StringIdRecord(
1608 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1611 addToUDTs(Ty, UnionTI);
1616 std::tuple<TypeIndex, TypeIndex, unsigned, bool>
1617 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1618 // Manually count members. MSVC appears to count everything that generates a
1619 // field list record. Each individual overload in a method overload group
1620 // contributes to this count, even though the overload group is a single field
1622 unsigned MemberCount = 0;
1623 ClassInfo Info = collectClassInfo(Ty);
1624 FieldListRecordBuilder Fields;
1626 // Create base classes.
1627 for (const DIDerivedType *I : Info.Inheritance) {
1628 if (I->getFlags() & DINode::FlagVirtual) {
1630 // FIXME: Emit VBPtrOffset when the frontend provides it.
1631 unsigned VBPtrOffset = 0;
1632 // FIXME: Despite the accessor name, the offset is really in bytes.
1633 unsigned VBTableIndex = I->getOffsetInBits() / 4;
1634 Fields.writeVirtualBaseClass(VirtualBaseClassRecord(
1635 translateAccessFlags(Ty->getTag(), I->getFlags()),
1636 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1639 assert(I->getOffsetInBits() % 8 == 0 &&
1640 "bases must be on byte boundaries");
1641 Fields.writeBaseClass(BaseClassRecord(
1642 translateAccessFlags(Ty->getTag(), I->getFlags()),
1643 getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8));
1648 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1649 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1650 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
1651 StringRef MemberName = Member->getName();
1652 MemberAccess Access =
1653 translateAccessFlags(Ty->getTag(), Member->getFlags());
1655 if (Member->isStaticMember()) {
1656 Fields.writeStaticDataMember(
1657 StaticDataMemberRecord(Access, MemberBaseType, MemberName));
1663 uint64_t MemberOffsetInBits =
1664 Member->getOffsetInBits() + MemberInfo.BaseOffset;
1665 if (Member->isBitField()) {
1666 uint64_t StartBitOffset = MemberOffsetInBits;
1667 if (const auto *CI =
1668 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
1669 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
1671 StartBitOffset -= MemberOffsetInBits;
1672 MemberBaseType = TypeTable.writeBitField(BitFieldRecord(
1673 MemberBaseType, Member->getSizeInBits(), StartBitOffset));
1675 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
1676 Fields.writeDataMember(DataMemberRecord(Access, MemberBaseType,
1677 MemberOffsetInBytes, MemberName));
1682 for (auto &MethodItr : Info.Methods) {
1683 StringRef Name = MethodItr.first->getString();
1685 std::vector<OneMethodRecord> Methods;
1686 for (const DISubprogram *SP : MethodItr.second) {
1687 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1688 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
1690 unsigned VFTableOffset = -1;
1692 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1695 OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced),
1696 translateMethodOptionFlags(SP),
1697 translateAccessFlags(Ty->getTag(), SP->getFlags()),
1698 VFTableOffset, Name));
1701 assert(Methods.size() > 0 && "Empty methods map entry");
1702 if (Methods.size() == 1)
1703 Fields.writeOneMethod(Methods[0]);
1705 TypeIndex MethodList =
1706 TypeTable.writeMethodOverloadList(MethodOverloadListRecord(Methods));
1707 Fields.writeOverloadedMethod(
1708 OverloadedMethodRecord(Methods.size(), MethodList, Name));
1712 // Create nested classes.
1713 for (const DICompositeType *Nested : Info.NestedClasses) {
1714 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
1715 Fields.writeNestedType(R);
1719 TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
1720 return std::make_tuple(FieldTI, TypeIndex(), MemberCount,
1721 !Info.NestedClasses.empty());
1724 TypeIndex CodeViewDebug::getVBPTypeIndex() {
1725 if (!VBPType.getIndex()) {
1726 // Make a 'const int *' type.
1727 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
1728 TypeIndex ModifiedTI = TypeTable.writeModifier(MR);
1730 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1731 : PointerKind::Near32;
1732 PointerMode PM = PointerMode::Pointer;
1733 PointerOptions PO = PointerOptions::None;
1734 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1736 VBPType = TypeTable.writePointer(PR);
1742 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
1743 const DIType *Ty = TypeRef.resolve();
1744 const DIType *ClassTy = ClassTyRef.resolve();
1746 // The null DIType is the void type. Don't try to hash it.
1748 return TypeIndex::Void();
1750 // Check if we've already translated this type. Don't try to do a
1751 // get-or-create style insertion that caches the hash lookup across the
1752 // lowerType call. It will update the TypeIndices map.
1753 auto I = TypeIndices.find({Ty, ClassTy});
1754 if (I != TypeIndices.end())
1757 TypeLoweringScope S(*this);
1758 TypeIndex TI = lowerType(Ty, ClassTy);
1759 return recordTypeIndexForDINode(Ty, TI, ClassTy);
1762 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1763 const DIType *Ty = TypeRef.resolve();
1765 // The null DIType is the void type. Don't try to hash it.
1767 return TypeIndex::Void();
1769 // If this is a non-record type, the complete type index is the same as the
1770 // normal type index. Just call getTypeIndex.
1771 switch (Ty->getTag()) {
1772 case dwarf::DW_TAG_class_type:
1773 case dwarf::DW_TAG_structure_type:
1774 case dwarf::DW_TAG_union_type:
1777 return getTypeIndex(Ty);
1780 // Check if we've already translated the complete record type. Lowering a
1781 // complete type should never trigger lowering another complete type, so we
1782 // can reuse the hash table lookup result.
1783 const auto *CTy = cast<DICompositeType>(Ty);
1784 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1785 if (!InsertResult.second)
1786 return InsertResult.first->second;
1788 TypeLoweringScope S(*this);
1790 // Make sure the forward declaration is emitted first. It's unclear if this
1791 // is necessary, but MSVC does it, and we should follow suit until we can show
1793 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1795 // Just use the forward decl if we don't have complete type info. This might
1796 // happen if the frontend is using modules and expects the complete definition
1797 // to be emitted elsewhere.
1798 if (CTy->isForwardDecl())
1802 switch (CTy->getTag()) {
1803 case dwarf::DW_TAG_class_type:
1804 case dwarf::DW_TAG_structure_type:
1805 TI = lowerCompleteTypeClass(CTy);
1807 case dwarf::DW_TAG_union_type:
1808 TI = lowerCompleteTypeUnion(CTy);
1811 llvm_unreachable("not a record");
1814 InsertResult.first->second = TI;
1818 /// Emit all the deferred complete record types. Try to do this in FIFO order,
1819 /// and do this until fixpoint, as each complete record type typically
1821 /// many other record types.
1822 void CodeViewDebug::emitDeferredCompleteTypes() {
1823 SmallVector<const DICompositeType *, 4> TypesToEmit;
1824 while (!DeferredCompleteTypes.empty()) {
1825 std::swap(DeferredCompleteTypes, TypesToEmit);
1826 for (const DICompositeType *RecordTy : TypesToEmit)
1827 getCompleteTypeIndex(RecordTy);
1828 TypesToEmit.clear();
1832 void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
1833 // Get the sorted list of parameters and emit them first.
1834 SmallVector<const LocalVariable *, 6> Params;
1835 for (const LocalVariable &L : Locals)
1836 if (L.DIVar->isParameter())
1837 Params.push_back(&L);
1838 std::sort(Params.begin(), Params.end(),
1839 [](const LocalVariable *L, const LocalVariable *R) {
1840 return L->DIVar->getArg() < R->DIVar->getArg();
1842 for (const LocalVariable *L : Params)
1843 emitLocalVariable(*L);
1845 // Next emit all non-parameters in the order that we found them.
1846 for (const LocalVariable &L : Locals)
1847 if (!L.DIVar->isParameter())
1848 emitLocalVariable(L);
1851 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1852 // LocalSym record, see SymbolRecord.h for more info.
1853 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1854 *LocalEnd = MMI->getContext().createTempSymbol();
1855 OS.AddComment("Record length");
1856 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1857 OS.EmitLabel(LocalBegin);
1859 OS.AddComment("Record kind: S_LOCAL");
1860 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
1862 LocalSymFlags Flags = LocalSymFlags::None;
1863 if (Var.DIVar->isParameter())
1864 Flags |= LocalSymFlags::IsParameter;
1865 if (Var.DefRanges.empty())
1866 Flags |= LocalSymFlags::IsOptimizedOut;
1868 OS.AddComment("TypeIndex");
1869 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
1870 OS.EmitIntValue(TI.getIndex(), 4);
1871 OS.AddComment("Flags");
1872 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
1873 // Truncate the name so we won't overflow the record length field.
1874 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
1875 OS.EmitLabel(LocalEnd);
1877 // Calculate the on disk prefix of the appropriate def range record. The
1878 // records and on disk formats are described in SymbolRecords.h. BytePrefix
1879 // should be big enough to hold all forms without memory allocation.
1880 SmallString<20> BytePrefix;
1881 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1883 // FIXME: Handle bitpieces.
1884 if (DefRange.StructOffset != 0)
1887 if (DefRange.InMemory) {
1888 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1889 0, 0, ArrayRef<LocalVariableAddrGap>());
1890 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
1892 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
1894 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1895 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
1897 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
1898 // Unclear what matters here.
1899 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1900 ArrayRef<LocalVariableAddrGap>());
1901 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
1903 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
1905 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1906 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
1908 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1912 void CodeViewDebug::endFunction(const MachineFunction *MF) {
1913 if (!Asm || !CurFn) // We haven't created any debug info for this function.
1916 const Function *GV = MF->getFunction();
1917 assert(FnDebugInfo.count(GV));
1918 assert(CurFn == &FnDebugInfo[GV]);
1920 collectVariableInfo(GV->getSubprogram());
1922 DebugHandlerBase::endFunction(MF);
1924 // Don't emit anything if we don't have any line tables.
1925 if (!CurFn->HaveLineInfo) {
1926 FnDebugInfo.erase(GV);
1931 CurFn->End = Asm->getFunctionEnd();
1936 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
1937 DebugHandlerBase::beginInstruction(MI);
1939 // Ignore DBG_VALUE locations and function prologue.
1940 if (!Asm || !CurFn || MI->isDebugValue() ||
1941 MI->getFlag(MachineInstr::FrameSetup))
1943 DebugLoc DL = MI->getDebugLoc();
1944 if (DL == PrevInstLoc || !DL)
1946 maybeRecordLocation(DL, Asm->MF);
1949 MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
1950 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
1951 *EndLabel = MMI->getContext().createTempSymbol();
1952 OS.EmitIntValue(unsigned(Kind), 4);
1953 OS.AddComment("Subsection size");
1954 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
1955 OS.EmitLabel(BeginLabel);
1959 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
1960 OS.EmitLabel(EndLabel);
1961 // Every subsection must be aligned to a 4-byte boundary.
1962 OS.EmitValueToAlignment(4);
1965 void CodeViewDebug::emitDebugInfoForUDTs(
1966 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
1967 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
1968 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
1969 *UDTRecordEnd = MMI->getContext().createTempSymbol();
1970 OS.AddComment("Record length");
1971 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
1972 OS.EmitLabel(UDTRecordBegin);
1974 OS.AddComment("Record kind: S_UDT");
1975 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
1977 OS.AddComment("Type");
1978 OS.EmitIntValue(UDT.second.getIndex(), 4);
1980 emitNullTerminatedSymbolName(OS, UDT.first);
1981 OS.EmitLabel(UDTRecordEnd);
1985 void CodeViewDebug::emitDebugInfoForGlobals() {
1986 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1987 for (const MDNode *Node : CUs->operands()) {
1988 const auto *CU = cast<DICompileUnit>(Node);
1990 // First, emit all globals that are not in a comdat in a single symbol
1991 // substream. MSVC doesn't like it if the substream is empty, so only open
1992 // it if we have at least one global to emit.
1993 switchToDebugSectionForSymbol(nullptr);
1994 MCSymbol *EndLabel = nullptr;
1995 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
1996 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
1997 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
1999 OS.AddComment("Symbol subsection for globals");
2000 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
2002 emitDebugInfoForGlobal(G, Asm->getSymbol(GV));
2007 endCVSubsection(EndLabel);
2009 // Second, emit each global that is in a comdat into its own .debug$S
2010 // section along with its own symbol substream.
2011 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
2012 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
2013 if (GV->hasComdat()) {
2014 MCSymbol *GVSym = Asm->getSymbol(GV);
2015 OS.AddComment("Symbol subsection for " +
2016 Twine(GlobalValue::getRealLinkageName(GV->getName())));
2017 switchToDebugSectionForSymbol(GVSym);
2018 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
2019 emitDebugInfoForGlobal(G, GVSym);
2020 endCVSubsection(EndLabel);
2027 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2028 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2029 for (const MDNode *Node : CUs->operands()) {
2030 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2031 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2033 // FIXME: Add to global/local DTU list.
2039 void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
2041 // DataSym record, see SymbolRecord.h for more info.
2042 // FIXME: Thread local data, etc
2043 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2044 *DataEnd = MMI->getContext().createTempSymbol();
2045 OS.AddComment("Record length");
2046 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2047 OS.EmitLabel(DataBegin);
2048 const auto *GV = cast<GlobalVariable>(DIGV->getVariable());
2049 if (DIGV->isLocalToUnit()) {
2050 if (GV->isThreadLocal()) {
2051 OS.AddComment("Record kind: S_LTHREAD32");
2052 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2054 OS.AddComment("Record kind: S_LDATA32");
2055 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2058 if (GV->isThreadLocal()) {
2059 OS.AddComment("Record kind: S_GTHREAD32");
2060 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2062 OS.AddComment("Record kind: S_GDATA32");
2063 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2066 OS.AddComment("Type");
2067 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2068 OS.AddComment("DataOffset");
2069 OS.EmitCOFFSecRel32(GVSym);
2070 OS.AddComment("Segment");
2071 OS.EmitCOFFSectionIndex(GVSym);
2072 OS.AddComment("Name");
2073 emitNullTerminatedSymbolName(OS, DIGV->getName());
2074 OS.EmitLabel(DataEnd);