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/TargetSubtargetInfo.h" 28 #include "llvm/Target/TargetRegisterInfo.h" 29 #include "llvm/Target/TargetFrameLowering.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 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) { 127 // It's possible to ask for the FuncId of a function which doesn't have a 128 // subprogram: inlining a function with debug info into a function with none. 129 if (!SP) 130 return TypeIndex::None(); 131 132 // Check if we've already translated this subprogram. 133 auto I = TypeIndices.find(SP); 134 if (I != TypeIndices.end()) 135 return I->second; 136 137 TypeIndex ParentScope = TypeIndex(0); 138 StringRef DisplayName = SP->getDisplayName(); 139 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName); 140 TypeIndex TI = TypeTable.writeFuncId(FuncId); 141 142 recordTypeIndexForDINode(SP, TI); 143 return TI; 144 } 145 146 void CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI) { 147 auto InsertResult = TypeIndices.insert({Node, TI}); 148 (void)InsertResult; 149 assert(InsertResult.second && "DINode was already assigned a type index"); 150 } 151 152 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var, 153 const DILocation *InlinedAt) { 154 if (InlinedAt) { 155 // This variable was inlined. Associate it with the InlineSite. 156 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram(); 157 InlineSite &Site = getInlineSite(InlinedAt, Inlinee); 158 Site.InlinedLocals.emplace_back(Var); 159 } else { 160 // This variable goes in the main ProcSym. 161 CurFn->Locals.emplace_back(Var); 162 } 163 } 164 165 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs, 166 const DILocation *Loc) { 167 auto B = Locs.begin(), E = Locs.end(); 168 if (std::find(B, E, Loc) == E) 169 Locs.push_back(Loc); 170 } 171 172 void CodeViewDebug::maybeRecordLocation(DebugLoc DL, 173 const MachineFunction *MF) { 174 // Skip this instruction if it has the same location as the previous one. 175 if (DL == CurFn->LastLoc) 176 return; 177 178 const DIScope *Scope = DL.get()->getScope(); 179 if (!Scope) 180 return; 181 182 // Skip this line if it is longer than the maximum we can record. 183 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true); 184 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() || 185 LI.isNeverStepInto()) 186 return; 187 188 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0); 189 if (CI.getStartColumn() != DL.getCol()) 190 return; 191 192 if (!CurFn->HaveLineInfo) 193 CurFn->HaveLineInfo = true; 194 unsigned FileId = 0; 195 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile()) 196 FileId = CurFn->LastFileId; 197 else 198 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile()); 199 CurFn->LastLoc = DL; 200 201 unsigned FuncId = CurFn->FuncId; 202 if (const DILocation *SiteLoc = DL->getInlinedAt()) { 203 const DILocation *Loc = DL.get(); 204 205 // If this location was actually inlined from somewhere else, give it the ID 206 // of the inline call site. 207 FuncId = 208 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId; 209 210 // Ensure we have links in the tree of inline call sites. 211 bool FirstLoc = true; 212 while ((SiteLoc = Loc->getInlinedAt())) { 213 InlineSite &Site = 214 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()); 215 if (!FirstLoc) 216 addLocIfNotPresent(Site.ChildSites, Loc); 217 FirstLoc = false; 218 Loc = SiteLoc; 219 } 220 addLocIfNotPresent(CurFn->ChildSites, Loc); 221 } 222 223 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(), 224 /*PrologueEnd=*/false, 225 /*IsStmt=*/false, DL->getFilename()); 226 } 227 228 void CodeViewDebug::emitCodeViewMagicVersion() { 229 OS.EmitValueToAlignment(4); 230 OS.AddComment("Debug section magic"); 231 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4); 232 } 233 234 void CodeViewDebug::endModule() { 235 if (FnDebugInfo.empty()) 236 return; 237 238 assert(Asm != nullptr); 239 240 // The COFF .debug$S section consists of several subsections, each starting 241 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length 242 // of the payload followed by the payload itself. The subsections are 4-byte 243 // aligned. 244 245 // Make a subsection for all the inlined subprograms. 246 emitInlineeLinesSubsection(); 247 248 // Emit per-function debug information. 249 for (auto &P : FnDebugInfo) 250 emitDebugInfoForFunction(P.first, P.second); 251 252 // Switch back to the generic .debug$S section after potentially processing 253 // comdat symbol sections. 254 switchToDebugSectionForSymbol(nullptr); 255 256 // This subsection holds a file index to offset in string table table. 257 OS.AddComment("File index to string table offset subsection"); 258 OS.EmitCVFileChecksumsDirective(); 259 260 // This subsection holds the string table. 261 OS.AddComment("String table"); 262 OS.EmitCVStringTableDirective(); 263 264 // Emit type information last, so that any types we translate while emitting 265 // function info are included. 266 emitTypeInformation(); 267 268 clear(); 269 } 270 271 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) { 272 // Microsoft's linker seems to have trouble with symbol names longer than 273 // 0xffd8 bytes. 274 S = S.substr(0, 0xffd8); 275 SmallString<32> NullTerminatedString(S); 276 NullTerminatedString.push_back('\0'); 277 OS.EmitBytes(NullTerminatedString); 278 } 279 280 void CodeViewDebug::emitTypeInformation() { 281 // Do nothing if we have no debug info or if no non-trivial types were emitted 282 // to TypeTable during codegen. 283 NamedMDNode *CU_Nodes = 284 MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 285 if (!CU_Nodes) 286 return; 287 if (TypeTable.empty()) 288 return; 289 290 // Start the .debug$T section with 0x4. 291 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection()); 292 emitCodeViewMagicVersion(); 293 294 SmallString<8> CommentPrefix; 295 if (OS.isVerboseAsm()) { 296 CommentPrefix += '\t'; 297 CommentPrefix += Asm->MAI->getCommentString(); 298 CommentPrefix += ' '; 299 } 300 301 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false); 302 TypeTable.ForEachRecord( 303 [&](TypeIndex Index, StringRef Record) { 304 if (OS.isVerboseAsm()) { 305 // Emit a block comment describing the type record for readability. 306 SmallString<512> CommentBlock; 307 raw_svector_ostream CommentOS(CommentBlock); 308 ScopedPrinter SP(CommentOS); 309 SP.setPrefix(CommentPrefix); 310 CVTD.setPrinter(&SP); 311 bool DumpSuccess = 312 CVTD.dump({Record.bytes_begin(), Record.bytes_end()}); 313 (void)DumpSuccess; 314 assert(DumpSuccess && "produced malformed type record"); 315 // emitRawComment will insert its own tab and comment string before 316 // the first line, so strip off our first one. It also prints its own 317 // newline. 318 OS.emitRawComment( 319 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim()); 320 } 321 OS.EmitBinaryData(Record); 322 }); 323 } 324 325 void CodeViewDebug::emitInlineeLinesSubsection() { 326 if (InlinedSubprograms.empty()) 327 return; 328 329 // Use the generic .debug$S section. 330 switchToDebugSectionForSymbol(nullptr); 331 332 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(), 333 *InlineEnd = MMI->getContext().createTempSymbol(); 334 335 OS.AddComment("Inlinee lines subsection"); 336 OS.EmitIntValue(unsigned(ModuleSubstreamKind::InlineeLines), 4); 337 OS.AddComment("Subsection size"); 338 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 4); 339 OS.EmitLabel(InlineBegin); 340 341 // We don't provide any extra file info. 342 // FIXME: Find out if debuggers use this info. 343 OS.AddComment("Inlinee lines signature"); 344 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4); 345 346 for (const DISubprogram *SP : InlinedSubprograms) { 347 assert(TypeIndices.count(SP)); 348 TypeIndex InlineeIdx = TypeIndices[SP]; 349 350 OS.AddBlankLine(); 351 unsigned FileId = maybeRecordFile(SP->getFile()); 352 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " + 353 SP->getFilename() + Twine(':') + Twine(SP->getLine())); 354 OS.AddBlankLine(); 355 // The filechecksum table uses 8 byte entries for now, and file ids start at 356 // 1. 357 unsigned FileOffset = (FileId - 1) * 8; 358 OS.AddComment("Type index of inlined function"); 359 OS.EmitIntValue(InlineeIdx.getIndex(), 4); 360 OS.AddComment("Offset into filechecksum table"); 361 OS.EmitIntValue(FileOffset, 4); 362 OS.AddComment("Starting line number"); 363 OS.EmitIntValue(SP->getLine(), 4); 364 } 365 366 OS.EmitLabel(InlineEnd); 367 } 368 369 void CodeViewDebug::collectInlineSiteChildren( 370 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI, 371 const InlineSite &Site) { 372 for (const DILocation *ChildSiteLoc : Site.ChildSites) { 373 auto I = FI.InlineSites.find(ChildSiteLoc); 374 const InlineSite &ChildSite = I->second; 375 Children.push_back(ChildSite.SiteFuncId); 376 collectInlineSiteChildren(Children, FI, ChildSite); 377 } 378 } 379 380 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI, 381 const DILocation *InlinedAt, 382 const InlineSite &Site) { 383 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(), 384 *InlineEnd = MMI->getContext().createTempSymbol(); 385 386 assert(TypeIndices.count(Site.Inlinee)); 387 TypeIndex InlineeIdx = TypeIndices[Site.Inlinee]; 388 389 // SymbolRecord 390 OS.AddComment("Record length"); 391 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength 392 OS.EmitLabel(InlineBegin); 393 OS.AddComment("Record kind: S_INLINESITE"); 394 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind 395 396 OS.AddComment("PtrParent"); 397 OS.EmitIntValue(0, 4); 398 OS.AddComment("PtrEnd"); 399 OS.EmitIntValue(0, 4); 400 OS.AddComment("Inlinee type index"); 401 OS.EmitIntValue(InlineeIdx.getIndex(), 4); 402 403 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile()); 404 unsigned StartLineNum = Site.Inlinee->getLine(); 405 SmallVector<unsigned, 3> SecondaryFuncIds; 406 collectInlineSiteChildren(SecondaryFuncIds, FI, Site); 407 408 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum, 409 FI.Begin, FI.End, SecondaryFuncIds); 410 411 OS.EmitLabel(InlineEnd); 412 413 for (const LocalVariable &Var : Site.InlinedLocals) 414 emitLocalVariable(Var); 415 416 // Recurse on child inlined call sites before closing the scope. 417 for (const DILocation *ChildSite : Site.ChildSites) { 418 auto I = FI.InlineSites.find(ChildSite); 419 assert(I != FI.InlineSites.end() && 420 "child site not in function inline site map"); 421 emitInlinedCallSite(FI, ChildSite, I->second); 422 } 423 424 // Close the scope. 425 OS.AddComment("Record length"); 426 OS.EmitIntValue(2, 2); // RecordLength 427 OS.AddComment("Record kind: S_INLINESITE_END"); 428 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind 429 } 430 431 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) { 432 // If we have a symbol, it may be in a section that is COMDAT. If so, find the 433 // comdat key. A section may be comdat because of -ffunction-sections or 434 // because it is comdat in the IR. 435 MCSectionCOFF *GVSec = 436 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr; 437 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr; 438 439 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>( 440 Asm->getObjFileLowering().getCOFFDebugSymbolsSection()); 441 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym); 442 443 OS.SwitchSection(DebugSec); 444 445 // Emit the magic version number if this is the first time we've switched to 446 // this section. 447 if (ComdatDebugSections.insert(DebugSec).second) 448 emitCodeViewMagicVersion(); 449 } 450 451 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, 452 FunctionInfo &FI) { 453 // For each function there is a separate subsection 454 // which holds the PC to file:line table. 455 const MCSymbol *Fn = Asm->getSymbol(GV); 456 assert(Fn); 457 458 // Switch to the to a comdat section, if appropriate. 459 switchToDebugSectionForSymbol(Fn); 460 461 StringRef FuncName; 462 if (auto *SP = GV->getSubprogram()) 463 FuncName = SP->getDisplayName(); 464 465 // If our DISubprogram name is empty, use the mangled name. 466 if (FuncName.empty()) 467 FuncName = GlobalValue::getRealLinkageName(GV->getName()); 468 469 // Emit a symbol subsection, required by VS2012+ to find function boundaries. 470 MCSymbol *SymbolsBegin = MMI->getContext().createTempSymbol(), 471 *SymbolsEnd = MMI->getContext().createTempSymbol(); 472 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 473 OS.EmitIntValue(unsigned(ModuleSubstreamKind::Symbols), 4); 474 OS.AddComment("Subsection size"); 475 OS.emitAbsoluteSymbolDiff(SymbolsEnd, SymbolsBegin, 4); 476 OS.EmitLabel(SymbolsBegin); 477 { 478 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(), 479 *ProcRecordEnd = MMI->getContext().createTempSymbol(); 480 OS.AddComment("Record length"); 481 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2); 482 OS.EmitLabel(ProcRecordBegin); 483 484 OS.AddComment("Record kind: S_GPROC32_ID"); 485 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2); 486 487 // These fields are filled in by tools like CVPACK which run after the fact. 488 OS.AddComment("PtrParent"); 489 OS.EmitIntValue(0, 4); 490 OS.AddComment("PtrEnd"); 491 OS.EmitIntValue(0, 4); 492 OS.AddComment("PtrNext"); 493 OS.EmitIntValue(0, 4); 494 // This is the important bit that tells the debugger where the function 495 // code is located and what's its size: 496 OS.AddComment("Code size"); 497 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4); 498 OS.AddComment("Offset after prologue"); 499 OS.EmitIntValue(0, 4); 500 OS.AddComment("Offset before epilogue"); 501 OS.EmitIntValue(0, 4); 502 OS.AddComment("Function type index"); 503 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4); 504 OS.AddComment("Function section relative address"); 505 OS.EmitCOFFSecRel32(Fn); 506 OS.AddComment("Function section index"); 507 OS.EmitCOFFSectionIndex(Fn); 508 OS.AddComment("Flags"); 509 OS.EmitIntValue(0, 1); 510 // Emit the function display name as a null-terminated string. 511 OS.AddComment("Function name"); 512 // Truncate the name so we won't overflow the record length field. 513 emitNullTerminatedSymbolName(OS, FuncName); 514 OS.EmitLabel(ProcRecordEnd); 515 516 for (const LocalVariable &Var : FI.Locals) 517 emitLocalVariable(Var); 518 519 // Emit inlined call site information. Only emit functions inlined directly 520 // into the parent function. We'll emit the other sites recursively as part 521 // of their parent inline site. 522 for (const DILocation *InlinedAt : FI.ChildSites) { 523 auto I = FI.InlineSites.find(InlinedAt); 524 assert(I != FI.InlineSites.end() && 525 "child site not in function inline site map"); 526 emitInlinedCallSite(FI, InlinedAt, I->second); 527 } 528 529 // We're done with this function. 530 OS.AddComment("Record length"); 531 OS.EmitIntValue(0x0002, 2); 532 OS.AddComment("Record kind: S_PROC_ID_END"); 533 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2); 534 } 535 OS.EmitLabel(SymbolsEnd); 536 // Every subsection must be aligned to a 4-byte boundary. 537 OS.EmitValueToAlignment(4); 538 539 // We have an assembler directive that takes care of the whole line table. 540 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End); 541 } 542 543 CodeViewDebug::LocalVarDefRange 544 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) { 545 LocalVarDefRange DR; 546 DR.InMemory = -1; 547 DR.DataOffset = Offset; 548 assert(DR.DataOffset == Offset && "truncation"); 549 DR.StructOffset = 0; 550 DR.CVRegister = CVRegister; 551 return DR; 552 } 553 554 CodeViewDebug::LocalVarDefRange 555 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) { 556 LocalVarDefRange DR; 557 DR.InMemory = 0; 558 DR.DataOffset = 0; 559 DR.StructOffset = 0; 560 DR.CVRegister = CVRegister; 561 return DR; 562 } 563 564 void CodeViewDebug::collectVariableInfoFromMMITable( 565 DenseSet<InlinedVariable> &Processed) { 566 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget(); 567 const TargetFrameLowering *TFI = TSI.getFrameLowering(); 568 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 569 570 for (const MachineModuleInfo::VariableDbgInfo &VI : 571 MMI->getVariableDbgInfo()) { 572 if (!VI.Var) 573 continue; 574 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 575 "Expected inlined-at fields to agree"); 576 577 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt())); 578 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 579 580 // If variable scope is not found then skip this variable. 581 if (!Scope) 582 continue; 583 584 // Get the frame register used and the offset. 585 unsigned FrameReg = 0; 586 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg); 587 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); 588 589 // Calculate the label ranges. 590 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset); 591 for (const InsnRange &Range : Scope->getRanges()) { 592 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 593 const MCSymbol *End = getLabelAfterInsn(Range.second); 594 End = End ? End : Asm->getFunctionEnd(); 595 DefRange.Ranges.emplace_back(Begin, End); 596 } 597 598 LocalVariable Var; 599 Var.DIVar = VI.Var; 600 Var.DefRanges.emplace_back(std::move(DefRange)); 601 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt()); 602 } 603 } 604 605 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) { 606 DenseSet<InlinedVariable> Processed; 607 // Grab the variable info that was squirreled away in the MMI side-table. 608 collectVariableInfoFromMMITable(Processed); 609 610 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 611 612 for (const auto &I : DbgValues) { 613 InlinedVariable IV = I.first; 614 if (Processed.count(IV)) 615 continue; 616 const DILocalVariable *DIVar = IV.first; 617 const DILocation *InlinedAt = IV.second; 618 619 // Instruction ranges, specifying where IV is accessible. 620 const auto &Ranges = I.second; 621 622 LexicalScope *Scope = nullptr; 623 if (InlinedAt) 624 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt); 625 else 626 Scope = LScopes.findLexicalScope(DIVar->getScope()); 627 // If variable scope is not found then skip this variable. 628 if (!Scope) 629 continue; 630 631 LocalVariable Var; 632 Var.DIVar = DIVar; 633 634 // Calculate the definition ranges. 635 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 636 const InsnRange &Range = *I; 637 const MachineInstr *DVInst = Range.first; 638 assert(DVInst->isDebugValue() && "Invalid History entry"); 639 const DIExpression *DIExpr = DVInst->getDebugExpression(); 640 641 // Bail if there is a complex DWARF expression for now. 642 if (DIExpr && DIExpr->getNumElements() > 0) 643 continue; 644 645 // Bail if operand 0 is not a valid register. This means the variable is a 646 // simple constant, or is described by a complex expression. 647 // FIXME: Find a way to represent constant variables, since they are 648 // relatively common. 649 unsigned Reg = 650 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0; 651 if (Reg == 0) 652 continue; 653 654 // Handle the two cases we can handle: indirect in memory and in register. 655 bool IsIndirect = DVInst->getOperand(1).isImm(); 656 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg()); 657 { 658 LocalVarDefRange DefRange; 659 if (IsIndirect) { 660 int64_t Offset = DVInst->getOperand(1).getImm(); 661 DefRange = createDefRangeMem(CVReg, Offset); 662 } else { 663 DefRange = createDefRangeReg(CVReg); 664 } 665 if (Var.DefRanges.empty() || 666 Var.DefRanges.back().isDifferentLocation(DefRange)) { 667 Var.DefRanges.emplace_back(std::move(DefRange)); 668 } 669 } 670 671 // Compute the label range. 672 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 673 const MCSymbol *End = getLabelAfterInsn(Range.second); 674 if (!End) { 675 if (std::next(I) != E) 676 End = getLabelBeforeInsn(std::next(I)->first); 677 else 678 End = Asm->getFunctionEnd(); 679 } 680 681 // If the last range end is our begin, just extend the last range. 682 // Otherwise make a new range. 683 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges = 684 Var.DefRanges.back().Ranges; 685 if (!Ranges.empty() && Ranges.back().second == Begin) 686 Ranges.back().second = End; 687 else 688 Ranges.emplace_back(Begin, End); 689 690 // FIXME: Do more range combining. 691 } 692 693 recordLocalVariable(std::move(Var), InlinedAt); 694 } 695 } 696 697 void CodeViewDebug::beginFunction(const MachineFunction *MF) { 698 assert(!CurFn && "Can't process two functions at once!"); 699 700 if (!Asm || !MMI->hasDebugInfo()) 701 return; 702 703 DebugHandlerBase::beginFunction(MF); 704 705 const Function *GV = MF->getFunction(); 706 assert(FnDebugInfo.count(GV) == false); 707 CurFn = &FnDebugInfo[GV]; 708 CurFn->FuncId = NextFuncId++; 709 CurFn->Begin = Asm->getFunctionBegin(); 710 711 // Find the end of the function prolog. First known non-DBG_VALUE and 712 // non-frame setup location marks the beginning of the function body. 713 // FIXME: is there a simpler a way to do this? Can we just search 714 // for the first instruction of the function, not the last of the prolog? 715 DebugLoc PrologEndLoc; 716 bool EmptyPrologue = true; 717 for (const auto &MBB : *MF) { 718 for (const auto &MI : MBB) { 719 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) && 720 MI.getDebugLoc()) { 721 PrologEndLoc = MI.getDebugLoc(); 722 break; 723 } else if (!MI.isDebugValue()) { 724 EmptyPrologue = false; 725 } 726 } 727 } 728 729 // Record beginning of function if we have a non-empty prologue. 730 if (PrologEndLoc && !EmptyPrologue) { 731 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc(); 732 maybeRecordLocation(FnStartDL, MF); 733 } 734 } 735 736 TypeIndex CodeViewDebug::lowerType(const DIType *Ty) { 737 // Generic dispatch for lowering an unknown type. 738 switch (Ty->getTag()) { 739 case dwarf::DW_TAG_typedef: 740 return lowerTypeAlias(cast<DIDerivedType>(Ty)); 741 case dwarf::DW_TAG_base_type: 742 return lowerTypeBasic(cast<DIBasicType>(Ty)); 743 case dwarf::DW_TAG_pointer_type: 744 case dwarf::DW_TAG_reference_type: 745 case dwarf::DW_TAG_rvalue_reference_type: 746 return lowerTypePointer(cast<DIDerivedType>(Ty)); 747 case dwarf::DW_TAG_ptr_to_member_type: 748 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty)); 749 case dwarf::DW_TAG_const_type: 750 case dwarf::DW_TAG_volatile_type: 751 return lowerTypeModifier(cast<DIDerivedType>(Ty)); 752 case dwarf::DW_TAG_subroutine_type: 753 return lowerTypeFunction(cast<DISubroutineType>(Ty)); 754 case dwarf::DW_TAG_class_type: 755 case dwarf::DW_TAG_structure_type: 756 return lowerTypeClass(cast<DICompositeType>(Ty)); 757 case dwarf::DW_TAG_union_type: 758 return lowerTypeUnion(cast<DICompositeType>(Ty)); 759 default: 760 // Use the null type index. 761 return TypeIndex(); 762 } 763 } 764 765 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) { 766 // TODO: MSVC emits a S_UDT record. 767 DITypeRef UnderlyingTypeRef = Ty->getBaseType(); 768 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef); 769 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) && 770 Ty->getName() == "HRESULT") 771 return TypeIndex(SimpleTypeKind::HResult); 772 return UnderlyingTypeIndex; 773 } 774 775 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) { 776 TypeIndex Index; 777 dwarf::TypeKind Kind; 778 uint32_t ByteSize; 779 780 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding()); 781 ByteSize = Ty->getSizeInBits() / 8; 782 783 SimpleTypeKind STK = SimpleTypeKind::None; 784 switch (Kind) { 785 case dwarf::DW_ATE_address: 786 // FIXME: Translate 787 break; 788 case dwarf::DW_ATE_boolean: 789 switch (ByteSize) { 790 case 1: STK = SimpleTypeKind::Boolean8; break; 791 case 2: STK = SimpleTypeKind::Boolean16; break; 792 case 4: STK = SimpleTypeKind::Boolean32; break; 793 case 8: STK = SimpleTypeKind::Boolean64; break; 794 case 16: STK = SimpleTypeKind::Boolean128; break; 795 } 796 break; 797 case dwarf::DW_ATE_complex_float: 798 switch (ByteSize) { 799 case 2: STK = SimpleTypeKind::Complex16; break; 800 case 4: STK = SimpleTypeKind::Complex32; break; 801 case 8: STK = SimpleTypeKind::Complex64; break; 802 case 10: STK = SimpleTypeKind::Complex80; break; 803 case 16: STK = SimpleTypeKind::Complex128; break; 804 } 805 break; 806 case dwarf::DW_ATE_float: 807 switch (ByteSize) { 808 case 2: STK = SimpleTypeKind::Float16; break; 809 case 4: STK = SimpleTypeKind::Float32; break; 810 case 6: STK = SimpleTypeKind::Float48; break; 811 case 8: STK = SimpleTypeKind::Float64; break; 812 case 10: STK = SimpleTypeKind::Float80; break; 813 case 16: STK = SimpleTypeKind::Float128; break; 814 } 815 break; 816 case dwarf::DW_ATE_signed: 817 switch (ByteSize) { 818 case 1: STK = SimpleTypeKind::SByte; break; 819 case 2: STK = SimpleTypeKind::Int16Short; break; 820 case 4: STK = SimpleTypeKind::Int32; break; 821 case 8: STK = SimpleTypeKind::Int64Quad; break; 822 case 16: STK = SimpleTypeKind::Int128Oct; break; 823 } 824 break; 825 case dwarf::DW_ATE_unsigned: 826 switch (ByteSize) { 827 case 1: STK = SimpleTypeKind::Byte; break; 828 case 2: STK = SimpleTypeKind::UInt16Short; break; 829 case 4: STK = SimpleTypeKind::UInt32; break; 830 case 8: STK = SimpleTypeKind::UInt64Quad; break; 831 case 16: STK = SimpleTypeKind::UInt128Oct; break; 832 } 833 break; 834 case dwarf::DW_ATE_UTF: 835 switch (ByteSize) { 836 case 2: STK = SimpleTypeKind::Character16; break; 837 case 4: STK = SimpleTypeKind::Character32; break; 838 } 839 break; 840 case dwarf::DW_ATE_signed_char: 841 if (ByteSize == 1) 842 STK = SimpleTypeKind::SignedCharacter; 843 break; 844 case dwarf::DW_ATE_unsigned_char: 845 if (ByteSize == 1) 846 STK = SimpleTypeKind::UnsignedCharacter; 847 break; 848 default: 849 break; 850 } 851 852 // Apply some fixups based on the source-level type name. 853 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int") 854 STK = SimpleTypeKind::Int32Long; 855 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int") 856 STK = SimpleTypeKind::UInt32Long; 857 if ((STK == SimpleTypeKind::Int16Short || 858 STK == SimpleTypeKind::UInt16Short) && 859 Ty->getName() == "wchar_t") 860 STK = SimpleTypeKind::WideCharacter; 861 if ((STK == SimpleTypeKind::SignedCharacter || 862 STK == SimpleTypeKind::UnsignedCharacter) && 863 Ty->getName() == "char") 864 STK = SimpleTypeKind::NarrowCharacter; 865 866 return TypeIndex(STK); 867 } 868 869 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) { 870 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType()); 871 872 // Pointers to simple types can use SimpleTypeMode, rather than having a 873 // dedicated pointer type record. 874 if (PointeeTI.isSimple() && 875 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct && 876 Ty->getTag() == dwarf::DW_TAG_pointer_type) { 877 SimpleTypeMode Mode = Ty->getSizeInBits() == 64 878 ? SimpleTypeMode::NearPointer64 879 : SimpleTypeMode::NearPointer32; 880 return TypeIndex(PointeeTI.getSimpleKind(), Mode); 881 } 882 883 PointerKind PK = 884 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32; 885 PointerMode PM = PointerMode::Pointer; 886 switch (Ty->getTag()) { 887 default: llvm_unreachable("not a pointer tag type"); 888 case dwarf::DW_TAG_pointer_type: 889 PM = PointerMode::Pointer; 890 break; 891 case dwarf::DW_TAG_reference_type: 892 PM = PointerMode::LValueReference; 893 break; 894 case dwarf::DW_TAG_rvalue_reference_type: 895 PM = PointerMode::RValueReference; 896 break; 897 } 898 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method 899 // 'this' pointer, but not normal contexts. Figure out what we're supposed to 900 // do. 901 PointerOptions PO = PointerOptions::None; 902 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8); 903 return TypeTable.writePointer(PR); 904 } 905 906 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) { 907 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type); 908 TypeIndex ClassTI = getTypeIndex(Ty->getClassType()); 909 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType()); 910 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64 911 : PointerKind::Near32; 912 PointerMode PM = isa<DISubroutineType>(Ty->getBaseType()) 913 ? PointerMode::PointerToMemberFunction 914 : PointerMode::PointerToDataMember; 915 PointerOptions PO = PointerOptions::None; // FIXME 916 // FIXME: Thread this ABI info through metadata. 917 PointerToMemberRepresentation PMR = PointerToMemberRepresentation::Unknown; 918 MemberPointerInfo MPI(ClassTI, PMR); 919 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8, MPI); 920 return TypeTable.writePointer(PR); 921 } 922 923 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) { 924 ModifierOptions Mods = ModifierOptions::None; 925 bool IsModifier = true; 926 const DIType *BaseTy = Ty; 927 while (IsModifier && BaseTy) { 928 // FIXME: Need to add DWARF tag for __unaligned. 929 switch (BaseTy->getTag()) { 930 case dwarf::DW_TAG_const_type: 931 Mods |= ModifierOptions::Const; 932 break; 933 case dwarf::DW_TAG_volatile_type: 934 Mods |= ModifierOptions::Volatile; 935 break; 936 default: 937 IsModifier = false; 938 break; 939 } 940 if (IsModifier) 941 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve(); 942 } 943 TypeIndex ModifiedTI = getTypeIndex(BaseTy); 944 ModifierRecord MR(ModifiedTI, Mods); 945 return TypeTable.writeModifier(MR); 946 } 947 948 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) { 949 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; 950 for (DITypeRef ArgTypeRef : Ty->getTypeArray()) 951 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef)); 952 953 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 954 ArrayRef<TypeIndex> ArgTypeIndices = None; 955 if (!ReturnAndArgTypeIndices.empty()) { 956 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices); 957 ReturnTypeIndex = ReturnAndArgTypesRef.front(); 958 ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); 959 } 960 961 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 962 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec); 963 964 // TODO: We should use DW_AT_calling_convention to determine what CC this 965 // procedure record should have. 966 // TODO: Some functions are member functions, we should use a more appropriate 967 // record for those. 968 ProcedureRecord Procedure(ReturnTypeIndex, CallingConvention::NearC, 969 FunctionOptions::None, ArgTypeIndices.size(), 970 ArgListIndex); 971 return TypeTable.writeProcedure(Procedure); 972 } 973 974 static MemberAccess translateAccessFlags(unsigned RecordTag, 975 const DIType *Member) { 976 switch (Member->getFlags() & DINode::FlagAccessibility) { 977 case DINode::FlagPrivate: return MemberAccess::Private; 978 case DINode::FlagPublic: return MemberAccess::Public; 979 case DINode::FlagProtected: return MemberAccess::Protected; 980 case 0: 981 // If there was no explicit access control, provide the default for the tag. 982 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private 983 : MemberAccess::Public; 984 } 985 llvm_unreachable("access flags are exclusive"); 986 } 987 988 static TypeRecordKind getRecordKind(const DICompositeType *Ty) { 989 switch (Ty->getTag()) { 990 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class; 991 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct; 992 } 993 llvm_unreachable("unexpected tag"); 994 } 995 996 /// Return the HasUniqueName option if it should be present in ClassOptions, or 997 /// None otherwise. 998 static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) { 999 // MSVC always sets this flag now, even for local types. Clang doesn't always 1000 // appear to give every type a linkage name, which may be problematic for us. 1001 // FIXME: Investigate the consequences of not following them here. 1002 return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName 1003 : ClassOptions::None; 1004 } 1005 1006 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) { 1007 // First, construct the forward decl. Don't look into Ty to compute the 1008 // forward decl options, since it might not be available in all TUs. 1009 TypeRecordKind Kind = getRecordKind(Ty); 1010 ClassOptions CO = 1011 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty); 1012 TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord( 1013 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(), 1014 TypeIndex(), TypeIndex(), 0, Ty->getName(), Ty->getIdentifier())); 1015 return FwdDeclTI; 1016 } 1017 1018 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) { 1019 // Construct the field list and complete type record. 1020 TypeRecordKind Kind = getRecordKind(Ty); 1021 // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass. 1022 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty); 1023 TypeIndex FTI; 1024 unsigned FieldCount; 1025 std::tie(FTI, FieldCount) = lowerRecordFieldList(Ty); 1026 1027 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 1028 return TypeTable.writeClass(ClassRecord(Kind, FieldCount, CO, HfaKind::None, 1029 WindowsRTClassKind::None, FTI, 1030 TypeIndex(), TypeIndex(), SizeInBytes, 1031 Ty->getName(), Ty->getIdentifier())); 1032 // FIXME: Make an LF_UDT_SRC_LINE record. 1033 } 1034 1035 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) { 1036 ClassOptions CO = 1037 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty); 1038 TypeIndex FwdDeclTI = 1039 TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0, 1040 Ty->getName(), Ty->getIdentifier())); 1041 return FwdDeclTI; 1042 } 1043 1044 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) { 1045 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty); 1046 TypeIndex FTI; 1047 unsigned FieldCount; 1048 std::tie(FTI, FieldCount) = lowerRecordFieldList(Ty); 1049 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 1050 return TypeTable.writeUnion(UnionRecord(FieldCount, CO, HfaKind::None, FTI, 1051 SizeInBytes, Ty->getName(), 1052 Ty->getIdentifier())); 1053 // FIXME: Make an LF_UDT_SRC_LINE record. 1054 } 1055 1056 std::pair<TypeIndex, unsigned> 1057 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) { 1058 // Manually count members. MSVC appears to count everything that generates a 1059 // field list record. Each individual overload in a method overload group 1060 // contributes to this count, even though the overload group is a single field 1061 // list record. 1062 unsigned MemberCount = 0; 1063 FieldListRecordBuilder Fields; 1064 for (const DINode *Element : Ty->getElements()) { 1065 // We assume that the frontend provides all members in source declaration 1066 // order, which is what MSVC does. 1067 if (!Element) 1068 continue; 1069 if (auto *SP = dyn_cast<DISubprogram>(Element)) { 1070 // C++ method. 1071 // FIXME: Overloaded methods are grouped together, so we'll need two 1072 // passes to group them. 1073 (void)SP; 1074 } else if (auto *Member = dyn_cast<DIDerivedType>(Element)) { 1075 if (Member->getTag() == dwarf::DW_TAG_member) { 1076 if (Member->isStaticMember()) { 1077 // Static data member. 1078 Fields.writeStaticDataMember(StaticDataMemberRecord( 1079 translateAccessFlags(Ty->getTag(), Member), 1080 getTypeIndex(Member->getBaseType()), Member->getName())); 1081 MemberCount++; 1082 } else { 1083 // Data member. 1084 // FIXME: Make a BitFieldRecord for bitfields. 1085 Fields.writeDataMember(DataMemberRecord( 1086 translateAccessFlags(Ty->getTag(), Member), 1087 getTypeIndex(Member->getBaseType()), 1088 Member->getOffsetInBits() / 8, Member->getName())); 1089 MemberCount++; 1090 } 1091 } else if (Member->getTag() == dwarf::DW_TAG_friend) { 1092 // Ignore friend members. It appears that MSVC emitted info about 1093 // friends in the past, but modern versions do not. 1094 } 1095 // FIXME: Get clang to emit nested types here and do something with 1096 // them. 1097 } 1098 // Skip other unrecognized kinds of elements. 1099 } 1100 return {TypeTable.writeFieldList(Fields), MemberCount}; 1101 } 1102 1103 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef) { 1104 const DIType *Ty = TypeRef.resolve(); 1105 1106 // The null DIType is the void type. Don't try to hash it. 1107 if (!Ty) 1108 return TypeIndex::Void(); 1109 1110 // Check if we've already translated this type. Don't try to do a 1111 // get-or-create style insertion that caches the hash lookup across the 1112 // lowerType call. It will update the TypeIndices map. 1113 auto I = TypeIndices.find(Ty); 1114 if (I != TypeIndices.end()) 1115 return I->second; 1116 1117 TypeIndex TI = lowerType(Ty); 1118 1119 recordTypeIndexForDINode(Ty, TI); 1120 return TI; 1121 } 1122 1123 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) { 1124 const DIType *Ty = TypeRef.resolve(); 1125 1126 // The null DIType is the void type. Don't try to hash it. 1127 if (!Ty) 1128 return TypeIndex::Void(); 1129 1130 // If this is a non-record type, the complete type index is the same as the 1131 // normal type index. Just call getTypeIndex. 1132 switch (Ty->getTag()) { 1133 case dwarf::DW_TAG_class_type: 1134 case dwarf::DW_TAG_structure_type: 1135 case dwarf::DW_TAG_union_type: 1136 break; 1137 default: 1138 return getTypeIndex(Ty); 1139 } 1140 1141 // Check if we've already translated the complete record type. Lowering a 1142 // complete type should never trigger lowering another complete type, so we 1143 // can reuse the hash table lookup result. 1144 const auto *CTy = cast<DICompositeType>(Ty); 1145 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()}); 1146 if (!InsertResult.second) 1147 return InsertResult.first->second; 1148 1149 // Make sure the forward declaration is emitted first. It's unclear if this 1150 // is necessary, but MSVC does it, and we should follow suit until we can show 1151 // otherwise. 1152 TypeIndex FwdDeclTI = getTypeIndex(CTy); 1153 1154 // Just use the forward decl if we don't have complete type info. This might 1155 // happen if the frontend is using modules and expects the complete definition 1156 // to be emitted elsewhere. 1157 if (CTy->isForwardDecl()) 1158 return FwdDeclTI; 1159 1160 TypeIndex TI; 1161 switch (CTy->getTag()) { 1162 case dwarf::DW_TAG_class_type: 1163 case dwarf::DW_TAG_structure_type: 1164 TI = lowerCompleteTypeClass(CTy); 1165 break; 1166 case dwarf::DW_TAG_union_type: 1167 TI = lowerCompleteTypeUnion(CTy); 1168 break; 1169 default: 1170 llvm_unreachable("not a record"); 1171 } 1172 1173 InsertResult.first->second = TI; 1174 return TI; 1175 } 1176 1177 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) { 1178 // LocalSym record, see SymbolRecord.h for more info. 1179 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(), 1180 *LocalEnd = MMI->getContext().createTempSymbol(); 1181 OS.AddComment("Record length"); 1182 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2); 1183 OS.EmitLabel(LocalBegin); 1184 1185 OS.AddComment("Record kind: S_LOCAL"); 1186 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2); 1187 1188 LocalSymFlags Flags = LocalSymFlags::None; 1189 if (Var.DIVar->isParameter()) 1190 Flags |= LocalSymFlags::IsParameter; 1191 if (Var.DefRanges.empty()) 1192 Flags |= LocalSymFlags::IsOptimizedOut; 1193 1194 OS.AddComment("TypeIndex"); 1195 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType()); 1196 OS.EmitIntValue(TI.getIndex(), 4); 1197 OS.AddComment("Flags"); 1198 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2); 1199 // Truncate the name so we won't overflow the record length field. 1200 emitNullTerminatedSymbolName(OS, Var.DIVar->getName()); 1201 OS.EmitLabel(LocalEnd); 1202 1203 // Calculate the on disk prefix of the appropriate def range record. The 1204 // records and on disk formats are described in SymbolRecords.h. BytePrefix 1205 // should be big enough to hold all forms without memory allocation. 1206 SmallString<20> BytePrefix; 1207 for (const LocalVarDefRange &DefRange : Var.DefRanges) { 1208 BytePrefix.clear(); 1209 // FIXME: Handle bitpieces. 1210 if (DefRange.StructOffset != 0) 1211 continue; 1212 1213 if (DefRange.InMemory) { 1214 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0, 1215 0, 0, ArrayRef<LocalVariableAddrGap>()); 1216 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL); 1217 BytePrefix += 1218 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 1219 BytePrefix += 1220 StringRef(reinterpret_cast<const char *>(&Sym.Header), 1221 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange)); 1222 } else { 1223 assert(DefRange.DataOffset == 0 && "unexpected offset into register"); 1224 // Unclear what matters here. 1225 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0, 1226 ArrayRef<LocalVariableAddrGap>()); 1227 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER); 1228 BytePrefix += 1229 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 1230 BytePrefix += 1231 StringRef(reinterpret_cast<const char *>(&Sym.Header), 1232 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange)); 1233 } 1234 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix); 1235 } 1236 } 1237 1238 void CodeViewDebug::endFunction(const MachineFunction *MF) { 1239 if (!Asm || !CurFn) // We haven't created any debug info for this function. 1240 return; 1241 1242 const Function *GV = MF->getFunction(); 1243 assert(FnDebugInfo.count(GV)); 1244 assert(CurFn == &FnDebugInfo[GV]); 1245 1246 collectVariableInfo(GV->getSubprogram()); 1247 1248 DebugHandlerBase::endFunction(MF); 1249 1250 // Don't emit anything if we don't have any line tables. 1251 if (!CurFn->HaveLineInfo) { 1252 FnDebugInfo.erase(GV); 1253 CurFn = nullptr; 1254 return; 1255 } 1256 1257 CurFn->End = Asm->getFunctionEnd(); 1258 1259 CurFn = nullptr; 1260 } 1261 1262 void CodeViewDebug::beginInstruction(const MachineInstr *MI) { 1263 DebugHandlerBase::beginInstruction(MI); 1264 1265 // Ignore DBG_VALUE locations and function prologue. 1266 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup)) 1267 return; 1268 DebugLoc DL = MI->getDebugLoc(); 1269 if (DL == PrevInstLoc || !DL) 1270 return; 1271 maybeRecordLocation(DL, Asm->MF); 1272 } 1273