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