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