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