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