1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains support for writing Microsoft CodeView debug info. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeViewDebug.h" 14 #include "DwarfExpression.h" 15 #include "llvm/ADT/APSInt.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/DenseSet.h" 19 #include "llvm/ADT/MapVector.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallString.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/ADT/TinyPtrVector.h" 27 #include "llvm/ADT/Triple.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/BinaryFormat/COFF.h" 30 #include "llvm/BinaryFormat/Dwarf.h" 31 #include "llvm/CodeGen/AsmPrinter.h" 32 #include "llvm/CodeGen/LexicalScopes.h" 33 #include "llvm/CodeGen/MachineFrameInfo.h" 34 #include "llvm/CodeGen/MachineFunction.h" 35 #include "llvm/CodeGen/MachineInstr.h" 36 #include "llvm/CodeGen/MachineModuleInfo.h" 37 #include "llvm/CodeGen/MachineOperand.h" 38 #include "llvm/CodeGen/TargetFrameLowering.h" 39 #include "llvm/CodeGen/TargetRegisterInfo.h" 40 #include "llvm/CodeGen/TargetSubtargetInfo.h" 41 #include "llvm/Config/llvm-config.h" 42 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" 43 #include "llvm/DebugInfo/CodeView/CodeView.h" 44 #include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h" 45 #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h" 46 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h" 47 #include "llvm/DebugInfo/CodeView/EnumTables.h" 48 #include "llvm/DebugInfo/CodeView/Line.h" 49 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 50 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h" 51 #include "llvm/DebugInfo/CodeView/TypeIndex.h" 52 #include "llvm/DebugInfo/CodeView/TypeRecord.h" 53 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h" 54 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h" 55 #include "llvm/IR/Constants.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/DebugInfoMetadata.h" 58 #include "llvm/IR/DebugLoc.h" 59 #include "llvm/IR/Function.h" 60 #include "llvm/IR/GlobalValue.h" 61 #include "llvm/IR/GlobalVariable.h" 62 #include "llvm/IR/Metadata.h" 63 #include "llvm/IR/Module.h" 64 #include "llvm/MC/MCAsmInfo.h" 65 #include "llvm/MC/MCContext.h" 66 #include "llvm/MC/MCSectionCOFF.h" 67 #include "llvm/MC/MCStreamer.h" 68 #include "llvm/MC/MCSymbol.h" 69 #include "llvm/Support/BinaryByteStream.h" 70 #include "llvm/Support/BinaryStreamReader.h" 71 #include "llvm/Support/BinaryStreamWriter.h" 72 #include "llvm/Support/Casting.h" 73 #include "llvm/Support/CommandLine.h" 74 #include "llvm/Support/Compiler.h" 75 #include "llvm/Support/Endian.h" 76 #include "llvm/Support/Error.h" 77 #include "llvm/Support/ErrorHandling.h" 78 #include "llvm/Support/FormatVariadic.h" 79 #include "llvm/Support/Path.h" 80 #include "llvm/Support/SMLoc.h" 81 #include "llvm/Support/ScopedPrinter.h" 82 #include "llvm/Target/TargetLoweringObjectFile.h" 83 #include "llvm/Target/TargetMachine.h" 84 #include <algorithm> 85 #include <cassert> 86 #include <cctype> 87 #include <cstddef> 88 #include <cstdint> 89 #include <iterator> 90 #include <limits> 91 #include <string> 92 #include <utility> 93 #include <vector> 94 95 using namespace llvm; 96 using namespace llvm::codeview; 97 98 namespace { 99 class CVMCAdapter : public CodeViewRecordStreamer { 100 public: 101 CVMCAdapter(MCStreamer &OS) : OS(&OS) {} 102 103 void EmitBytes(StringRef Data) { OS->EmitBytes(Data); } 104 105 void EmitIntValue(uint64_t Value, unsigned Size) { 106 OS->EmitIntValueInHex(Value, Size); 107 } 108 109 void EmitBinaryData(StringRef Data) { OS->EmitBinaryData(Data); } 110 111 void AddComment(const Twine &T) { OS->AddComment(T); } 112 113 private: 114 MCStreamer *OS = nullptr; 115 }; 116 } // namespace 117 118 static CPUType mapArchToCVCPUType(Triple::ArchType Type) { 119 switch (Type) { 120 case Triple::ArchType::x86: 121 return CPUType::Pentium3; 122 case Triple::ArchType::x86_64: 123 return CPUType::X64; 124 case Triple::ArchType::thumb: 125 return CPUType::Thumb; 126 case Triple::ArchType::aarch64: 127 return CPUType::ARM64; 128 default: 129 report_fatal_error("target architecture doesn't map to a CodeView CPUType"); 130 } 131 } 132 133 CodeViewDebug::CodeViewDebug(AsmPrinter *AP) 134 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) { 135 // If module doesn't have named metadata anchors or COFF debug section 136 // is not available, skip any debug info related stuff. 137 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") || 138 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) { 139 Asm = nullptr; 140 MMI->setDebugInfoAvailability(false); 141 return; 142 } 143 // Tell MMI that we have debug info. 144 MMI->setDebugInfoAvailability(true); 145 146 TheCPU = 147 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch()); 148 149 collectGlobalVariableInfo(); 150 151 // Check if we should emit type record hashes. 152 ConstantInt *GH = mdconst::extract_or_null<ConstantInt>( 153 MMI->getModule()->getModuleFlag("CodeViewGHash")); 154 EmitDebugGlobalHashes = GH && !GH->isZero(); 155 } 156 157 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) { 158 std::string &Filepath = FileToFilepathMap[File]; 159 if (!Filepath.empty()) 160 return Filepath; 161 162 StringRef Dir = File->getDirectory(), Filename = File->getFilename(); 163 164 // If this is a Unix-style path, just use it as is. Don't try to canonicalize 165 // it textually because one of the path components could be a symlink. 166 if (Dir.startswith("/") || Filename.startswith("/")) { 167 if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix)) 168 return Filename; 169 Filepath = Dir; 170 if (Dir.back() != '/') 171 Filepath += '/'; 172 Filepath += Filename; 173 return Filepath; 174 } 175 176 // Clang emits directory and relative filename info into the IR, but CodeView 177 // operates on full paths. We could change Clang to emit full paths too, but 178 // that would increase the IR size and probably not needed for other users. 179 // For now, just concatenate and canonicalize the path here. 180 if (Filename.find(':') == 1) 181 Filepath = Filename; 182 else 183 Filepath = (Dir + "\\" + Filename).str(); 184 185 // Canonicalize the path. We have to do it textually because we may no longer 186 // have access the file in the filesystem. 187 // First, replace all slashes with backslashes. 188 std::replace(Filepath.begin(), Filepath.end(), '/', '\\'); 189 190 // Remove all "\.\" with "\". 191 size_t Cursor = 0; 192 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos) 193 Filepath.erase(Cursor, 2); 194 195 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original 196 // path should be well-formatted, e.g. start with a drive letter, etc. 197 Cursor = 0; 198 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) { 199 // Something's wrong if the path starts with "\..\", abort. 200 if (Cursor == 0) 201 break; 202 203 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1); 204 if (PrevSlash == std::string::npos) 205 // Something's wrong, abort. 206 break; 207 208 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash); 209 // The next ".." might be following the one we've just erased. 210 Cursor = PrevSlash; 211 } 212 213 // Remove all duplicate backslashes. 214 Cursor = 0; 215 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos) 216 Filepath.erase(Cursor, 1); 217 218 return Filepath; 219 } 220 221 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) { 222 StringRef FullPath = getFullFilepath(F); 223 unsigned NextId = FileIdMap.size() + 1; 224 auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId)); 225 if (Insertion.second) { 226 // We have to compute the full filepath and emit a .cv_file directive. 227 ArrayRef<uint8_t> ChecksumAsBytes; 228 FileChecksumKind CSKind = FileChecksumKind::None; 229 if (F->getChecksum()) { 230 std::string Checksum = fromHex(F->getChecksum()->Value); 231 void *CKMem = OS.getContext().allocate(Checksum.size(), 1); 232 memcpy(CKMem, Checksum.data(), Checksum.size()); 233 ChecksumAsBytes = ArrayRef<uint8_t>( 234 reinterpret_cast<const uint8_t *>(CKMem), Checksum.size()); 235 switch (F->getChecksum()->Kind) { 236 case DIFile::CSK_MD5: CSKind = FileChecksumKind::MD5; break; 237 case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break; 238 } 239 } 240 bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes, 241 static_cast<unsigned>(CSKind)); 242 (void)Success; 243 assert(Success && ".cv_file directive failed"); 244 } 245 return Insertion.first->second; 246 } 247 248 CodeViewDebug::InlineSite & 249 CodeViewDebug::getInlineSite(const DILocation *InlinedAt, 250 const DISubprogram *Inlinee) { 251 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()}); 252 InlineSite *Site = &SiteInsertion.first->second; 253 if (SiteInsertion.second) { 254 unsigned ParentFuncId = CurFn->FuncId; 255 if (const DILocation *OuterIA = InlinedAt->getInlinedAt()) 256 ParentFuncId = 257 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram()) 258 .SiteFuncId; 259 260 Site->SiteFuncId = NextFuncId++; 261 OS.EmitCVInlineSiteIdDirective( 262 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()), 263 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc()); 264 Site->Inlinee = Inlinee; 265 InlinedSubprograms.insert(Inlinee); 266 getFuncIdForSubprogram(Inlinee); 267 } 268 return *Site; 269 } 270 271 static StringRef getPrettyScopeName(const DIScope *Scope) { 272 StringRef ScopeName = Scope->getName(); 273 if (!ScopeName.empty()) 274 return ScopeName; 275 276 switch (Scope->getTag()) { 277 case dwarf::DW_TAG_enumeration_type: 278 case dwarf::DW_TAG_class_type: 279 case dwarf::DW_TAG_structure_type: 280 case dwarf::DW_TAG_union_type: 281 return "<unnamed-tag>"; 282 case dwarf::DW_TAG_namespace: 283 return "`anonymous namespace'"; 284 } 285 286 return StringRef(); 287 } 288 289 static const DISubprogram *getQualifiedNameComponents( 290 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) { 291 const DISubprogram *ClosestSubprogram = nullptr; 292 while (Scope != nullptr) { 293 if (ClosestSubprogram == nullptr) 294 ClosestSubprogram = dyn_cast<DISubprogram>(Scope); 295 StringRef ScopeName = getPrettyScopeName(Scope); 296 if (!ScopeName.empty()) 297 QualifiedNameComponents.push_back(ScopeName); 298 Scope = Scope->getScope(); 299 } 300 return ClosestSubprogram; 301 } 302 303 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents, 304 StringRef TypeName) { 305 std::string FullyQualifiedName; 306 for (StringRef QualifiedNameComponent : 307 llvm::reverse(QualifiedNameComponents)) { 308 FullyQualifiedName.append(QualifiedNameComponent); 309 FullyQualifiedName.append("::"); 310 } 311 FullyQualifiedName.append(TypeName); 312 return FullyQualifiedName; 313 } 314 315 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) { 316 SmallVector<StringRef, 5> QualifiedNameComponents; 317 getQualifiedNameComponents(Scope, QualifiedNameComponents); 318 return getQualifiedName(QualifiedNameComponents, Name); 319 } 320 321 struct CodeViewDebug::TypeLoweringScope { 322 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; } 323 ~TypeLoweringScope() { 324 // Don't decrement TypeEmissionLevel until after emitting deferred types, so 325 // inner TypeLoweringScopes don't attempt to emit deferred types. 326 if (CVD.TypeEmissionLevel == 1) 327 CVD.emitDeferredCompleteTypes(); 328 --CVD.TypeEmissionLevel; 329 } 330 CodeViewDebug &CVD; 331 }; 332 333 static std::string getFullyQualifiedName(const DIScope *Ty) { 334 const DIScope *Scope = Ty->getScope(); 335 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty)); 336 } 337 338 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) { 339 // No scope means global scope and that uses the zero index. 340 if (!Scope || isa<DIFile>(Scope)) 341 return TypeIndex(); 342 343 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type"); 344 345 // Check if we've already translated this scope. 346 auto I = TypeIndices.find({Scope, nullptr}); 347 if (I != TypeIndices.end()) 348 return I->second; 349 350 // Build the fully qualified name of the scope. 351 std::string ScopeName = getFullyQualifiedName(Scope); 352 StringIdRecord SID(TypeIndex(), ScopeName); 353 auto TI = TypeTable.writeLeafType(SID); 354 return recordTypeIndexForDINode(Scope, TI); 355 } 356 357 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) { 358 assert(SP); 359 360 // Check if we've already translated this subprogram. 361 auto I = TypeIndices.find({SP, nullptr}); 362 if (I != TypeIndices.end()) 363 return I->second; 364 365 // The display name includes function template arguments. Drop them to match 366 // MSVC. 367 StringRef DisplayName = SP->getName().split('<').first; 368 369 const DIScope *Scope = SP->getScope(); 370 TypeIndex TI; 371 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) { 372 // If the scope is a DICompositeType, then this must be a method. Member 373 // function types take some special handling, and require access to the 374 // subprogram. 375 TypeIndex ClassType = getTypeIndex(Class); 376 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class), 377 DisplayName); 378 TI = TypeTable.writeLeafType(MFuncId); 379 } else { 380 // Otherwise, this must be a free function. 381 TypeIndex ParentScope = getScopeIndex(Scope); 382 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName); 383 TI = TypeTable.writeLeafType(FuncId); 384 } 385 386 return recordTypeIndexForDINode(SP, TI); 387 } 388 389 static bool isNonTrivial(const DICompositeType *DCTy) { 390 return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial); 391 } 392 393 static FunctionOptions 394 getFunctionOptions(const DISubroutineType *Ty, 395 const DICompositeType *ClassTy = nullptr, 396 StringRef SPName = StringRef("")) { 397 FunctionOptions FO = FunctionOptions::None; 398 const DIType *ReturnTy = nullptr; 399 if (auto TypeArray = Ty->getTypeArray()) { 400 if (TypeArray.size()) 401 ReturnTy = TypeArray[0]; 402 } 403 404 if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) { 405 if (isNonTrivial(ReturnDCTy)) 406 FO |= FunctionOptions::CxxReturnUdt; 407 } 408 409 // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison. 410 if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) { 411 FO |= FunctionOptions::Constructor; 412 413 // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag. 414 415 } 416 return FO; 417 } 418 419 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP, 420 const DICompositeType *Class) { 421 // Always use the method declaration as the key for the function type. The 422 // method declaration contains the this adjustment. 423 if (SP->getDeclaration()) 424 SP = SP->getDeclaration(); 425 assert(!SP->getDeclaration() && "should use declaration as key"); 426 427 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide 428 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}. 429 auto I = TypeIndices.find({SP, Class}); 430 if (I != TypeIndices.end()) 431 return I->second; 432 433 // Make sure complete type info for the class is emitted *after* the member 434 // function type, as the complete class type is likely to reference this 435 // member function type. 436 TypeLoweringScope S(*this); 437 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0; 438 439 FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName()); 440 TypeIndex TI = lowerTypeMemberFunction( 441 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO); 442 return recordTypeIndexForDINode(SP, TI, Class); 443 } 444 445 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, 446 TypeIndex TI, 447 const DIType *ClassTy) { 448 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI}); 449 (void)InsertResult; 450 assert(InsertResult.second && "DINode was already assigned a type index"); 451 return TI; 452 } 453 454 unsigned CodeViewDebug::getPointerSizeInBytes() { 455 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8; 456 } 457 458 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var, 459 const LexicalScope *LS) { 460 if (const DILocation *InlinedAt = LS->getInlinedAt()) { 461 // This variable was inlined. Associate it with the InlineSite. 462 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram(); 463 InlineSite &Site = getInlineSite(InlinedAt, Inlinee); 464 Site.InlinedLocals.emplace_back(Var); 465 } else { 466 // This variable goes into the corresponding lexical scope. 467 ScopeVariables[LS].emplace_back(Var); 468 } 469 } 470 471 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs, 472 const DILocation *Loc) { 473 auto B = Locs.begin(), E = Locs.end(); 474 if (std::find(B, E, Loc) == E) 475 Locs.push_back(Loc); 476 } 477 478 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL, 479 const MachineFunction *MF) { 480 // Skip this instruction if it has the same location as the previous one. 481 if (!DL || DL == PrevInstLoc) 482 return; 483 484 const DIScope *Scope = DL.get()->getScope(); 485 if (!Scope) 486 return; 487 488 // Skip this line if it is longer than the maximum we can record. 489 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true); 490 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() || 491 LI.isNeverStepInto()) 492 return; 493 494 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0); 495 if (CI.getStartColumn() != DL.getCol()) 496 return; 497 498 if (!CurFn->HaveLineInfo) 499 CurFn->HaveLineInfo = true; 500 unsigned FileId = 0; 501 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile()) 502 FileId = CurFn->LastFileId; 503 else 504 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile()); 505 PrevInstLoc = DL; 506 507 unsigned FuncId = CurFn->FuncId; 508 if (const DILocation *SiteLoc = DL->getInlinedAt()) { 509 const DILocation *Loc = DL.get(); 510 511 // If this location was actually inlined from somewhere else, give it the ID 512 // of the inline call site. 513 FuncId = 514 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId; 515 516 // Ensure we have links in the tree of inline call sites. 517 bool FirstLoc = true; 518 while ((SiteLoc = Loc->getInlinedAt())) { 519 InlineSite &Site = 520 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()); 521 if (!FirstLoc) 522 addLocIfNotPresent(Site.ChildSites, Loc); 523 FirstLoc = false; 524 Loc = SiteLoc; 525 } 526 addLocIfNotPresent(CurFn->ChildSites, Loc); 527 } 528 529 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(), 530 /*PrologueEnd=*/false, /*IsStmt=*/false, 531 DL->getFilename(), SMLoc()); 532 } 533 534 void CodeViewDebug::emitCodeViewMagicVersion() { 535 OS.EmitValueToAlignment(4); 536 OS.AddComment("Debug section magic"); 537 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4); 538 } 539 540 void CodeViewDebug::endModule() { 541 if (!Asm || !MMI->hasDebugInfo()) 542 return; 543 544 assert(Asm != nullptr); 545 546 // The COFF .debug$S section consists of several subsections, each starting 547 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length 548 // of the payload followed by the payload itself. The subsections are 4-byte 549 // aligned. 550 551 // Use the generic .debug$S section, and make a subsection for all the inlined 552 // subprograms. 553 switchToDebugSectionForSymbol(nullptr); 554 555 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols); 556 emitCompilerInformation(); 557 endCVSubsection(CompilerInfo); 558 559 emitInlineeLinesSubsection(); 560 561 // Emit per-function debug information. 562 for (auto &P : FnDebugInfo) 563 if (!P.first->isDeclarationForLinker()) 564 emitDebugInfoForFunction(P.first, *P.second); 565 566 // Emit global variable debug information. 567 setCurrentSubprogram(nullptr); 568 emitDebugInfoForGlobals(); 569 570 // Emit retained types. 571 emitDebugInfoForRetainedTypes(); 572 573 // Switch back to the generic .debug$S section after potentially processing 574 // comdat symbol sections. 575 switchToDebugSectionForSymbol(nullptr); 576 577 // Emit UDT records for any types used by global variables. 578 if (!GlobalUDTs.empty()) { 579 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols); 580 emitDebugInfoForUDTs(GlobalUDTs); 581 endCVSubsection(SymbolsEnd); 582 } 583 584 // This subsection holds a file index to offset in string table table. 585 OS.AddComment("File index to string table offset subsection"); 586 OS.EmitCVFileChecksumsDirective(); 587 588 // This subsection holds the string table. 589 OS.AddComment("String table"); 590 OS.EmitCVStringTableDirective(); 591 592 // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol 593 // subsection in the generic .debug$S section at the end. There is no 594 // particular reason for this ordering other than to match MSVC. 595 emitBuildInfo(); 596 597 // Emit type information and hashes last, so that any types we translate while 598 // emitting function info are included. 599 emitTypeInformation(); 600 601 if (EmitDebugGlobalHashes) 602 emitTypeGlobalHashes(); 603 604 clear(); 605 } 606 607 static void 608 emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S, 609 unsigned MaxFixedRecordLength = 0xF00) { 610 // The maximum CV record length is 0xFF00. Most of the strings we emit appear 611 // after a fixed length portion of the record. The fixed length portion should 612 // always be less than 0xF00 (3840) bytes, so truncate the string so that the 613 // overall record size is less than the maximum allowed. 614 SmallString<32> NullTerminatedString( 615 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1)); 616 NullTerminatedString.push_back('\0'); 617 OS.EmitBytes(NullTerminatedString); 618 } 619 620 static StringRef getTypeLeafName(TypeLeafKind TypeKind) { 621 for (const EnumEntry<TypeLeafKind> &EE : getTypeLeafNames()) 622 if (EE.Value == TypeKind) 623 return EE.Name; 624 return ""; 625 } 626 627 void CodeViewDebug::emitTypeInformation() { 628 if (TypeTable.empty()) 629 return; 630 631 // Start the .debug$T or .debug$P section with 0x4. 632 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection()); 633 emitCodeViewMagicVersion(); 634 635 SmallString<8> CommentPrefix; 636 if (OS.isVerboseAsm()) { 637 CommentPrefix += '\t'; 638 CommentPrefix += Asm->MAI->getCommentString(); 639 CommentPrefix += ' '; 640 } 641 642 TypeTableCollection Table(TypeTable.records()); 643 SmallString<512> CommentBlock; 644 raw_svector_ostream CommentOS(CommentBlock); 645 std::unique_ptr<ScopedPrinter> SP; 646 std::unique_ptr<TypeDumpVisitor> TDV; 647 TypeVisitorCallbackPipeline Pipeline; 648 649 if (OS.isVerboseAsm()) { 650 // To construct block comment describing the type record for readability. 651 SP = llvm::make_unique<ScopedPrinter>(CommentOS); 652 SP->setPrefix(CommentPrefix); 653 TDV = llvm::make_unique<TypeDumpVisitor>(Table, SP.get(), false); 654 Pipeline.addCallbackToPipeline(*TDV); 655 } 656 657 // To emit type record using Codeview MCStreamer adapter 658 CVMCAdapter CVMCOS(OS); 659 TypeRecordMapping typeMapping(CVMCOS); 660 Pipeline.addCallbackToPipeline(typeMapping); 661 662 Optional<TypeIndex> B = Table.getFirst(); 663 while (B) { 664 // This will fail if the record data is invalid. 665 CVType Record = Table.getType(*B); 666 667 CommentBlock.clear(); 668 669 auto RecordLen = Record.length(); 670 auto RecordKind = Record.kind(); 671 if (OS.isVerboseAsm()) 672 CVMCOS.AddComment("Record length"); 673 CVMCOS.EmitIntValue(RecordLen - 2, 2); 674 if (OS.isVerboseAsm()) 675 CVMCOS.AddComment("Record kind: " + getTypeLeafName(RecordKind)); 676 CVMCOS.EmitIntValue(RecordKind, sizeof(RecordKind)); 677 678 Error E = codeview::visitTypeRecord(Record, *B, Pipeline); 679 680 if (E) { 681 logAllUnhandledErrors(std::move(E), errs(), "error: "); 682 llvm_unreachable("produced malformed type record"); 683 } 684 685 if (OS.isVerboseAsm()) { 686 // emitRawComment will insert its own tab and comment string before 687 // the first line, so strip off our first one. It also prints its own 688 // newline. 689 OS.emitRawComment( 690 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim()); 691 } 692 B = Table.getNext(*B); 693 } 694 } 695 696 void CodeViewDebug::emitTypeGlobalHashes() { 697 if (TypeTable.empty()) 698 return; 699 700 // Start the .debug$H section with the version and hash algorithm, currently 701 // hardcoded to version 0, SHA1. 702 OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection()); 703 704 OS.EmitValueToAlignment(4); 705 OS.AddComment("Magic"); 706 OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4); 707 OS.AddComment("Section Version"); 708 OS.EmitIntValue(0, 2); 709 OS.AddComment("Hash Algorithm"); 710 OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2); 711 712 TypeIndex TI(TypeIndex::FirstNonSimpleIndex); 713 for (const auto &GHR : TypeTable.hashes()) { 714 if (OS.isVerboseAsm()) { 715 // Emit an EOL-comment describing which TypeIndex this hash corresponds 716 // to, as well as the stringified SHA1 hash. 717 SmallString<32> Comment; 718 raw_svector_ostream CommentOS(Comment); 719 CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR); 720 OS.AddComment(Comment); 721 ++TI; 722 } 723 assert(GHR.Hash.size() == 8); 724 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()), 725 GHR.Hash.size()); 726 OS.EmitBinaryData(S); 727 } 728 } 729 730 static SourceLanguage MapDWLangToCVLang(unsigned DWLang) { 731 switch (DWLang) { 732 case dwarf::DW_LANG_C: 733 case dwarf::DW_LANG_C89: 734 case dwarf::DW_LANG_C99: 735 case dwarf::DW_LANG_C11: 736 case dwarf::DW_LANG_ObjC: 737 return SourceLanguage::C; 738 case dwarf::DW_LANG_C_plus_plus: 739 case dwarf::DW_LANG_C_plus_plus_03: 740 case dwarf::DW_LANG_C_plus_plus_11: 741 case dwarf::DW_LANG_C_plus_plus_14: 742 return SourceLanguage::Cpp; 743 case dwarf::DW_LANG_Fortran77: 744 case dwarf::DW_LANG_Fortran90: 745 case dwarf::DW_LANG_Fortran03: 746 case dwarf::DW_LANG_Fortran08: 747 return SourceLanguage::Fortran; 748 case dwarf::DW_LANG_Pascal83: 749 return SourceLanguage::Pascal; 750 case dwarf::DW_LANG_Cobol74: 751 case dwarf::DW_LANG_Cobol85: 752 return SourceLanguage::Cobol; 753 case dwarf::DW_LANG_Java: 754 return SourceLanguage::Java; 755 case dwarf::DW_LANG_D: 756 return SourceLanguage::D; 757 case dwarf::DW_LANG_Swift: 758 return SourceLanguage::Swift; 759 default: 760 // There's no CodeView representation for this language, and CV doesn't 761 // have an "unknown" option for the language field, so we'll use MASM, 762 // as it's very low level. 763 return SourceLanguage::Masm; 764 } 765 } 766 767 namespace { 768 struct Version { 769 int Part[4]; 770 }; 771 } // end anonymous namespace 772 773 // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out 774 // the version number. 775 static Version parseVersion(StringRef Name) { 776 Version V = {{0}}; 777 int N = 0; 778 for (const char C : Name) { 779 if (isdigit(C)) { 780 V.Part[N] *= 10; 781 V.Part[N] += C - '0'; 782 } else if (C == '.') { 783 ++N; 784 if (N >= 4) 785 return V; 786 } else if (N > 0) 787 return V; 788 } 789 return V; 790 } 791 792 void CodeViewDebug::emitCompilerInformation() { 793 MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3); 794 uint32_t Flags = 0; 795 796 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 797 const MDNode *Node = *CUs->operands().begin(); 798 const auto *CU = cast<DICompileUnit>(Node); 799 800 // The low byte of the flags indicates the source language. 801 Flags = MapDWLangToCVLang(CU->getSourceLanguage()); 802 // TODO: Figure out which other flags need to be set. 803 804 OS.AddComment("Flags and language"); 805 OS.EmitIntValue(Flags, 4); 806 807 OS.AddComment("CPUType"); 808 OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2); 809 810 StringRef CompilerVersion = CU->getProducer(); 811 Version FrontVer = parseVersion(CompilerVersion); 812 OS.AddComment("Frontend version"); 813 for (int N = 0; N < 4; ++N) 814 OS.EmitIntValue(FrontVer.Part[N], 2); 815 816 // Some Microsoft tools, like Binscope, expect a backend version number of at 817 // least 8.something, so we'll coerce the LLVM version into a form that 818 // guarantees it'll be big enough without really lying about the version. 819 int Major = 1000 * LLVM_VERSION_MAJOR + 820 10 * LLVM_VERSION_MINOR + 821 LLVM_VERSION_PATCH; 822 // Clamp it for builds that use unusually large version numbers. 823 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max()); 824 Version BackVer = {{ Major, 0, 0, 0 }}; 825 OS.AddComment("Backend version"); 826 for (int N = 0; N < 4; ++N) 827 OS.EmitIntValue(BackVer.Part[N], 2); 828 829 OS.AddComment("Null-terminated compiler version string"); 830 emitNullTerminatedSymbolName(OS, CompilerVersion); 831 832 endSymbolRecord(CompilerEnd); 833 } 834 835 static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable, 836 StringRef S) { 837 StringIdRecord SIR(TypeIndex(0x0), S); 838 return TypeTable.writeLeafType(SIR); 839 } 840 841 void CodeViewDebug::emitBuildInfo() { 842 // First, make LF_BUILDINFO. It's a sequence of strings with various bits of 843 // build info. The known prefix is: 844 // - Absolute path of current directory 845 // - Compiler path 846 // - Main source file path, relative to CWD or absolute 847 // - Type server PDB file 848 // - Canonical compiler command line 849 // If frontend and backend compilation are separated (think llc or LTO), it's 850 // not clear if the compiler path should refer to the executable for the 851 // frontend or the backend. Leave it blank for now. 852 TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {}; 853 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 854 const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs. 855 const auto *CU = cast<DICompileUnit>(Node); 856 const DIFile *MainSourceFile = CU->getFile(); 857 BuildInfoArgs[BuildInfoRecord::CurrentDirectory] = 858 getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory()); 859 BuildInfoArgs[BuildInfoRecord::SourceFile] = 860 getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename()); 861 // FIXME: Path to compiler and command line. PDB is intentionally blank unless 862 // we implement /Zi type servers. 863 BuildInfoRecord BIR(BuildInfoArgs); 864 TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR); 865 866 // Make a new .debug$S subsection for the S_BUILDINFO record, which points 867 // from the module symbols into the type stream. 868 MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols); 869 MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO); 870 OS.AddComment("LF_BUILDINFO index"); 871 OS.EmitIntValue(BuildInfoIndex.getIndex(), 4); 872 endSymbolRecord(BIEnd); 873 endCVSubsection(BISubsecEnd); 874 } 875 876 void CodeViewDebug::emitInlineeLinesSubsection() { 877 if (InlinedSubprograms.empty()) 878 return; 879 880 OS.AddComment("Inlinee lines subsection"); 881 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines); 882 883 // We emit the checksum info for files. This is used by debuggers to 884 // determine if a pdb matches the source before loading it. Visual Studio, 885 // for instance, will display a warning that the breakpoints are not valid if 886 // the pdb does not match the source. 887 OS.AddComment("Inlinee lines signature"); 888 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4); 889 890 for (const DISubprogram *SP : InlinedSubprograms) { 891 assert(TypeIndices.count({SP, nullptr})); 892 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}]; 893 894 OS.AddBlankLine(); 895 unsigned FileId = maybeRecordFile(SP->getFile()); 896 OS.AddComment("Inlined function " + SP->getName() + " starts at " + 897 SP->getFilename() + Twine(':') + Twine(SP->getLine())); 898 OS.AddBlankLine(); 899 OS.AddComment("Type index of inlined function"); 900 OS.EmitIntValue(InlineeIdx.getIndex(), 4); 901 OS.AddComment("Offset into filechecksum table"); 902 OS.EmitCVFileChecksumOffsetDirective(FileId); 903 OS.AddComment("Starting line number"); 904 OS.EmitIntValue(SP->getLine(), 4); 905 } 906 907 endCVSubsection(InlineEnd); 908 } 909 910 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI, 911 const DILocation *InlinedAt, 912 const InlineSite &Site) { 913 assert(TypeIndices.count({Site.Inlinee, nullptr})); 914 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}]; 915 916 // SymbolRecord 917 MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE); 918 919 OS.AddComment("PtrParent"); 920 OS.EmitIntValue(0, 4); 921 OS.AddComment("PtrEnd"); 922 OS.EmitIntValue(0, 4); 923 OS.AddComment("Inlinee type index"); 924 OS.EmitIntValue(InlineeIdx.getIndex(), 4); 925 926 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile()); 927 unsigned StartLineNum = Site.Inlinee->getLine(); 928 929 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum, 930 FI.Begin, FI.End); 931 932 endSymbolRecord(InlineEnd); 933 934 emitLocalVariableList(FI, Site.InlinedLocals); 935 936 // Recurse on child inlined call sites before closing the scope. 937 for (const DILocation *ChildSite : Site.ChildSites) { 938 auto I = FI.InlineSites.find(ChildSite); 939 assert(I != FI.InlineSites.end() && 940 "child site not in function inline site map"); 941 emitInlinedCallSite(FI, ChildSite, I->second); 942 } 943 944 // Close the scope. 945 emitEndSymbolRecord(SymbolKind::S_INLINESITE_END); 946 } 947 948 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) { 949 // If we have a symbol, it may be in a section that is COMDAT. If so, find the 950 // comdat key. A section may be comdat because of -ffunction-sections or 951 // because it is comdat in the IR. 952 MCSectionCOFF *GVSec = 953 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr; 954 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr; 955 956 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>( 957 Asm->getObjFileLowering().getCOFFDebugSymbolsSection()); 958 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym); 959 960 OS.SwitchSection(DebugSec); 961 962 // Emit the magic version number if this is the first time we've switched to 963 // this section. 964 if (ComdatDebugSections.insert(DebugSec).second) 965 emitCodeViewMagicVersion(); 966 } 967 968 // Emit an S_THUNK32/S_END symbol pair for a thunk routine. 969 // The only supported thunk ordinal is currently the standard type. 970 void CodeViewDebug::emitDebugInfoForThunk(const Function *GV, 971 FunctionInfo &FI, 972 const MCSymbol *Fn) { 973 std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName()); 974 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind. 975 976 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 977 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols); 978 979 // Emit S_THUNK32 980 MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32); 981 OS.AddComment("PtrParent"); 982 OS.EmitIntValue(0, 4); 983 OS.AddComment("PtrEnd"); 984 OS.EmitIntValue(0, 4); 985 OS.AddComment("PtrNext"); 986 OS.EmitIntValue(0, 4); 987 OS.AddComment("Thunk section relative address"); 988 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0); 989 OS.AddComment("Thunk section index"); 990 OS.EmitCOFFSectionIndex(Fn); 991 OS.AddComment("Code size"); 992 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2); 993 OS.AddComment("Ordinal"); 994 OS.EmitIntValue(unsigned(ordinal), 1); 995 OS.AddComment("Function name"); 996 emitNullTerminatedSymbolName(OS, FuncName); 997 // Additional fields specific to the thunk ordinal would go here. 998 endSymbolRecord(ThunkRecordEnd); 999 1000 // Local variables/inlined routines are purposely omitted here. The point of 1001 // marking this as a thunk is so Visual Studio will NOT stop in this routine. 1002 1003 // Emit S_PROC_ID_END 1004 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END); 1005 1006 endCVSubsection(SymbolsEnd); 1007 } 1008 1009 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, 1010 FunctionInfo &FI) { 1011 // For each function there is a separate subsection which holds the PC to 1012 // file:line table. 1013 const MCSymbol *Fn = Asm->getSymbol(GV); 1014 assert(Fn); 1015 1016 // Switch to the to a comdat section, if appropriate. 1017 switchToDebugSectionForSymbol(Fn); 1018 1019 std::string FuncName; 1020 auto *SP = GV->getSubprogram(); 1021 assert(SP); 1022 setCurrentSubprogram(SP); 1023 1024 if (SP->isThunk()) { 1025 emitDebugInfoForThunk(GV, FI, Fn); 1026 return; 1027 } 1028 1029 // If we have a display name, build the fully qualified name by walking the 1030 // chain of scopes. 1031 if (!SP->getName().empty()) 1032 FuncName = getFullyQualifiedName(SP->getScope(), SP->getName()); 1033 1034 // If our DISubprogram name is empty, use the mangled name. 1035 if (FuncName.empty()) 1036 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName()); 1037 1038 // Emit FPO data, but only on 32-bit x86. No other platforms use it. 1039 if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86) 1040 OS.EmitCVFPOData(Fn); 1041 1042 // Emit a symbol subsection, required by VS2012+ to find function boundaries. 1043 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 1044 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols); 1045 { 1046 SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID 1047 : SymbolKind::S_GPROC32_ID; 1048 MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind); 1049 1050 // These fields are filled in by tools like CVPACK which run after the fact. 1051 OS.AddComment("PtrParent"); 1052 OS.EmitIntValue(0, 4); 1053 OS.AddComment("PtrEnd"); 1054 OS.EmitIntValue(0, 4); 1055 OS.AddComment("PtrNext"); 1056 OS.EmitIntValue(0, 4); 1057 // This is the important bit that tells the debugger where the function 1058 // code is located and what's its size: 1059 OS.AddComment("Code size"); 1060 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4); 1061 OS.AddComment("Offset after prologue"); 1062 OS.EmitIntValue(0, 4); 1063 OS.AddComment("Offset before epilogue"); 1064 OS.EmitIntValue(0, 4); 1065 OS.AddComment("Function type index"); 1066 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4); 1067 OS.AddComment("Function section relative address"); 1068 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0); 1069 OS.AddComment("Function section index"); 1070 OS.EmitCOFFSectionIndex(Fn); 1071 OS.AddComment("Flags"); 1072 OS.EmitIntValue(0, 1); 1073 // Emit the function display name as a null-terminated string. 1074 OS.AddComment("Function name"); 1075 // Truncate the name so we won't overflow the record length field. 1076 emitNullTerminatedSymbolName(OS, FuncName); 1077 endSymbolRecord(ProcRecordEnd); 1078 1079 MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC); 1080 // Subtract out the CSR size since MSVC excludes that and we include it. 1081 OS.AddComment("FrameSize"); 1082 OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4); 1083 OS.AddComment("Padding"); 1084 OS.EmitIntValue(0, 4); 1085 OS.AddComment("Offset of padding"); 1086 OS.EmitIntValue(0, 4); 1087 OS.AddComment("Bytes of callee saved registers"); 1088 OS.EmitIntValue(FI.CSRSize, 4); 1089 OS.AddComment("Exception handler offset"); 1090 OS.EmitIntValue(0, 4); 1091 OS.AddComment("Exception handler section"); 1092 OS.EmitIntValue(0, 2); 1093 OS.AddComment("Flags (defines frame register)"); 1094 OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4); 1095 endSymbolRecord(FrameProcEnd); 1096 1097 emitLocalVariableList(FI, FI.Locals); 1098 emitGlobalVariableList(FI.Globals); 1099 emitLexicalBlockList(FI.ChildBlocks, FI); 1100 1101 // Emit inlined call site information. Only emit functions inlined directly 1102 // into the parent function. We'll emit the other sites recursively as part 1103 // of their parent inline site. 1104 for (const DILocation *InlinedAt : FI.ChildSites) { 1105 auto I = FI.InlineSites.find(InlinedAt); 1106 assert(I != FI.InlineSites.end() && 1107 "child site not in function inline site map"); 1108 emitInlinedCallSite(FI, InlinedAt, I->second); 1109 } 1110 1111 for (auto Annot : FI.Annotations) { 1112 MCSymbol *Label = Annot.first; 1113 MDTuple *Strs = cast<MDTuple>(Annot.second); 1114 MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION); 1115 OS.EmitCOFFSecRel32(Label, /*Offset=*/0); 1116 // FIXME: Make sure we don't overflow the max record size. 1117 OS.EmitCOFFSectionIndex(Label); 1118 OS.EmitIntValue(Strs->getNumOperands(), 2); 1119 for (Metadata *MD : Strs->operands()) { 1120 // MDStrings are null terminated, so we can do EmitBytes and get the 1121 // nice .asciz directive. 1122 StringRef Str = cast<MDString>(MD)->getString(); 1123 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString"); 1124 OS.EmitBytes(StringRef(Str.data(), Str.size() + 1)); 1125 } 1126 endSymbolRecord(AnnotEnd); 1127 } 1128 1129 for (auto HeapAllocSite : FI.HeapAllocSites) { 1130 MCSymbol *BeginLabel = std::get<0>(HeapAllocSite); 1131 MCSymbol *EndLabel = std::get<1>(HeapAllocSite); 1132 1133 // The labels might not be defined if the instruction was replaced 1134 // somewhere in the codegen pipeline. 1135 if (!BeginLabel->isDefined() || !EndLabel->isDefined()) 1136 continue; 1137 1138 const DIType *DITy = std::get<2>(HeapAllocSite); 1139 MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE); 1140 OS.AddComment("Call site offset"); 1141 OS.EmitCOFFSecRel32(BeginLabel, /*Offset=*/0); 1142 OS.AddComment("Call site section index"); 1143 OS.EmitCOFFSectionIndex(BeginLabel); 1144 OS.AddComment("Call instruction length"); 1145 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2); 1146 OS.AddComment("Type index"); 1147 OS.EmitIntValue(getCompleteTypeIndex(DITy).getIndex(), 4); 1148 endSymbolRecord(HeapAllocEnd); 1149 } 1150 1151 if (SP != nullptr) 1152 emitDebugInfoForUDTs(LocalUDTs); 1153 1154 // We're done with this function. 1155 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END); 1156 } 1157 endCVSubsection(SymbolsEnd); 1158 1159 // We have an assembler directive that takes care of the whole line table. 1160 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End); 1161 } 1162 1163 CodeViewDebug::LocalVarDefRange 1164 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) { 1165 LocalVarDefRange DR; 1166 DR.InMemory = -1; 1167 DR.DataOffset = Offset; 1168 assert(DR.DataOffset == Offset && "truncation"); 1169 DR.IsSubfield = 0; 1170 DR.StructOffset = 0; 1171 DR.CVRegister = CVRegister; 1172 return DR; 1173 } 1174 1175 void CodeViewDebug::collectVariableInfoFromMFTable( 1176 DenseSet<InlinedEntity> &Processed) { 1177 const MachineFunction &MF = *Asm->MF; 1178 const TargetSubtargetInfo &TSI = MF.getSubtarget(); 1179 const TargetFrameLowering *TFI = TSI.getFrameLowering(); 1180 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 1181 1182 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) { 1183 if (!VI.Var) 1184 continue; 1185 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 1186 "Expected inlined-at fields to agree"); 1187 1188 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt())); 1189 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 1190 1191 // If variable scope is not found then skip this variable. 1192 if (!Scope) 1193 continue; 1194 1195 // If the variable has an attached offset expression, extract it. 1196 // FIXME: Try to handle DW_OP_deref as well. 1197 int64_t ExprOffset = 0; 1198 bool Deref = false; 1199 if (VI.Expr) { 1200 // If there is one DW_OP_deref element, use offset of 0 and keep going. 1201 if (VI.Expr->getNumElements() == 1 && 1202 VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref) 1203 Deref = true; 1204 else if (!VI.Expr->extractIfOffset(ExprOffset)) 1205 continue; 1206 } 1207 1208 // Get the frame register used and the offset. 1209 unsigned FrameReg = 0; 1210 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg); 1211 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); 1212 1213 // Calculate the label ranges. 1214 LocalVarDefRange DefRange = 1215 createDefRangeMem(CVReg, FrameOffset + ExprOffset); 1216 1217 for (const InsnRange &Range : Scope->getRanges()) { 1218 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 1219 const MCSymbol *End = getLabelAfterInsn(Range.second); 1220 End = End ? End : Asm->getFunctionEnd(); 1221 DefRange.Ranges.emplace_back(Begin, End); 1222 } 1223 1224 LocalVariable Var; 1225 Var.DIVar = VI.Var; 1226 Var.DefRanges.emplace_back(std::move(DefRange)); 1227 if (Deref) 1228 Var.UseReferenceType = true; 1229 1230 recordLocalVariable(std::move(Var), Scope); 1231 } 1232 } 1233 1234 static bool canUseReferenceType(const DbgVariableLocation &Loc) { 1235 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0; 1236 } 1237 1238 static bool needsReferenceType(const DbgVariableLocation &Loc) { 1239 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0; 1240 } 1241 1242 void CodeViewDebug::calculateRanges( 1243 LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) { 1244 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 1245 1246 // Calculate the definition ranges. 1247 for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) { 1248 const auto &Entry = *I; 1249 if (!Entry.isDbgValue()) 1250 continue; 1251 const MachineInstr *DVInst = Entry.getInstr(); 1252 assert(DVInst->isDebugValue() && "Invalid History entry"); 1253 // FIXME: Find a way to represent constant variables, since they are 1254 // relatively common. 1255 Optional<DbgVariableLocation> Location = 1256 DbgVariableLocation::extractFromMachineInstruction(*DVInst); 1257 if (!Location) 1258 continue; 1259 1260 // CodeView can only express variables in register and variables in memory 1261 // at a constant offset from a register. However, for variables passed 1262 // indirectly by pointer, it is common for that pointer to be spilled to a 1263 // stack location. For the special case of one offseted load followed by a 1264 // zero offset load (a pointer spilled to the stack), we change the type of 1265 // the local variable from a value type to a reference type. This tricks the 1266 // debugger into doing the load for us. 1267 if (Var.UseReferenceType) { 1268 // We're using a reference type. Drop the last zero offset load. 1269 if (canUseReferenceType(*Location)) 1270 Location->LoadChain.pop_back(); 1271 else 1272 continue; 1273 } else if (needsReferenceType(*Location)) { 1274 // This location can't be expressed without switching to a reference type. 1275 // Start over using that. 1276 Var.UseReferenceType = true; 1277 Var.DefRanges.clear(); 1278 calculateRanges(Var, Entries); 1279 return; 1280 } 1281 1282 // We can only handle a register or an offseted load of a register. 1283 if (Location->Register == 0 || Location->LoadChain.size() > 1) 1284 continue; 1285 { 1286 LocalVarDefRange DR; 1287 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register); 1288 DR.InMemory = !Location->LoadChain.empty(); 1289 DR.DataOffset = 1290 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0; 1291 if (Location->FragmentInfo) { 1292 DR.IsSubfield = true; 1293 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8; 1294 } else { 1295 DR.IsSubfield = false; 1296 DR.StructOffset = 0; 1297 } 1298 1299 if (Var.DefRanges.empty() || 1300 Var.DefRanges.back().isDifferentLocation(DR)) { 1301 Var.DefRanges.emplace_back(std::move(DR)); 1302 } 1303 } 1304 1305 // Compute the label range. 1306 const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr()); 1307 const MCSymbol *End; 1308 if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) { 1309 auto &EndingEntry = Entries[Entry.getEndIndex()]; 1310 End = EndingEntry.isDbgValue() 1311 ? getLabelBeforeInsn(EndingEntry.getInstr()) 1312 : getLabelAfterInsn(EndingEntry.getInstr()); 1313 } else 1314 End = Asm->getFunctionEnd(); 1315 1316 // If the last range end is our begin, just extend the last range. 1317 // Otherwise make a new range. 1318 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R = 1319 Var.DefRanges.back().Ranges; 1320 if (!R.empty() && R.back().second == Begin) 1321 R.back().second = End; 1322 else 1323 R.emplace_back(Begin, End); 1324 1325 // FIXME: Do more range combining. 1326 } 1327 } 1328 1329 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) { 1330 DenseSet<InlinedEntity> Processed; 1331 // Grab the variable info that was squirreled away in the MMI side-table. 1332 collectVariableInfoFromMFTable(Processed); 1333 1334 for (const auto &I : DbgValues) { 1335 InlinedEntity IV = I.first; 1336 if (Processed.count(IV)) 1337 continue; 1338 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first); 1339 const DILocation *InlinedAt = IV.second; 1340 1341 // Instruction ranges, specifying where IV is accessible. 1342 const auto &Entries = I.second; 1343 1344 LexicalScope *Scope = nullptr; 1345 if (InlinedAt) 1346 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt); 1347 else 1348 Scope = LScopes.findLexicalScope(DIVar->getScope()); 1349 // If variable scope is not found then skip this variable. 1350 if (!Scope) 1351 continue; 1352 1353 LocalVariable Var; 1354 Var.DIVar = DIVar; 1355 1356 calculateRanges(Var, Entries); 1357 recordLocalVariable(std::move(Var), Scope); 1358 } 1359 } 1360 1361 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) { 1362 const TargetSubtargetInfo &TSI = MF->getSubtarget(); 1363 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 1364 const MachineFrameInfo &MFI = MF->getFrameInfo(); 1365 const Function &GV = MF->getFunction(); 1366 auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()}); 1367 assert(Insertion.second && "function already has info"); 1368 CurFn = Insertion.first->second.get(); 1369 CurFn->FuncId = NextFuncId++; 1370 CurFn->Begin = Asm->getFunctionBegin(); 1371 1372 // The S_FRAMEPROC record reports the stack size, and how many bytes of 1373 // callee-saved registers were used. For targets that don't use a PUSH 1374 // instruction (AArch64), this will be zero. 1375 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters(); 1376 CurFn->FrameSize = MFI.getStackSize(); 1377 CurFn->OffsetAdjustment = MFI.getOffsetAdjustment(); 1378 CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF); 1379 1380 // For this function S_FRAMEPROC record, figure out which codeview register 1381 // will be the frame pointer. 1382 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None. 1383 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None. 1384 if (CurFn->FrameSize > 0) { 1385 if (!TSI.getFrameLowering()->hasFP(*MF)) { 1386 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr; 1387 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr; 1388 } else { 1389 // If there is an FP, parameters are always relative to it. 1390 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr; 1391 if (CurFn->HasStackRealignment) { 1392 // If the stack needs realignment, locals are relative to SP or VFRAME. 1393 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr; 1394 } else { 1395 // Otherwise, locals are relative to EBP, and we probably have VLAs or 1396 // other stack adjustments. 1397 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr; 1398 } 1399 } 1400 } 1401 1402 // Compute other frame procedure options. 1403 FrameProcedureOptions FPO = FrameProcedureOptions::None; 1404 if (MFI.hasVarSizedObjects()) 1405 FPO |= FrameProcedureOptions::HasAlloca; 1406 if (MF->exposesReturnsTwice()) 1407 FPO |= FrameProcedureOptions::HasSetJmp; 1408 // FIXME: Set HasLongJmp if we ever track that info. 1409 if (MF->hasInlineAsm()) 1410 FPO |= FrameProcedureOptions::HasInlineAssembly; 1411 if (GV.hasPersonalityFn()) { 1412 if (isAsynchronousEHPersonality( 1413 classifyEHPersonality(GV.getPersonalityFn()))) 1414 FPO |= FrameProcedureOptions::HasStructuredExceptionHandling; 1415 else 1416 FPO |= FrameProcedureOptions::HasExceptionHandling; 1417 } 1418 if (GV.hasFnAttribute(Attribute::InlineHint)) 1419 FPO |= FrameProcedureOptions::MarkedInline; 1420 if (GV.hasFnAttribute(Attribute::Naked)) 1421 FPO |= FrameProcedureOptions::Naked; 1422 if (MFI.hasStackProtectorIndex()) 1423 FPO |= FrameProcedureOptions::SecurityChecks; 1424 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U); 1425 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U); 1426 if (Asm->TM.getOptLevel() != CodeGenOpt::None && 1427 !GV.hasOptSize() && !GV.hasOptNone()) 1428 FPO |= FrameProcedureOptions::OptimizedForSpeed; 1429 // FIXME: Set GuardCfg when it is implemented. 1430 CurFn->FrameProcOpts = FPO; 1431 1432 OS.EmitCVFuncIdDirective(CurFn->FuncId); 1433 1434 // Find the end of the function prolog. First known non-DBG_VALUE and 1435 // non-frame setup location marks the beginning of the function body. 1436 // FIXME: is there a simpler a way to do this? Can we just search 1437 // for the first instruction of the function, not the last of the prolog? 1438 DebugLoc PrologEndLoc; 1439 bool EmptyPrologue = true; 1440 for (const auto &MBB : *MF) { 1441 for (const auto &MI : MBB) { 1442 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && 1443 MI.getDebugLoc()) { 1444 PrologEndLoc = MI.getDebugLoc(); 1445 break; 1446 } else if (!MI.isMetaInstruction()) { 1447 EmptyPrologue = false; 1448 } 1449 } 1450 } 1451 1452 // Record beginning of function if we have a non-empty prologue. 1453 if (PrologEndLoc && !EmptyPrologue) { 1454 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc(); 1455 maybeRecordLocation(FnStartDL, MF); 1456 } 1457 } 1458 1459 static bool shouldEmitUdt(const DIType *T) { 1460 if (!T) 1461 return false; 1462 1463 // MSVC does not emit UDTs for typedefs that are scoped to classes. 1464 if (T->getTag() == dwarf::DW_TAG_typedef) { 1465 if (DIScope *Scope = T->getScope()) { 1466 switch (Scope->getTag()) { 1467 case dwarf::DW_TAG_structure_type: 1468 case dwarf::DW_TAG_class_type: 1469 case dwarf::DW_TAG_union_type: 1470 return false; 1471 } 1472 } 1473 } 1474 1475 while (true) { 1476 if (!T || T->isForwardDecl()) 1477 return false; 1478 1479 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T); 1480 if (!DT) 1481 return true; 1482 T = DT->getBaseType(); 1483 } 1484 return true; 1485 } 1486 1487 void CodeViewDebug::addToUDTs(const DIType *Ty) { 1488 // Don't record empty UDTs. 1489 if (Ty->getName().empty()) 1490 return; 1491 if (!shouldEmitUdt(Ty)) 1492 return; 1493 1494 SmallVector<StringRef, 5> QualifiedNameComponents; 1495 const DISubprogram *ClosestSubprogram = 1496 getQualifiedNameComponents(Ty->getScope(), QualifiedNameComponents); 1497 1498 std::string FullyQualifiedName = 1499 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty)); 1500 1501 if (ClosestSubprogram == nullptr) { 1502 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty); 1503 } else if (ClosestSubprogram == CurrentSubprogram) { 1504 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty); 1505 } 1506 1507 // TODO: What if the ClosestSubprogram is neither null or the current 1508 // subprogram? Currently, the UDT just gets dropped on the floor. 1509 // 1510 // The current behavior is not desirable. To get maximal fidelity, we would 1511 // need to perform all type translation before beginning emission of .debug$S 1512 // and then make LocalUDTs a member of FunctionInfo 1513 } 1514 1515 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) { 1516 // Generic dispatch for lowering an unknown type. 1517 switch (Ty->getTag()) { 1518 case dwarf::DW_TAG_array_type: 1519 return lowerTypeArray(cast<DICompositeType>(Ty)); 1520 case dwarf::DW_TAG_typedef: 1521 return lowerTypeAlias(cast<DIDerivedType>(Ty)); 1522 case dwarf::DW_TAG_base_type: 1523 return lowerTypeBasic(cast<DIBasicType>(Ty)); 1524 case dwarf::DW_TAG_pointer_type: 1525 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type") 1526 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty)); 1527 LLVM_FALLTHROUGH; 1528 case dwarf::DW_TAG_reference_type: 1529 case dwarf::DW_TAG_rvalue_reference_type: 1530 return lowerTypePointer(cast<DIDerivedType>(Ty)); 1531 case dwarf::DW_TAG_ptr_to_member_type: 1532 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty)); 1533 case dwarf::DW_TAG_restrict_type: 1534 case dwarf::DW_TAG_const_type: 1535 case dwarf::DW_TAG_volatile_type: 1536 // TODO: add support for DW_TAG_atomic_type here 1537 return lowerTypeModifier(cast<DIDerivedType>(Ty)); 1538 case dwarf::DW_TAG_subroutine_type: 1539 if (ClassTy) { 1540 // The member function type of a member function pointer has no 1541 // ThisAdjustment. 1542 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy, 1543 /*ThisAdjustment=*/0, 1544 /*IsStaticMethod=*/false); 1545 } 1546 return lowerTypeFunction(cast<DISubroutineType>(Ty)); 1547 case dwarf::DW_TAG_enumeration_type: 1548 return lowerTypeEnum(cast<DICompositeType>(Ty)); 1549 case dwarf::DW_TAG_class_type: 1550 case dwarf::DW_TAG_structure_type: 1551 return lowerTypeClass(cast<DICompositeType>(Ty)); 1552 case dwarf::DW_TAG_union_type: 1553 return lowerTypeUnion(cast<DICompositeType>(Ty)); 1554 case dwarf::DW_TAG_unspecified_type: 1555 if (Ty->getName() == "decltype(nullptr)") 1556 return TypeIndex::NullptrT(); 1557 return TypeIndex::None(); 1558 default: 1559 // Use the null type index. 1560 return TypeIndex(); 1561 } 1562 } 1563 1564 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) { 1565 TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType()); 1566 StringRef TypeName = Ty->getName(); 1567 1568 addToUDTs(Ty); 1569 1570 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) && 1571 TypeName == "HRESULT") 1572 return TypeIndex(SimpleTypeKind::HResult); 1573 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) && 1574 TypeName == "wchar_t") 1575 return TypeIndex(SimpleTypeKind::WideCharacter); 1576 1577 return UnderlyingTypeIndex; 1578 } 1579 1580 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) { 1581 const DIType *ElementType = Ty->getBaseType(); 1582 TypeIndex ElementTypeIndex = getTypeIndex(ElementType); 1583 // IndexType is size_t, which depends on the bitness of the target. 1584 TypeIndex IndexType = getPointerSizeInBytes() == 8 1585 ? TypeIndex(SimpleTypeKind::UInt64Quad) 1586 : TypeIndex(SimpleTypeKind::UInt32Long); 1587 1588 uint64_t ElementSize = getBaseTypeSize(ElementType) / 8; 1589 1590 // Add subranges to array type. 1591 DINodeArray Elements = Ty->getElements(); 1592 for (int i = Elements.size() - 1; i >= 0; --i) { 1593 const DINode *Element = Elements[i]; 1594 assert(Element->getTag() == dwarf::DW_TAG_subrange_type); 1595 1596 const DISubrange *Subrange = cast<DISubrange>(Element); 1597 assert(Subrange->getLowerBound() == 0 && 1598 "codeview doesn't support subranges with lower bounds"); 1599 int64_t Count = -1; 1600 if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>()) 1601 Count = CI->getSExtValue(); 1602 1603 // Forward declarations of arrays without a size and VLAs use a count of -1. 1604 // Emit a count of zero in these cases to match what MSVC does for arrays 1605 // without a size. MSVC doesn't support VLAs, so it's not clear what we 1606 // should do for them even if we could distinguish them. 1607 if (Count == -1) 1608 Count = 0; 1609 1610 // Update the element size and element type index for subsequent subranges. 1611 ElementSize *= Count; 1612 1613 // If this is the outermost array, use the size from the array. It will be 1614 // more accurate if we had a VLA or an incomplete element type size. 1615 uint64_t ArraySize = 1616 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize; 1617 1618 StringRef Name = (i == 0) ? Ty->getName() : ""; 1619 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name); 1620 ElementTypeIndex = TypeTable.writeLeafType(AR); 1621 } 1622 1623 return ElementTypeIndex; 1624 } 1625 1626 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) { 1627 TypeIndex Index; 1628 dwarf::TypeKind Kind; 1629 uint32_t ByteSize; 1630 1631 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding()); 1632 ByteSize = Ty->getSizeInBits() / 8; 1633 1634 SimpleTypeKind STK = SimpleTypeKind::None; 1635 switch (Kind) { 1636 case dwarf::DW_ATE_address: 1637 // FIXME: Translate 1638 break; 1639 case dwarf::DW_ATE_boolean: 1640 switch (ByteSize) { 1641 case 1: STK = SimpleTypeKind::Boolean8; break; 1642 case 2: STK = SimpleTypeKind::Boolean16; break; 1643 case 4: STK = SimpleTypeKind::Boolean32; break; 1644 case 8: STK = SimpleTypeKind::Boolean64; break; 1645 case 16: STK = SimpleTypeKind::Boolean128; break; 1646 } 1647 break; 1648 case dwarf::DW_ATE_complex_float: 1649 switch (ByteSize) { 1650 case 2: STK = SimpleTypeKind::Complex16; break; 1651 case 4: STK = SimpleTypeKind::Complex32; break; 1652 case 8: STK = SimpleTypeKind::Complex64; break; 1653 case 10: STK = SimpleTypeKind::Complex80; break; 1654 case 16: STK = SimpleTypeKind::Complex128; break; 1655 } 1656 break; 1657 case dwarf::DW_ATE_float: 1658 switch (ByteSize) { 1659 case 2: STK = SimpleTypeKind::Float16; break; 1660 case 4: STK = SimpleTypeKind::Float32; break; 1661 case 6: STK = SimpleTypeKind::Float48; break; 1662 case 8: STK = SimpleTypeKind::Float64; break; 1663 case 10: STK = SimpleTypeKind::Float80; break; 1664 case 16: STK = SimpleTypeKind::Float128; break; 1665 } 1666 break; 1667 case dwarf::DW_ATE_signed: 1668 switch (ByteSize) { 1669 case 1: STK = SimpleTypeKind::SignedCharacter; break; 1670 case 2: STK = SimpleTypeKind::Int16Short; break; 1671 case 4: STK = SimpleTypeKind::Int32; break; 1672 case 8: STK = SimpleTypeKind::Int64Quad; break; 1673 case 16: STK = SimpleTypeKind::Int128Oct; break; 1674 } 1675 break; 1676 case dwarf::DW_ATE_unsigned: 1677 switch (ByteSize) { 1678 case 1: STK = SimpleTypeKind::UnsignedCharacter; break; 1679 case 2: STK = SimpleTypeKind::UInt16Short; break; 1680 case 4: STK = SimpleTypeKind::UInt32; break; 1681 case 8: STK = SimpleTypeKind::UInt64Quad; break; 1682 case 16: STK = SimpleTypeKind::UInt128Oct; break; 1683 } 1684 break; 1685 case dwarf::DW_ATE_UTF: 1686 switch (ByteSize) { 1687 case 2: STK = SimpleTypeKind::Character16; break; 1688 case 4: STK = SimpleTypeKind::Character32; break; 1689 } 1690 break; 1691 case dwarf::DW_ATE_signed_char: 1692 if (ByteSize == 1) 1693 STK = SimpleTypeKind::SignedCharacter; 1694 break; 1695 case dwarf::DW_ATE_unsigned_char: 1696 if (ByteSize == 1) 1697 STK = SimpleTypeKind::UnsignedCharacter; 1698 break; 1699 default: 1700 break; 1701 } 1702 1703 // Apply some fixups based on the source-level type name. 1704 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int") 1705 STK = SimpleTypeKind::Int32Long; 1706 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int") 1707 STK = SimpleTypeKind::UInt32Long; 1708 if (STK == SimpleTypeKind::UInt16Short && 1709 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t")) 1710 STK = SimpleTypeKind::WideCharacter; 1711 if ((STK == SimpleTypeKind::SignedCharacter || 1712 STK == SimpleTypeKind::UnsignedCharacter) && 1713 Ty->getName() == "char") 1714 STK = SimpleTypeKind::NarrowCharacter; 1715 1716 return TypeIndex(STK); 1717 } 1718 1719 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty, 1720 PointerOptions PO) { 1721 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType()); 1722 1723 // Pointers to simple types without any options can use SimpleTypeMode, rather 1724 // than having a dedicated pointer type record. 1725 if (PointeeTI.isSimple() && PO == PointerOptions::None && 1726 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct && 1727 Ty->getTag() == dwarf::DW_TAG_pointer_type) { 1728 SimpleTypeMode Mode = Ty->getSizeInBits() == 64 1729 ? SimpleTypeMode::NearPointer64 1730 : SimpleTypeMode::NearPointer32; 1731 return TypeIndex(PointeeTI.getSimpleKind(), Mode); 1732 } 1733 1734 PointerKind PK = 1735 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32; 1736 PointerMode PM = PointerMode::Pointer; 1737 switch (Ty->getTag()) { 1738 default: llvm_unreachable("not a pointer tag type"); 1739 case dwarf::DW_TAG_pointer_type: 1740 PM = PointerMode::Pointer; 1741 break; 1742 case dwarf::DW_TAG_reference_type: 1743 PM = PointerMode::LValueReference; 1744 break; 1745 case dwarf::DW_TAG_rvalue_reference_type: 1746 PM = PointerMode::RValueReference; 1747 break; 1748 } 1749 1750 if (Ty->isObjectPointer()) 1751 PO |= PointerOptions::Const; 1752 1753 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8); 1754 return TypeTable.writeLeafType(PR); 1755 } 1756 1757 static PointerToMemberRepresentation 1758 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) { 1759 // SizeInBytes being zero generally implies that the member pointer type was 1760 // incomplete, which can happen if it is part of a function prototype. In this 1761 // case, use the unknown model instead of the general model. 1762 if (IsPMF) { 1763 switch (Flags & DINode::FlagPtrToMemberRep) { 1764 case 0: 1765 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1766 : PointerToMemberRepresentation::GeneralFunction; 1767 case DINode::FlagSingleInheritance: 1768 return PointerToMemberRepresentation::SingleInheritanceFunction; 1769 case DINode::FlagMultipleInheritance: 1770 return PointerToMemberRepresentation::MultipleInheritanceFunction; 1771 case DINode::FlagVirtualInheritance: 1772 return PointerToMemberRepresentation::VirtualInheritanceFunction; 1773 } 1774 } else { 1775 switch (Flags & DINode::FlagPtrToMemberRep) { 1776 case 0: 1777 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1778 : PointerToMemberRepresentation::GeneralData; 1779 case DINode::FlagSingleInheritance: 1780 return PointerToMemberRepresentation::SingleInheritanceData; 1781 case DINode::FlagMultipleInheritance: 1782 return PointerToMemberRepresentation::MultipleInheritanceData; 1783 case DINode::FlagVirtualInheritance: 1784 return PointerToMemberRepresentation::VirtualInheritanceData; 1785 } 1786 } 1787 llvm_unreachable("invalid ptr to member representation"); 1788 } 1789 1790 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty, 1791 PointerOptions PO) { 1792 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type); 1793 TypeIndex ClassTI = getTypeIndex(Ty->getClassType()); 1794 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType()); 1795 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64 1796 : PointerKind::Near32; 1797 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType()); 1798 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction 1799 : PointerMode::PointerToDataMember; 1800 1801 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big"); 1802 uint8_t SizeInBytes = Ty->getSizeInBits() / 8; 1803 MemberPointerInfo MPI( 1804 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags())); 1805 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI); 1806 return TypeTable.writeLeafType(PR); 1807 } 1808 1809 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't 1810 /// have a translation, use the NearC convention. 1811 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) { 1812 switch (DwarfCC) { 1813 case dwarf::DW_CC_normal: return CallingConvention::NearC; 1814 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast; 1815 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall; 1816 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall; 1817 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal; 1818 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector; 1819 } 1820 return CallingConvention::NearC; 1821 } 1822 1823 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) { 1824 ModifierOptions Mods = ModifierOptions::None; 1825 PointerOptions PO = PointerOptions::None; 1826 bool IsModifier = true; 1827 const DIType *BaseTy = Ty; 1828 while (IsModifier && BaseTy) { 1829 // FIXME: Need to add DWARF tags for __unaligned and _Atomic 1830 switch (BaseTy->getTag()) { 1831 case dwarf::DW_TAG_const_type: 1832 Mods |= ModifierOptions::Const; 1833 PO |= PointerOptions::Const; 1834 break; 1835 case dwarf::DW_TAG_volatile_type: 1836 Mods |= ModifierOptions::Volatile; 1837 PO |= PointerOptions::Volatile; 1838 break; 1839 case dwarf::DW_TAG_restrict_type: 1840 // Only pointer types be marked with __restrict. There is no known flag 1841 // for __restrict in LF_MODIFIER records. 1842 PO |= PointerOptions::Restrict; 1843 break; 1844 default: 1845 IsModifier = false; 1846 break; 1847 } 1848 if (IsModifier) 1849 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType(); 1850 } 1851 1852 // Check if the inner type will use an LF_POINTER record. If so, the 1853 // qualifiers will go in the LF_POINTER record. This comes up for types like 1854 // 'int *const' and 'int *__restrict', not the more common cases like 'const 1855 // char *'. 1856 if (BaseTy) { 1857 switch (BaseTy->getTag()) { 1858 case dwarf::DW_TAG_pointer_type: 1859 case dwarf::DW_TAG_reference_type: 1860 case dwarf::DW_TAG_rvalue_reference_type: 1861 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO); 1862 case dwarf::DW_TAG_ptr_to_member_type: 1863 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO); 1864 default: 1865 break; 1866 } 1867 } 1868 1869 TypeIndex ModifiedTI = getTypeIndex(BaseTy); 1870 1871 // Return the base type index if there aren't any modifiers. For example, the 1872 // metadata could contain restrict wrappers around non-pointer types. 1873 if (Mods == ModifierOptions::None) 1874 return ModifiedTI; 1875 1876 ModifierRecord MR(ModifiedTI, Mods); 1877 return TypeTable.writeLeafType(MR); 1878 } 1879 1880 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) { 1881 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; 1882 for (const DIType *ArgType : Ty->getTypeArray()) 1883 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType)); 1884 1885 // MSVC uses type none for variadic argument. 1886 if (ReturnAndArgTypeIndices.size() > 1 && 1887 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) { 1888 ReturnAndArgTypeIndices.back() = TypeIndex::None(); 1889 } 1890 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 1891 ArrayRef<TypeIndex> ArgTypeIndices = None; 1892 if (!ReturnAndArgTypeIndices.empty()) { 1893 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices); 1894 ReturnTypeIndex = ReturnAndArgTypesRef.front(); 1895 ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); 1896 } 1897 1898 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 1899 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec); 1900 1901 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 1902 1903 FunctionOptions FO = getFunctionOptions(Ty); 1904 ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(), 1905 ArgListIndex); 1906 return TypeTable.writeLeafType(Procedure); 1907 } 1908 1909 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty, 1910 const DIType *ClassTy, 1911 int ThisAdjustment, 1912 bool IsStaticMethod, 1913 FunctionOptions FO) { 1914 // Lower the containing class type. 1915 TypeIndex ClassType = getTypeIndex(ClassTy); 1916 1917 DITypeRefArray ReturnAndArgs = Ty->getTypeArray(); 1918 1919 unsigned Index = 0; 1920 SmallVector<TypeIndex, 8> ArgTypeIndices; 1921 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 1922 if (ReturnAndArgs.size() > Index) { 1923 ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]); 1924 } 1925 1926 // If the first argument is a pointer type and this isn't a static method, 1927 // treat it as the special 'this' parameter, which is encoded separately from 1928 // the arguments. 1929 TypeIndex ThisTypeIndex; 1930 if (!IsStaticMethod && ReturnAndArgs.size() > Index) { 1931 if (const DIDerivedType *PtrTy = 1932 dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) { 1933 if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) { 1934 ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty); 1935 Index++; 1936 } 1937 } 1938 } 1939 1940 while (Index < ReturnAndArgs.size()) 1941 ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++])); 1942 1943 // MSVC uses type none for variadic argument. 1944 if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void()) 1945 ArgTypeIndices.back() = TypeIndex::None(); 1946 1947 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 1948 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec); 1949 1950 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 1951 1952 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO, 1953 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment); 1954 return TypeTable.writeLeafType(MFR); 1955 } 1956 1957 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) { 1958 unsigned VSlotCount = 1959 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize()); 1960 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near); 1961 1962 VFTableShapeRecord VFTSR(Slots); 1963 return TypeTable.writeLeafType(VFTSR); 1964 } 1965 1966 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) { 1967 switch (Flags & DINode::FlagAccessibility) { 1968 case DINode::FlagPrivate: return MemberAccess::Private; 1969 case DINode::FlagPublic: return MemberAccess::Public; 1970 case DINode::FlagProtected: return MemberAccess::Protected; 1971 case 0: 1972 // If there was no explicit access control, provide the default for the tag. 1973 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private 1974 : MemberAccess::Public; 1975 } 1976 llvm_unreachable("access flags are exclusive"); 1977 } 1978 1979 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) { 1980 if (SP->isArtificial()) 1981 return MethodOptions::CompilerGenerated; 1982 1983 // FIXME: Handle other MethodOptions. 1984 1985 return MethodOptions::None; 1986 } 1987 1988 static MethodKind translateMethodKindFlags(const DISubprogram *SP, 1989 bool Introduced) { 1990 if (SP->getFlags() & DINode::FlagStaticMember) 1991 return MethodKind::Static; 1992 1993 switch (SP->getVirtuality()) { 1994 case dwarf::DW_VIRTUALITY_none: 1995 break; 1996 case dwarf::DW_VIRTUALITY_virtual: 1997 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual; 1998 case dwarf::DW_VIRTUALITY_pure_virtual: 1999 return Introduced ? MethodKind::PureIntroducingVirtual 2000 : MethodKind::PureVirtual; 2001 default: 2002 llvm_unreachable("unhandled virtuality case"); 2003 } 2004 2005 return MethodKind::Vanilla; 2006 } 2007 2008 static TypeRecordKind getRecordKind(const DICompositeType *Ty) { 2009 switch (Ty->getTag()) { 2010 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class; 2011 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct; 2012 } 2013 llvm_unreachable("unexpected tag"); 2014 } 2015 2016 /// Return ClassOptions that should be present on both the forward declaration 2017 /// and the defintion of a tag type. 2018 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) { 2019 ClassOptions CO = ClassOptions::None; 2020 2021 // MSVC always sets this flag, even for local types. Clang doesn't always 2022 // appear to give every type a linkage name, which may be problematic for us. 2023 // FIXME: Investigate the consequences of not following them here. 2024 if (!Ty->getIdentifier().empty()) 2025 CO |= ClassOptions::HasUniqueName; 2026 2027 // Put the Nested flag on a type if it appears immediately inside a tag type. 2028 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass 2029 // here. That flag is only set on definitions, and not forward declarations. 2030 const DIScope *ImmediateScope = Ty->getScope(); 2031 if (ImmediateScope && isa<DICompositeType>(ImmediateScope)) 2032 CO |= ClassOptions::Nested; 2033 2034 // Put the Scoped flag on function-local types. MSVC puts this flag for enum 2035 // type only when it has an immediate function scope. Clang never puts enums 2036 // inside DILexicalBlock scopes. Enum types, as generated by clang, are 2037 // always in function, class, or file scopes. 2038 if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) { 2039 if (ImmediateScope && isa<DISubprogram>(ImmediateScope)) 2040 CO |= ClassOptions::Scoped; 2041 } else { 2042 for (const DIScope *Scope = ImmediateScope; Scope != nullptr; 2043 Scope = Scope->getScope()) { 2044 if (isa<DISubprogram>(Scope)) { 2045 CO |= ClassOptions::Scoped; 2046 break; 2047 } 2048 } 2049 } 2050 2051 return CO; 2052 } 2053 2054 void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) { 2055 switch (Ty->getTag()) { 2056 case dwarf::DW_TAG_class_type: 2057 case dwarf::DW_TAG_structure_type: 2058 case dwarf::DW_TAG_union_type: 2059 case dwarf::DW_TAG_enumeration_type: 2060 break; 2061 default: 2062 return; 2063 } 2064 2065 if (const auto *File = Ty->getFile()) { 2066 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File)); 2067 TypeIndex SIDI = TypeTable.writeLeafType(SIDR); 2068 2069 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine()); 2070 TypeTable.writeLeafType(USLR); 2071 } 2072 } 2073 2074 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) { 2075 ClassOptions CO = getCommonClassOptions(Ty); 2076 TypeIndex FTI; 2077 unsigned EnumeratorCount = 0; 2078 2079 if (Ty->isForwardDecl()) { 2080 CO |= ClassOptions::ForwardReference; 2081 } else { 2082 ContinuationRecordBuilder ContinuationBuilder; 2083 ContinuationBuilder.begin(ContinuationRecordKind::FieldList); 2084 for (const DINode *Element : Ty->getElements()) { 2085 // We assume that the frontend provides all members in source declaration 2086 // order, which is what MSVC does. 2087 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) { 2088 EnumeratorRecord ER(MemberAccess::Public, 2089 APSInt::getUnsigned(Enumerator->getValue()), 2090 Enumerator->getName()); 2091 ContinuationBuilder.writeMemberType(ER); 2092 EnumeratorCount++; 2093 } 2094 } 2095 FTI = TypeTable.insertRecord(ContinuationBuilder); 2096 } 2097 2098 std::string FullName = getFullyQualifiedName(Ty); 2099 2100 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(), 2101 getTypeIndex(Ty->getBaseType())); 2102 TypeIndex EnumTI = TypeTable.writeLeafType(ER); 2103 2104 addUDTSrcLine(Ty, EnumTI); 2105 2106 return EnumTI; 2107 } 2108 2109 //===----------------------------------------------------------------------===// 2110 // ClassInfo 2111 //===----------------------------------------------------------------------===// 2112 2113 struct llvm::ClassInfo { 2114 struct MemberInfo { 2115 const DIDerivedType *MemberTypeNode; 2116 uint64_t BaseOffset; 2117 }; 2118 // [MemberInfo] 2119 using MemberList = std::vector<MemberInfo>; 2120 2121 using MethodsList = TinyPtrVector<const DISubprogram *>; 2122 // MethodName -> MethodsList 2123 using MethodsMap = MapVector<MDString *, MethodsList>; 2124 2125 /// Base classes. 2126 std::vector<const DIDerivedType *> Inheritance; 2127 2128 /// Direct members. 2129 MemberList Members; 2130 // Direct overloaded methods gathered by name. 2131 MethodsMap Methods; 2132 2133 TypeIndex VShapeTI; 2134 2135 std::vector<const DIType *> NestedTypes; 2136 }; 2137 2138 void CodeViewDebug::clear() { 2139 assert(CurFn == nullptr); 2140 FileIdMap.clear(); 2141 FnDebugInfo.clear(); 2142 FileToFilepathMap.clear(); 2143 LocalUDTs.clear(); 2144 GlobalUDTs.clear(); 2145 TypeIndices.clear(); 2146 CompleteTypeIndices.clear(); 2147 ScopeGlobals.clear(); 2148 } 2149 2150 void CodeViewDebug::collectMemberInfo(ClassInfo &Info, 2151 const DIDerivedType *DDTy) { 2152 if (!DDTy->getName().empty()) { 2153 Info.Members.push_back({DDTy, 0}); 2154 return; 2155 } 2156 2157 // An unnamed member may represent a nested struct or union. Attempt to 2158 // interpret the unnamed member as a DICompositeType possibly wrapped in 2159 // qualifier types. Add all the indirect fields to the current record if that 2160 // succeeds, and drop the member if that fails. 2161 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!"); 2162 uint64_t Offset = DDTy->getOffsetInBits(); 2163 const DIType *Ty = DDTy->getBaseType(); 2164 bool FullyResolved = false; 2165 while (!FullyResolved) { 2166 switch (Ty->getTag()) { 2167 case dwarf::DW_TAG_const_type: 2168 case dwarf::DW_TAG_volatile_type: 2169 // FIXME: we should apply the qualifier types to the indirect fields 2170 // rather than dropping them. 2171 Ty = cast<DIDerivedType>(Ty)->getBaseType(); 2172 break; 2173 default: 2174 FullyResolved = true; 2175 break; 2176 } 2177 } 2178 2179 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty); 2180 if (!DCTy) 2181 return; 2182 2183 ClassInfo NestedInfo = collectClassInfo(DCTy); 2184 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members) 2185 Info.Members.push_back( 2186 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset}); 2187 } 2188 2189 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) { 2190 ClassInfo Info; 2191 // Add elements to structure type. 2192 DINodeArray Elements = Ty->getElements(); 2193 for (auto *Element : Elements) { 2194 // We assume that the frontend provides all members in source declaration 2195 // order, which is what MSVC does. 2196 if (!Element) 2197 continue; 2198 if (auto *SP = dyn_cast<DISubprogram>(Element)) { 2199 Info.Methods[SP->getRawName()].push_back(SP); 2200 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) { 2201 if (DDTy->getTag() == dwarf::DW_TAG_member) { 2202 collectMemberInfo(Info, DDTy); 2203 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) { 2204 Info.Inheritance.push_back(DDTy); 2205 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type && 2206 DDTy->getName() == "__vtbl_ptr_type") { 2207 Info.VShapeTI = getTypeIndex(DDTy); 2208 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) { 2209 Info.NestedTypes.push_back(DDTy); 2210 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) { 2211 // Ignore friend members. It appears that MSVC emitted info about 2212 // friends in the past, but modern versions do not. 2213 } 2214 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) { 2215 Info.NestedTypes.push_back(Composite); 2216 } 2217 // Skip other unrecognized kinds of elements. 2218 } 2219 return Info; 2220 } 2221 2222 static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) { 2223 // This routine is used by lowerTypeClass and lowerTypeUnion to determine 2224 // if a complete type should be emitted instead of a forward reference. 2225 return Ty->getName().empty() && Ty->getIdentifier().empty() && 2226 !Ty->isForwardDecl(); 2227 } 2228 2229 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) { 2230 // Emit the complete type for unnamed structs. C++ classes with methods 2231 // which have a circular reference back to the class type are expected to 2232 // be named by the front-end and should not be "unnamed". C unnamed 2233 // structs should not have circular references. 2234 if (shouldAlwaysEmitCompleteClassType(Ty)) { 2235 // If this unnamed complete type is already in the process of being defined 2236 // then the description of the type is malformed and cannot be emitted 2237 // into CodeView correctly so report a fatal error. 2238 auto I = CompleteTypeIndices.find(Ty); 2239 if (I != CompleteTypeIndices.end() && I->second == TypeIndex()) 2240 report_fatal_error("cannot debug circular reference to unnamed type"); 2241 return getCompleteTypeIndex(Ty); 2242 } 2243 2244 // First, construct the forward decl. Don't look into Ty to compute the 2245 // forward decl options, since it might not be available in all TUs. 2246 TypeRecordKind Kind = getRecordKind(Ty); 2247 ClassOptions CO = 2248 ClassOptions::ForwardReference | getCommonClassOptions(Ty); 2249 std::string FullName = getFullyQualifiedName(Ty); 2250 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0, 2251 FullName, Ty->getIdentifier()); 2252 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR); 2253 if (!Ty->isForwardDecl()) 2254 DeferredCompleteTypes.push_back(Ty); 2255 return FwdDeclTI; 2256 } 2257 2258 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) { 2259 // Construct the field list and complete type record. 2260 TypeRecordKind Kind = getRecordKind(Ty); 2261 ClassOptions CO = getCommonClassOptions(Ty); 2262 TypeIndex FieldTI; 2263 TypeIndex VShapeTI; 2264 unsigned FieldCount; 2265 bool ContainsNestedClass; 2266 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) = 2267 lowerRecordFieldList(Ty); 2268 2269 if (ContainsNestedClass) 2270 CO |= ClassOptions::ContainsNestedClass; 2271 2272 // MSVC appears to set this flag by searching any destructor or method with 2273 // FunctionOptions::Constructor among the emitted members. Clang AST has all 2274 // the members, however special member functions are not yet emitted into 2275 // debug information. For now checking a class's non-triviality seems enough. 2276 // FIXME: not true for a nested unnamed struct. 2277 if (isNonTrivial(Ty)) 2278 CO |= ClassOptions::HasConstructorOrDestructor; 2279 2280 std::string FullName = getFullyQualifiedName(Ty); 2281 2282 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 2283 2284 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI, 2285 SizeInBytes, FullName, Ty->getIdentifier()); 2286 TypeIndex ClassTI = TypeTable.writeLeafType(CR); 2287 2288 addUDTSrcLine(Ty, ClassTI); 2289 2290 addToUDTs(Ty); 2291 2292 return ClassTI; 2293 } 2294 2295 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) { 2296 // Emit the complete type for unnamed unions. 2297 if (shouldAlwaysEmitCompleteClassType(Ty)) 2298 return getCompleteTypeIndex(Ty); 2299 2300 ClassOptions CO = 2301 ClassOptions::ForwardReference | getCommonClassOptions(Ty); 2302 std::string FullName = getFullyQualifiedName(Ty); 2303 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier()); 2304 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR); 2305 if (!Ty->isForwardDecl()) 2306 DeferredCompleteTypes.push_back(Ty); 2307 return FwdDeclTI; 2308 } 2309 2310 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) { 2311 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty); 2312 TypeIndex FieldTI; 2313 unsigned FieldCount; 2314 bool ContainsNestedClass; 2315 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) = 2316 lowerRecordFieldList(Ty); 2317 2318 if (ContainsNestedClass) 2319 CO |= ClassOptions::ContainsNestedClass; 2320 2321 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 2322 std::string FullName = getFullyQualifiedName(Ty); 2323 2324 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName, 2325 Ty->getIdentifier()); 2326 TypeIndex UnionTI = TypeTable.writeLeafType(UR); 2327 2328 addUDTSrcLine(Ty, UnionTI); 2329 2330 addToUDTs(Ty); 2331 2332 return UnionTI; 2333 } 2334 2335 std::tuple<TypeIndex, TypeIndex, unsigned, bool> 2336 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) { 2337 // Manually count members. MSVC appears to count everything that generates a 2338 // field list record. Each individual overload in a method overload group 2339 // contributes to this count, even though the overload group is a single field 2340 // list record. 2341 unsigned MemberCount = 0; 2342 ClassInfo Info = collectClassInfo(Ty); 2343 ContinuationRecordBuilder ContinuationBuilder; 2344 ContinuationBuilder.begin(ContinuationRecordKind::FieldList); 2345 2346 // Create base classes. 2347 for (const DIDerivedType *I : Info.Inheritance) { 2348 if (I->getFlags() & DINode::FlagVirtual) { 2349 // Virtual base. 2350 unsigned VBPtrOffset = I->getVBPtrOffset(); 2351 // FIXME: Despite the accessor name, the offset is really in bytes. 2352 unsigned VBTableIndex = I->getOffsetInBits() / 4; 2353 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase 2354 ? TypeRecordKind::IndirectVirtualBaseClass 2355 : TypeRecordKind::VirtualBaseClass; 2356 VirtualBaseClassRecord VBCR( 2357 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()), 2358 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset, 2359 VBTableIndex); 2360 2361 ContinuationBuilder.writeMemberType(VBCR); 2362 MemberCount++; 2363 } else { 2364 assert(I->getOffsetInBits() % 8 == 0 && 2365 "bases must be on byte boundaries"); 2366 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()), 2367 getTypeIndex(I->getBaseType()), 2368 I->getOffsetInBits() / 8); 2369 ContinuationBuilder.writeMemberType(BCR); 2370 MemberCount++; 2371 } 2372 } 2373 2374 // Create members. 2375 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) { 2376 const DIDerivedType *Member = MemberInfo.MemberTypeNode; 2377 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType()); 2378 StringRef MemberName = Member->getName(); 2379 MemberAccess Access = 2380 translateAccessFlags(Ty->getTag(), Member->getFlags()); 2381 2382 if (Member->isStaticMember()) { 2383 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName); 2384 ContinuationBuilder.writeMemberType(SDMR); 2385 MemberCount++; 2386 continue; 2387 } 2388 2389 // Virtual function pointer member. 2390 if ((Member->getFlags() & DINode::FlagArtificial) && 2391 Member->getName().startswith("_vptr$")) { 2392 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType())); 2393 ContinuationBuilder.writeMemberType(VFPR); 2394 MemberCount++; 2395 continue; 2396 } 2397 2398 // Data member. 2399 uint64_t MemberOffsetInBits = 2400 Member->getOffsetInBits() + MemberInfo.BaseOffset; 2401 if (Member->isBitField()) { 2402 uint64_t StartBitOffset = MemberOffsetInBits; 2403 if (const auto *CI = 2404 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) { 2405 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset; 2406 } 2407 StartBitOffset -= MemberOffsetInBits; 2408 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(), 2409 StartBitOffset); 2410 MemberBaseType = TypeTable.writeLeafType(BFR); 2411 } 2412 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8; 2413 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes, 2414 MemberName); 2415 ContinuationBuilder.writeMemberType(DMR); 2416 MemberCount++; 2417 } 2418 2419 // Create methods 2420 for (auto &MethodItr : Info.Methods) { 2421 StringRef Name = MethodItr.first->getString(); 2422 2423 std::vector<OneMethodRecord> Methods; 2424 for (const DISubprogram *SP : MethodItr.second) { 2425 TypeIndex MethodType = getMemberFunctionType(SP, Ty); 2426 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual; 2427 2428 unsigned VFTableOffset = -1; 2429 if (Introduced) 2430 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes(); 2431 2432 Methods.push_back(OneMethodRecord( 2433 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()), 2434 translateMethodKindFlags(SP, Introduced), 2435 translateMethodOptionFlags(SP), VFTableOffset, Name)); 2436 MemberCount++; 2437 } 2438 assert(!Methods.empty() && "Empty methods map entry"); 2439 if (Methods.size() == 1) 2440 ContinuationBuilder.writeMemberType(Methods[0]); 2441 else { 2442 // FIXME: Make this use its own ContinuationBuilder so that 2443 // MethodOverloadList can be split correctly. 2444 MethodOverloadListRecord MOLR(Methods); 2445 TypeIndex MethodList = TypeTable.writeLeafType(MOLR); 2446 2447 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name); 2448 ContinuationBuilder.writeMemberType(OMR); 2449 } 2450 } 2451 2452 // Create nested classes. 2453 for (const DIType *Nested : Info.NestedTypes) { 2454 NestedTypeRecord R(getTypeIndex(Nested), Nested->getName()); 2455 ContinuationBuilder.writeMemberType(R); 2456 MemberCount++; 2457 } 2458 2459 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder); 2460 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount, 2461 !Info.NestedTypes.empty()); 2462 } 2463 2464 TypeIndex CodeViewDebug::getVBPTypeIndex() { 2465 if (!VBPType.getIndex()) { 2466 // Make a 'const int *' type. 2467 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const); 2468 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR); 2469 2470 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64 2471 : PointerKind::Near32; 2472 PointerMode PM = PointerMode::Pointer; 2473 PointerOptions PO = PointerOptions::None; 2474 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes()); 2475 VBPType = TypeTable.writeLeafType(PR); 2476 } 2477 2478 return VBPType; 2479 } 2480 2481 TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) { 2482 // The null DIType is the void type. Don't try to hash it. 2483 if (!Ty) 2484 return TypeIndex::Void(); 2485 2486 // Check if we've already translated this type. Don't try to do a 2487 // get-or-create style insertion that caches the hash lookup across the 2488 // lowerType call. It will update the TypeIndices map. 2489 auto I = TypeIndices.find({Ty, ClassTy}); 2490 if (I != TypeIndices.end()) 2491 return I->second; 2492 2493 TypeLoweringScope S(*this); 2494 TypeIndex TI = lowerType(Ty, ClassTy); 2495 return recordTypeIndexForDINode(Ty, TI, ClassTy); 2496 } 2497 2498 codeview::TypeIndex 2499 CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy, 2500 const DISubroutineType *SubroutineTy) { 2501 assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type && 2502 "this type must be a pointer type"); 2503 2504 PointerOptions Options = PointerOptions::None; 2505 if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference) 2506 Options = PointerOptions::LValueRefThisPointer; 2507 else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference) 2508 Options = PointerOptions::RValueRefThisPointer; 2509 2510 // Check if we've already translated this type. If there is no ref qualifier 2511 // on the function then we look up this pointer type with no associated class 2512 // so that the TypeIndex for the this pointer can be shared with the type 2513 // index for other pointers to this class type. If there is a ref qualifier 2514 // then we lookup the pointer using the subroutine as the parent type. 2515 auto I = TypeIndices.find({PtrTy, SubroutineTy}); 2516 if (I != TypeIndices.end()) 2517 return I->second; 2518 2519 TypeLoweringScope S(*this); 2520 TypeIndex TI = lowerTypePointer(PtrTy, Options); 2521 return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy); 2522 } 2523 2524 TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) { 2525 PointerRecord PR(getTypeIndex(Ty), 2526 getPointerSizeInBytes() == 8 ? PointerKind::Near64 2527 : PointerKind::Near32, 2528 PointerMode::LValueReference, PointerOptions::None, 2529 Ty->getSizeInBits() / 8); 2530 return TypeTable.writeLeafType(PR); 2531 } 2532 2533 TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) { 2534 // The null DIType is the void type. Don't try to hash it. 2535 if (!Ty) 2536 return TypeIndex::Void(); 2537 2538 // Look through typedefs when getting the complete type index. Call 2539 // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are 2540 // emitted only once. 2541 if (Ty->getTag() == dwarf::DW_TAG_typedef) 2542 (void)getTypeIndex(Ty); 2543 while (Ty->getTag() == dwarf::DW_TAG_typedef) 2544 Ty = cast<DIDerivedType>(Ty)->getBaseType(); 2545 2546 // If this is a non-record type, the complete type index is the same as the 2547 // normal type index. Just call getTypeIndex. 2548 switch (Ty->getTag()) { 2549 case dwarf::DW_TAG_class_type: 2550 case dwarf::DW_TAG_structure_type: 2551 case dwarf::DW_TAG_union_type: 2552 break; 2553 default: 2554 return getTypeIndex(Ty); 2555 } 2556 2557 const auto *CTy = cast<DICompositeType>(Ty); 2558 2559 TypeLoweringScope S(*this); 2560 2561 // Make sure the forward declaration is emitted first. It's unclear if this 2562 // is necessary, but MSVC does it, and we should follow suit until we can show 2563 // otherwise. 2564 // We only emit a forward declaration for named types. 2565 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) { 2566 TypeIndex FwdDeclTI = getTypeIndex(CTy); 2567 2568 // Just use the forward decl if we don't have complete type info. This 2569 // might happen if the frontend is using modules and expects the complete 2570 // definition to be emitted elsewhere. 2571 if (CTy->isForwardDecl()) 2572 return FwdDeclTI; 2573 } 2574 2575 // Check if we've already translated the complete record type. 2576 // Insert the type with a null TypeIndex to signify that the type is currently 2577 // being lowered. 2578 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()}); 2579 if (!InsertResult.second) 2580 return InsertResult.first->second; 2581 2582 TypeIndex TI; 2583 switch (CTy->getTag()) { 2584 case dwarf::DW_TAG_class_type: 2585 case dwarf::DW_TAG_structure_type: 2586 TI = lowerCompleteTypeClass(CTy); 2587 break; 2588 case dwarf::DW_TAG_union_type: 2589 TI = lowerCompleteTypeUnion(CTy); 2590 break; 2591 default: 2592 llvm_unreachable("not a record"); 2593 } 2594 2595 // Update the type index associated with this CompositeType. This cannot 2596 // use the 'InsertResult' iterator above because it is potentially 2597 // invalidated by map insertions which can occur while lowering the class 2598 // type above. 2599 CompleteTypeIndices[CTy] = TI; 2600 return TI; 2601 } 2602 2603 /// Emit all the deferred complete record types. Try to do this in FIFO order, 2604 /// and do this until fixpoint, as each complete record type typically 2605 /// references 2606 /// many other record types. 2607 void CodeViewDebug::emitDeferredCompleteTypes() { 2608 SmallVector<const DICompositeType *, 4> TypesToEmit; 2609 while (!DeferredCompleteTypes.empty()) { 2610 std::swap(DeferredCompleteTypes, TypesToEmit); 2611 for (const DICompositeType *RecordTy : TypesToEmit) 2612 getCompleteTypeIndex(RecordTy); 2613 TypesToEmit.clear(); 2614 } 2615 } 2616 2617 void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI, 2618 ArrayRef<LocalVariable> Locals) { 2619 // Get the sorted list of parameters and emit them first. 2620 SmallVector<const LocalVariable *, 6> Params; 2621 for (const LocalVariable &L : Locals) 2622 if (L.DIVar->isParameter()) 2623 Params.push_back(&L); 2624 llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) { 2625 return L->DIVar->getArg() < R->DIVar->getArg(); 2626 }); 2627 for (const LocalVariable *L : Params) 2628 emitLocalVariable(FI, *L); 2629 2630 // Next emit all non-parameters in the order that we found them. 2631 for (const LocalVariable &L : Locals) 2632 if (!L.DIVar->isParameter()) 2633 emitLocalVariable(FI, L); 2634 } 2635 2636 /// Only call this on endian-specific types like ulittle16_t and little32_t, or 2637 /// structs composed of them. 2638 template <typename T> 2639 static void copyBytesForDefRange(SmallString<20> &BytePrefix, 2640 SymbolKind SymKind, const T &DefRangeHeader) { 2641 BytePrefix.resize(2 + sizeof(T)); 2642 ulittle16_t SymKindLE = ulittle16_t(SymKind); 2643 memcpy(&BytePrefix[0], &SymKindLE, 2); 2644 memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T)); 2645 } 2646 2647 void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI, 2648 const LocalVariable &Var) { 2649 // LocalSym record, see SymbolRecord.h for more info. 2650 MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL); 2651 2652 LocalSymFlags Flags = LocalSymFlags::None; 2653 if (Var.DIVar->isParameter()) 2654 Flags |= LocalSymFlags::IsParameter; 2655 if (Var.DefRanges.empty()) 2656 Flags |= LocalSymFlags::IsOptimizedOut; 2657 2658 OS.AddComment("TypeIndex"); 2659 TypeIndex TI = Var.UseReferenceType 2660 ? getTypeIndexForReferenceTo(Var.DIVar->getType()) 2661 : getCompleteTypeIndex(Var.DIVar->getType()); 2662 OS.EmitIntValue(TI.getIndex(), 4); 2663 OS.AddComment("Flags"); 2664 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2); 2665 // Truncate the name so we won't overflow the record length field. 2666 emitNullTerminatedSymbolName(OS, Var.DIVar->getName()); 2667 endSymbolRecord(LocalEnd); 2668 2669 // Calculate the on disk prefix of the appropriate def range record. The 2670 // records and on disk formats are described in SymbolRecords.h. BytePrefix 2671 // should be big enough to hold all forms without memory allocation. 2672 SmallString<20> BytePrefix; 2673 for (const LocalVarDefRange &DefRange : Var.DefRanges) { 2674 BytePrefix.clear(); 2675 if (DefRange.InMemory) { 2676 int Offset = DefRange.DataOffset; 2677 unsigned Reg = DefRange.CVRegister; 2678 2679 // 32-bit x86 call sequences often use PUSH instructions, which disrupt 2680 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0, 2681 // instead. In frames without stack realignment, $T0 will be the CFA. 2682 if (RegisterId(Reg) == RegisterId::ESP) { 2683 Reg = unsigned(RegisterId::VFRAME); 2684 Offset += FI.OffsetAdjustment; 2685 } 2686 2687 // If we can use the chosen frame pointer for the frame and this isn't a 2688 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record. 2689 // Otherwise, use S_DEFRANGE_REGISTER_REL. 2690 EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU); 2691 if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None && 2692 (bool(Flags & LocalSymFlags::IsParameter) 2693 ? (EncFP == FI.EncodedParamFramePtrReg) 2694 : (EncFP == FI.EncodedLocalFramePtrReg))) { 2695 little32_t FPOffset = little32_t(Offset); 2696 copyBytesForDefRange(BytePrefix, S_DEFRANGE_FRAMEPOINTER_REL, FPOffset); 2697 } else { 2698 uint16_t RegRelFlags = 0; 2699 if (DefRange.IsSubfield) { 2700 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag | 2701 (DefRange.StructOffset 2702 << DefRangeRegisterRelSym::OffsetInParentShift); 2703 } 2704 DefRangeRegisterRelSym::Header DRHdr; 2705 DRHdr.Register = Reg; 2706 DRHdr.Flags = RegRelFlags; 2707 DRHdr.BasePointerOffset = Offset; 2708 copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER_REL, DRHdr); 2709 } 2710 } else { 2711 assert(DefRange.DataOffset == 0 && "unexpected offset into register"); 2712 if (DefRange.IsSubfield) { 2713 DefRangeSubfieldRegisterSym::Header DRHdr; 2714 DRHdr.Register = DefRange.CVRegister; 2715 DRHdr.MayHaveNoName = 0; 2716 DRHdr.OffsetInParent = DefRange.StructOffset; 2717 copyBytesForDefRange(BytePrefix, S_DEFRANGE_SUBFIELD_REGISTER, DRHdr); 2718 } else { 2719 DefRangeRegisterSym::Header DRHdr; 2720 DRHdr.Register = DefRange.CVRegister; 2721 DRHdr.MayHaveNoName = 0; 2722 copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER, DRHdr); 2723 } 2724 } 2725 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix); 2726 } 2727 } 2728 2729 void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks, 2730 const FunctionInfo& FI) { 2731 for (LexicalBlock *Block : Blocks) 2732 emitLexicalBlock(*Block, FI); 2733 } 2734 2735 /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a 2736 /// lexical block scope. 2737 void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block, 2738 const FunctionInfo& FI) { 2739 MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32); 2740 OS.AddComment("PtrParent"); 2741 OS.EmitIntValue(0, 4); // PtrParent 2742 OS.AddComment("PtrEnd"); 2743 OS.EmitIntValue(0, 4); // PtrEnd 2744 OS.AddComment("Code size"); 2745 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size 2746 OS.AddComment("Function section relative address"); 2747 OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset 2748 OS.AddComment("Function section index"); 2749 OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol 2750 OS.AddComment("Lexical block name"); 2751 emitNullTerminatedSymbolName(OS, Block.Name); // Name 2752 endSymbolRecord(RecordEnd); 2753 2754 // Emit variables local to this lexical block. 2755 emitLocalVariableList(FI, Block.Locals); 2756 emitGlobalVariableList(Block.Globals); 2757 2758 // Emit lexical blocks contained within this block. 2759 emitLexicalBlockList(Block.Children, FI); 2760 2761 // Close the lexical block scope. 2762 emitEndSymbolRecord(SymbolKind::S_END); 2763 } 2764 2765 /// Convenience routine for collecting lexical block information for a list 2766 /// of lexical scopes. 2767 void CodeViewDebug::collectLexicalBlockInfo( 2768 SmallVectorImpl<LexicalScope *> &Scopes, 2769 SmallVectorImpl<LexicalBlock *> &Blocks, 2770 SmallVectorImpl<LocalVariable> &Locals, 2771 SmallVectorImpl<CVGlobalVariable> &Globals) { 2772 for (LexicalScope *Scope : Scopes) 2773 collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals); 2774 } 2775 2776 /// Populate the lexical blocks and local variable lists of the parent with 2777 /// information about the specified lexical scope. 2778 void CodeViewDebug::collectLexicalBlockInfo( 2779 LexicalScope &Scope, 2780 SmallVectorImpl<LexicalBlock *> &ParentBlocks, 2781 SmallVectorImpl<LocalVariable> &ParentLocals, 2782 SmallVectorImpl<CVGlobalVariable> &ParentGlobals) { 2783 if (Scope.isAbstractScope()) 2784 return; 2785 2786 // Gather information about the lexical scope including local variables, 2787 // global variables, and address ranges. 2788 bool IgnoreScope = false; 2789 auto LI = ScopeVariables.find(&Scope); 2790 SmallVectorImpl<LocalVariable> *Locals = 2791 LI != ScopeVariables.end() ? &LI->second : nullptr; 2792 auto GI = ScopeGlobals.find(Scope.getScopeNode()); 2793 SmallVectorImpl<CVGlobalVariable> *Globals = 2794 GI != ScopeGlobals.end() ? GI->second.get() : nullptr; 2795 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode()); 2796 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges(); 2797 2798 // Ignore lexical scopes which do not contain variables. 2799 if (!Locals && !Globals) 2800 IgnoreScope = true; 2801 2802 // Ignore lexical scopes which are not lexical blocks. 2803 if (!DILB) 2804 IgnoreScope = true; 2805 2806 // Ignore scopes which have too many address ranges to represent in the 2807 // current CodeView format or do not have a valid address range. 2808 // 2809 // For lexical scopes with multiple address ranges you may be tempted to 2810 // construct a single range covering every instruction where the block is 2811 // live and everything in between. Unfortunately, Visual Studio only 2812 // displays variables from the first matching lexical block scope. If the 2813 // first lexical block contains exception handling code or cold code which 2814 // is moved to the bottom of the routine creating a single range covering 2815 // nearly the entire routine, then it will hide all other lexical blocks 2816 // and the variables they contain. 2817 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second)) 2818 IgnoreScope = true; 2819 2820 if (IgnoreScope) { 2821 // This scope can be safely ignored and eliminating it will reduce the 2822 // size of the debug information. Be sure to collect any variable and scope 2823 // information from the this scope or any of its children and collapse them 2824 // into the parent scope. 2825 if (Locals) 2826 ParentLocals.append(Locals->begin(), Locals->end()); 2827 if (Globals) 2828 ParentGlobals.append(Globals->begin(), Globals->end()); 2829 collectLexicalBlockInfo(Scope.getChildren(), 2830 ParentBlocks, 2831 ParentLocals, 2832 ParentGlobals); 2833 return; 2834 } 2835 2836 // Create a new CodeView lexical block for this lexical scope. If we've 2837 // seen this DILexicalBlock before then the scope tree is malformed and 2838 // we can handle this gracefully by not processing it a second time. 2839 auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()}); 2840 if (!BlockInsertion.second) 2841 return; 2842 2843 // Create a lexical block containing the variables and collect the the 2844 // lexical block information for the children. 2845 const InsnRange &Range = Ranges.front(); 2846 assert(Range.first && Range.second); 2847 LexicalBlock &Block = BlockInsertion.first->second; 2848 Block.Begin = getLabelBeforeInsn(Range.first); 2849 Block.End = getLabelAfterInsn(Range.second); 2850 assert(Block.Begin && "missing label for scope begin"); 2851 assert(Block.End && "missing label for scope end"); 2852 Block.Name = DILB->getName(); 2853 if (Locals) 2854 Block.Locals = std::move(*Locals); 2855 if (Globals) 2856 Block.Globals = std::move(*Globals); 2857 ParentBlocks.push_back(&Block); 2858 collectLexicalBlockInfo(Scope.getChildren(), 2859 Block.Children, 2860 Block.Locals, 2861 Block.Globals); 2862 } 2863 2864 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) { 2865 const Function &GV = MF->getFunction(); 2866 assert(FnDebugInfo.count(&GV)); 2867 assert(CurFn == FnDebugInfo[&GV].get()); 2868 2869 collectVariableInfo(GV.getSubprogram()); 2870 2871 // Build the lexical block structure to emit for this routine. 2872 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope()) 2873 collectLexicalBlockInfo(*CFS, 2874 CurFn->ChildBlocks, 2875 CurFn->Locals, 2876 CurFn->Globals); 2877 2878 // Clear the scope and variable information from the map which will not be 2879 // valid after we have finished processing this routine. This also prepares 2880 // the map for the subsequent routine. 2881 ScopeVariables.clear(); 2882 2883 // Don't emit anything if we don't have any line tables. 2884 // Thunks are compiler-generated and probably won't have source correlation. 2885 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) { 2886 FnDebugInfo.erase(&GV); 2887 CurFn = nullptr; 2888 return; 2889 } 2890 2891 CurFn->Annotations = MF->getCodeViewAnnotations(); 2892 CurFn->HeapAllocSites = MF->getCodeViewHeapAllocSites(); 2893 2894 CurFn->End = Asm->getFunctionEnd(); 2895 2896 CurFn = nullptr; 2897 } 2898 2899 void CodeViewDebug::beginInstruction(const MachineInstr *MI) { 2900 DebugHandlerBase::beginInstruction(MI); 2901 2902 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue. 2903 if (!Asm || !CurFn || MI->isDebugInstr() || 2904 MI->getFlag(MachineInstr::FrameSetup)) 2905 return; 2906 2907 // If the first instruction of a new MBB has no location, find the first 2908 // instruction with a location and use that. 2909 DebugLoc DL = MI->getDebugLoc(); 2910 if (!DL && MI->getParent() != PrevInstBB) { 2911 for (const auto &NextMI : *MI->getParent()) { 2912 if (NextMI.isDebugInstr()) 2913 continue; 2914 DL = NextMI.getDebugLoc(); 2915 if (DL) 2916 break; 2917 } 2918 } 2919 PrevInstBB = MI->getParent(); 2920 2921 // If we still don't have a debug location, don't record a location. 2922 if (!DL) 2923 return; 2924 2925 maybeRecordLocation(DL, Asm->MF); 2926 } 2927 2928 MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) { 2929 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(), 2930 *EndLabel = MMI->getContext().createTempSymbol(); 2931 OS.EmitIntValue(unsigned(Kind), 4); 2932 OS.AddComment("Subsection size"); 2933 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4); 2934 OS.EmitLabel(BeginLabel); 2935 return EndLabel; 2936 } 2937 2938 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) { 2939 OS.EmitLabel(EndLabel); 2940 // Every subsection must be aligned to a 4-byte boundary. 2941 OS.EmitValueToAlignment(4); 2942 } 2943 2944 static StringRef getSymbolName(SymbolKind SymKind) { 2945 for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames()) 2946 if (EE.Value == SymKind) 2947 return EE.Name; 2948 return ""; 2949 } 2950 2951 MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) { 2952 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(), 2953 *EndLabel = MMI->getContext().createTempSymbol(); 2954 OS.AddComment("Record length"); 2955 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2); 2956 OS.EmitLabel(BeginLabel); 2957 if (OS.isVerboseAsm()) 2958 OS.AddComment("Record kind: " + getSymbolName(SymKind)); 2959 OS.EmitIntValue(unsigned(SymKind), 2); 2960 return EndLabel; 2961 } 2962 2963 void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) { 2964 // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid 2965 // an extra copy of every symbol record in LLD. This increases object file 2966 // size by less than 1% in the clang build, and is compatible with the Visual 2967 // C++ linker. 2968 OS.EmitValueToAlignment(4); 2969 OS.EmitLabel(SymEnd); 2970 } 2971 2972 void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) { 2973 OS.AddComment("Record length"); 2974 OS.EmitIntValue(2, 2); 2975 if (OS.isVerboseAsm()) 2976 OS.AddComment("Record kind: " + getSymbolName(EndKind)); 2977 OS.EmitIntValue(unsigned(EndKind), 2); // Record Kind 2978 } 2979 2980 void CodeViewDebug::emitDebugInfoForUDTs( 2981 ArrayRef<std::pair<std::string, const DIType *>> UDTs) { 2982 for (const auto &UDT : UDTs) { 2983 const DIType *T = UDT.second; 2984 assert(shouldEmitUdt(T)); 2985 2986 MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT); 2987 OS.AddComment("Type"); 2988 OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4); 2989 emitNullTerminatedSymbolName(OS, UDT.first); 2990 endSymbolRecord(UDTRecordEnd); 2991 } 2992 } 2993 2994 void CodeViewDebug::collectGlobalVariableInfo() { 2995 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *> 2996 GlobalMap; 2997 for (const GlobalVariable &GV : MMI->getModule()->globals()) { 2998 SmallVector<DIGlobalVariableExpression *, 1> GVEs; 2999 GV.getDebugInfo(GVEs); 3000 for (const auto *GVE : GVEs) 3001 GlobalMap[GVE] = &GV; 3002 } 3003 3004 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 3005 for (const MDNode *Node : CUs->operands()) { 3006 const auto *CU = cast<DICompileUnit>(Node); 3007 for (const auto *GVE : CU->getGlobalVariables()) { 3008 const DIGlobalVariable *DIGV = GVE->getVariable(); 3009 const DIExpression *DIE = GVE->getExpression(); 3010 3011 // Emit constant global variables in a global symbol section. 3012 if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) { 3013 CVGlobalVariable CVGV = {DIGV, DIE}; 3014 GlobalVariables.emplace_back(std::move(CVGV)); 3015 } 3016 3017 const auto *GV = GlobalMap.lookup(GVE); 3018 if (!GV || GV->isDeclarationForLinker()) 3019 continue; 3020 3021 DIScope *Scope = DIGV->getScope(); 3022 SmallVector<CVGlobalVariable, 1> *VariableList; 3023 if (Scope && isa<DILocalScope>(Scope)) { 3024 // Locate a global variable list for this scope, creating one if 3025 // necessary. 3026 auto Insertion = ScopeGlobals.insert( 3027 {Scope, std::unique_ptr<GlobalVariableList>()}); 3028 if (Insertion.second) 3029 Insertion.first->second = llvm::make_unique<GlobalVariableList>(); 3030 VariableList = Insertion.first->second.get(); 3031 } else if (GV->hasComdat()) 3032 // Emit this global variable into a COMDAT section. 3033 VariableList = &ComdatVariables; 3034 else 3035 // Emit this global variable in a single global symbol section. 3036 VariableList = &GlobalVariables; 3037 CVGlobalVariable CVGV = {DIGV, GV}; 3038 VariableList->emplace_back(std::move(CVGV)); 3039 } 3040 } 3041 } 3042 3043 void CodeViewDebug::emitDebugInfoForGlobals() { 3044 // First, emit all globals that are not in a comdat in a single symbol 3045 // substream. MSVC doesn't like it if the substream is empty, so only open 3046 // it if we have at least one global to emit. 3047 switchToDebugSectionForSymbol(nullptr); 3048 if (!GlobalVariables.empty()) { 3049 OS.AddComment("Symbol subsection for globals"); 3050 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols); 3051 emitGlobalVariableList(GlobalVariables); 3052 endCVSubsection(EndLabel); 3053 } 3054 3055 // Second, emit each global that is in a comdat into its own .debug$S 3056 // section along with its own symbol substream. 3057 for (const CVGlobalVariable &CVGV : ComdatVariables) { 3058 const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>(); 3059 MCSymbol *GVSym = Asm->getSymbol(GV); 3060 OS.AddComment("Symbol subsection for " + 3061 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName()))); 3062 switchToDebugSectionForSymbol(GVSym); 3063 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols); 3064 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. 3065 emitDebugInfoForGlobal(CVGV); 3066 endCVSubsection(EndLabel); 3067 } 3068 } 3069 3070 void CodeViewDebug::emitDebugInfoForRetainedTypes() { 3071 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 3072 for (const MDNode *Node : CUs->operands()) { 3073 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) { 3074 if (DIType *RT = dyn_cast<DIType>(Ty)) { 3075 getTypeIndex(RT); 3076 // FIXME: Add to global/local DTU list. 3077 } 3078 } 3079 } 3080 } 3081 3082 // Emit each global variable in the specified array. 3083 void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) { 3084 for (const CVGlobalVariable &CVGV : Globals) { 3085 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. 3086 emitDebugInfoForGlobal(CVGV); 3087 } 3088 } 3089 3090 void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) { 3091 const DIGlobalVariable *DIGV = CVGV.DIGV; 3092 if (const GlobalVariable *GV = 3093 CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) { 3094 // DataSym record, see SymbolRecord.h for more info. Thread local data 3095 // happens to have the same format as global data. 3096 MCSymbol *GVSym = Asm->getSymbol(GV); 3097 SymbolKind DataSym = GV->isThreadLocal() 3098 ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32 3099 : SymbolKind::S_GTHREAD32) 3100 : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32 3101 : SymbolKind::S_GDATA32); 3102 MCSymbol *DataEnd = beginSymbolRecord(DataSym); 3103 OS.AddComment("Type"); 3104 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4); 3105 OS.AddComment("DataOffset"); 3106 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0); 3107 OS.AddComment("Segment"); 3108 OS.EmitCOFFSectionIndex(GVSym); 3109 OS.AddComment("Name"); 3110 const unsigned LengthOfDataRecord = 12; 3111 emitNullTerminatedSymbolName(OS, DIGV->getName(), LengthOfDataRecord); 3112 endSymbolRecord(DataEnd); 3113 } else { 3114 // FIXME: Currently this only emits the global variables in the IR metadata. 3115 // This should also emit enums and static data members. 3116 const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>(); 3117 assert(DIE->isConstant() && 3118 "Global constant variables must contain a constant expression."); 3119 uint64_t Val = DIE->getElement(1); 3120 3121 MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT); 3122 OS.AddComment("Type"); 3123 OS.EmitIntValue(getTypeIndex(DIGV->getType()).getIndex(), 4); 3124 OS.AddComment("Value"); 3125 3126 // Encoded integers shouldn't need more than 10 bytes. 3127 uint8_t data[10]; 3128 BinaryStreamWriter Writer(data, llvm::support::endianness::little); 3129 CodeViewRecordIO IO(Writer); 3130 cantFail(IO.mapEncodedInteger(Val)); 3131 StringRef SRef((char *)data, Writer.getOffset()); 3132 OS.EmitBinaryData(SRef); 3133 3134 OS.AddComment("Name"); 3135 const DIScope *Scope = DIGV->getScope(); 3136 // For static data members, get the scope from the declaration. 3137 if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>( 3138 DIGV->getRawStaticDataMemberDeclaration())) 3139 Scope = MemberDecl->getScope(); 3140 emitNullTerminatedSymbolName(OS, 3141 getFullyQualifiedName(Scope, DIGV->getName())); 3142 endSymbolRecord(SConstantEnd); 3143 } 3144 } 3145