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