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