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