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