1 //===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains support for writing Microsoft CodeView debug info. 11 // 12 //===----------------------------------------------------------------------===// 13 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" 35 36 using namespace llvm; 37 using namespace llvm::codeview; 38 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()) { 45 Asm = nullptr; 46 return; 47 } 48 49 // Tell MMI that we have debug info. 50 MMI->setDebugInfoAvailability(true); 51 } 52 53 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) { 54 std::string &Filepath = FileToFilepathMap[File]; 55 if (!Filepath.empty()) 56 return Filepath; 57 58 StringRef Dir = File->getDirectory(), Filename = File->getFilename(); 59 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) 65 Filepath = Filename; 66 else 67 Filepath = (Dir + "\\" + Filename).str(); 68 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(), '/', '\\'); 73 74 // Remove all "\.\" with "\". 75 size_t Cursor = 0; 76 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos) 77 Filepath.erase(Cursor, 2); 78 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. 81 Cursor = 0; 82 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) { 83 // Something's wrong if the path starts with "\..\", abort. 84 if (Cursor == 0) 85 break; 86 87 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1); 88 if (PrevSlash == std::string::npos) 89 // Something's wrong, abort. 90 break; 91 92 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash); 93 // The next ".." might be following the one we've just erased. 94 Cursor = PrevSlash; 95 } 96 97 // Remove all duplicate backslashes. 98 Cursor = 0; 99 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos) 100 Filepath.erase(Cursor, 1); 101 102 return Filepath; 103 } 104 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"); 113 } 114 return Insertion.first->second; 115 } 116 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); 127 } 128 return *Site; 129 } 130 131 static const DISubprogram *getQualifiedNameComponents( 132 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) { 133 const DISubprogram *ClosestSubprogram = nullptr; 134 while (Scope != nullptr) { 135 if (ClosestSubprogram == nullptr) 136 ClosestSubprogram = dyn_cast<DISubprogram>(Scope); 137 StringRef ScopeName = Scope->getName(); 138 if (!ScopeName.empty()) 139 QualifiedNameComponents.push_back(ScopeName); 140 Scope = Scope->getScope().resolve(); 141 } 142 return ClosestSubprogram; 143 } 144 145 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents, 146 StringRef TypeName) { 147 std::string FullyQualifiedName; 148 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) { 149 FullyQualifiedName.append(QualifiedNameComponent); 150 FullyQualifiedName.append("::"); 151 } 152 FullyQualifiedName.append(TypeName); 153 return FullyQualifiedName; 154 } 155 156 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) { 157 SmallVector<StringRef, 5> QualifiedNameComponents; 158 getQualifiedNameComponents(Scope, QualifiedNameComponents); 159 return getQualifiedName(QualifiedNameComponents, Name); 160 } 161 162 struct CodeViewDebug::TypeLoweringScope { 163 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; } 164 ~TypeLoweringScope() { 165 // Don't decrement TypeEmissionLevel until after emitting deferred types, so 166 // inner TypeLoweringScopes don't attempt to emit deferred types. 167 if (CVD.TypeEmissionLevel == 1) 168 CVD.emitDeferredCompleteTypes(); 169 --CVD.TypeEmissionLevel; 170 } 171 CodeViewDebug &CVD; 172 }; 173 174 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) { 175 // No scope means global scope and that uses the zero index. 176 if (!Scope || isa<DIFile>(Scope)) 177 return TypeIndex(); 178 179 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type"); 180 181 // Check if we've already translated this scope. 182 auto I = TypeIndices.find({Scope, nullptr}); 183 if (I != TypeIndices.end()) 184 return I->second; 185 186 // Build the fully qualified name of the scope. 187 std::string ScopeName = 188 getFullyQualifiedName(Scope->getScope().resolve(), Scope->getName()); 189 TypeIndex TI = 190 TypeTable.writeStringId(StringIdRecord(TypeIndex(), ScopeName)); 191 return recordTypeIndexForDINode(Scope, TI); 192 } 193 194 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) { 195 // It's possible to ask for the FuncId of a function which doesn't have a 196 // subprogram: inlining a function with debug info into a function with none. 197 if (!SP) 198 return TypeIndex::None(); 199 200 // Check if we've already translated this subprogram. 201 auto I = TypeIndices.find({SP, nullptr}); 202 if (I != TypeIndices.end()) 203 return I->second; 204 205 // The display name includes function template arguments. Drop them to match 206 // MSVC. 207 StringRef DisplayName = SP->getDisplayName().split('<').first; 208 209 const DIScope *Scope = SP->getScope().resolve(); 210 TypeIndex TI; 211 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) { 212 // If the scope is a DICompositeType, then this must be a method. Member 213 // function types take some special handling, and require access to the 214 // subprogram. 215 TypeIndex ClassType = getTypeIndex(Class); 216 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class), 217 DisplayName); 218 TI = TypeTable.writeMemberFuncId(MFuncId); 219 } else { 220 // Otherwise, this must be a free function. 221 TypeIndex ParentScope = getScopeIndex(Scope); 222 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName); 223 TI = TypeTable.writeFuncId(FuncId); 224 } 225 226 return recordTypeIndexForDINode(SP, TI); 227 } 228 229 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP, 230 const DICompositeType *Class) { 231 // Always use the method declaration as the key for the function type. The 232 // method declaration contains the this adjustment. 233 if (SP->getDeclaration()) 234 SP = SP->getDeclaration(); 235 assert(!SP->getDeclaration() && "should use declaration as key"); 236 237 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide 238 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}. 239 auto I = TypeIndices.find({SP, Class}); 240 if (I != TypeIndices.end()) 241 return I->second; 242 243 // Make sure complete type info for the class is emitted *after* the member 244 // function type, as the complete class type is likely to reference this 245 // member function type. 246 TypeLoweringScope S(*this); 247 TypeIndex TI = 248 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment()); 249 return recordTypeIndexForDINode(SP, TI, Class); 250 } 251 252 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI, 253 const DIType *ClassTy) { 254 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI}); 255 (void)InsertResult; 256 assert(InsertResult.second && "DINode was already assigned a type index"); 257 return TI; 258 } 259 260 unsigned CodeViewDebug::getPointerSizeInBytes() { 261 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8; 262 } 263 264 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var, 265 const DILocation *InlinedAt) { 266 if (InlinedAt) { 267 // This variable was inlined. Associate it with the InlineSite. 268 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram(); 269 InlineSite &Site = getInlineSite(InlinedAt, Inlinee); 270 Site.InlinedLocals.emplace_back(Var); 271 } else { 272 // This variable goes in the main ProcSym. 273 CurFn->Locals.emplace_back(Var); 274 } 275 } 276 277 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs, 278 const DILocation *Loc) { 279 auto B = Locs.begin(), E = Locs.end(); 280 if (std::find(B, E, Loc) == E) 281 Locs.push_back(Loc); 282 } 283 284 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL, 285 const MachineFunction *MF) { 286 // Skip this instruction if it has the same location as the previous one. 287 if (DL == CurFn->LastLoc) 288 return; 289 290 const DIScope *Scope = DL.get()->getScope(); 291 if (!Scope) 292 return; 293 294 // Skip this line if it is longer than the maximum we can record. 295 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true); 296 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() || 297 LI.isNeverStepInto()) 298 return; 299 300 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0); 301 if (CI.getStartColumn() != DL.getCol()) 302 return; 303 304 if (!CurFn->HaveLineInfo) 305 CurFn->HaveLineInfo = true; 306 unsigned FileId = 0; 307 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile()) 308 FileId = CurFn->LastFileId; 309 else 310 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile()); 311 CurFn->LastLoc = DL; 312 313 unsigned FuncId = CurFn->FuncId; 314 if (const DILocation *SiteLoc = DL->getInlinedAt()) { 315 const DILocation *Loc = DL.get(); 316 317 // If this location was actually inlined from somewhere else, give it the ID 318 // of the inline call site. 319 FuncId = 320 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId; 321 322 // Ensure we have links in the tree of inline call sites. 323 bool FirstLoc = true; 324 while ((SiteLoc = Loc->getInlinedAt())) { 325 InlineSite &Site = 326 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()); 327 if (!FirstLoc) 328 addLocIfNotPresent(Site.ChildSites, Loc); 329 FirstLoc = false; 330 Loc = SiteLoc; 331 } 332 addLocIfNotPresent(CurFn->ChildSites, Loc); 333 } 334 335 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(), 336 /*PrologueEnd=*/false, 337 /*IsStmt=*/false, DL->getFilename()); 338 } 339 340 void CodeViewDebug::emitCodeViewMagicVersion() { 341 OS.EmitValueToAlignment(4); 342 OS.AddComment("Debug section magic"); 343 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4); 344 } 345 346 void CodeViewDebug::endModule() { 347 if (!Asm || !MMI->hasDebugInfo()) 348 return; 349 350 assert(Asm != nullptr); 351 352 // The COFF .debug$S section consists of several subsections, each starting 353 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length 354 // of the payload followed by the payload itself. The subsections are 4-byte 355 // aligned. 356 357 // Use the generic .debug$S section, and make a subsection for all the inlined 358 // subprograms. 359 switchToDebugSectionForSymbol(nullptr); 360 emitInlineeLinesSubsection(); 361 362 // Emit per-function debug information. 363 for (auto &P : FnDebugInfo) 364 if (!P.first->isDeclarationForLinker()) 365 emitDebugInfoForFunction(P.first, P.second); 366 367 // Emit global variable debug information. 368 setCurrentSubprogram(nullptr); 369 emitDebugInfoForGlobals(); 370 371 // Emit retained types. 372 emitDebugInfoForRetainedTypes(); 373 374 // Switch back to the generic .debug$S section after potentially processing 375 // comdat symbol sections. 376 switchToDebugSectionForSymbol(nullptr); 377 378 // Emit UDT records for any types used by global variables. 379 if (!GlobalUDTs.empty()) { 380 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols); 381 emitDebugInfoForUDTs(GlobalUDTs); 382 endCVSubsection(SymbolsEnd); 383 } 384 385 // This subsection holds a file index to offset in string table table. 386 OS.AddComment("File index to string table offset subsection"); 387 OS.EmitCVFileChecksumsDirective(); 388 389 // This subsection holds the string table. 390 OS.AddComment("String table"); 391 OS.EmitCVStringTableDirective(); 392 393 // Emit type information last, so that any types we translate while emitting 394 // function info are included. 395 emitTypeInformation(); 396 397 clear(); 398 } 399 400 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) { 401 // Microsoft's linker seems to have trouble with symbol names longer than 402 // 0xffd8 bytes. 403 S = S.substr(0, 0xffd8); 404 SmallString<32> NullTerminatedString(S); 405 NullTerminatedString.push_back('\0'); 406 OS.EmitBytes(NullTerminatedString); 407 } 408 409 void CodeViewDebug::emitTypeInformation() { 410 // Do nothing if we have no debug info or if no non-trivial types were emitted 411 // to TypeTable during codegen. 412 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 413 if (!CU_Nodes) 414 return; 415 if (TypeTable.empty()) 416 return; 417 418 // Start the .debug$T section with 0x4. 419 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection()); 420 emitCodeViewMagicVersion(); 421 422 SmallString<8> CommentPrefix; 423 if (OS.isVerboseAsm()) { 424 CommentPrefix += '\t'; 425 CommentPrefix += Asm->MAI->getCommentString(); 426 CommentPrefix += ' '; 427 } 428 429 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false); 430 TypeTable.ForEachRecord( 431 [&](TypeIndex Index, StringRef Record) { 432 if (OS.isVerboseAsm()) { 433 // Emit a block comment describing the type record for readability. 434 SmallString<512> CommentBlock; 435 raw_svector_ostream CommentOS(CommentBlock); 436 ScopedPrinter SP(CommentOS); 437 SP.setPrefix(CommentPrefix); 438 CVTD.setPrinter(&SP); 439 Error E = CVTD.dump({Record.bytes_begin(), Record.bytes_end()}); 440 if (E) { 441 logAllUnhandledErrors(std::move(E), errs(), "error: "); 442 llvm_unreachable("produced malformed type record"); 443 } 444 // emitRawComment will insert its own tab and comment string before 445 // the first line, so strip off our first one. It also prints its own 446 // newline. 447 OS.emitRawComment( 448 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim()); 449 } else { 450 #ifndef NDEBUG 451 // Assert that the type data is valid even if we aren't dumping 452 // comments. The MSVC linker doesn't do much type record validation, 453 // so the first link of an invalid type record can succeed while 454 // subsequent links will fail with LNK1285. 455 ByteStream<> Stream({Record.bytes_begin(), Record.bytes_end()}); 456 CVTypeArray Types; 457 StreamReader Reader(Stream); 458 Error E = Reader.readArray(Types, Reader.getLength()); 459 if (!E) { 460 TypeVisitorCallbacks C; 461 E = CVTypeVisitor(C).visitTypeStream(Types); 462 } 463 if (E) { 464 logAllUnhandledErrors(std::move(E), errs(), "error: "); 465 llvm_unreachable("produced malformed type record"); 466 } 467 #endif 468 } 469 OS.EmitBinaryData(Record); 470 }); 471 } 472 473 void CodeViewDebug::emitInlineeLinesSubsection() { 474 if (InlinedSubprograms.empty()) 475 return; 476 477 OS.AddComment("Inlinee lines subsection"); 478 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines); 479 480 // We don't provide any extra file info. 481 // FIXME: Find out if debuggers use this info. 482 OS.AddComment("Inlinee lines signature"); 483 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4); 484 485 for (const DISubprogram *SP : InlinedSubprograms) { 486 assert(TypeIndices.count({SP, nullptr})); 487 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}]; 488 489 OS.AddBlankLine(); 490 unsigned FileId = maybeRecordFile(SP->getFile()); 491 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " + 492 SP->getFilename() + Twine(':') + Twine(SP->getLine())); 493 OS.AddBlankLine(); 494 // The filechecksum table uses 8 byte entries for now, and file ids start at 495 // 1. 496 unsigned FileOffset = (FileId - 1) * 8; 497 OS.AddComment("Type index of inlined function"); 498 OS.EmitIntValue(InlineeIdx.getIndex(), 4); 499 OS.AddComment("Offset into filechecksum table"); 500 OS.EmitIntValue(FileOffset, 4); 501 OS.AddComment("Starting line number"); 502 OS.EmitIntValue(SP->getLine(), 4); 503 } 504 505 endCVSubsection(InlineEnd); 506 } 507 508 void CodeViewDebug::collectInlineSiteChildren( 509 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI, 510 const InlineSite &Site) { 511 for (const DILocation *ChildSiteLoc : Site.ChildSites) { 512 auto I = FI.InlineSites.find(ChildSiteLoc); 513 const InlineSite &ChildSite = I->second; 514 Children.push_back(ChildSite.SiteFuncId); 515 collectInlineSiteChildren(Children, FI, ChildSite); 516 } 517 } 518 519 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI, 520 const DILocation *InlinedAt, 521 const InlineSite &Site) { 522 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(), 523 *InlineEnd = MMI->getContext().createTempSymbol(); 524 525 assert(TypeIndices.count({Site.Inlinee, nullptr})); 526 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}]; 527 528 // SymbolRecord 529 OS.AddComment("Record length"); 530 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength 531 OS.EmitLabel(InlineBegin); 532 OS.AddComment("Record kind: S_INLINESITE"); 533 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind 534 535 OS.AddComment("PtrParent"); 536 OS.EmitIntValue(0, 4); 537 OS.AddComment("PtrEnd"); 538 OS.EmitIntValue(0, 4); 539 OS.AddComment("Inlinee type index"); 540 OS.EmitIntValue(InlineeIdx.getIndex(), 4); 541 542 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile()); 543 unsigned StartLineNum = Site.Inlinee->getLine(); 544 SmallVector<unsigned, 3> SecondaryFuncIds; 545 collectInlineSiteChildren(SecondaryFuncIds, FI, Site); 546 547 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum, 548 FI.Begin, FI.End, SecondaryFuncIds); 549 550 OS.EmitLabel(InlineEnd); 551 552 emitLocalVariableList(Site.InlinedLocals); 553 554 // Recurse on child inlined call sites before closing the scope. 555 for (const DILocation *ChildSite : Site.ChildSites) { 556 auto I = FI.InlineSites.find(ChildSite); 557 assert(I != FI.InlineSites.end() && 558 "child site not in function inline site map"); 559 emitInlinedCallSite(FI, ChildSite, I->second); 560 } 561 562 // Close the scope. 563 OS.AddComment("Record length"); 564 OS.EmitIntValue(2, 2); // RecordLength 565 OS.AddComment("Record kind: S_INLINESITE_END"); 566 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind 567 } 568 569 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) { 570 // If we have a symbol, it may be in a section that is COMDAT. If so, find the 571 // comdat key. A section may be comdat because of -ffunction-sections or 572 // because it is comdat in the IR. 573 MCSectionCOFF *GVSec = 574 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr; 575 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr; 576 577 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>( 578 Asm->getObjFileLowering().getCOFFDebugSymbolsSection()); 579 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym); 580 581 OS.SwitchSection(DebugSec); 582 583 // Emit the magic version number if this is the first time we've switched to 584 // this section. 585 if (ComdatDebugSections.insert(DebugSec).second) 586 emitCodeViewMagicVersion(); 587 } 588 589 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, 590 FunctionInfo &FI) { 591 // For each function there is a separate subsection 592 // which holds the PC to file:line table. 593 const MCSymbol *Fn = Asm->getSymbol(GV); 594 assert(Fn); 595 596 // Switch to the to a comdat section, if appropriate. 597 switchToDebugSectionForSymbol(Fn); 598 599 std::string FuncName; 600 auto *SP = GV->getSubprogram(); 601 setCurrentSubprogram(SP); 602 603 // If we have a display name, build the fully qualified name by walking the 604 // chain of scopes. 605 if (SP != nullptr && !SP->getDisplayName().empty()) 606 FuncName = 607 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName()); 608 609 // If our DISubprogram name is empty, use the mangled name. 610 if (FuncName.empty()) 611 FuncName = GlobalValue::getRealLinkageName(GV->getName()); 612 613 // Emit a symbol subsection, required by VS2012+ to find function boundaries. 614 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 615 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols); 616 { 617 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(), 618 *ProcRecordEnd = MMI->getContext().createTempSymbol(); 619 OS.AddComment("Record length"); 620 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2); 621 OS.EmitLabel(ProcRecordBegin); 622 623 OS.AddComment("Record kind: S_GPROC32_ID"); 624 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2); 625 626 // These fields are filled in by tools like CVPACK which run after the fact. 627 OS.AddComment("PtrParent"); 628 OS.EmitIntValue(0, 4); 629 OS.AddComment("PtrEnd"); 630 OS.EmitIntValue(0, 4); 631 OS.AddComment("PtrNext"); 632 OS.EmitIntValue(0, 4); 633 // This is the important bit that tells the debugger where the function 634 // code is located and what's its size: 635 OS.AddComment("Code size"); 636 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4); 637 OS.AddComment("Offset after prologue"); 638 OS.EmitIntValue(0, 4); 639 OS.AddComment("Offset before epilogue"); 640 OS.EmitIntValue(0, 4); 641 OS.AddComment("Function type index"); 642 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4); 643 OS.AddComment("Function section relative address"); 644 OS.EmitCOFFSecRel32(Fn); 645 OS.AddComment("Function section index"); 646 OS.EmitCOFFSectionIndex(Fn); 647 OS.AddComment("Flags"); 648 OS.EmitIntValue(0, 1); 649 // Emit the function display name as a null-terminated string. 650 OS.AddComment("Function name"); 651 // Truncate the name so we won't overflow the record length field. 652 emitNullTerminatedSymbolName(OS, FuncName); 653 OS.EmitLabel(ProcRecordEnd); 654 655 emitLocalVariableList(FI.Locals); 656 657 // Emit inlined call site information. Only emit functions inlined directly 658 // into the parent function. We'll emit the other sites recursively as part 659 // of their parent inline site. 660 for (const DILocation *InlinedAt : FI.ChildSites) { 661 auto I = FI.InlineSites.find(InlinedAt); 662 assert(I != FI.InlineSites.end() && 663 "child site not in function inline site map"); 664 emitInlinedCallSite(FI, InlinedAt, I->second); 665 } 666 667 if (SP != nullptr) 668 emitDebugInfoForUDTs(LocalUDTs); 669 670 // We're done with this function. 671 OS.AddComment("Record length"); 672 OS.EmitIntValue(0x0002, 2); 673 OS.AddComment("Record kind: S_PROC_ID_END"); 674 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2); 675 } 676 endCVSubsection(SymbolsEnd); 677 678 // We have an assembler directive that takes care of the whole line table. 679 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End); 680 } 681 682 CodeViewDebug::LocalVarDefRange 683 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) { 684 LocalVarDefRange DR; 685 DR.InMemory = -1; 686 DR.DataOffset = Offset; 687 assert(DR.DataOffset == Offset && "truncation"); 688 DR.StructOffset = 0; 689 DR.CVRegister = CVRegister; 690 return DR; 691 } 692 693 CodeViewDebug::LocalVarDefRange 694 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) { 695 LocalVarDefRange DR; 696 DR.InMemory = 0; 697 DR.DataOffset = 0; 698 DR.StructOffset = 0; 699 DR.CVRegister = CVRegister; 700 return DR; 701 } 702 703 void CodeViewDebug::collectVariableInfoFromMMITable( 704 DenseSet<InlinedVariable> &Processed) { 705 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget(); 706 const TargetFrameLowering *TFI = TSI.getFrameLowering(); 707 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 708 709 for (const MachineModuleInfo::VariableDbgInfo &VI : 710 MMI->getVariableDbgInfo()) { 711 if (!VI.Var) 712 continue; 713 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 714 "Expected inlined-at fields to agree"); 715 716 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt())); 717 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 718 719 // If variable scope is not found then skip this variable. 720 if (!Scope) 721 continue; 722 723 // Get the frame register used and the offset. 724 unsigned FrameReg = 0; 725 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg); 726 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); 727 728 // Calculate the label ranges. 729 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset); 730 for (const InsnRange &Range : Scope->getRanges()) { 731 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 732 const MCSymbol *End = getLabelAfterInsn(Range.second); 733 End = End ? End : Asm->getFunctionEnd(); 734 DefRange.Ranges.emplace_back(Begin, End); 735 } 736 737 LocalVariable Var; 738 Var.DIVar = VI.Var; 739 Var.DefRanges.emplace_back(std::move(DefRange)); 740 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt()); 741 } 742 } 743 744 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) { 745 DenseSet<InlinedVariable> Processed; 746 // Grab the variable info that was squirreled away in the MMI side-table. 747 collectVariableInfoFromMMITable(Processed); 748 749 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 750 751 for (const auto &I : DbgValues) { 752 InlinedVariable IV = I.first; 753 if (Processed.count(IV)) 754 continue; 755 const DILocalVariable *DIVar = IV.first; 756 const DILocation *InlinedAt = IV.second; 757 758 // Instruction ranges, specifying where IV is accessible. 759 const auto &Ranges = I.second; 760 761 LexicalScope *Scope = nullptr; 762 if (InlinedAt) 763 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt); 764 else 765 Scope = LScopes.findLexicalScope(DIVar->getScope()); 766 // If variable scope is not found then skip this variable. 767 if (!Scope) 768 continue; 769 770 LocalVariable Var; 771 Var.DIVar = DIVar; 772 773 // Calculate the definition ranges. 774 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 775 const InsnRange &Range = *I; 776 const MachineInstr *DVInst = Range.first; 777 assert(DVInst->isDebugValue() && "Invalid History entry"); 778 const DIExpression *DIExpr = DVInst->getDebugExpression(); 779 780 // Bail if there is a complex DWARF expression for now. 781 if (DIExpr && DIExpr->getNumElements() > 0) 782 continue; 783 784 // Bail if operand 0 is not a valid register. This means the variable is a 785 // simple constant, or is described by a complex expression. 786 // FIXME: Find a way to represent constant variables, since they are 787 // relatively common. 788 unsigned Reg = 789 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0; 790 if (Reg == 0) 791 continue; 792 793 // Handle the two cases we can handle: indirect in memory and in register. 794 bool IsIndirect = DVInst->getOperand(1).isImm(); 795 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg()); 796 { 797 LocalVarDefRange DefRange; 798 if (IsIndirect) { 799 int64_t Offset = DVInst->getOperand(1).getImm(); 800 DefRange = createDefRangeMem(CVReg, Offset); 801 } else { 802 DefRange = createDefRangeReg(CVReg); 803 } 804 if (Var.DefRanges.empty() || 805 Var.DefRanges.back().isDifferentLocation(DefRange)) { 806 Var.DefRanges.emplace_back(std::move(DefRange)); 807 } 808 } 809 810 // Compute the label range. 811 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 812 const MCSymbol *End = getLabelAfterInsn(Range.second); 813 if (!End) { 814 if (std::next(I) != E) 815 End = getLabelBeforeInsn(std::next(I)->first); 816 else 817 End = Asm->getFunctionEnd(); 818 } 819 820 // If the last range end is our begin, just extend the last range. 821 // Otherwise make a new range. 822 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges = 823 Var.DefRanges.back().Ranges; 824 if (!Ranges.empty() && Ranges.back().second == Begin) 825 Ranges.back().second = End; 826 else 827 Ranges.emplace_back(Begin, End); 828 829 // FIXME: Do more range combining. 830 } 831 832 recordLocalVariable(std::move(Var), InlinedAt); 833 } 834 } 835 836 void CodeViewDebug::beginFunction(const MachineFunction *MF) { 837 assert(!CurFn && "Can't process two functions at once!"); 838 839 if (!Asm || !MMI->hasDebugInfo()) 840 return; 841 842 DebugHandlerBase::beginFunction(MF); 843 844 const Function *GV = MF->getFunction(); 845 assert(FnDebugInfo.count(GV) == false); 846 CurFn = &FnDebugInfo[GV]; 847 CurFn->FuncId = NextFuncId++; 848 CurFn->Begin = Asm->getFunctionBegin(); 849 850 // Find the end of the function prolog. First known non-DBG_VALUE and 851 // non-frame setup location marks the beginning of the function body. 852 // FIXME: is there a simpler a way to do this? Can we just search 853 // for the first instruction of the function, not the last of the prolog? 854 DebugLoc PrologEndLoc; 855 bool EmptyPrologue = true; 856 for (const auto &MBB : *MF) { 857 for (const auto &MI : MBB) { 858 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) && 859 MI.getDebugLoc()) { 860 PrologEndLoc = MI.getDebugLoc(); 861 break; 862 } else if (!MI.isDebugValue()) { 863 EmptyPrologue = false; 864 } 865 } 866 } 867 868 // Record beginning of function if we have a non-empty prologue. 869 if (PrologEndLoc && !EmptyPrologue) { 870 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc(); 871 maybeRecordLocation(FnStartDL, MF); 872 } 873 } 874 875 void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) { 876 // Don't record empty UDTs. 877 if (Ty->getName().empty()) 878 return; 879 880 SmallVector<StringRef, 5> QualifiedNameComponents; 881 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents( 882 Ty->getScope().resolve(), QualifiedNameComponents); 883 884 std::string FullyQualifiedName = 885 getQualifiedName(QualifiedNameComponents, Ty->getName()); 886 887 if (ClosestSubprogram == nullptr) 888 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI); 889 else if (ClosestSubprogram == CurrentSubprogram) 890 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI); 891 892 // TODO: What if the ClosestSubprogram is neither null or the current 893 // subprogram? Currently, the UDT just gets dropped on the floor. 894 // 895 // The current behavior is not desirable. To get maximal fidelity, we would 896 // need to perform all type translation before beginning emission of .debug$S 897 // and then make LocalUDTs a member of FunctionInfo 898 } 899 900 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) { 901 // Generic dispatch for lowering an unknown type. 902 switch (Ty->getTag()) { 903 case dwarf::DW_TAG_array_type: 904 return lowerTypeArray(cast<DICompositeType>(Ty)); 905 case dwarf::DW_TAG_typedef: 906 return lowerTypeAlias(cast<DIDerivedType>(Ty)); 907 case dwarf::DW_TAG_base_type: 908 return lowerTypeBasic(cast<DIBasicType>(Ty)); 909 case dwarf::DW_TAG_pointer_type: 910 case dwarf::DW_TAG_reference_type: 911 case dwarf::DW_TAG_rvalue_reference_type: 912 return lowerTypePointer(cast<DIDerivedType>(Ty)); 913 case dwarf::DW_TAG_ptr_to_member_type: 914 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty)); 915 case dwarf::DW_TAG_const_type: 916 case dwarf::DW_TAG_volatile_type: 917 return lowerTypeModifier(cast<DIDerivedType>(Ty)); 918 case dwarf::DW_TAG_subroutine_type: 919 if (ClassTy) { 920 // The member function type of a member function pointer has no 921 // ThisAdjustment. 922 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy, 923 /*ThisAdjustment=*/0); 924 } 925 return lowerTypeFunction(cast<DISubroutineType>(Ty)); 926 case dwarf::DW_TAG_enumeration_type: 927 return lowerTypeEnum(cast<DICompositeType>(Ty)); 928 case dwarf::DW_TAG_class_type: 929 case dwarf::DW_TAG_structure_type: 930 return lowerTypeClass(cast<DICompositeType>(Ty)); 931 case dwarf::DW_TAG_union_type: 932 return lowerTypeUnion(cast<DICompositeType>(Ty)); 933 default: 934 // Use the null type index. 935 return TypeIndex(); 936 } 937 } 938 939 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) { 940 DITypeRef UnderlyingTypeRef = Ty->getBaseType(); 941 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef); 942 StringRef TypeName = Ty->getName(); 943 944 addToUDTs(Ty, UnderlyingTypeIndex); 945 946 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) && 947 TypeName == "HRESULT") 948 return TypeIndex(SimpleTypeKind::HResult); 949 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) && 950 TypeName == "wchar_t") 951 return TypeIndex(SimpleTypeKind::WideCharacter); 952 953 return UnderlyingTypeIndex; 954 } 955 956 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) { 957 DITypeRef ElementTypeRef = Ty->getBaseType(); 958 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef); 959 // IndexType is size_t, which depends on the bitness of the target. 960 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8 961 ? TypeIndex(SimpleTypeKind::UInt64Quad) 962 : TypeIndex(SimpleTypeKind::UInt32Long); 963 uint64_t Size = Ty->getSizeInBits() / 8; 964 ArrayRecord Record(ElementTypeIndex, IndexType, Size, Ty->getName()); 965 return TypeTable.writeArray(Record); 966 } 967 968 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) { 969 TypeIndex Index; 970 dwarf::TypeKind Kind; 971 uint32_t ByteSize; 972 973 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding()); 974 ByteSize = Ty->getSizeInBits() / 8; 975 976 SimpleTypeKind STK = SimpleTypeKind::None; 977 switch (Kind) { 978 case dwarf::DW_ATE_address: 979 // FIXME: Translate 980 break; 981 case dwarf::DW_ATE_boolean: 982 switch (ByteSize) { 983 case 1: STK = SimpleTypeKind::Boolean8; break; 984 case 2: STK = SimpleTypeKind::Boolean16; break; 985 case 4: STK = SimpleTypeKind::Boolean32; break; 986 case 8: STK = SimpleTypeKind::Boolean64; break; 987 case 16: STK = SimpleTypeKind::Boolean128; break; 988 } 989 break; 990 case dwarf::DW_ATE_complex_float: 991 switch (ByteSize) { 992 case 2: STK = SimpleTypeKind::Complex16; break; 993 case 4: STK = SimpleTypeKind::Complex32; break; 994 case 8: STK = SimpleTypeKind::Complex64; break; 995 case 10: STK = SimpleTypeKind::Complex80; break; 996 case 16: STK = SimpleTypeKind::Complex128; break; 997 } 998 break; 999 case dwarf::DW_ATE_float: 1000 switch (ByteSize) { 1001 case 2: STK = SimpleTypeKind::Float16; break; 1002 case 4: STK = SimpleTypeKind::Float32; break; 1003 case 6: STK = SimpleTypeKind::Float48; break; 1004 case 8: STK = SimpleTypeKind::Float64; break; 1005 case 10: STK = SimpleTypeKind::Float80; break; 1006 case 16: STK = SimpleTypeKind::Float128; break; 1007 } 1008 break; 1009 case dwarf::DW_ATE_signed: 1010 switch (ByteSize) { 1011 case 1: STK = SimpleTypeKind::SByte; break; 1012 case 2: STK = SimpleTypeKind::Int16Short; break; 1013 case 4: STK = SimpleTypeKind::Int32; break; 1014 case 8: STK = SimpleTypeKind::Int64Quad; break; 1015 case 16: STK = SimpleTypeKind::Int128Oct; break; 1016 } 1017 break; 1018 case dwarf::DW_ATE_unsigned: 1019 switch (ByteSize) { 1020 case 1: STK = SimpleTypeKind::Byte; break; 1021 case 2: STK = SimpleTypeKind::UInt16Short; break; 1022 case 4: STK = SimpleTypeKind::UInt32; break; 1023 case 8: STK = SimpleTypeKind::UInt64Quad; break; 1024 case 16: STK = SimpleTypeKind::UInt128Oct; break; 1025 } 1026 break; 1027 case dwarf::DW_ATE_UTF: 1028 switch (ByteSize) { 1029 case 2: STK = SimpleTypeKind::Character16; break; 1030 case 4: STK = SimpleTypeKind::Character32; break; 1031 } 1032 break; 1033 case dwarf::DW_ATE_signed_char: 1034 if (ByteSize == 1) 1035 STK = SimpleTypeKind::SignedCharacter; 1036 break; 1037 case dwarf::DW_ATE_unsigned_char: 1038 if (ByteSize == 1) 1039 STK = SimpleTypeKind::UnsignedCharacter; 1040 break; 1041 default: 1042 break; 1043 } 1044 1045 // Apply some fixups based on the source-level type name. 1046 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int") 1047 STK = SimpleTypeKind::Int32Long; 1048 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int") 1049 STK = SimpleTypeKind::UInt32Long; 1050 if (STK == SimpleTypeKind::UInt16Short && 1051 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t")) 1052 STK = SimpleTypeKind::WideCharacter; 1053 if ((STK == SimpleTypeKind::SignedCharacter || 1054 STK == SimpleTypeKind::UnsignedCharacter) && 1055 Ty->getName() == "char") 1056 STK = SimpleTypeKind::NarrowCharacter; 1057 1058 return TypeIndex(STK); 1059 } 1060 1061 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) { 1062 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType()); 1063 1064 // While processing the type being pointed to it is possible we already 1065 // created this pointer type. If so, we check here and return the existing 1066 // pointer type. 1067 auto I = TypeIndices.find({Ty, nullptr}); 1068 if (I != TypeIndices.end()) 1069 return I->second; 1070 1071 // Pointers to simple types can use SimpleTypeMode, rather than having a 1072 // dedicated pointer type record. 1073 if (PointeeTI.isSimple() && 1074 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct && 1075 Ty->getTag() == dwarf::DW_TAG_pointer_type) { 1076 SimpleTypeMode Mode = Ty->getSizeInBits() == 64 1077 ? SimpleTypeMode::NearPointer64 1078 : SimpleTypeMode::NearPointer32; 1079 return TypeIndex(PointeeTI.getSimpleKind(), Mode); 1080 } 1081 1082 PointerKind PK = 1083 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32; 1084 PointerMode PM = PointerMode::Pointer; 1085 switch (Ty->getTag()) { 1086 default: llvm_unreachable("not a pointer tag type"); 1087 case dwarf::DW_TAG_pointer_type: 1088 PM = PointerMode::Pointer; 1089 break; 1090 case dwarf::DW_TAG_reference_type: 1091 PM = PointerMode::LValueReference; 1092 break; 1093 case dwarf::DW_TAG_rvalue_reference_type: 1094 PM = PointerMode::RValueReference; 1095 break; 1096 } 1097 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method 1098 // 'this' pointer, but not normal contexts. Figure out what we're supposed to 1099 // do. 1100 PointerOptions PO = PointerOptions::None; 1101 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8); 1102 return TypeTable.writePointer(PR); 1103 } 1104 1105 static PointerToMemberRepresentation 1106 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) { 1107 // SizeInBytes being zero generally implies that the member pointer type was 1108 // incomplete, which can happen if it is part of a function prototype. In this 1109 // case, use the unknown model instead of the general model. 1110 if (IsPMF) { 1111 switch (Flags & DINode::FlagPtrToMemberRep) { 1112 case 0: 1113 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1114 : PointerToMemberRepresentation::GeneralFunction; 1115 case DINode::FlagSingleInheritance: 1116 return PointerToMemberRepresentation::SingleInheritanceFunction; 1117 case DINode::FlagMultipleInheritance: 1118 return PointerToMemberRepresentation::MultipleInheritanceFunction; 1119 case DINode::FlagVirtualInheritance: 1120 return PointerToMemberRepresentation::VirtualInheritanceFunction; 1121 } 1122 } else { 1123 switch (Flags & DINode::FlagPtrToMemberRep) { 1124 case 0: 1125 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1126 : PointerToMemberRepresentation::GeneralData; 1127 case DINode::FlagSingleInheritance: 1128 return PointerToMemberRepresentation::SingleInheritanceData; 1129 case DINode::FlagMultipleInheritance: 1130 return PointerToMemberRepresentation::MultipleInheritanceData; 1131 case DINode::FlagVirtualInheritance: 1132 return PointerToMemberRepresentation::VirtualInheritanceData; 1133 } 1134 } 1135 llvm_unreachable("invalid ptr to member representation"); 1136 } 1137 1138 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) { 1139 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type); 1140 TypeIndex ClassTI = getTypeIndex(Ty->getClassType()); 1141 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType()); 1142 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64 1143 : PointerKind::Near32; 1144 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType()); 1145 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction 1146 : PointerMode::PointerToDataMember; 1147 PointerOptions PO = PointerOptions::None; // FIXME 1148 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big"); 1149 uint8_t SizeInBytes = Ty->getSizeInBits() / 8; 1150 MemberPointerInfo MPI( 1151 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags())); 1152 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI); 1153 return TypeTable.writePointer(PR); 1154 } 1155 1156 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't 1157 /// have a translation, use the NearC convention. 1158 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) { 1159 switch (DwarfCC) { 1160 case dwarf::DW_CC_normal: return CallingConvention::NearC; 1161 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast; 1162 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall; 1163 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall; 1164 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal; 1165 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector; 1166 } 1167 return CallingConvention::NearC; 1168 } 1169 1170 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) { 1171 ModifierOptions Mods = ModifierOptions::None; 1172 bool IsModifier = true; 1173 const DIType *BaseTy = Ty; 1174 while (IsModifier && BaseTy) { 1175 // FIXME: Need to add DWARF tag for __unaligned. 1176 switch (BaseTy->getTag()) { 1177 case dwarf::DW_TAG_const_type: 1178 Mods |= ModifierOptions::Const; 1179 break; 1180 case dwarf::DW_TAG_volatile_type: 1181 Mods |= ModifierOptions::Volatile; 1182 break; 1183 default: 1184 IsModifier = false; 1185 break; 1186 } 1187 if (IsModifier) 1188 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve(); 1189 } 1190 TypeIndex ModifiedTI = getTypeIndex(BaseTy); 1191 1192 // While processing the type being pointed to, it is possible we already 1193 // created this modifier type. If so, we check here and return the existing 1194 // modifier type. 1195 auto I = TypeIndices.find({Ty, nullptr}); 1196 if (I != TypeIndices.end()) 1197 return I->second; 1198 1199 ModifierRecord MR(ModifiedTI, Mods); 1200 return TypeTable.writeModifier(MR); 1201 } 1202 1203 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) { 1204 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; 1205 for (DITypeRef ArgTypeRef : Ty->getTypeArray()) 1206 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef)); 1207 1208 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 1209 ArrayRef<TypeIndex> ArgTypeIndices = None; 1210 if (!ReturnAndArgTypeIndices.empty()) { 1211 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices); 1212 ReturnTypeIndex = ReturnAndArgTypesRef.front(); 1213 ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); 1214 } 1215 1216 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 1217 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec); 1218 1219 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 1220 1221 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None, 1222 ArgTypeIndices.size(), ArgListIndex); 1223 return TypeTable.writeProcedure(Procedure); 1224 } 1225 1226 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty, 1227 const DIType *ClassTy, 1228 int ThisAdjustment) { 1229 // Lower the containing class type. 1230 TypeIndex ClassType = getTypeIndex(ClassTy); 1231 1232 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; 1233 for (DITypeRef ArgTypeRef : Ty->getTypeArray()) 1234 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef)); 1235 1236 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 1237 ArrayRef<TypeIndex> ArgTypeIndices = None; 1238 if (!ReturnAndArgTypeIndices.empty()) { 1239 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices); 1240 ReturnTypeIndex = ReturnAndArgTypesRef.front(); 1241 ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); 1242 } 1243 TypeIndex ThisTypeIndex = TypeIndex::Void(); 1244 if (!ArgTypeIndices.empty()) { 1245 ThisTypeIndex = ArgTypeIndices.front(); 1246 ArgTypeIndices = ArgTypeIndices.drop_front(); 1247 } 1248 1249 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 1250 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec); 1251 1252 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 1253 1254 // TODO: Need to use the correct values for: 1255 // FunctionOptions 1256 // ThisPointerAdjustment. 1257 TypeIndex TI = TypeTable.writeMemberFunction(MemberFunctionRecord( 1258 ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None, 1259 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment)); 1260 1261 return TI; 1262 } 1263 1264 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) { 1265 switch (Flags & DINode::FlagAccessibility) { 1266 case DINode::FlagPrivate: return MemberAccess::Private; 1267 case DINode::FlagPublic: return MemberAccess::Public; 1268 case DINode::FlagProtected: return MemberAccess::Protected; 1269 case 0: 1270 // If there was no explicit access control, provide the default for the tag. 1271 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private 1272 : MemberAccess::Public; 1273 } 1274 llvm_unreachable("access flags are exclusive"); 1275 } 1276 1277 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) { 1278 if (SP->isArtificial()) 1279 return MethodOptions::CompilerGenerated; 1280 1281 // FIXME: Handle other MethodOptions. 1282 1283 return MethodOptions::None; 1284 } 1285 1286 static MethodKind translateMethodKindFlags(const DISubprogram *SP, 1287 bool Introduced) { 1288 switch (SP->getVirtuality()) { 1289 case dwarf::DW_VIRTUALITY_none: 1290 break; 1291 case dwarf::DW_VIRTUALITY_virtual: 1292 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual; 1293 case dwarf::DW_VIRTUALITY_pure_virtual: 1294 return Introduced ? MethodKind::PureIntroducingVirtual 1295 : MethodKind::PureVirtual; 1296 default: 1297 llvm_unreachable("unhandled virtuality case"); 1298 } 1299 1300 // FIXME: Get Clang to mark DISubprogram as static and do something with it. 1301 1302 return MethodKind::Vanilla; 1303 } 1304 1305 static TypeRecordKind getRecordKind(const DICompositeType *Ty) { 1306 switch (Ty->getTag()) { 1307 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class; 1308 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct; 1309 } 1310 llvm_unreachable("unexpected tag"); 1311 } 1312 1313 /// Return the HasUniqueName option if it should be present in ClassOptions, or 1314 /// None otherwise. 1315 static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) { 1316 // MSVC always sets this flag now, even for local types. Clang doesn't always 1317 // appear to give every type a linkage name, which may be problematic for us. 1318 // FIXME: Investigate the consequences of not following them here. 1319 return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName 1320 : ClassOptions::None; 1321 } 1322 1323 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) { 1324 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty); 1325 TypeIndex FTI; 1326 unsigned EnumeratorCount = 0; 1327 1328 if (Ty->isForwardDecl()) { 1329 CO |= ClassOptions::ForwardReference; 1330 } else { 1331 FieldListRecordBuilder Fields; 1332 for (const DINode *Element : Ty->getElements()) { 1333 // We assume that the frontend provides all members in source declaration 1334 // order, which is what MSVC does. 1335 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) { 1336 Fields.writeEnumerator(EnumeratorRecord( 1337 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()), 1338 Enumerator->getName())); 1339 EnumeratorCount++; 1340 } 1341 } 1342 FTI = TypeTable.writeFieldList(Fields); 1343 } 1344 1345 std::string FullName = 1346 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName()); 1347 1348 return TypeTable.writeEnum(EnumRecord(EnumeratorCount, CO, FTI, FullName, 1349 Ty->getIdentifier(), 1350 getTypeIndex(Ty->getBaseType()))); 1351 } 1352 1353 //===----------------------------------------------------------------------===// 1354 // ClassInfo 1355 //===----------------------------------------------------------------------===// 1356 1357 struct llvm::ClassInfo { 1358 struct MemberInfo { 1359 const DIDerivedType *MemberTypeNode; 1360 unsigned BaseOffset; 1361 }; 1362 // [MemberInfo] 1363 typedef std::vector<MemberInfo> MemberList; 1364 1365 typedef TinyPtrVector<const DISubprogram *> MethodsList; 1366 // MethodName -> MethodsList 1367 typedef MapVector<MDString *, MethodsList> MethodsMap; 1368 1369 /// Base classes. 1370 std::vector<const DIDerivedType *> Inheritance; 1371 1372 /// Direct members. 1373 MemberList Members; 1374 // Direct overloaded methods gathered by name. 1375 MethodsMap Methods; 1376 }; 1377 1378 void CodeViewDebug::clear() { 1379 assert(CurFn == nullptr); 1380 FileIdMap.clear(); 1381 FnDebugInfo.clear(); 1382 FileToFilepathMap.clear(); 1383 LocalUDTs.clear(); 1384 GlobalUDTs.clear(); 1385 TypeIndices.clear(); 1386 CompleteTypeIndices.clear(); 1387 } 1388 1389 void CodeViewDebug::collectMemberInfo(ClassInfo &Info, 1390 const DIDerivedType *DDTy) { 1391 if (!DDTy->getName().empty()) { 1392 Info.Members.push_back({DDTy, 0}); 1393 return; 1394 } 1395 // An unnamed member must represent a nested struct or union. Add all the 1396 // indirect fields to the current record. 1397 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!"); 1398 unsigned Offset = DDTy->getOffsetInBits() / 8; 1399 const DIType *Ty = DDTy->getBaseType().resolve(); 1400 const DICompositeType *DCTy = cast<DICompositeType>(Ty); 1401 ClassInfo NestedInfo = collectClassInfo(DCTy); 1402 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members) 1403 Info.Members.push_back( 1404 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset}); 1405 } 1406 1407 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) { 1408 ClassInfo Info; 1409 // Add elements to structure type. 1410 DINodeArray Elements = Ty->getElements(); 1411 for (auto *Element : Elements) { 1412 // We assume that the frontend provides all members in source declaration 1413 // order, which is what MSVC does. 1414 if (!Element) 1415 continue; 1416 if (auto *SP = dyn_cast<DISubprogram>(Element)) { 1417 Info.Methods[SP->getRawName()].push_back(SP); 1418 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) { 1419 if (DDTy->getTag() == dwarf::DW_TAG_member) { 1420 collectMemberInfo(Info, DDTy); 1421 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) { 1422 Info.Inheritance.push_back(DDTy); 1423 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) { 1424 // Ignore friend members. It appears that MSVC emitted info about 1425 // friends in the past, but modern versions do not. 1426 } 1427 // FIXME: Get Clang to emit function virtual table here and handle it. 1428 // FIXME: Get clang to emit nested types here and do something with 1429 // them. 1430 } 1431 // Skip other unrecognized kinds of elements. 1432 } 1433 return Info; 1434 } 1435 1436 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) { 1437 // First, construct the forward decl. Don't look into Ty to compute the 1438 // forward decl options, since it might not be available in all TUs. 1439 TypeRecordKind Kind = getRecordKind(Ty); 1440 ClassOptions CO = 1441 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty); 1442 std::string FullName = 1443 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName()); 1444 TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord( 1445 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(), 1446 TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier())); 1447 if (!Ty->isForwardDecl()) 1448 DeferredCompleteTypes.push_back(Ty); 1449 return FwdDeclTI; 1450 } 1451 1452 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) { 1453 // Construct the field list and complete type record. 1454 TypeRecordKind Kind = getRecordKind(Ty); 1455 // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass. 1456 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty); 1457 TypeIndex FieldTI; 1458 TypeIndex VShapeTI; 1459 unsigned FieldCount; 1460 std::tie(FieldTI, VShapeTI, FieldCount) = lowerRecordFieldList(Ty); 1461 1462 std::string FullName = 1463 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName()); 1464 1465 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 1466 1467 TypeIndex ClassTI = TypeTable.writeClass(ClassRecord( 1468 Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI, 1469 TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier())); 1470 1471 TypeTable.writeUdtSourceLine(UdtSourceLineRecord( 1472 ClassTI, TypeTable.writeStringId(StringIdRecord( 1473 TypeIndex(0x0), getFullFilepath(Ty->getFile()))), 1474 Ty->getLine())); 1475 1476 addToUDTs(Ty, ClassTI); 1477 1478 return ClassTI; 1479 } 1480 1481 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) { 1482 ClassOptions CO = 1483 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty); 1484 std::string FullName = 1485 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName()); 1486 TypeIndex FwdDeclTI = 1487 TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0, 1488 FullName, Ty->getIdentifier())); 1489 if (!Ty->isForwardDecl()) 1490 DeferredCompleteTypes.push_back(Ty); 1491 return FwdDeclTI; 1492 } 1493 1494 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) { 1495 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty); 1496 TypeIndex FieldTI; 1497 unsigned FieldCount; 1498 std::tie(FieldTI, std::ignore, FieldCount) = lowerRecordFieldList(Ty); 1499 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 1500 std::string FullName = 1501 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName()); 1502 1503 TypeIndex UnionTI = TypeTable.writeUnion( 1504 UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName, 1505 Ty->getIdentifier())); 1506 1507 TypeTable.writeUdtSourceLine(UdtSourceLineRecord( 1508 UnionTI, TypeTable.writeStringId(StringIdRecord( 1509 TypeIndex(0x0), getFullFilepath(Ty->getFile()))), 1510 Ty->getLine())); 1511 1512 addToUDTs(Ty, UnionTI); 1513 1514 return UnionTI; 1515 } 1516 1517 std::tuple<TypeIndex, TypeIndex, unsigned> 1518 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) { 1519 // Manually count members. MSVC appears to count everything that generates a 1520 // field list record. Each individual overload in a method overload group 1521 // contributes to this count, even though the overload group is a single field 1522 // list record. 1523 unsigned MemberCount = 0; 1524 ClassInfo Info = collectClassInfo(Ty); 1525 FieldListRecordBuilder Fields; 1526 1527 // Create base classes. 1528 for (const DIDerivedType *I : Info.Inheritance) { 1529 if (I->getFlags() & DINode::FlagVirtual) { 1530 // Virtual base. 1531 // FIXME: Emit VBPtrOffset when the frontend provides it. 1532 unsigned VBPtrOffset = 0; 1533 // FIXME: Despite the accessor name, the offset is really in bytes. 1534 unsigned VBTableIndex = I->getOffsetInBits() / 4; 1535 Fields.writeVirtualBaseClass(VirtualBaseClassRecord( 1536 translateAccessFlags(Ty->getTag(), I->getFlags()), 1537 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset, 1538 VBTableIndex)); 1539 } else { 1540 assert(I->getOffsetInBits() % 8 == 0 && 1541 "bases must be on byte boundaries"); 1542 Fields.writeBaseClass(BaseClassRecord( 1543 translateAccessFlags(Ty->getTag(), I->getFlags()), 1544 getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8)); 1545 } 1546 } 1547 1548 // Create members. 1549 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) { 1550 const DIDerivedType *Member = MemberInfo.MemberTypeNode; 1551 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType()); 1552 StringRef MemberName = Member->getName(); 1553 MemberAccess Access = 1554 translateAccessFlags(Ty->getTag(), Member->getFlags()); 1555 1556 if (Member->isStaticMember()) { 1557 Fields.writeStaticDataMember( 1558 StaticDataMemberRecord(Access, MemberBaseType, MemberName)); 1559 MemberCount++; 1560 continue; 1561 } 1562 1563 // Data member. 1564 uint64_t MemberOffsetInBits = Member->getOffsetInBits(); 1565 if (Member->isBitField()) { 1566 uint64_t StartBitOffset = MemberOffsetInBits; 1567 if (const auto *CI = 1568 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) { 1569 MemberOffsetInBits = CI->getZExtValue(); 1570 } 1571 StartBitOffset -= MemberOffsetInBits; 1572 MemberBaseType = TypeTable.writeBitField(BitFieldRecord( 1573 MemberBaseType, Member->getSizeInBits(), StartBitOffset)); 1574 } 1575 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8; 1576 Fields.writeDataMember(DataMemberRecord(Access, MemberBaseType, 1577 MemberOffsetInBytes, MemberName)); 1578 MemberCount++; 1579 } 1580 1581 // Create methods 1582 for (auto &MethodItr : Info.Methods) { 1583 StringRef Name = MethodItr.first->getString(); 1584 1585 std::vector<OneMethodRecord> Methods; 1586 for (const DISubprogram *SP : MethodItr.second) { 1587 TypeIndex MethodType = getMemberFunctionType(SP, Ty); 1588 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual; 1589 1590 unsigned VFTableOffset = -1; 1591 if (Introduced) 1592 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes(); 1593 1594 Methods.push_back( 1595 OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced), 1596 translateMethodOptionFlags(SP), 1597 translateAccessFlags(Ty->getTag(), SP->getFlags()), 1598 VFTableOffset, Name)); 1599 MemberCount++; 1600 } 1601 assert(Methods.size() > 0 && "Empty methods map entry"); 1602 if (Methods.size() == 1) 1603 Fields.writeOneMethod(Methods[0]); 1604 else { 1605 TypeIndex MethodList = 1606 TypeTable.writeMethodOverloadList(MethodOverloadListRecord(Methods)); 1607 Fields.writeOverloadedMethod( 1608 OverloadedMethodRecord(Methods.size(), MethodList, Name)); 1609 } 1610 } 1611 TypeIndex FieldTI = TypeTable.writeFieldList(Fields); 1612 return std::make_tuple(FieldTI, TypeIndex(), MemberCount); 1613 } 1614 1615 TypeIndex CodeViewDebug::getVBPTypeIndex() { 1616 if (!VBPType.getIndex()) { 1617 // Make a 'const int *' type. 1618 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const); 1619 TypeIndex ModifiedTI = TypeTable.writeModifier(MR); 1620 1621 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64 1622 : PointerKind::Near32; 1623 PointerMode PM = PointerMode::Pointer; 1624 PointerOptions PO = PointerOptions::None; 1625 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes()); 1626 1627 VBPType = TypeTable.writePointer(PR); 1628 } 1629 1630 return VBPType; 1631 } 1632 1633 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) { 1634 const DIType *Ty = TypeRef.resolve(); 1635 const DIType *ClassTy = ClassTyRef.resolve(); 1636 1637 // The null DIType is the void type. Don't try to hash it. 1638 if (!Ty) 1639 return TypeIndex::Void(); 1640 1641 // Check if we've already translated this type. Don't try to do a 1642 // get-or-create style insertion that caches the hash lookup across the 1643 // lowerType call. It will update the TypeIndices map. 1644 auto I = TypeIndices.find({Ty, ClassTy}); 1645 if (I != TypeIndices.end()) 1646 return I->second; 1647 1648 TypeLoweringScope S(*this); 1649 TypeIndex TI = lowerType(Ty, ClassTy); 1650 return recordTypeIndexForDINode(Ty, TI, ClassTy); 1651 } 1652 1653 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) { 1654 const DIType *Ty = TypeRef.resolve(); 1655 1656 // The null DIType is the void type. Don't try to hash it. 1657 if (!Ty) 1658 return TypeIndex::Void(); 1659 1660 // If this is a non-record type, the complete type index is the same as the 1661 // normal type index. Just call getTypeIndex. 1662 switch (Ty->getTag()) { 1663 case dwarf::DW_TAG_class_type: 1664 case dwarf::DW_TAG_structure_type: 1665 case dwarf::DW_TAG_union_type: 1666 break; 1667 default: 1668 return getTypeIndex(Ty); 1669 } 1670 1671 // Check if we've already translated the complete record type. Lowering a 1672 // complete type should never trigger lowering another complete type, so we 1673 // can reuse the hash table lookup result. 1674 const auto *CTy = cast<DICompositeType>(Ty); 1675 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()}); 1676 if (!InsertResult.second) 1677 return InsertResult.first->second; 1678 1679 TypeLoweringScope S(*this); 1680 1681 // Make sure the forward declaration is emitted first. It's unclear if this 1682 // is necessary, but MSVC does it, and we should follow suit until we can show 1683 // otherwise. 1684 TypeIndex FwdDeclTI = getTypeIndex(CTy); 1685 1686 // Just use the forward decl if we don't have complete type info. This might 1687 // happen if the frontend is using modules and expects the complete definition 1688 // to be emitted elsewhere. 1689 if (CTy->isForwardDecl()) 1690 return FwdDeclTI; 1691 1692 TypeIndex TI; 1693 switch (CTy->getTag()) { 1694 case dwarf::DW_TAG_class_type: 1695 case dwarf::DW_TAG_structure_type: 1696 TI = lowerCompleteTypeClass(CTy); 1697 break; 1698 case dwarf::DW_TAG_union_type: 1699 TI = lowerCompleteTypeUnion(CTy); 1700 break; 1701 default: 1702 llvm_unreachable("not a record"); 1703 } 1704 1705 InsertResult.first->second = TI; 1706 return TI; 1707 } 1708 1709 /// Emit all the deferred complete record types. Try to do this in FIFO order, 1710 /// and do this until fixpoint, as each complete record type typically references 1711 /// many other record types. 1712 void CodeViewDebug::emitDeferredCompleteTypes() { 1713 SmallVector<const DICompositeType *, 4> TypesToEmit; 1714 while (!DeferredCompleteTypes.empty()) { 1715 std::swap(DeferredCompleteTypes, TypesToEmit); 1716 for (const DICompositeType *RecordTy : TypesToEmit) 1717 getCompleteTypeIndex(RecordTy); 1718 TypesToEmit.clear(); 1719 } 1720 } 1721 1722 void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) { 1723 // Get the sorted list of parameters and emit them first. 1724 SmallVector<const LocalVariable *, 6> Params; 1725 for (const LocalVariable &L : Locals) 1726 if (L.DIVar->isParameter()) 1727 Params.push_back(&L); 1728 std::sort(Params.begin(), Params.end(), 1729 [](const LocalVariable *L, const LocalVariable *R) { 1730 return L->DIVar->getArg() < R->DIVar->getArg(); 1731 }); 1732 for (const LocalVariable *L : Params) 1733 emitLocalVariable(*L); 1734 1735 // Next emit all non-parameters in the order that we found them. 1736 for (const LocalVariable &L : Locals) 1737 if (!L.DIVar->isParameter()) 1738 emitLocalVariable(L); 1739 } 1740 1741 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) { 1742 // LocalSym record, see SymbolRecord.h for more info. 1743 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(), 1744 *LocalEnd = MMI->getContext().createTempSymbol(); 1745 OS.AddComment("Record length"); 1746 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2); 1747 OS.EmitLabel(LocalBegin); 1748 1749 OS.AddComment("Record kind: S_LOCAL"); 1750 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2); 1751 1752 LocalSymFlags Flags = LocalSymFlags::None; 1753 if (Var.DIVar->isParameter()) 1754 Flags |= LocalSymFlags::IsParameter; 1755 if (Var.DefRanges.empty()) 1756 Flags |= LocalSymFlags::IsOptimizedOut; 1757 1758 OS.AddComment("TypeIndex"); 1759 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType()); 1760 OS.EmitIntValue(TI.getIndex(), 4); 1761 OS.AddComment("Flags"); 1762 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2); 1763 // Truncate the name so we won't overflow the record length field. 1764 emitNullTerminatedSymbolName(OS, Var.DIVar->getName()); 1765 OS.EmitLabel(LocalEnd); 1766 1767 // Calculate the on disk prefix of the appropriate def range record. The 1768 // records and on disk formats are described in SymbolRecords.h. BytePrefix 1769 // should be big enough to hold all forms without memory allocation. 1770 SmallString<20> BytePrefix; 1771 for (const LocalVarDefRange &DefRange : Var.DefRanges) { 1772 BytePrefix.clear(); 1773 // FIXME: Handle bitpieces. 1774 if (DefRange.StructOffset != 0) 1775 continue; 1776 1777 if (DefRange.InMemory) { 1778 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0, 1779 0, 0, ArrayRef<LocalVariableAddrGap>()); 1780 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL); 1781 BytePrefix += 1782 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 1783 BytePrefix += 1784 StringRef(reinterpret_cast<const char *>(&Sym.Header), 1785 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange)); 1786 } else { 1787 assert(DefRange.DataOffset == 0 && "unexpected offset into register"); 1788 // Unclear what matters here. 1789 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0, 1790 ArrayRef<LocalVariableAddrGap>()); 1791 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER); 1792 BytePrefix += 1793 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 1794 BytePrefix += 1795 StringRef(reinterpret_cast<const char *>(&Sym.Header), 1796 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange)); 1797 } 1798 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix); 1799 } 1800 } 1801 1802 void CodeViewDebug::endFunction(const MachineFunction *MF) { 1803 if (!Asm || !CurFn) // We haven't created any debug info for this function. 1804 return; 1805 1806 const Function *GV = MF->getFunction(); 1807 assert(FnDebugInfo.count(GV)); 1808 assert(CurFn == &FnDebugInfo[GV]); 1809 1810 collectVariableInfo(GV->getSubprogram()); 1811 1812 DebugHandlerBase::endFunction(MF); 1813 1814 // Don't emit anything if we don't have any line tables. 1815 if (!CurFn->HaveLineInfo) { 1816 FnDebugInfo.erase(GV); 1817 CurFn = nullptr; 1818 return; 1819 } 1820 1821 CurFn->End = Asm->getFunctionEnd(); 1822 1823 CurFn = nullptr; 1824 } 1825 1826 void CodeViewDebug::beginInstruction(const MachineInstr *MI) { 1827 DebugHandlerBase::beginInstruction(MI); 1828 1829 // Ignore DBG_VALUE locations and function prologue. 1830 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup)) 1831 return; 1832 DebugLoc DL = MI->getDebugLoc(); 1833 if (DL == PrevInstLoc || !DL) 1834 return; 1835 maybeRecordLocation(DL, Asm->MF); 1836 } 1837 1838 MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) { 1839 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(), 1840 *EndLabel = MMI->getContext().createTempSymbol(); 1841 OS.EmitIntValue(unsigned(Kind), 4); 1842 OS.AddComment("Subsection size"); 1843 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4); 1844 OS.EmitLabel(BeginLabel); 1845 return EndLabel; 1846 } 1847 1848 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) { 1849 OS.EmitLabel(EndLabel); 1850 // Every subsection must be aligned to a 4-byte boundary. 1851 OS.EmitValueToAlignment(4); 1852 } 1853 1854 void CodeViewDebug::emitDebugInfoForUDTs( 1855 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) { 1856 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) { 1857 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(), 1858 *UDTRecordEnd = MMI->getContext().createTempSymbol(); 1859 OS.AddComment("Record length"); 1860 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2); 1861 OS.EmitLabel(UDTRecordBegin); 1862 1863 OS.AddComment("Record kind: S_UDT"); 1864 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2); 1865 1866 OS.AddComment("Type"); 1867 OS.EmitIntValue(UDT.second.getIndex(), 4); 1868 1869 emitNullTerminatedSymbolName(OS, UDT.first); 1870 OS.EmitLabel(UDTRecordEnd); 1871 } 1872 } 1873 1874 void CodeViewDebug::emitDebugInfoForGlobals() { 1875 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 1876 for (const MDNode *Node : CUs->operands()) { 1877 const auto *CU = cast<DICompileUnit>(Node); 1878 1879 // First, emit all globals that are not in a comdat in a single symbol 1880 // substream. MSVC doesn't like it if the substream is empty, so only open 1881 // it if we have at least one global to emit. 1882 switchToDebugSectionForSymbol(nullptr); 1883 MCSymbol *EndLabel = nullptr; 1884 for (const DIGlobalVariable *G : CU->getGlobalVariables()) { 1885 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) { 1886 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) { 1887 if (!EndLabel) { 1888 OS.AddComment("Symbol subsection for globals"); 1889 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols); 1890 } 1891 emitDebugInfoForGlobal(G, Asm->getSymbol(GV)); 1892 } 1893 } 1894 } 1895 if (EndLabel) 1896 endCVSubsection(EndLabel); 1897 1898 // Second, emit each global that is in a comdat into its own .debug$S 1899 // section along with its own symbol substream. 1900 for (const DIGlobalVariable *G : CU->getGlobalVariables()) { 1901 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) { 1902 if (GV->hasComdat()) { 1903 MCSymbol *GVSym = Asm->getSymbol(GV); 1904 OS.AddComment("Symbol subsection for " + 1905 Twine(GlobalValue::getRealLinkageName(GV->getName()))); 1906 switchToDebugSectionForSymbol(GVSym); 1907 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols); 1908 emitDebugInfoForGlobal(G, GVSym); 1909 endCVSubsection(EndLabel); 1910 } 1911 } 1912 } 1913 } 1914 } 1915 1916 void CodeViewDebug::emitDebugInfoForRetainedTypes() { 1917 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 1918 for (const MDNode *Node : CUs->operands()) { 1919 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) { 1920 if (DIType *RT = dyn_cast<DIType>(Ty)) { 1921 getTypeIndex(RT); 1922 // FIXME: Add to global/local DTU list. 1923 } 1924 } 1925 } 1926 } 1927 1928 void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV, 1929 MCSymbol *GVSym) { 1930 // DataSym record, see SymbolRecord.h for more info. 1931 // FIXME: Thread local data, etc 1932 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(), 1933 *DataEnd = MMI->getContext().createTempSymbol(); 1934 OS.AddComment("Record length"); 1935 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2); 1936 OS.EmitLabel(DataBegin); 1937 OS.AddComment("Record kind: S_GDATA32"); 1938 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2); 1939 OS.AddComment("Type"); 1940 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4); 1941 OS.AddComment("DataOffset"); 1942 OS.EmitCOFFSecRel32(GVSym); 1943 OS.AddComment("Segment"); 1944 OS.EmitCOFFSectionIndex(GVSym); 1945 OS.AddComment("Name"); 1946 emitNullTerminatedSymbolName(OS, DIGV->getName()); 1947 OS.EmitLabel(DataEnd); 1948 } 1949