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 ArrayRef<TypeIndex> NoArgs; 265 ArgListRecord ArgListRec(TypeRecordKind::ArgList, NoArgs); 266 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec); 267 268 ProcedureRecord Procedure(TypeIndex::Void(), CallingConvention::NearC, 269 FunctionOptions::None, 0, ArgListIndex); 270 TypeIndex VoidFnTyIdx = TypeTable.writeProcedure(Procedure); 271 272 // Emit LF_FUNC_ID records for all inlined subprograms to the type stream. 273 // Allocate one type index for each func id. 274 for (auto *SP : InlinedSubprograms) { 275 TypeIndex ParentScope = TypeIndex(0); 276 StringRef DisplayName = SP->getDisplayName(); 277 FuncIdRecord FuncId(ParentScope, VoidFnTyIdx, DisplayName); 278 TypeTable.writeFuncId(FuncId); 279 } 280 281 TypeTable.ForEachRecord( 282 [&](TypeIndex Index, const MemoryTypeTableBuilder::Record *R) { 283 OS.AddComment("Type record length"); 284 OS.EmitIntValue(R->size(), 2); 285 OS.AddComment("Type record data"); 286 OS.EmitBytes(StringRef(R->data(), R->size())); 287 }); 288 } 289 290 void CodeViewDebug::emitInlineeFuncIdsAndLines() { 291 if (InlinedSubprograms.empty()) 292 return; 293 294 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(), 295 *InlineEnd = MMI->getContext().createTempSymbol(); 296 297 OS.AddComment("Inlinee lines subsection"); 298 OS.EmitIntValue(unsigned(ModuleSubstreamKind::InlineeLines), 4); 299 OS.AddComment("Subsection size"); 300 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 4); 301 OS.EmitLabel(InlineBegin); 302 303 // We don't provide any extra file info. 304 // FIXME: Find out if debuggers use this info. 305 OS.AddComment("Inlinee lines signature"); 306 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4); 307 308 unsigned InlineeIndex = FuncIdTypeIndexStart; 309 for (const DISubprogram *SP : InlinedSubprograms) { 310 OS.AddBlankLine(); 311 unsigned FileId = maybeRecordFile(SP->getFile()); 312 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " + 313 SP->getFilename() + Twine(':') + Twine(SP->getLine())); 314 OS.AddBlankLine(); 315 // The filechecksum table uses 8 byte entries for now, and file ids start at 316 // 1. 317 unsigned FileOffset = (FileId - 1) * 8; 318 OS.AddComment("Type index of inlined function"); 319 OS.EmitIntValue(InlineeIndex, 4); 320 OS.AddComment("Offset into filechecksum table"); 321 OS.EmitIntValue(FileOffset, 4); 322 OS.AddComment("Starting line number"); 323 OS.EmitIntValue(SP->getLine(), 4); 324 325 // The next inlined subprogram has the next function id. 326 InlineeIndex++; 327 } 328 329 OS.EmitLabel(InlineEnd); 330 } 331 332 void CodeViewDebug::collectInlineSiteChildren( 333 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI, 334 const InlineSite &Site) { 335 for (const DILocation *ChildSiteLoc : Site.ChildSites) { 336 auto I = FI.InlineSites.find(ChildSiteLoc); 337 const InlineSite &ChildSite = I->second; 338 Children.push_back(ChildSite.SiteFuncId); 339 collectInlineSiteChildren(Children, FI, ChildSite); 340 } 341 } 342 343 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI, 344 const DILocation *InlinedAt, 345 const InlineSite &Site) { 346 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(), 347 *InlineEnd = MMI->getContext().createTempSymbol(); 348 349 assert(SubprogramIndices.count(Site.Inlinee)); 350 unsigned InlineeIdx = FuncIdTypeIndexStart + SubprogramIndices[Site.Inlinee]; 351 352 // SymbolRecord 353 OS.AddComment("Record length"); 354 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength 355 OS.EmitLabel(InlineBegin); 356 OS.AddComment("Record kind: S_INLINESITE"); 357 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind 358 359 OS.AddComment("PtrParent"); 360 OS.EmitIntValue(0, 4); 361 OS.AddComment("PtrEnd"); 362 OS.EmitIntValue(0, 4); 363 OS.AddComment("Inlinee type index"); 364 OS.EmitIntValue(InlineeIdx, 4); 365 366 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile()); 367 unsigned StartLineNum = Site.Inlinee->getLine(); 368 SmallVector<unsigned, 3> SecondaryFuncIds; 369 collectInlineSiteChildren(SecondaryFuncIds, FI, Site); 370 371 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum, 372 FI.Begin, FI.End, SecondaryFuncIds); 373 374 OS.EmitLabel(InlineEnd); 375 376 for (const LocalVariable &Var : Site.InlinedLocals) 377 emitLocalVariable(Var); 378 379 // Recurse on child inlined call sites before closing the scope. 380 for (const DILocation *ChildSite : Site.ChildSites) { 381 auto I = FI.InlineSites.find(ChildSite); 382 assert(I != FI.InlineSites.end() && 383 "child site not in function inline site map"); 384 emitInlinedCallSite(FI, ChildSite, I->second); 385 } 386 387 // Close the scope. 388 OS.AddComment("Record length"); 389 OS.EmitIntValue(2, 2); // RecordLength 390 OS.AddComment("Record kind: S_INLINESITE_END"); 391 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind 392 } 393 394 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, 395 FunctionInfo &FI) { 396 // For each function there is a separate subsection 397 // which holds the PC to file:line table. 398 const MCSymbol *Fn = Asm->getSymbol(GV); 399 assert(Fn); 400 401 StringRef FuncName; 402 if (auto *SP = GV->getSubprogram()) 403 FuncName = SP->getDisplayName(); 404 405 // If our DISubprogram name is empty, use the mangled name. 406 if (FuncName.empty()) 407 FuncName = GlobalValue::getRealLinkageName(GV->getName()); 408 409 // Emit a symbol subsection, required by VS2012+ to find function boundaries. 410 MCSymbol *SymbolsBegin = MMI->getContext().createTempSymbol(), 411 *SymbolsEnd = MMI->getContext().createTempSymbol(); 412 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 413 OS.EmitIntValue(unsigned(ModuleSubstreamKind::Symbols), 4); 414 OS.AddComment("Subsection size"); 415 OS.emitAbsoluteSymbolDiff(SymbolsEnd, SymbolsBegin, 4); 416 OS.EmitLabel(SymbolsBegin); 417 { 418 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(), 419 *ProcRecordEnd = MMI->getContext().createTempSymbol(); 420 OS.AddComment("Record length"); 421 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2); 422 OS.EmitLabel(ProcRecordBegin); 423 424 OS.AddComment("Record kind: S_GPROC32_ID"); 425 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2); 426 427 // These fields are filled in by tools like CVPACK which run after the fact. 428 OS.AddComment("PtrParent"); 429 OS.EmitIntValue(0, 4); 430 OS.AddComment("PtrEnd"); 431 OS.EmitIntValue(0, 4); 432 OS.AddComment("PtrNext"); 433 OS.EmitIntValue(0, 4); 434 // This is the important bit that tells the debugger where the function 435 // code is located and what's its size: 436 OS.AddComment("Code size"); 437 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4); 438 OS.AddComment("Offset after prologue"); 439 OS.EmitIntValue(0, 4); 440 OS.AddComment("Offset before epilogue"); 441 OS.EmitIntValue(0, 4); 442 OS.AddComment("Function type index"); 443 OS.EmitIntValue(0, 4); 444 OS.AddComment("Function section relative address"); 445 OS.EmitCOFFSecRel32(Fn); 446 OS.AddComment("Function section index"); 447 OS.EmitCOFFSectionIndex(Fn); 448 OS.AddComment("Flags"); 449 OS.EmitIntValue(0, 1); 450 // Emit the function display name as a null-terminated string. 451 OS.AddComment("Function name"); 452 // Truncate the name so we won't overflow the record length field. 453 emitNullTerminatedSymbolName(OS, FuncName); 454 OS.EmitLabel(ProcRecordEnd); 455 456 for (const LocalVariable &Var : FI.Locals) 457 emitLocalVariable(Var); 458 459 // Emit inlined call site information. Only emit functions inlined directly 460 // into the parent function. We'll emit the other sites recursively as part 461 // of their parent inline site. 462 for (const DILocation *InlinedAt : FI.ChildSites) { 463 auto I = FI.InlineSites.find(InlinedAt); 464 assert(I != FI.InlineSites.end() && 465 "child site not in function inline site map"); 466 emitInlinedCallSite(FI, InlinedAt, I->second); 467 } 468 469 // We're done with this function. 470 OS.AddComment("Record length"); 471 OS.EmitIntValue(0x0002, 2); 472 OS.AddComment("Record kind: S_PROC_ID_END"); 473 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2); 474 } 475 OS.EmitLabel(SymbolsEnd); 476 // Every subsection must be aligned to a 4-byte boundary. 477 OS.EmitValueToAlignment(4); 478 479 // We have an assembler directive that takes care of the whole line table. 480 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End); 481 } 482 483 CodeViewDebug::LocalVarDefRange 484 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) { 485 LocalVarDefRange DR; 486 DR.InMemory = -1; 487 DR.DataOffset = Offset; 488 assert(DR.DataOffset == Offset && "truncation"); 489 DR.StructOffset = 0; 490 DR.CVRegister = CVRegister; 491 return DR; 492 } 493 494 CodeViewDebug::LocalVarDefRange 495 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) { 496 LocalVarDefRange DR; 497 DR.InMemory = 0; 498 DR.DataOffset = 0; 499 DR.StructOffset = 0; 500 DR.CVRegister = CVRegister; 501 return DR; 502 } 503 504 void CodeViewDebug::collectVariableInfoFromMMITable( 505 DenseSet<InlinedVariable> &Processed) { 506 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget(); 507 const TargetFrameLowering *TFI = TSI.getFrameLowering(); 508 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 509 510 for (const MachineModuleInfo::VariableDbgInfo &VI : 511 MMI->getVariableDbgInfo()) { 512 if (!VI.Var) 513 continue; 514 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 515 "Expected inlined-at fields to agree"); 516 517 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt())); 518 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 519 520 // If variable scope is not found then skip this variable. 521 if (!Scope) 522 continue; 523 524 // Get the frame register used and the offset. 525 unsigned FrameReg = 0; 526 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg); 527 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); 528 529 // Calculate the label ranges. 530 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset); 531 for (const InsnRange &Range : Scope->getRanges()) { 532 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 533 const MCSymbol *End = getLabelAfterInsn(Range.second); 534 End = End ? End : Asm->getFunctionEnd(); 535 DefRange.Ranges.emplace_back(Begin, End); 536 } 537 538 LocalVariable Var; 539 Var.DIVar = VI.Var; 540 Var.DefRanges.emplace_back(std::move(DefRange)); 541 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt()); 542 } 543 } 544 545 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) { 546 DenseSet<InlinedVariable> Processed; 547 // Grab the variable info that was squirreled away in the MMI side-table. 548 collectVariableInfoFromMMITable(Processed); 549 550 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 551 552 for (const auto &I : DbgValues) { 553 InlinedVariable IV = I.first; 554 if (Processed.count(IV)) 555 continue; 556 const DILocalVariable *DIVar = IV.first; 557 const DILocation *InlinedAt = IV.second; 558 559 // Instruction ranges, specifying where IV is accessible. 560 const auto &Ranges = I.second; 561 562 LexicalScope *Scope = nullptr; 563 if (InlinedAt) 564 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt); 565 else 566 Scope = LScopes.findLexicalScope(DIVar->getScope()); 567 // If variable scope is not found then skip this variable. 568 if (!Scope) 569 continue; 570 571 LocalVariable Var; 572 Var.DIVar = DIVar; 573 574 // Calculate the definition ranges. 575 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 576 const InsnRange &Range = *I; 577 const MachineInstr *DVInst = Range.first; 578 assert(DVInst->isDebugValue() && "Invalid History entry"); 579 const DIExpression *DIExpr = DVInst->getDebugExpression(); 580 581 // Bail if there is a complex DWARF expression for now. 582 if (DIExpr && DIExpr->getNumElements() > 0) 583 continue; 584 585 // Bail if operand 0 is not a valid register. This means the variable is a 586 // simple constant, or is described by a complex expression. 587 // FIXME: Find a way to represent constant variables, since they are 588 // relatively common. 589 unsigned Reg = 590 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0; 591 if (Reg == 0) 592 continue; 593 594 // Handle the two cases we can handle: indirect in memory and in register. 595 bool IsIndirect = DVInst->getOperand(1).isImm(); 596 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg()); 597 { 598 LocalVarDefRange DefRange; 599 if (IsIndirect) { 600 int64_t Offset = DVInst->getOperand(1).getImm(); 601 DefRange = createDefRangeMem(CVReg, Offset); 602 } else { 603 DefRange = createDefRangeReg(CVReg); 604 } 605 if (Var.DefRanges.empty() || 606 Var.DefRanges.back().isDifferentLocation(DefRange)) { 607 Var.DefRanges.emplace_back(std::move(DefRange)); 608 } 609 } 610 611 // Compute the label range. 612 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 613 const MCSymbol *End = getLabelAfterInsn(Range.second); 614 if (!End) { 615 if (std::next(I) != E) 616 End = getLabelBeforeInsn(std::next(I)->first); 617 else 618 End = Asm->getFunctionEnd(); 619 } 620 621 // If the last range end is our begin, just extend the last range. 622 // Otherwise make a new range. 623 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges = 624 Var.DefRanges.back().Ranges; 625 if (!Ranges.empty() && Ranges.back().second == Begin) 626 Ranges.back().second = End; 627 else 628 Ranges.emplace_back(Begin, End); 629 630 // FIXME: Do more range combining. 631 } 632 633 recordLocalVariable(std::move(Var), InlinedAt); 634 } 635 } 636 637 void CodeViewDebug::beginFunction(const MachineFunction *MF) { 638 assert(!CurFn && "Can't process two functions at once!"); 639 640 if (!Asm || !MMI->hasDebugInfo()) 641 return; 642 643 DebugHandlerBase::beginFunction(MF); 644 645 const Function *GV = MF->getFunction(); 646 assert(FnDebugInfo.count(GV) == false); 647 CurFn = &FnDebugInfo[GV]; 648 CurFn->FuncId = NextFuncId++; 649 CurFn->Begin = Asm->getFunctionBegin(); 650 651 // Find the end of the function prolog. First known non-DBG_VALUE and 652 // non-frame setup location marks the beginning of the function body. 653 // FIXME: is there a simpler a way to do this? Can we just search 654 // for the first instruction of the function, not the last of the prolog? 655 DebugLoc PrologEndLoc; 656 bool EmptyPrologue = true; 657 for (const auto &MBB : *MF) { 658 for (const auto &MI : MBB) { 659 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) && 660 MI.getDebugLoc()) { 661 PrologEndLoc = MI.getDebugLoc(); 662 break; 663 } else if (!MI.isDebugValue()) { 664 EmptyPrologue = false; 665 } 666 } 667 } 668 669 // Record beginning of function if we have a non-empty prologue. 670 if (PrologEndLoc && !EmptyPrologue) { 671 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc(); 672 maybeRecordLocation(FnStartDL, MF); 673 } 674 } 675 676 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) { 677 // LocalSym record, see SymbolRecord.h for more info. 678 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(), 679 *LocalEnd = MMI->getContext().createTempSymbol(); 680 OS.AddComment("Record length"); 681 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2); 682 OS.EmitLabel(LocalBegin); 683 684 OS.AddComment("Record kind: S_LOCAL"); 685 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2); 686 687 LocalSymFlags Flags = LocalSymFlags::None; 688 if (Var.DIVar->isParameter()) 689 Flags |= LocalSymFlags::IsParameter; 690 if (Var.DefRanges.empty()) 691 Flags |= LocalSymFlags::IsOptimizedOut; 692 693 OS.AddComment("TypeIndex"); 694 OS.EmitIntValue(TypeIndex::Int32().getIndex(), 4); 695 OS.AddComment("Flags"); 696 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2); 697 // Truncate the name so we won't overflow the record length field. 698 emitNullTerminatedSymbolName(OS, Var.DIVar->getName()); 699 OS.EmitLabel(LocalEnd); 700 701 // Calculate the on disk prefix of the appropriate def range record. The 702 // records and on disk formats are described in SymbolRecords.h. BytePrefix 703 // should be big enough to hold all forms without memory allocation. 704 SmallString<20> BytePrefix; 705 for (const LocalVarDefRange &DefRange : Var.DefRanges) { 706 BytePrefix.clear(); 707 // FIXME: Handle bitpieces. 708 if (DefRange.StructOffset != 0) 709 continue; 710 711 if (DefRange.InMemory) { 712 DefRangeRegisterRelSym Sym{}; 713 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL); 714 Sym.BaseRegister = DefRange.CVRegister; 715 Sym.Flags = 0; // Unclear what matters here. 716 Sym.BasePointerOffset = DefRange.DataOffset; 717 BytePrefix += 718 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 719 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym), 720 sizeof(Sym) - sizeof(LocalVariableAddrRange)); 721 } else { 722 assert(DefRange.DataOffset == 0 && "unexpected offset into register"); 723 DefRangeRegisterSym Sym{}; 724 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER); 725 Sym.Register = DefRange.CVRegister; 726 Sym.MayHaveNoName = 0; // Unclear what matters here. 727 BytePrefix += 728 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 729 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym), 730 sizeof(Sym) - sizeof(LocalVariableAddrRange)); 731 } 732 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix); 733 } 734 } 735 736 void CodeViewDebug::endFunction(const MachineFunction *MF) { 737 if (!Asm || !CurFn) // We haven't created any debug info for this function. 738 return; 739 740 const Function *GV = MF->getFunction(); 741 assert(FnDebugInfo.count(GV)); 742 assert(CurFn == &FnDebugInfo[GV]); 743 744 collectVariableInfo(GV->getSubprogram()); 745 746 DebugHandlerBase::endFunction(MF); 747 748 // Don't emit anything if we don't have any line tables. 749 if (!CurFn->HaveLineInfo) { 750 FnDebugInfo.erase(GV); 751 CurFn = nullptr; 752 return; 753 } 754 755 CurFn->End = Asm->getFunctionEnd(); 756 757 CurFn = nullptr; 758 } 759 760 void CodeViewDebug::beginInstruction(const MachineInstr *MI) { 761 DebugHandlerBase::beginInstruction(MI); 762 763 // Ignore DBG_VALUE locations and function prologue. 764 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup)) 765 return; 766 DebugLoc DL = MI->getDebugLoc(); 767 if (DL == PrevInstLoc || !DL) 768 return; 769 maybeRecordLocation(DL, Asm->MF); 770 } 771