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