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