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