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