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/Line.h" 17 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 18 #include "llvm/DebugInfo/CodeView/TypeIndex.h" 19 #include "llvm/DebugInfo/CodeView/TypeRecord.h" 20 #include "llvm/MC/MCExpr.h" 21 #include "llvm/MC/MCSymbol.h" 22 #include "llvm/Support/COFF.h" 23 #include "llvm/Target/TargetSubtargetInfo.h" 24 #include "llvm/Target/TargetRegisterInfo.h" 25 #include "llvm/Target/TargetFrameLowering.h" 26 27 using namespace llvm; 28 using namespace llvm::codeview; 29 30 CodeViewDebug::CodeViewDebug(AsmPrinter *AP) 31 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) { 32 // If module doesn't have named metadata anchors or COFF debug section 33 // is not available, skip any debug info related stuff. 34 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") || 35 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) { 36 Asm = nullptr; 37 return; 38 } 39 40 // Tell MMI that we have debug info. 41 MMI->setDebugInfoAvailability(true); 42 } 43 44 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) { 45 std::string &Filepath = FileToFilepathMap[File]; 46 if (!Filepath.empty()) 47 return Filepath; 48 49 StringRef Dir = File->getDirectory(), Filename = File->getFilename(); 50 51 // Clang emits directory and relative filename info into the IR, but CodeView 52 // operates on full paths. We could change Clang to emit full paths too, but 53 // that would increase the IR size and probably not needed for other users. 54 // For now, just concatenate and canonicalize the path here. 55 if (Filename.find(':') == 1) 56 Filepath = Filename; 57 else 58 Filepath = (Dir + "\\" + Filename).str(); 59 60 // Canonicalize the path. We have to do it textually because we may no longer 61 // have access the file in the filesystem. 62 // First, replace all slashes with backslashes. 63 std::replace(Filepath.begin(), Filepath.end(), '/', '\\'); 64 65 // Remove all "\.\" with "\". 66 size_t Cursor = 0; 67 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos) 68 Filepath.erase(Cursor, 2); 69 70 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original 71 // path should be well-formatted, e.g. start with a drive letter, etc. 72 Cursor = 0; 73 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) { 74 // Something's wrong if the path starts with "\..\", abort. 75 if (Cursor == 0) 76 break; 77 78 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1); 79 if (PrevSlash == std::string::npos) 80 // Something's wrong, abort. 81 break; 82 83 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash); 84 // The next ".." might be following the one we've just erased. 85 Cursor = PrevSlash; 86 } 87 88 // Remove all duplicate backslashes. 89 Cursor = 0; 90 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos) 91 Filepath.erase(Cursor, 1); 92 93 return Filepath; 94 } 95 96 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) { 97 unsigned NextId = FileIdMap.size() + 1; 98 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId)); 99 if (Insertion.second) { 100 // We have to compute the full filepath and emit a .cv_file directive. 101 StringRef FullPath = getFullFilepath(F); 102 NextId = OS.EmitCVFileDirective(NextId, FullPath); 103 assert(NextId == FileIdMap.size() && ".cv_file directive failed"); 104 } 105 return Insertion.first->second; 106 } 107 108 CodeViewDebug::InlineSite & 109 CodeViewDebug::getInlineSite(const DILocation *InlinedAt, 110 const DISubprogram *Inlinee) { 111 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()}); 112 InlineSite *Site = &SiteInsertion.first->second; 113 if (SiteInsertion.second) { 114 Site->SiteFuncId = NextFuncId++; 115 Site->Inlinee = Inlinee; 116 auto InlineeInsertion = 117 SubprogramIndices.insert({Inlinee, InlinedSubprograms.size()}); 118 if (InlineeInsertion.second) 119 InlinedSubprograms.push_back(Inlinee); 120 } 121 return *Site; 122 } 123 124 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var, 125 const DILocation *InlinedAt) { 126 if (InlinedAt) { 127 // This variable was inlined. Associate it with the InlineSite. 128 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram(); 129 InlineSite &Site = getInlineSite(InlinedAt, Inlinee); 130 Site.InlinedLocals.emplace_back(Var); 131 } else { 132 // This variable goes in the main ProcSym. 133 CurFn->Locals.emplace_back(Var); 134 } 135 } 136 137 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs, 138 const DILocation *Loc) { 139 auto B = Locs.begin(), E = Locs.end(); 140 if (std::find(B, E, Loc) == E) 141 Locs.push_back(Loc); 142 } 143 144 void CodeViewDebug::maybeRecordLocation(DebugLoc DL, 145 const MachineFunction *MF) { 146 // Skip this instruction if it has the same location as the previous one. 147 if (DL == CurFn->LastLoc) 148 return; 149 150 const DIScope *Scope = DL.get()->getScope(); 151 if (!Scope) 152 return; 153 154 // Skip this line if it is longer than the maximum we can record. 155 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true); 156 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() || 157 LI.isNeverStepInto()) 158 return; 159 160 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0); 161 if (CI.getStartColumn() != DL.getCol()) 162 return; 163 164 if (!CurFn->HaveLineInfo) 165 CurFn->HaveLineInfo = true; 166 unsigned FileId = 0; 167 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile()) 168 FileId = CurFn->LastFileId; 169 else 170 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile()); 171 CurFn->LastLoc = DL; 172 173 unsigned FuncId = CurFn->FuncId; 174 if (const DILocation *SiteLoc = DL->getInlinedAt()) { 175 const DILocation *Loc = DL.get(); 176 177 // If this location was actually inlined from somewhere else, give it the ID 178 // of the inline call site. 179 FuncId = 180 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId; 181 182 // Ensure we have links in the tree of inline call sites. 183 bool FirstLoc = true; 184 while ((SiteLoc = Loc->getInlinedAt())) { 185 InlineSite &Site = 186 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()); 187 if (!FirstLoc) 188 addLocIfNotPresent(Site.ChildSites, Loc); 189 FirstLoc = false; 190 Loc = SiteLoc; 191 } 192 addLocIfNotPresent(CurFn->ChildSites, Loc); 193 } 194 195 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(), 196 /*PrologueEnd=*/false, 197 /*IsStmt=*/false, DL->getFilename()); 198 } 199 200 void CodeViewDebug::endModule() { 201 if (FnDebugInfo.empty()) 202 return; 203 204 emitTypeInformation(); 205 206 // FIXME: For functions that are comdat, we should emit separate .debug$S 207 // sections that are comdat associative with the main function instead of 208 // having one big .debug$S section. 209 assert(Asm != nullptr); 210 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugSymbolsSection()); 211 OS.AddComment("Debug section magic"); 212 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4); 213 214 // The COFF .debug$S section consists of several subsections, each starting 215 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length 216 // of the payload followed by the payload itself. The subsections are 4-byte 217 // aligned. 218 219 // Make a subsection for all the inlined subprograms. 220 emitInlineeFuncIdsAndLines(); 221 222 // Emit per-function debug information. 223 for (auto &P : FnDebugInfo) 224 emitDebugInfoForFunction(P.first, P.second); 225 226 // This subsection holds a file index to offset in string table table. 227 OS.AddComment("File index to string table offset subsection"); 228 OS.EmitCVFileChecksumsDirective(); 229 230 // This subsection holds the string table. 231 OS.AddComment("String table"); 232 OS.EmitCVStringTableDirective(); 233 234 clear(); 235 } 236 237 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) { 238 // Microsoft's linker seems to have trouble with symbol names longer than 239 // 0xffd8 bytes. 240 S = S.substr(0, 0xffd8); 241 SmallString<32> NullTerminatedString(S); 242 NullTerminatedString.push_back('\0'); 243 OS.EmitBytes(NullTerminatedString); 244 } 245 246 void CodeViewDebug::emitTypeInformation() { 247 // Do nothing if we have no debug info or no inlined subprograms. The types 248 // we currently emit exist only to support inlined call site info. 249 NamedMDNode *CU_Nodes = 250 MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 251 if (!CU_Nodes) 252 return; 253 if (InlinedSubprograms.empty()) 254 return; 255 256 // Start the .debug$T section with 0x4. 257 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection()); 258 OS.AddComment("Debug section magic"); 259 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4); 260 261 // This type info currently only holds function ids for use with inline call 262 // frame info. All functions are assigned a simple 'void ()' type. Emit that 263 // type here. 264 unsigned ArgListIndex = getNextTypeIndex(); 265 OS.AddComment("Type record length"); 266 OS.EmitIntValue(2 + sizeof(ArgList), 2); 267 OS.AddComment("Leaf type: LF_ARGLIST"); 268 OS.EmitIntValue(LF_ARGLIST, 2); 269 OS.AddComment("Number of arguments"); 270 OS.EmitIntValue(0, 4); 271 272 unsigned VoidFnTyIdx = getNextTypeIndex(); 273 OS.AddComment("Type record length"); 274 OS.EmitIntValue(2 + sizeof(ProcedureType), 2); 275 OS.AddComment("Leaf type: LF_PROCEDURE"); 276 OS.EmitIntValue(LF_PROCEDURE, 2); 277 OS.AddComment("Return type index"); 278 OS.EmitIntValue(TypeIndex::Void().getIndex(), 4); 279 OS.AddComment("Calling convention"); 280 OS.EmitIntValue(char(CallingConvention::NearC), 1); 281 OS.AddComment("Function options"); 282 OS.EmitIntValue(char(FunctionOptions::None), 1); 283 OS.AddComment("# of parameters"); 284 OS.EmitIntValue(0, 2); 285 OS.AddComment("Argument list type index"); 286 OS.EmitIntValue(ArgListIndex, 4); 287 288 // Emit LF_FUNC_ID records for all inlined subprograms to the type stream. 289 // Allocate one type index for each func id. 290 unsigned NextIdx = getNextTypeIndex(InlinedSubprograms.size()); 291 (void)NextIdx; 292 assert(NextIdx == FuncIdTypeIndexStart && "func id type indices broken"); 293 for (auto *SP : InlinedSubprograms) { 294 StringRef DisplayName = SP->getDisplayName(); 295 OS.AddComment("Type record length"); 296 MCSymbol *FuncBegin = MMI->getContext().createTempSymbol(), 297 *FuncEnd = MMI->getContext().createTempSymbol(); 298 OS.emitAbsoluteSymbolDiff(FuncEnd, FuncBegin, 2); 299 OS.EmitLabel(FuncBegin); 300 OS.AddComment("Leaf type: LF_FUNC_ID"); 301 OS.EmitIntValue(LF_FUNC_ID, 2); 302 303 OS.AddComment("Scope type index"); 304 OS.EmitIntValue(0, 4); 305 OS.AddComment("Function type"); 306 OS.EmitIntValue(VoidFnTyIdx, 4); 307 { 308 OS.AddComment("Function name"); 309 emitNullTerminatedSymbolName(OS, DisplayName); 310 } 311 OS.EmitLabel(FuncEnd); 312 } 313 } 314 315 void CodeViewDebug::emitInlineeFuncIdsAndLines() { 316 if (InlinedSubprograms.empty()) 317 return; 318 319 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(), 320 *InlineEnd = MMI->getContext().createTempSymbol(); 321 322 OS.AddComment("Inlinee lines subsection"); 323 OS.EmitIntValue(unsigned(ModuleSubstreamKind::InlineeLines), 4); 324 OS.AddComment("Subsection size"); 325 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 4); 326 OS.EmitLabel(InlineBegin); 327 328 // We don't provide any extra file info. 329 // FIXME: Find out if debuggers use this info. 330 OS.AddComment("Inlinee lines signature"); 331 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4); 332 333 unsigned InlineeIndex = FuncIdTypeIndexStart; 334 for (const DISubprogram *SP : InlinedSubprograms) { 335 OS.AddBlankLine(); 336 unsigned FileId = maybeRecordFile(SP->getFile()); 337 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " + 338 SP->getFilename() + Twine(':') + Twine(SP->getLine())); 339 OS.AddBlankLine(); 340 // The filechecksum table uses 8 byte entries for now, and file ids start at 341 // 1. 342 unsigned FileOffset = (FileId - 1) * 8; 343 OS.AddComment("Type index of inlined function"); 344 OS.EmitIntValue(InlineeIndex, 4); 345 OS.AddComment("Offset into filechecksum table"); 346 OS.EmitIntValue(FileOffset, 4); 347 OS.AddComment("Starting line number"); 348 OS.EmitIntValue(SP->getLine(), 4); 349 350 // The next inlined subprogram has the next function id. 351 InlineeIndex++; 352 } 353 354 OS.EmitLabel(InlineEnd); 355 } 356 357 void CodeViewDebug::collectInlineSiteChildren( 358 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI, 359 const InlineSite &Site) { 360 for (const DILocation *ChildSiteLoc : Site.ChildSites) { 361 auto I = FI.InlineSites.find(ChildSiteLoc); 362 const InlineSite &ChildSite = I->second; 363 Children.push_back(ChildSite.SiteFuncId); 364 collectInlineSiteChildren(Children, FI, ChildSite); 365 } 366 } 367 368 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI, 369 const DILocation *InlinedAt, 370 const InlineSite &Site) { 371 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(), 372 *InlineEnd = MMI->getContext().createTempSymbol(); 373 374 assert(SubprogramIndices.count(Site.Inlinee)); 375 unsigned InlineeIdx = FuncIdTypeIndexStart + SubprogramIndices[Site.Inlinee]; 376 377 // SymbolRecord 378 OS.AddComment("Record length"); 379 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength 380 OS.EmitLabel(InlineBegin); 381 OS.AddComment("Record kind: S_INLINESITE"); 382 OS.EmitIntValue(SymbolRecordKind::S_INLINESITE, 2); // RecordKind 383 384 OS.AddComment("PtrParent"); 385 OS.EmitIntValue(0, 4); 386 OS.AddComment("PtrEnd"); 387 OS.EmitIntValue(0, 4); 388 OS.AddComment("Inlinee type index"); 389 OS.EmitIntValue(InlineeIdx, 4); 390 391 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile()); 392 unsigned StartLineNum = Site.Inlinee->getLine(); 393 SmallVector<unsigned, 3> SecondaryFuncIds; 394 collectInlineSiteChildren(SecondaryFuncIds, FI, Site); 395 396 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum, 397 FI.Begin, FI.End, SecondaryFuncIds); 398 399 OS.EmitLabel(InlineEnd); 400 401 for (const LocalVariable &Var : Site.InlinedLocals) 402 emitLocalVariable(Var); 403 404 // Recurse on child inlined call sites before closing the scope. 405 for (const DILocation *ChildSite : Site.ChildSites) { 406 auto I = FI.InlineSites.find(ChildSite); 407 assert(I != FI.InlineSites.end() && 408 "child site not in function inline site map"); 409 emitInlinedCallSite(FI, ChildSite, I->second); 410 } 411 412 // Close the scope. 413 OS.AddComment("Record length"); 414 OS.EmitIntValue(2, 2); // RecordLength 415 OS.AddComment("Record kind: S_INLINESITE_END"); 416 OS.EmitIntValue(SymbolRecordKind::S_INLINESITE_END, 2); // RecordKind 417 } 418 419 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, 420 FunctionInfo &FI) { 421 // For each function there is a separate subsection 422 // which holds the PC to file:line table. 423 const MCSymbol *Fn = Asm->getSymbol(GV); 424 assert(Fn); 425 426 StringRef FuncName; 427 if (auto *SP = GV->getSubprogram()) 428 FuncName = SP->getDisplayName(); 429 430 // If our DISubprogram name is empty, use the mangled name. 431 if (FuncName.empty()) 432 FuncName = GlobalValue::getRealLinkageName(GV->getName()); 433 434 // Emit a symbol subsection, required by VS2012+ to find function boundaries. 435 MCSymbol *SymbolsBegin = MMI->getContext().createTempSymbol(), 436 *SymbolsEnd = MMI->getContext().createTempSymbol(); 437 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 438 OS.EmitIntValue(unsigned(ModuleSubstreamKind::Symbols), 4); 439 OS.AddComment("Subsection size"); 440 OS.emitAbsoluteSymbolDiff(SymbolsEnd, SymbolsBegin, 4); 441 OS.EmitLabel(SymbolsBegin); 442 { 443 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(), 444 *ProcRecordEnd = MMI->getContext().createTempSymbol(); 445 OS.AddComment("Record length"); 446 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2); 447 OS.EmitLabel(ProcRecordBegin); 448 449 OS.AddComment("Record kind: S_GPROC32_ID"); 450 OS.EmitIntValue(unsigned(SymbolRecordKind::S_GPROC32_ID), 2); 451 452 // These fields are filled in by tools like CVPACK which run after the fact. 453 OS.AddComment("PtrParent"); 454 OS.EmitIntValue(0, 4); 455 OS.AddComment("PtrEnd"); 456 OS.EmitIntValue(0, 4); 457 OS.AddComment("PtrNext"); 458 OS.EmitIntValue(0, 4); 459 // This is the important bit that tells the debugger where the function 460 // code is located and what's its size: 461 OS.AddComment("Code size"); 462 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4); 463 OS.AddComment("Offset after prologue"); 464 OS.EmitIntValue(0, 4); 465 OS.AddComment("Offset before epilogue"); 466 OS.EmitIntValue(0, 4); 467 OS.AddComment("Function type index"); 468 OS.EmitIntValue(0, 4); 469 OS.AddComment("Function section relative address"); 470 OS.EmitCOFFSecRel32(Fn); 471 OS.AddComment("Function section index"); 472 OS.EmitCOFFSectionIndex(Fn); 473 OS.AddComment("Flags"); 474 OS.EmitIntValue(0, 1); 475 // Emit the function display name as a null-terminated string. 476 OS.AddComment("Function name"); 477 // Truncate the name so we won't overflow the record length field. 478 emitNullTerminatedSymbolName(OS, FuncName); 479 OS.EmitLabel(ProcRecordEnd); 480 481 for (const LocalVariable &Var : FI.Locals) 482 emitLocalVariable(Var); 483 484 // Emit inlined call site information. Only emit functions inlined directly 485 // into the parent function. We'll emit the other sites recursively as part 486 // of their parent inline site. 487 for (const DILocation *InlinedAt : FI.ChildSites) { 488 auto I = FI.InlineSites.find(InlinedAt); 489 assert(I != FI.InlineSites.end() && 490 "child site not in function inline site map"); 491 emitInlinedCallSite(FI, InlinedAt, I->second); 492 } 493 494 // We're done with this function. 495 OS.AddComment("Record length"); 496 OS.EmitIntValue(0x0002, 2); 497 OS.AddComment("Record kind: S_PROC_ID_END"); 498 OS.EmitIntValue(unsigned(SymbolRecordKind::S_PROC_ID_END), 2); 499 } 500 OS.EmitLabel(SymbolsEnd); 501 // Every subsection must be aligned to a 4-byte boundary. 502 OS.EmitValueToAlignment(4); 503 504 // We have an assembler directive that takes care of the whole line table. 505 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End); 506 } 507 508 CodeViewDebug::LocalVarDefRange 509 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) { 510 LocalVarDefRange DR; 511 DR.InMemory = -1; 512 DR.DataOffset = Offset; 513 assert(DR.DataOffset == Offset && "truncation"); 514 DR.StructOffset = 0; 515 DR.CVRegister = CVRegister; 516 return DR; 517 } 518 519 CodeViewDebug::LocalVarDefRange 520 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) { 521 LocalVarDefRange DR; 522 DR.InMemory = 0; 523 DR.DataOffset = 0; 524 DR.StructOffset = 0; 525 DR.CVRegister = CVRegister; 526 return DR; 527 } 528 529 void CodeViewDebug::collectVariableInfoFromMMITable( 530 DenseSet<InlinedVariable> &Processed) { 531 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget(); 532 const TargetFrameLowering *TFI = TSI.getFrameLowering(); 533 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 534 535 for (const MachineModuleInfo::VariableDbgInfo &VI : 536 MMI->getVariableDbgInfo()) { 537 if (!VI.Var) 538 continue; 539 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 540 "Expected inlined-at fields to agree"); 541 542 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt())); 543 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 544 545 // If variable scope is not found then skip this variable. 546 if (!Scope) 547 continue; 548 549 // Get the frame register used and the offset. 550 unsigned FrameReg = 0; 551 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg); 552 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); 553 554 // Calculate the label ranges. 555 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset); 556 for (const InsnRange &Range : Scope->getRanges()) { 557 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 558 const MCSymbol *End = getLabelAfterInsn(Range.second); 559 End = End ? End : Asm->getFunctionEnd(); 560 DefRange.Ranges.emplace_back(Begin, End); 561 } 562 563 LocalVariable Var; 564 Var.DIVar = VI.Var; 565 Var.DefRanges.emplace_back(std::move(DefRange)); 566 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt()); 567 } 568 } 569 570 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) { 571 DenseSet<InlinedVariable> Processed; 572 // Grab the variable info that was squirreled away in the MMI side-table. 573 collectVariableInfoFromMMITable(Processed); 574 575 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 576 577 for (const auto &I : DbgValues) { 578 InlinedVariable IV = I.first; 579 if (Processed.count(IV)) 580 continue; 581 const DILocalVariable *DIVar = IV.first; 582 const DILocation *InlinedAt = IV.second; 583 584 // Instruction ranges, specifying where IV is accessible. 585 const auto &Ranges = I.second; 586 587 LexicalScope *Scope = nullptr; 588 if (InlinedAt) 589 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt); 590 else 591 Scope = LScopes.findLexicalScope(DIVar->getScope()); 592 // If variable scope is not found then skip this variable. 593 if (!Scope) 594 continue; 595 596 LocalVariable Var; 597 Var.DIVar = DIVar; 598 599 // Calculate the definition ranges. 600 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 601 const InsnRange &Range = *I; 602 const MachineInstr *DVInst = Range.first; 603 assert(DVInst->isDebugValue() && "Invalid History entry"); 604 const DIExpression *DIExpr = DVInst->getDebugExpression(); 605 606 // Bail if there is a complex DWARF expression for now. 607 if (DIExpr && DIExpr->getNumElements() > 0) 608 continue; 609 610 // Bail if operand 0 is not a valid register. This means the variable is a 611 // simple constant, or is described by a complex expression. 612 // FIXME: Find a way to represent constant variables, since they are 613 // relatively common. 614 unsigned Reg = 615 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0; 616 if (Reg == 0) 617 continue; 618 619 // Handle the two cases we can handle: indirect in memory and in register. 620 bool IsIndirect = DVInst->getOperand(1).isImm(); 621 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg()); 622 { 623 LocalVarDefRange DefRange; 624 if (IsIndirect) { 625 int64_t Offset = DVInst->getOperand(1).getImm(); 626 DefRange = createDefRangeMem(CVReg, Offset); 627 } else { 628 DefRange = createDefRangeReg(CVReg); 629 } 630 if (Var.DefRanges.empty() || 631 Var.DefRanges.back().isDifferentLocation(DefRange)) { 632 Var.DefRanges.emplace_back(std::move(DefRange)); 633 } 634 } 635 636 // Compute the label range. 637 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 638 const MCSymbol *End = getLabelAfterInsn(Range.second); 639 if (!End) { 640 if (std::next(I) != E) 641 End = getLabelBeforeInsn(std::next(I)->first); 642 else 643 End = Asm->getFunctionEnd(); 644 } 645 646 // If the last range end is our begin, just extend the last range. 647 // Otherwise make a new range. 648 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges = 649 Var.DefRanges.back().Ranges; 650 if (!Ranges.empty() && Ranges.back().second == Begin) 651 Ranges.back().second = End; 652 else 653 Ranges.emplace_back(Begin, End); 654 655 // FIXME: Do more range combining. 656 } 657 658 recordLocalVariable(std::move(Var), InlinedAt); 659 } 660 } 661 662 void CodeViewDebug::beginFunction(const MachineFunction *MF) { 663 assert(!CurFn && "Can't process two functions at once!"); 664 665 if (!Asm || !MMI->hasDebugInfo()) 666 return; 667 668 DebugHandlerBase::beginFunction(MF); 669 670 const Function *GV = MF->getFunction(); 671 assert(FnDebugInfo.count(GV) == false); 672 CurFn = &FnDebugInfo[GV]; 673 CurFn->FuncId = NextFuncId++; 674 CurFn->Begin = Asm->getFunctionBegin(); 675 676 // Find the end of the function prolog. First known non-DBG_VALUE and 677 // non-frame setup location marks the beginning of the function body. 678 // FIXME: is there a simpler a way to do this? Can we just search 679 // for the first instruction of the function, not the last of the prolog? 680 DebugLoc PrologEndLoc; 681 bool EmptyPrologue = true; 682 for (const auto &MBB : *MF) { 683 for (const auto &MI : MBB) { 684 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) && 685 MI.getDebugLoc()) { 686 PrologEndLoc = MI.getDebugLoc(); 687 break; 688 } else if (!MI.isDebugValue()) { 689 EmptyPrologue = false; 690 } 691 } 692 } 693 694 // Record beginning of function if we have a non-empty prologue. 695 if (PrologEndLoc && !EmptyPrologue) { 696 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc(); 697 maybeRecordLocation(FnStartDL, MF); 698 } 699 } 700 701 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) { 702 // LocalSym record, see SymbolRecord.h for more info. 703 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(), 704 *LocalEnd = MMI->getContext().createTempSymbol(); 705 OS.AddComment("Record length"); 706 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2); 707 OS.EmitLabel(LocalBegin); 708 709 OS.AddComment("Record kind: S_LOCAL"); 710 OS.EmitIntValue(unsigned(SymbolRecordKind::S_LOCAL), 2); 711 712 uint16_t Flags = 0; 713 if (Var.DIVar->isParameter()) 714 Flags |= LocalSym::IsParameter; 715 if (Var.DefRanges.empty()) 716 Flags |= LocalSym::IsOptimizedOut; 717 718 OS.AddComment("TypeIndex"); 719 OS.EmitIntValue(TypeIndex::Int32().getIndex(), 4); 720 OS.AddComment("Flags"); 721 OS.EmitIntValue(Flags, 2); 722 // Truncate the name so we won't overflow the record length field. 723 emitNullTerminatedSymbolName(OS, Var.DIVar->getName()); 724 OS.EmitLabel(LocalEnd); 725 726 // Calculate the on disk prefix of the appropriate def range record. The 727 // records and on disk formats are described in SymbolRecords.h. BytePrefix 728 // should be big enough to hold all forms without memory allocation. 729 SmallString<20> BytePrefix; 730 for (const LocalVarDefRange &DefRange : Var.DefRanges) { 731 BytePrefix.clear(); 732 // FIXME: Handle bitpieces. 733 if (DefRange.StructOffset != 0) 734 continue; 735 736 if (DefRange.InMemory) { 737 DefRangeRegisterRelSym Sym{}; 738 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL); 739 Sym.BaseRegister = DefRange.CVRegister; 740 Sym.Flags = 0; // Unclear what matters here. 741 Sym.BasePointerOffset = DefRange.DataOffset; 742 BytePrefix += 743 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 744 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym), 745 sizeof(Sym) - sizeof(LocalVariableAddrRange)); 746 } else { 747 assert(DefRange.DataOffset == 0 && "unexpected offset into register"); 748 DefRangeRegisterSym Sym{}; 749 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER); 750 Sym.Register = DefRange.CVRegister; 751 Sym.MayHaveNoName = 0; // Unclear what matters here. 752 BytePrefix += 753 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 754 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym), 755 sizeof(Sym) - sizeof(LocalVariableAddrRange)); 756 } 757 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix); 758 } 759 } 760 761 void CodeViewDebug::endFunction(const MachineFunction *MF) { 762 if (!Asm || !CurFn) // We haven't created any debug info for this function. 763 return; 764 765 const Function *GV = MF->getFunction(); 766 assert(FnDebugInfo.count(GV)); 767 assert(CurFn == &FnDebugInfo[GV]); 768 769 collectVariableInfo(GV->getSubprogram()); 770 771 DebugHandlerBase::endFunction(MF); 772 773 // Don't emit anything if we don't have any line tables. 774 if (!CurFn->HaveLineInfo) { 775 FnDebugInfo.erase(GV); 776 CurFn = nullptr; 777 return; 778 } 779 780 CurFn->End = Asm->getFunctionEnd(); 781 782 CurFn = nullptr; 783 } 784 785 void CodeViewDebug::beginInstruction(const MachineInstr *MI) { 786 DebugHandlerBase::beginInstruction(MI); 787 788 // Ignore DBG_VALUE locations and function prologue. 789 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup)) 790 return; 791 DebugLoc DL = MI->getDebugLoc(); 792 if (DL == PrevInstLoc || !DL) 793 return; 794 maybeRecordLocation(DL, Asm->MF); 795 } 796