1 #include "PdbAstBuilder.h" 2 3 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" 4 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h" 5 #include "llvm/DebugInfo/CodeView/RecordName.h" 6 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h" 7 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 8 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h" 9 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h" 10 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h" 11 #include "llvm/DebugInfo/PDB/Native/DbiStream.h" 12 #include "llvm/DebugInfo/PDB/Native/PublicsStream.h" 13 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h" 14 #include "llvm/DebugInfo/PDB/Native/TpiStream.h" 15 #include "llvm/Demangle/MicrosoftDemangle.h" 16 17 #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h" 18 #include "Plugins/ExpressionParser/Clang/ClangUtil.h" 19 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h" 20 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h" 21 #include "lldb/Core/Module.h" 22 #include "lldb/Symbol/ObjectFile.h" 23 #include "lldb/Utility/LLDBAssert.h" 24 25 #include "PdbUtil.h" 26 #include "UdtRecordCompleter.h" 27 28 using namespace lldb_private; 29 using namespace lldb_private::npdb; 30 using namespace llvm::codeview; 31 using namespace llvm::pdb; 32 33 namespace { 34 struct CreateMethodDecl : public TypeVisitorCallbacks { 35 CreateMethodDecl(PdbIndex &m_index, TypeSystemClang &m_clang, 36 TypeIndex func_type_index, 37 clang::FunctionDecl *&function_decl, 38 lldb::opaque_compiler_type_t parent_ty, 39 llvm::StringRef proc_name, CompilerType func_ct) 40 : m_index(m_index), m_clang(m_clang), func_type_index(func_type_index), 41 function_decl(function_decl), parent_ty(parent_ty), 42 proc_name(proc_name), func_ct(func_ct) {} 43 PdbIndex &m_index; 44 TypeSystemClang &m_clang; 45 TypeIndex func_type_index; 46 clang::FunctionDecl *&function_decl; 47 lldb::opaque_compiler_type_t parent_ty; 48 llvm::StringRef proc_name; 49 CompilerType func_ct; 50 51 llvm::Error visitKnownMember(CVMemberRecord &cvr, 52 OverloadedMethodRecord &overloaded) override { 53 TypeIndex method_list_idx = overloaded.MethodList; 54 55 CVType method_list_type = m_index.tpi().getType(method_list_idx); 56 assert(method_list_type.kind() == LF_METHODLIST); 57 58 MethodOverloadListRecord method_list; 59 llvm::cantFail(TypeDeserializer::deserializeAs<MethodOverloadListRecord>( 60 method_list_type, method_list)); 61 62 for (const OneMethodRecord &method : method_list.Methods) { 63 if (method.getType().getIndex() == func_type_index.getIndex()) 64 AddMethod(overloaded.Name, method.getAccess(), method.getOptions(), 65 method.Attrs); 66 } 67 68 return llvm::Error::success(); 69 } 70 71 llvm::Error visitKnownMember(CVMemberRecord &cvr, 72 OneMethodRecord &record) override { 73 AddMethod(record.getName(), record.getAccess(), record.getOptions(), 74 record.Attrs); 75 return llvm::Error::success(); 76 } 77 78 void AddMethod(llvm::StringRef name, MemberAccess access, 79 MethodOptions options, MemberAttributes attrs) { 80 if (name != proc_name || function_decl) 81 return; 82 lldb::AccessType access_type = TranslateMemberAccess(access); 83 bool is_virtual = attrs.isVirtual(); 84 bool is_static = attrs.isStatic(); 85 bool is_artificial = (options & MethodOptions::CompilerGenerated) == 86 MethodOptions::CompilerGenerated; 87 function_decl = m_clang.AddMethodToCXXRecordType( 88 parent_ty, proc_name, 89 /*mangled_name=*/nullptr, func_ct, /*access=*/access_type, 90 /*is_virtual=*/is_virtual, /*is_static=*/is_static, 91 /*is_inline=*/false, /*is_explicit=*/false, 92 /*is_attr_used=*/false, /*is_artificial=*/is_artificial); 93 } 94 }; 95 } // namespace 96 97 static llvm::Optional<PdbCompilandSymId> FindSymbolScope(PdbIndex &index, 98 PdbCompilandSymId id) { 99 CVSymbol sym = index.ReadSymbolRecord(id); 100 if (symbolOpensScope(sym.kind())) { 101 // If this exact symbol opens a scope, we can just directly access its 102 // parent. 103 id.offset = getScopeParentOffset(sym); 104 // Global symbols have parent offset of 0. Return llvm::None to indicate 105 // this. 106 if (id.offset == 0) 107 return llvm::None; 108 return id; 109 } 110 111 // Otherwise we need to start at the beginning and iterate forward until we 112 // reach (or pass) this particular symbol 113 CompilandIndexItem &cii = index.compilands().GetOrCreateCompiland(id.modi); 114 const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray(); 115 116 auto begin = syms.begin(); 117 auto end = syms.at(id.offset); 118 std::vector<PdbCompilandSymId> scope_stack; 119 120 while (begin != end) { 121 if (begin.offset() > id.offset) { 122 // We passed it. We couldn't even find this symbol record. 123 lldbassert(false && "Invalid compiland symbol id!"); 124 return llvm::None; 125 } 126 127 // We haven't found the symbol yet. Check if we need to open or close the 128 // scope stack. 129 if (symbolOpensScope(begin->kind())) { 130 // We can use the end offset of the scope to determine whether or not 131 // we can just outright skip this entire scope. 132 uint32_t scope_end = getScopeEndOffset(*begin); 133 if (scope_end < id.offset) { 134 begin = syms.at(scope_end); 135 } else { 136 // The symbol we're looking for is somewhere in this scope. 137 scope_stack.emplace_back(id.modi, begin.offset()); 138 } 139 } else if (symbolEndsScope(begin->kind())) { 140 scope_stack.pop_back(); 141 } 142 ++begin; 143 } 144 if (scope_stack.empty()) 145 return llvm::None; 146 // We have a match! Return the top of the stack 147 return scope_stack.back(); 148 } 149 150 static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) { 151 switch (cr.Kind) { 152 case TypeRecordKind::Class: 153 return clang::TTK_Class; 154 case TypeRecordKind::Struct: 155 return clang::TTK_Struct; 156 case TypeRecordKind::Union: 157 return clang::TTK_Union; 158 case TypeRecordKind::Interface: 159 return clang::TTK_Interface; 160 case TypeRecordKind::Enum: 161 return clang::TTK_Enum; 162 default: 163 lldbassert(false && "Invalid tag record kind!"); 164 return clang::TTK_Struct; 165 } 166 } 167 168 static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) { 169 if (args.empty()) 170 return false; 171 return args.back() == TypeIndex::None(); 172 } 173 174 static bool 175 AnyScopesHaveTemplateParams(llvm::ArrayRef<llvm::ms_demangle::Node *> scopes) { 176 for (llvm::ms_demangle::Node *n : scopes) { 177 auto *idn = static_cast<llvm::ms_demangle::IdentifierNode *>(n); 178 if (idn->TemplateParams) 179 return true; 180 } 181 return false; 182 } 183 184 static llvm::Optional<clang::CallingConv> 185 TranslateCallingConvention(llvm::codeview::CallingConvention conv) { 186 using CC = llvm::codeview::CallingConvention; 187 switch (conv) { 188 189 case CC::NearC: 190 case CC::FarC: 191 return clang::CallingConv::CC_C; 192 case CC::NearPascal: 193 case CC::FarPascal: 194 return clang::CallingConv::CC_X86Pascal; 195 case CC::NearFast: 196 case CC::FarFast: 197 return clang::CallingConv::CC_X86FastCall; 198 case CC::NearStdCall: 199 case CC::FarStdCall: 200 return clang::CallingConv::CC_X86StdCall; 201 case CC::ThisCall: 202 return clang::CallingConv::CC_X86ThisCall; 203 case CC::NearVector: 204 return clang::CallingConv::CC_X86VectorCall; 205 default: 206 return llvm::None; 207 } 208 } 209 210 static llvm::Optional<CVTagRecord> 211 GetNestedTagDefinition(const NestedTypeRecord &Record, 212 const CVTagRecord &parent, TpiStream &tpi) { 213 // An LF_NESTTYPE is essentially a nested typedef / using declaration, but it 214 // is also used to indicate the primary definition of a nested class. That is 215 // to say, if you have: 216 // struct A { 217 // struct B {}; 218 // using C = B; 219 // }; 220 // Then in the debug info, this will appear as: 221 // LF_STRUCTURE `A::B` [type index = N] 222 // LF_STRUCTURE `A` 223 // LF_NESTTYPE [name = `B`, index = N] 224 // LF_NESTTYPE [name = `C`, index = N] 225 // In order to accurately reconstruct the decl context hierarchy, we need to 226 // know which ones are actual definitions and which ones are just aliases. 227 228 // If it's a simple type, then this is something like `using foo = int`. 229 if (Record.Type.isSimple()) 230 return llvm::None; 231 232 CVType cvt = tpi.getType(Record.Type); 233 234 if (!IsTagRecord(cvt)) 235 return llvm::None; 236 237 // If it's an inner definition, then treat whatever name we have here as a 238 // single component of a mangled name. So we can inject it into the parent's 239 // mangled name to see if it matches. 240 CVTagRecord child = CVTagRecord::create(cvt); 241 std::string qname = std::string(parent.asTag().getUniqueName()); 242 if (qname.size() < 4 || child.asTag().getUniqueName().size() < 4) 243 return llvm::None; 244 245 // qname[3] is the tag type identifier (struct, class, union, etc). Since the 246 // inner tag type is not necessarily the same as the outer tag type, re-write 247 // it to match the inner tag type. 248 qname[3] = child.asTag().getUniqueName()[3]; 249 std::string piece; 250 if (qname[3] == 'W') 251 piece = "4"; 252 piece += Record.Name; 253 piece.push_back('@'); 254 qname.insert(4, std::move(piece)); 255 if (qname != child.asTag().UniqueName) 256 return llvm::None; 257 258 return std::move(child); 259 } 260 261 static bool IsAnonymousNamespaceName(llvm::StringRef name) { 262 return name == "`anonymous namespace'" || name == "`anonymous-namespace'"; 263 } 264 265 PdbAstBuilder::PdbAstBuilder(ObjectFile &obj, PdbIndex &index, TypeSystemClang &clang) 266 : m_index(index), m_clang(clang) { 267 BuildParentMap(); 268 } 269 270 lldb_private::CompilerDeclContext PdbAstBuilder::GetTranslationUnitDecl() { 271 return ToCompilerDeclContext(*m_clang.GetTranslationUnitDecl()); 272 } 273 274 std::pair<clang::DeclContext *, std::string> 275 PdbAstBuilder::CreateDeclInfoForType(const TagRecord &record, TypeIndex ti) { 276 // FIXME: Move this to GetDeclContextContainingUID. 277 if (!record.hasUniqueName()) 278 return CreateDeclInfoForUndecoratedName(record.Name); 279 280 llvm::ms_demangle::Demangler demangler; 281 StringView sv(record.UniqueName.begin(), record.UniqueName.size()); 282 llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv); 283 if (demangler.Error) 284 return {m_clang.GetTranslationUnitDecl(), std::string(record.UniqueName)}; 285 286 llvm::ms_demangle::IdentifierNode *idn = 287 ttn->QualifiedName->getUnqualifiedIdentifier(); 288 std::string uname = idn->toString(llvm::ms_demangle::OF_NoTagSpecifier); 289 290 llvm::ms_demangle::NodeArrayNode *name_components = 291 ttn->QualifiedName->Components; 292 llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes, 293 name_components->Count - 1); 294 295 clang::DeclContext *context = m_clang.GetTranslationUnitDecl(); 296 297 // If this type doesn't have a parent type in the debug info, then the best we 298 // can do is to say that it's either a series of namespaces (if the scope is 299 // non-empty), or the translation unit (if the scope is empty). 300 auto parent_iter = m_parent_types.find(ti); 301 if (parent_iter == m_parent_types.end()) { 302 if (scopes.empty()) 303 return {context, uname}; 304 305 // If there is no parent in the debug info, but some of the scopes have 306 // template params, then this is a case of bad debug info. See, for 307 // example, llvm.org/pr39607. We don't want to create an ambiguity between 308 // a NamespaceDecl and a CXXRecordDecl, so instead we create a class at 309 // global scope with the fully qualified name. 310 if (AnyScopesHaveTemplateParams(scopes)) 311 return {context, std::string(record.Name)}; 312 313 for (llvm::ms_demangle::Node *scope : scopes) { 314 auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope); 315 std::string str = nii->toString(); 316 context = GetOrCreateNamespaceDecl(str.c_str(), *context); 317 } 318 return {context, uname}; 319 } 320 321 // Otherwise, all we need to do is get the parent type of this type and 322 // recurse into our lazy type creation / AST reconstruction logic to get an 323 // LLDB TypeSP for the parent. This will cause the AST to automatically get 324 // the right DeclContext created for any parent. 325 clang::QualType parent_qt = GetOrCreateType(parent_iter->second); 326 if (parent_qt.isNull()) 327 return {nullptr, ""}; 328 329 context = clang::TagDecl::castToDeclContext(parent_qt->getAsTagDecl()); 330 return {context, uname}; 331 } 332 333 void PdbAstBuilder::BuildParentMap() { 334 LazyRandomTypeCollection &types = m_index.tpi().typeCollection(); 335 336 llvm::DenseMap<TypeIndex, TypeIndex> forward_to_full; 337 llvm::DenseMap<TypeIndex, TypeIndex> full_to_forward; 338 339 struct RecordIndices { 340 TypeIndex forward; 341 TypeIndex full; 342 }; 343 344 llvm::StringMap<RecordIndices> record_indices; 345 346 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) { 347 CVType type = types.getType(*ti); 348 if (!IsTagRecord(type)) 349 continue; 350 351 CVTagRecord tag = CVTagRecord::create(type); 352 353 RecordIndices &indices = record_indices[tag.asTag().getUniqueName()]; 354 if (tag.asTag().isForwardRef()) 355 indices.forward = *ti; 356 else 357 indices.full = *ti; 358 359 if (indices.full != TypeIndex::None() && 360 indices.forward != TypeIndex::None()) { 361 forward_to_full[indices.forward] = indices.full; 362 full_to_forward[indices.full] = indices.forward; 363 } 364 365 // We're looking for LF_NESTTYPE records in the field list, so ignore 366 // forward references (no field list), and anything without a nested class 367 // (since there won't be any LF_NESTTYPE records). 368 if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass()) 369 continue; 370 371 struct ProcessTpiStream : public TypeVisitorCallbacks { 372 ProcessTpiStream(PdbIndex &index, TypeIndex parent, 373 const CVTagRecord &parent_cvt, 374 llvm::DenseMap<TypeIndex, TypeIndex> &parents) 375 : index(index), parents(parents), parent(parent), 376 parent_cvt(parent_cvt) {} 377 378 PdbIndex &index; 379 llvm::DenseMap<TypeIndex, TypeIndex> &parents; 380 381 unsigned unnamed_type_index = 1; 382 TypeIndex parent; 383 const CVTagRecord &parent_cvt; 384 385 llvm::Error visitKnownMember(CVMemberRecord &CVR, 386 NestedTypeRecord &Record) override { 387 std::string unnamed_type_name; 388 if (Record.Name.empty()) { 389 unnamed_type_name = 390 llvm::formatv("<unnamed-type-$S{0}>", unnamed_type_index).str(); 391 Record.Name = unnamed_type_name; 392 ++unnamed_type_index; 393 } 394 llvm::Optional<CVTagRecord> tag = 395 GetNestedTagDefinition(Record, parent_cvt, index.tpi()); 396 if (!tag) 397 return llvm::ErrorSuccess(); 398 399 parents[Record.Type] = parent; 400 return llvm::ErrorSuccess(); 401 } 402 }; 403 404 CVType field_list_cvt = m_index.tpi().getType(tag.asTag().FieldList); 405 ProcessTpiStream process(m_index, *ti, tag, m_parent_types); 406 FieldListRecord field_list; 407 if (llvm::Error error = TypeDeserializer::deserializeAs<FieldListRecord>( 408 field_list_cvt, field_list)) 409 llvm::consumeError(std::move(error)); 410 if (llvm::Error error = visitMemberRecordStream(field_list.Data, process)) 411 llvm::consumeError(std::move(error)); 412 } 413 414 // Now that we know the forward -> full mapping of all type indices, we can 415 // re-write all the indices. At the end of this process, we want a mapping 416 // consisting of fwd -> full and full -> full for all child -> parent indices. 417 // We can re-write the values in place, but for the keys, we must save them 418 // off so that we don't modify the map in place while also iterating it. 419 std::vector<TypeIndex> full_keys; 420 std::vector<TypeIndex> fwd_keys; 421 for (auto &entry : m_parent_types) { 422 TypeIndex key = entry.first; 423 TypeIndex value = entry.second; 424 425 auto iter = forward_to_full.find(value); 426 if (iter != forward_to_full.end()) 427 entry.second = iter->second; 428 429 iter = forward_to_full.find(key); 430 if (iter != forward_to_full.end()) 431 fwd_keys.push_back(key); 432 else 433 full_keys.push_back(key); 434 } 435 for (TypeIndex fwd : fwd_keys) { 436 TypeIndex full = forward_to_full[fwd]; 437 m_parent_types[full] = m_parent_types[fwd]; 438 } 439 for (TypeIndex full : full_keys) { 440 TypeIndex fwd = full_to_forward[full]; 441 m_parent_types[fwd] = m_parent_types[full]; 442 } 443 444 // Now that 445 } 446 447 static bool isLocalVariableType(SymbolKind K) { 448 switch (K) { 449 case S_REGISTER: 450 case S_REGREL32: 451 case S_LOCAL: 452 return true; 453 default: 454 break; 455 } 456 return false; 457 } 458 459 static std::string 460 RenderScopeList(llvm::ArrayRef<llvm::ms_demangle::Node *> nodes) { 461 lldbassert(!nodes.empty()); 462 463 std::string result = nodes.front()->toString(); 464 nodes = nodes.drop_front(); 465 while (!nodes.empty()) { 466 result += "::"; 467 result += nodes.front()->toString(llvm::ms_demangle::OF_NoTagSpecifier); 468 nodes = nodes.drop_front(); 469 } 470 return result; 471 } 472 473 static llvm::Optional<PublicSym32> FindPublicSym(const SegmentOffset &addr, 474 SymbolStream &syms, 475 PublicsStream &publics) { 476 llvm::FixedStreamArray<ulittle32_t> addr_map = publics.getAddressMap(); 477 auto iter = std::lower_bound( 478 addr_map.begin(), addr_map.end(), addr, 479 [&](const ulittle32_t &x, const SegmentOffset &y) { 480 CVSymbol s1 = syms.readRecord(x); 481 lldbassert(s1.kind() == S_PUB32); 482 PublicSym32 p1; 483 llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(s1, p1)); 484 if (p1.Segment < y.segment) 485 return true; 486 return p1.Offset < y.offset; 487 }); 488 if (iter == addr_map.end()) 489 return llvm::None; 490 CVSymbol sym = syms.readRecord(*iter); 491 lldbassert(sym.kind() == S_PUB32); 492 PublicSym32 p; 493 llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(sym, p)); 494 if (p.Segment == addr.segment && p.Offset == addr.offset) 495 return p; 496 return llvm::None; 497 } 498 499 clang::Decl *PdbAstBuilder::GetOrCreateSymbolForId(PdbCompilandSymId id) { 500 CVSymbol cvs = m_index.ReadSymbolRecord(id); 501 502 if (isLocalVariableType(cvs.kind())) { 503 clang::DeclContext *scope = GetParentDeclContext(id); 504 clang::Decl *scope_decl = clang::Decl::castFromDeclContext(scope); 505 PdbCompilandSymId scope_id = 506 PdbSymUid(m_decl_to_status[scope_decl].uid).asCompilandSym(); 507 return GetOrCreateVariableDecl(scope_id, id); 508 } 509 510 switch (cvs.kind()) { 511 case S_GPROC32: 512 case S_LPROC32: 513 return GetOrCreateFunctionDecl(id); 514 case S_GDATA32: 515 case S_LDATA32: 516 case S_GTHREAD32: 517 case S_CONSTANT: 518 // global variable 519 return nullptr; 520 case S_BLOCK32: 521 return GetOrCreateBlockDecl(id); 522 case S_INLINESITE: 523 return GetOrCreateInlinedFunctionDecl(id); 524 default: 525 return nullptr; 526 } 527 } 528 529 llvm::Optional<CompilerDecl> PdbAstBuilder::GetOrCreateDeclForUid(PdbSymUid uid) { 530 if (clang::Decl *result = TryGetDecl(uid)) 531 return ToCompilerDecl(*result); 532 533 clang::Decl *result = nullptr; 534 switch (uid.kind()) { 535 case PdbSymUidKind::CompilandSym: 536 result = GetOrCreateSymbolForId(uid.asCompilandSym()); 537 break; 538 case PdbSymUidKind::Type: { 539 clang::QualType qt = GetOrCreateType(uid.asTypeSym()); 540 if (qt.isNull()) 541 return llvm::None; 542 if (auto *tag = qt->getAsTagDecl()) { 543 result = tag; 544 break; 545 } 546 return llvm::None; 547 } 548 default: 549 return llvm::None; 550 } 551 552 if (!result) 553 return llvm::None; 554 m_uid_to_decl[toOpaqueUid(uid)] = result; 555 return ToCompilerDecl(*result); 556 } 557 558 clang::DeclContext *PdbAstBuilder::GetOrCreateDeclContextForUid(PdbSymUid uid) { 559 if (uid.kind() == PdbSymUidKind::CompilandSym) { 560 if (uid.asCompilandSym().offset == 0) 561 return FromCompilerDeclContext(GetTranslationUnitDecl()); 562 } 563 auto option = GetOrCreateDeclForUid(uid); 564 if (!option) 565 return nullptr; 566 clang::Decl *decl = FromCompilerDecl(*option); 567 if (!decl) 568 return nullptr; 569 570 return clang::Decl::castToDeclContext(decl); 571 } 572 573 std::pair<clang::DeclContext *, std::string> 574 PdbAstBuilder::CreateDeclInfoForUndecoratedName(llvm::StringRef name) { 575 MSVCUndecoratedNameParser parser(name); 576 llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers(); 577 578 auto context = FromCompilerDeclContext(GetTranslationUnitDecl()); 579 580 llvm::StringRef uname = specs.back().GetBaseName(); 581 specs = specs.drop_back(); 582 if (specs.empty()) 583 return {context, std::string(name)}; 584 585 llvm::StringRef scope_name = specs.back().GetFullName(); 586 587 // It might be a class name, try that first. 588 std::vector<TypeIndex> types = m_index.tpi().findRecordsByName(scope_name); 589 while (!types.empty()) { 590 clang::QualType qt = GetOrCreateType(types.back()); 591 if (qt.isNull()) 592 continue; 593 clang::TagDecl *tag = qt->getAsTagDecl(); 594 if (tag) 595 return {clang::TagDecl::castToDeclContext(tag), std::string(uname)}; 596 types.pop_back(); 597 } 598 599 // If that fails, treat it as a series of namespaces. 600 for (const MSVCUndecoratedNameSpecifier &spec : specs) { 601 std::string ns_name = spec.GetBaseName().str(); 602 context = GetOrCreateNamespaceDecl(ns_name.c_str(), *context); 603 } 604 return {context, std::string(uname)}; 605 } 606 607 clang::DeclContext * 608 PdbAstBuilder::GetParentDeclContextForSymbol(const CVSymbol &sym) { 609 if (!SymbolHasAddress(sym)) 610 return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first; 611 SegmentOffset addr = GetSegmentAndOffset(sym); 612 llvm::Optional<PublicSym32> pub = 613 FindPublicSym(addr, m_index.symrecords(), m_index.publics()); 614 if (!pub) 615 return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first; 616 617 llvm::ms_demangle::Demangler demangler; 618 StringView name{pub->Name.begin(), pub->Name.size()}; 619 llvm::ms_demangle::SymbolNode *node = demangler.parse(name); 620 if (!node) 621 return FromCompilerDeclContext(GetTranslationUnitDecl()); 622 llvm::ArrayRef<llvm::ms_demangle::Node *> name_components{ 623 node->Name->Components->Nodes, node->Name->Components->Count - 1}; 624 625 if (!name_components.empty()) { 626 // Render the current list of scope nodes as a fully qualified name, and 627 // look it up in the debug info as a type name. If we find something, 628 // this is a type (which may itself be prefixed by a namespace). If we 629 // don't, this is a list of namespaces. 630 std::string qname = RenderScopeList(name_components); 631 std::vector<TypeIndex> matches = m_index.tpi().findRecordsByName(qname); 632 while (!matches.empty()) { 633 clang::QualType qt = GetOrCreateType(matches.back()); 634 if (qt.isNull()) 635 continue; 636 clang::TagDecl *tag = qt->getAsTagDecl(); 637 if (tag) 638 return clang::TagDecl::castToDeclContext(tag); 639 matches.pop_back(); 640 } 641 } 642 643 // It's not a type. It must be a series of namespaces. 644 auto context = FromCompilerDeclContext(GetTranslationUnitDecl()); 645 while (!name_components.empty()) { 646 std::string ns = name_components.front()->toString(); 647 context = GetOrCreateNamespaceDecl(ns.c_str(), *context); 648 name_components = name_components.drop_front(); 649 } 650 return context; 651 } 652 653 clang::DeclContext *PdbAstBuilder::GetParentDeclContext(PdbSymUid uid) { 654 // We must do this *without* calling GetOrCreate on the current uid, as 655 // that would be an infinite recursion. 656 switch (uid.kind()) { 657 case PdbSymUidKind::CompilandSym: { 658 llvm::Optional<PdbCompilandSymId> scope = 659 FindSymbolScope(m_index, uid.asCompilandSym()); 660 if (scope) 661 return GetOrCreateDeclContextForUid(*scope); 662 663 CVSymbol sym = m_index.ReadSymbolRecord(uid.asCompilandSym()); 664 return GetParentDeclContextForSymbol(sym); 665 } 666 case PdbSymUidKind::Type: { 667 // It could be a namespace, class, or global. We don't support nested 668 // functions yet. Anyway, we just need to consult the parent type map. 669 PdbTypeSymId type_id = uid.asTypeSym(); 670 auto iter = m_parent_types.find(type_id.index); 671 if (iter == m_parent_types.end()) 672 return FromCompilerDeclContext(GetTranslationUnitDecl()); 673 return GetOrCreateDeclContextForUid(PdbTypeSymId(iter->second)); 674 } 675 case PdbSymUidKind::FieldListMember: 676 // In this case the parent DeclContext is the one for the class that this 677 // member is inside of. 678 break; 679 case PdbSymUidKind::GlobalSym: { 680 // If this refers to a compiland symbol, just recurse in with that symbol. 681 // The only other possibilities are S_CONSTANT and S_UDT, in which case we 682 // need to parse the undecorated name to figure out the scope, then look 683 // that up in the TPI stream. If it's found, it's a type, othewrise it's 684 // a series of namespaces. 685 // FIXME: do this. 686 CVSymbol global = m_index.ReadSymbolRecord(uid.asGlobalSym()); 687 switch (global.kind()) { 688 case SymbolKind::S_GDATA32: 689 case SymbolKind::S_LDATA32: 690 return GetParentDeclContextForSymbol(global); 691 case SymbolKind::S_PROCREF: 692 case SymbolKind::S_LPROCREF: { 693 ProcRefSym ref{global.kind()}; 694 llvm::cantFail( 695 SymbolDeserializer::deserializeAs<ProcRefSym>(global, ref)); 696 PdbCompilandSymId cu_sym_id{ref.modi(), ref.SymOffset}; 697 return GetParentDeclContext(cu_sym_id); 698 } 699 case SymbolKind::S_CONSTANT: 700 case SymbolKind::S_UDT: 701 return CreateDeclInfoForUndecoratedName(getSymbolName(global)).first; 702 default: 703 break; 704 } 705 break; 706 } 707 default: 708 break; 709 } 710 return FromCompilerDeclContext(GetTranslationUnitDecl()); 711 } 712 713 bool PdbAstBuilder::CompleteType(clang::QualType qt) { 714 if (qt.isNull()) 715 return false; 716 clang::TagDecl *tag = qt->getAsTagDecl(); 717 if (qt->isArrayType()) { 718 const clang::Type *element_type = qt->getArrayElementTypeNoTypeQual(); 719 tag = element_type->getAsTagDecl(); 720 } 721 if (!tag) 722 return false; 723 724 return CompleteTagDecl(*tag); 725 } 726 727 bool PdbAstBuilder::CompleteTagDecl(clang::TagDecl &tag) { 728 // If this is not in our map, it's an error. 729 auto status_iter = m_decl_to_status.find(&tag); 730 lldbassert(status_iter != m_decl_to_status.end()); 731 732 // If it's already complete, just return. 733 DeclStatus &status = status_iter->second; 734 if (status.resolved) 735 return true; 736 737 PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym(); 738 739 lldbassert(IsTagRecord(type_id, m_index.tpi())); 740 741 clang::QualType tag_qt = m_clang.getASTContext().getTypeDeclType(&tag); 742 TypeSystemClang::SetHasExternalStorage(tag_qt.getAsOpaquePtr(), false); 743 744 TypeIndex tag_ti = type_id.index; 745 CVType cvt = m_index.tpi().getType(tag_ti); 746 if (cvt.kind() == LF_MODIFIER) 747 tag_ti = LookThroughModifierRecord(cvt); 748 749 PdbTypeSymId best_ti = GetBestPossibleDecl(tag_ti, m_index.tpi()); 750 cvt = m_index.tpi().getType(best_ti.index); 751 lldbassert(IsTagRecord(cvt)); 752 753 if (IsForwardRefUdt(cvt)) { 754 // If we can't find a full decl for this forward ref anywhere in the debug 755 // info, then we have no way to complete it. 756 return false; 757 } 758 759 TypeIndex field_list_ti = GetFieldListIndex(cvt); 760 CVType field_list_cvt = m_index.tpi().getType(field_list_ti); 761 if (field_list_cvt.kind() != LF_FIELDLIST) 762 return false; 763 FieldListRecord field_list; 764 if (llvm::Error error = TypeDeserializer::deserializeAs<FieldListRecord>( 765 field_list_cvt, field_list)) 766 llvm::consumeError(std::move(error)); 767 768 // Visit all members of this class, then perform any finalization necessary 769 // to complete the class. 770 CompilerType ct = ToCompilerType(tag_qt); 771 UdtRecordCompleter completer(best_ti, ct, tag, *this, m_index, 772 m_cxx_record_map); 773 llvm::Error error = 774 llvm::codeview::visitMemberRecordStream(field_list.Data, completer); 775 completer.complete(); 776 777 status.resolved = true; 778 if (error) { 779 llvm::consumeError(std::move(error)); 780 return false; 781 } 782 return true; 783 } 784 785 clang::QualType PdbAstBuilder::CreateSimpleType(TypeIndex ti) { 786 if (ti == TypeIndex::NullptrT()) 787 return GetBasicType(lldb::eBasicTypeNullPtr); 788 789 if (ti.getSimpleMode() != SimpleTypeMode::Direct) { 790 clang::QualType direct_type = GetOrCreateType(ti.makeDirect()); 791 if (direct_type.isNull()) 792 return {}; 793 return m_clang.getASTContext().getPointerType(direct_type); 794 } 795 796 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated) 797 return {}; 798 799 lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind()); 800 if (bt == lldb::eBasicTypeInvalid) 801 return {}; 802 803 return GetBasicType(bt); 804 } 805 806 clang::QualType PdbAstBuilder::CreatePointerType(const PointerRecord &pointer) { 807 clang::QualType pointee_type = GetOrCreateType(pointer.ReferentType); 808 809 // This can happen for pointers to LF_VTSHAPE records, which we shouldn't 810 // create in the AST. 811 if (pointee_type.isNull()) 812 return {}; 813 814 if (pointer.isPointerToMember()) { 815 MemberPointerInfo mpi = pointer.getMemberInfo(); 816 clang::QualType class_type = GetOrCreateType(mpi.ContainingType); 817 if (class_type.isNull()) 818 return {}; 819 if (clang::TagDecl *tag = class_type->getAsTagDecl()) { 820 clang::MSInheritanceAttr::Spelling spelling; 821 switch (mpi.Representation) { 822 case llvm::codeview::PointerToMemberRepresentation::SingleInheritanceData: 823 case llvm::codeview::PointerToMemberRepresentation:: 824 SingleInheritanceFunction: 825 spelling = 826 clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance; 827 break; 828 case llvm::codeview::PointerToMemberRepresentation:: 829 MultipleInheritanceData: 830 case llvm::codeview::PointerToMemberRepresentation:: 831 MultipleInheritanceFunction: 832 spelling = 833 clang::MSInheritanceAttr::Spelling::Keyword_multiple_inheritance; 834 break; 835 case llvm::codeview::PointerToMemberRepresentation:: 836 VirtualInheritanceData: 837 case llvm::codeview::PointerToMemberRepresentation:: 838 VirtualInheritanceFunction: 839 spelling = 840 clang::MSInheritanceAttr::Spelling::Keyword_virtual_inheritance; 841 break; 842 case llvm::codeview::PointerToMemberRepresentation::Unknown: 843 spelling = 844 clang::MSInheritanceAttr::Spelling::Keyword_unspecified_inheritance; 845 break; 846 default: 847 spelling = clang::MSInheritanceAttr::Spelling::SpellingNotCalculated; 848 break; 849 } 850 tag->addAttr(clang::MSInheritanceAttr::CreateImplicit( 851 m_clang.getASTContext(), spelling)); 852 } 853 return m_clang.getASTContext().getMemberPointerType( 854 pointee_type, class_type.getTypePtr()); 855 } 856 857 clang::QualType pointer_type; 858 if (pointer.getMode() == PointerMode::LValueReference) 859 pointer_type = m_clang.getASTContext().getLValueReferenceType(pointee_type); 860 else if (pointer.getMode() == PointerMode::RValueReference) 861 pointer_type = m_clang.getASTContext().getRValueReferenceType(pointee_type); 862 else 863 pointer_type = m_clang.getASTContext().getPointerType(pointee_type); 864 865 if ((pointer.getOptions() & PointerOptions::Const) != PointerOptions::None) 866 pointer_type.addConst(); 867 868 if ((pointer.getOptions() & PointerOptions::Volatile) != PointerOptions::None) 869 pointer_type.addVolatile(); 870 871 if ((pointer.getOptions() & PointerOptions::Restrict) != PointerOptions::None) 872 pointer_type.addRestrict(); 873 874 return pointer_type; 875 } 876 877 clang::QualType 878 PdbAstBuilder::CreateModifierType(const ModifierRecord &modifier) { 879 clang::QualType unmodified_type = GetOrCreateType(modifier.ModifiedType); 880 if (unmodified_type.isNull()) 881 return {}; 882 883 if ((modifier.Modifiers & ModifierOptions::Const) != ModifierOptions::None) 884 unmodified_type.addConst(); 885 if ((modifier.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None) 886 unmodified_type.addVolatile(); 887 888 return unmodified_type; 889 } 890 891 clang::QualType PdbAstBuilder::CreateRecordType(PdbTypeSymId id, 892 const TagRecord &record) { 893 clang::DeclContext *context = nullptr; 894 std::string uname; 895 std::tie(context, uname) = CreateDeclInfoForType(record, id.index); 896 if (!context) 897 return {}; 898 899 clang::TagTypeKind ttk = TranslateUdtKind(record); 900 lldb::AccessType access = 901 (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic; 902 903 ClangASTMetadata metadata; 904 metadata.SetUserID(toOpaqueUid(id)); 905 metadata.SetIsDynamicCXXType(false); 906 907 CompilerType ct = 908 m_clang.CreateRecordType(context, OptionalClangModuleID(), access, uname, 909 ttk, lldb::eLanguageTypeC_plus_plus, &metadata); 910 911 lldbassert(ct.IsValid()); 912 913 TypeSystemClang::StartTagDeclarationDefinition(ct); 914 915 // Even if it's possible, don't complete it at this point. Just mark it 916 // forward resolved, and if/when LLDB needs the full definition, it can 917 // ask us. 918 clang::QualType result = 919 clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType()); 920 921 TypeSystemClang::SetHasExternalStorage(result.getAsOpaquePtr(), true); 922 return result; 923 } 924 925 clang::Decl *PdbAstBuilder::TryGetDecl(PdbSymUid uid) const { 926 auto iter = m_uid_to_decl.find(toOpaqueUid(uid)); 927 if (iter != m_uid_to_decl.end()) 928 return iter->second; 929 return nullptr; 930 } 931 932 clang::NamespaceDecl * 933 PdbAstBuilder::GetOrCreateNamespaceDecl(const char *name, 934 clang::DeclContext &context) { 935 return m_clang.GetUniqueNamespaceDeclaration( 936 IsAnonymousNamespaceName(name) ? nullptr : name, &context, 937 OptionalClangModuleID()); 938 } 939 940 clang::BlockDecl * 941 PdbAstBuilder::GetOrCreateBlockDecl(PdbCompilandSymId block_id) { 942 if (clang::Decl *decl = TryGetDecl(block_id)) 943 return llvm::dyn_cast<clang::BlockDecl>(decl); 944 945 clang::DeclContext *scope = GetParentDeclContext(block_id); 946 947 clang::BlockDecl *block_decl = 948 m_clang.CreateBlockDeclaration(scope, OptionalClangModuleID()); 949 m_uid_to_decl.insert({toOpaqueUid(block_id), block_decl}); 950 951 DeclStatus status; 952 status.resolved = true; 953 status.uid = toOpaqueUid(block_id); 954 m_decl_to_status.insert({block_decl, status}); 955 956 return block_decl; 957 } 958 959 clang::VarDecl *PdbAstBuilder::CreateVariableDecl(PdbSymUid uid, CVSymbol sym, 960 clang::DeclContext &scope) { 961 VariableInfo var_info = GetVariableNameInfo(sym); 962 clang::QualType qt = GetOrCreateType(var_info.type); 963 if (qt.isNull()) 964 return nullptr; 965 966 clang::VarDecl *var_decl = m_clang.CreateVariableDeclaration( 967 &scope, OptionalClangModuleID(), var_info.name.str().c_str(), qt); 968 969 m_uid_to_decl[toOpaqueUid(uid)] = var_decl; 970 DeclStatus status; 971 status.resolved = true; 972 status.uid = toOpaqueUid(uid); 973 m_decl_to_status.insert({var_decl, status}); 974 return var_decl; 975 } 976 977 clang::VarDecl * 978 PdbAstBuilder::GetOrCreateVariableDecl(PdbCompilandSymId scope_id, 979 PdbCompilandSymId var_id) { 980 if (clang::Decl *decl = TryGetDecl(var_id)) 981 return llvm::dyn_cast<clang::VarDecl>(decl); 982 983 clang::DeclContext *scope = GetOrCreateDeclContextForUid(scope_id); 984 if (!scope) 985 return nullptr; 986 987 CVSymbol sym = m_index.ReadSymbolRecord(var_id); 988 return CreateVariableDecl(PdbSymUid(var_id), sym, *scope); 989 } 990 991 clang::VarDecl *PdbAstBuilder::GetOrCreateVariableDecl(PdbGlobalSymId var_id) { 992 if (clang::Decl *decl = TryGetDecl(var_id)) 993 return llvm::dyn_cast<clang::VarDecl>(decl); 994 995 CVSymbol sym = m_index.ReadSymbolRecord(var_id); 996 auto context = FromCompilerDeclContext(GetTranslationUnitDecl()); 997 return CreateVariableDecl(PdbSymUid(var_id), sym, *context); 998 } 999 1000 clang::TypedefNameDecl * 1001 PdbAstBuilder::GetOrCreateTypedefDecl(PdbGlobalSymId id) { 1002 if (clang::Decl *decl = TryGetDecl(id)) 1003 return llvm::dyn_cast<clang::TypedefNameDecl>(decl); 1004 1005 CVSymbol sym = m_index.ReadSymbolRecord(id); 1006 lldbassert(sym.kind() == S_UDT); 1007 UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym)); 1008 1009 clang::DeclContext *scope = GetParentDeclContext(id); 1010 1011 PdbTypeSymId real_type_id{udt.Type, false}; 1012 clang::QualType qt = GetOrCreateType(real_type_id); 1013 if (qt.isNull()) 1014 return nullptr; 1015 1016 std::string uname = std::string(DropNameScope(udt.Name)); 1017 1018 CompilerType ct = ToCompilerType(qt).CreateTypedef( 1019 uname.c_str(), ToCompilerDeclContext(*scope), 0); 1020 clang::TypedefNameDecl *tnd = m_clang.GetAsTypedefDecl(ct); 1021 DeclStatus status; 1022 status.resolved = true; 1023 status.uid = toOpaqueUid(id); 1024 m_decl_to_status.insert({tnd, status}); 1025 return tnd; 1026 } 1027 1028 clang::QualType PdbAstBuilder::GetBasicType(lldb::BasicType type) { 1029 CompilerType ct = m_clang.GetBasicType(type); 1030 return clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType()); 1031 } 1032 1033 clang::QualType PdbAstBuilder::CreateType(PdbTypeSymId type) { 1034 if (type.index.isSimple()) 1035 return CreateSimpleType(type.index); 1036 1037 CVType cvt = m_index.tpi().getType(type.index); 1038 1039 if (cvt.kind() == LF_MODIFIER) { 1040 ModifierRecord modifier; 1041 llvm::cantFail( 1042 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier)); 1043 return CreateModifierType(modifier); 1044 } 1045 1046 if (cvt.kind() == LF_POINTER) { 1047 PointerRecord pointer; 1048 llvm::cantFail( 1049 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer)); 1050 return CreatePointerType(pointer); 1051 } 1052 1053 if (IsTagRecord(cvt)) { 1054 CVTagRecord tag = CVTagRecord::create(cvt); 1055 if (tag.kind() == CVTagRecord::Union) 1056 return CreateRecordType(type.index, tag.asUnion()); 1057 if (tag.kind() == CVTagRecord::Enum) 1058 return CreateEnumType(type.index, tag.asEnum()); 1059 return CreateRecordType(type.index, tag.asClass()); 1060 } 1061 1062 if (cvt.kind() == LF_ARRAY) { 1063 ArrayRecord ar; 1064 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar)); 1065 return CreateArrayType(ar); 1066 } 1067 1068 if (cvt.kind() == LF_PROCEDURE) { 1069 ProcedureRecord pr; 1070 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr)); 1071 return CreateFunctionType(pr.ArgumentList, pr.ReturnType, pr.CallConv); 1072 } 1073 1074 if (cvt.kind() == LF_MFUNCTION) { 1075 MemberFunctionRecord mfr; 1076 llvm::cantFail( 1077 TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr)); 1078 return CreateFunctionType(mfr.ArgumentList, mfr.ReturnType, mfr.CallConv); 1079 } 1080 1081 return {}; 1082 } 1083 1084 clang::QualType PdbAstBuilder::GetOrCreateType(PdbTypeSymId type) { 1085 if (type.index.isNoneType()) 1086 return {}; 1087 1088 lldb::user_id_t uid = toOpaqueUid(type); 1089 auto iter = m_uid_to_type.find(uid); 1090 if (iter != m_uid_to_type.end()) 1091 return iter->second; 1092 1093 PdbTypeSymId best_type = GetBestPossibleDecl(type, m_index.tpi()); 1094 1095 clang::QualType qt; 1096 if (best_type.index != type.index) { 1097 // This is a forward decl. Call GetOrCreate on the full decl, then map the 1098 // forward decl id to the full decl QualType. 1099 clang::QualType qt = GetOrCreateType(best_type); 1100 if (qt.isNull()) 1101 return {}; 1102 m_uid_to_type[toOpaqueUid(type)] = qt; 1103 return qt; 1104 } 1105 1106 // This is either a full decl, or a forward decl with no matching full decl 1107 // in the debug info. 1108 qt = CreateType(type); 1109 if (qt.isNull()) 1110 return {}; 1111 1112 m_uid_to_type[toOpaqueUid(type)] = qt; 1113 if (IsTagRecord(type, m_index.tpi())) { 1114 clang::TagDecl *tag = qt->getAsTagDecl(); 1115 lldbassert(m_decl_to_status.count(tag) == 0); 1116 1117 DeclStatus &status = m_decl_to_status[tag]; 1118 status.uid = uid; 1119 status.resolved = false; 1120 } 1121 return qt; 1122 } 1123 1124 clang::FunctionDecl * 1125 PdbAstBuilder::CreateFunctionDecl(PdbCompilandSymId func_id, 1126 llvm::StringRef func_name, TypeIndex func_ti, 1127 CompilerType func_ct, uint32_t param_count, 1128 clang::StorageClass func_storage, 1129 bool is_inline, clang::DeclContext *parent) { 1130 clang::FunctionDecl *function_decl = nullptr; 1131 if (parent->isRecord()) { 1132 clang::QualType parent_qt = llvm::cast<clang::TypeDecl>(parent) 1133 ->getTypeForDecl() 1134 ->getCanonicalTypeInternal(); 1135 lldb::opaque_compiler_type_t parent_opaque_ty = 1136 ToCompilerType(parent_qt).GetOpaqueQualType(); 1137 // FIXME: Remove this workaround. 1138 auto iter = m_cxx_record_map.find(parent_opaque_ty); 1139 if (iter != m_cxx_record_map.end()) { 1140 if (iter->getSecond().contains({func_name, func_ct})) { 1141 return nullptr; 1142 } 1143 } 1144 1145 CVType cvt = m_index.tpi().getType(func_ti); 1146 MemberFunctionRecord func_record(static_cast<TypeRecordKind>(cvt.kind())); 1147 llvm::cantFail(TypeDeserializer::deserializeAs<MemberFunctionRecord>( 1148 cvt, func_record)); 1149 TypeIndex class_index = func_record.getClassType(); 1150 1151 CVType parent_cvt = m_index.tpi().getType(class_index); 1152 TagRecord tag_record = CVTagRecord::create(parent_cvt).asTag(); 1153 // If it's a forward reference, try to get the real TypeIndex. 1154 if (tag_record.isForwardRef()) { 1155 llvm::Expected<TypeIndex> eti = 1156 m_index.tpi().findFullDeclForForwardRef(class_index); 1157 if (eti) { 1158 tag_record = CVTagRecord::create(m_index.tpi().getType(*eti)).asTag(); 1159 } 1160 } 1161 if (!tag_record.FieldList.isSimple()) { 1162 CVType field_list_cvt = m_index.tpi().getType(tag_record.FieldList); 1163 FieldListRecord field_list; 1164 if (llvm::Error error = TypeDeserializer::deserializeAs<FieldListRecord>( 1165 field_list_cvt, field_list)) 1166 llvm::consumeError(std::move(error)); 1167 CreateMethodDecl process(m_index, m_clang, func_ti, function_decl, 1168 parent_opaque_ty, func_name, func_ct); 1169 if (llvm::Error err = visitMemberRecordStream(field_list.Data, process)) 1170 llvm::consumeError(std::move(err)); 1171 } 1172 1173 if (!function_decl) { 1174 function_decl = m_clang.AddMethodToCXXRecordType( 1175 parent_opaque_ty, func_name, 1176 /*mangled_name=*/nullptr, func_ct, 1177 /*access=*/lldb::AccessType::eAccessPublic, 1178 /*is_virtual=*/false, /*is_static=*/false, 1179 /*is_inline=*/false, /*is_explicit=*/false, 1180 /*is_attr_used=*/false, /*is_artificial=*/false); 1181 } 1182 m_cxx_record_map[parent_opaque_ty].insert({func_name, func_ct}); 1183 } else { 1184 function_decl = m_clang.CreateFunctionDeclaration( 1185 parent, OptionalClangModuleID(), func_name, func_ct, func_storage, 1186 is_inline); 1187 CreateFunctionParameters(func_id, *function_decl, param_count); 1188 } 1189 return function_decl; 1190 } 1191 1192 clang::FunctionDecl * 1193 PdbAstBuilder::GetOrCreateInlinedFunctionDecl(PdbCompilandSymId inlinesite_id) { 1194 CompilandIndexItem *cii = 1195 m_index.compilands().GetCompiland(inlinesite_id.modi); 1196 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(inlinesite_id.offset); 1197 InlineSiteSym inline_site(static_cast<SymbolRecordKind>(sym.kind())); 1198 cantFail(SymbolDeserializer::deserializeAs<InlineSiteSym>(sym, inline_site)); 1199 1200 // Inlinee is the id index to the function id record that is inlined. 1201 PdbTypeSymId func_id(inline_site.Inlinee, true); 1202 // Look up the function decl by the id index to see if we have created a 1203 // function decl for a different inlinesite that refers the same function. 1204 if (clang::Decl *decl = TryGetDecl(func_id)) 1205 return llvm::dyn_cast<clang::FunctionDecl>(decl); 1206 clang::FunctionDecl *function_decl = 1207 CreateFunctionDeclFromId(func_id, inlinesite_id); 1208 if (function_decl == nullptr) 1209 return nullptr; 1210 1211 // Use inline site id in m_decl_to_status because it's expected to be a 1212 // PdbCompilandSymId so that we can parse local variables info after it. 1213 uint64_t inlinesite_uid = toOpaqueUid(inlinesite_id); 1214 DeclStatus status; 1215 status.resolved = true; 1216 status.uid = inlinesite_uid; 1217 m_decl_to_status.insert({function_decl, status}); 1218 // Use the index in IPI stream as uid in m_uid_to_decl, because index in IPI 1219 // stream are unique and there could be multiple inline sites (different ids) 1220 // referring the same inline function. This avoid creating multiple same 1221 // inline function delcs. 1222 uint64_t func_uid = toOpaqueUid(func_id); 1223 lldbassert(m_uid_to_decl.count(func_uid) == 0); 1224 m_uid_to_decl[func_uid] = function_decl; 1225 return function_decl; 1226 } 1227 1228 clang::FunctionDecl * 1229 PdbAstBuilder::CreateFunctionDeclFromId(PdbTypeSymId func_tid, 1230 PdbCompilandSymId func_sid) { 1231 lldbassert(func_tid.is_ipi); 1232 CVType func_cvt = m_index.ipi().getType(func_tid.index); 1233 llvm::StringRef func_name; 1234 TypeIndex func_ti; 1235 clang::DeclContext *parent = nullptr; 1236 switch (func_cvt.kind()) { 1237 case LF_MFUNC_ID: { 1238 MemberFuncIdRecord mfr; 1239 cantFail( 1240 TypeDeserializer::deserializeAs<MemberFuncIdRecord>(func_cvt, mfr)); 1241 func_name = mfr.getName(); 1242 func_ti = mfr.getFunctionType(); 1243 PdbTypeSymId class_type_id(mfr.ClassType, false); 1244 parent = GetOrCreateDeclContextForUid(class_type_id); 1245 break; 1246 } 1247 case LF_FUNC_ID: { 1248 FuncIdRecord fir; 1249 cantFail(TypeDeserializer::deserializeAs<FuncIdRecord>(func_cvt, fir)); 1250 func_name = fir.getName(); 1251 func_ti = fir.getFunctionType(); 1252 parent = FromCompilerDeclContext(GetTranslationUnitDecl()); 1253 if (!fir.ParentScope.isNoneType()) { 1254 CVType parent_cvt = m_index.ipi().getType(fir.ParentScope); 1255 if (parent_cvt.kind() == LF_STRING_ID) { 1256 StringIdRecord sir; 1257 cantFail( 1258 TypeDeserializer::deserializeAs<StringIdRecord>(parent_cvt, sir)); 1259 parent = GetOrCreateNamespaceDecl(sir.String.data(), *parent); 1260 } 1261 } 1262 break; 1263 } 1264 default: 1265 lldbassert(false && "Invalid function id type!"); 1266 } 1267 clang::QualType func_qt = GetOrCreateType(func_ti); 1268 if (func_qt.isNull()) 1269 return nullptr; 1270 CompilerType func_ct = ToCompilerType(func_qt); 1271 uint32_t param_count = 1272 llvm::cast<clang::FunctionProtoType>(func_qt)->getNumParams(); 1273 return CreateFunctionDecl(func_sid, func_name, func_ti, func_ct, param_count, 1274 clang::SC_None, true, parent); 1275 } 1276 1277 clang::FunctionDecl * 1278 PdbAstBuilder::GetOrCreateFunctionDecl(PdbCompilandSymId func_id) { 1279 if (clang::Decl *decl = TryGetDecl(func_id)) 1280 return llvm::dyn_cast<clang::FunctionDecl>(decl); 1281 1282 clang::DeclContext *parent = GetParentDeclContext(PdbSymUid(func_id)); 1283 std::string context_name; 1284 if (clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(parent)) { 1285 context_name = ns->getQualifiedNameAsString(); 1286 } else if (clang::TagDecl *tag = llvm::dyn_cast<clang::TagDecl>(parent)) { 1287 context_name = tag->getQualifiedNameAsString(); 1288 } 1289 1290 CVSymbol cvs = m_index.ReadSymbolRecord(func_id); 1291 ProcSym proc(static_cast<SymbolRecordKind>(cvs.kind())); 1292 llvm::cantFail(SymbolDeserializer::deserializeAs<ProcSym>(cvs, proc)); 1293 1294 PdbTypeSymId type_id(proc.FunctionType); 1295 clang::QualType qt = GetOrCreateType(type_id); 1296 if (qt.isNull()) 1297 return nullptr; 1298 1299 clang::StorageClass storage = clang::SC_None; 1300 if (proc.Kind == SymbolRecordKind::ProcSym) 1301 storage = clang::SC_Static; 1302 1303 const clang::FunctionProtoType *func_type = 1304 llvm::dyn_cast<clang::FunctionProtoType>(qt); 1305 1306 CompilerType func_ct = ToCompilerType(qt); 1307 1308 llvm::StringRef proc_name = proc.Name; 1309 proc_name.consume_front(context_name); 1310 proc_name.consume_front("::"); 1311 1312 clang::FunctionDecl *function_decl = 1313 CreateFunctionDecl(func_id, proc_name, proc.FunctionType, func_ct, 1314 func_type->getNumParams(), storage, false, parent); 1315 if (function_decl == nullptr) 1316 return nullptr; 1317 1318 lldbassert(m_uid_to_decl.count(toOpaqueUid(func_id)) == 0); 1319 m_uid_to_decl[toOpaqueUid(func_id)] = function_decl; 1320 DeclStatus status; 1321 status.resolved = true; 1322 status.uid = toOpaqueUid(func_id); 1323 m_decl_to_status.insert({function_decl, status}); 1324 1325 return function_decl; 1326 } 1327 1328 void PdbAstBuilder::CreateFunctionParameters(PdbCompilandSymId func_id, 1329 clang::FunctionDecl &function_decl, 1330 uint32_t param_count) { 1331 CompilandIndexItem *cii = m_index.compilands().GetCompiland(func_id.modi); 1332 CVSymbolArray scope = 1333 cii->m_debug_stream.getSymbolArrayForScope(func_id.offset); 1334 1335 scope.drop_front(); 1336 auto begin = scope.begin(); 1337 auto end = scope.end(); 1338 std::vector<clang::ParmVarDecl *> params; 1339 for (uint32_t i = 0; i < param_count && begin != end;) { 1340 uint32_t record_offset = begin.offset(); 1341 CVSymbol sym = *begin++; 1342 1343 TypeIndex param_type; 1344 llvm::StringRef param_name; 1345 switch (sym.kind()) { 1346 case S_REGREL32: { 1347 RegRelativeSym reg(SymbolRecordKind::RegRelativeSym); 1348 cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg)); 1349 param_type = reg.Type; 1350 param_name = reg.Name; 1351 break; 1352 } 1353 case S_REGISTER: { 1354 RegisterSym reg(SymbolRecordKind::RegisterSym); 1355 cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg)); 1356 param_type = reg.Index; 1357 param_name = reg.Name; 1358 break; 1359 } 1360 case S_LOCAL: { 1361 LocalSym local(SymbolRecordKind::LocalSym); 1362 cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local)); 1363 if ((local.Flags & LocalSymFlags::IsParameter) == LocalSymFlags::None) 1364 continue; 1365 param_type = local.Type; 1366 param_name = local.Name; 1367 break; 1368 } 1369 case S_BLOCK32: 1370 case S_INLINESITE: 1371 case S_INLINESITE2: 1372 // All parameters should come before the first block/inlinesite. If that 1373 // isn't the case, then perhaps this is bad debug info that doesn't 1374 // contain information about all parameters. 1375 return; 1376 default: 1377 continue; 1378 } 1379 1380 PdbCompilandSymId param_uid(func_id.modi, record_offset); 1381 clang::QualType qt = GetOrCreateType(param_type); 1382 if (qt.isNull()) 1383 return; 1384 1385 CompilerType param_type_ct = m_clang.GetType(qt); 1386 clang::ParmVarDecl *param = m_clang.CreateParameterDeclaration( 1387 &function_decl, OptionalClangModuleID(), param_name.str().c_str(), 1388 param_type_ct, clang::SC_None, true); 1389 lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0); 1390 1391 m_uid_to_decl[toOpaqueUid(param_uid)] = param; 1392 params.push_back(param); 1393 ++i; 1394 } 1395 1396 if (!params.empty() && params.size() == param_count) 1397 m_clang.SetFunctionParameters(&function_decl, params); 1398 } 1399 1400 clang::QualType PdbAstBuilder::CreateEnumType(PdbTypeSymId id, 1401 const EnumRecord &er) { 1402 clang::DeclContext *decl_context = nullptr; 1403 std::string uname; 1404 std::tie(decl_context, uname) = CreateDeclInfoForType(er, id.index); 1405 if (!decl_context) 1406 return {}; 1407 1408 clang::QualType underlying_type = GetOrCreateType(er.UnderlyingType); 1409 if (underlying_type.isNull()) 1410 return {}; 1411 1412 Declaration declaration; 1413 CompilerType enum_ct = m_clang.CreateEnumerationType( 1414 uname, decl_context, OptionalClangModuleID(), declaration, 1415 ToCompilerType(underlying_type), er.isScoped()); 1416 1417 TypeSystemClang::StartTagDeclarationDefinition(enum_ct); 1418 TypeSystemClang::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true); 1419 1420 return clang::QualType::getFromOpaquePtr(enum_ct.GetOpaqueQualType()); 1421 } 1422 1423 clang::QualType PdbAstBuilder::CreateArrayType(const ArrayRecord &ar) { 1424 clang::QualType element_type = GetOrCreateType(ar.ElementType); 1425 1426 uint64_t element_size = GetSizeOfType({ar.ElementType}, m_index.tpi()); 1427 if (element_type.isNull() || element_size == 0) 1428 return {}; 1429 uint64_t element_count = ar.Size / element_size; 1430 1431 CompilerType array_ct = m_clang.CreateArrayType(ToCompilerType(element_type), 1432 element_count, false); 1433 return clang::QualType::getFromOpaquePtr(array_ct.GetOpaqueQualType()); 1434 } 1435 1436 clang::QualType PdbAstBuilder::CreateFunctionType( 1437 TypeIndex args_type_idx, TypeIndex return_type_idx, 1438 llvm::codeview::CallingConvention calling_convention) { 1439 TpiStream &stream = m_index.tpi(); 1440 CVType args_cvt = stream.getType(args_type_idx); 1441 ArgListRecord args; 1442 llvm::cantFail( 1443 TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args)); 1444 1445 llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices); 1446 bool is_variadic = IsCVarArgsFunction(arg_indices); 1447 if (is_variadic) 1448 arg_indices = arg_indices.drop_back(); 1449 1450 std::vector<CompilerType> arg_types; 1451 arg_types.reserve(arg_indices.size()); 1452 1453 for (TypeIndex arg_index : arg_indices) { 1454 clang::QualType arg_type = GetOrCreateType(arg_index); 1455 if (arg_type.isNull()) 1456 continue; 1457 arg_types.push_back(ToCompilerType(arg_type)); 1458 } 1459 1460 clang::QualType return_type = GetOrCreateType(return_type_idx); 1461 if (return_type.isNull()) 1462 return {}; 1463 1464 llvm::Optional<clang::CallingConv> cc = 1465 TranslateCallingConvention(calling_convention); 1466 if (!cc) 1467 return {}; 1468 1469 CompilerType return_ct = ToCompilerType(return_type); 1470 CompilerType func_sig_ast_type = m_clang.CreateFunctionType( 1471 return_ct, arg_types.data(), arg_types.size(), is_variadic, 0, *cc); 1472 1473 return clang::QualType::getFromOpaquePtr( 1474 func_sig_ast_type.GetOpaqueQualType()); 1475 } 1476 1477 static bool isTagDecl(clang::DeclContext &context) { 1478 return llvm::isa<clang::TagDecl>(&context); 1479 } 1480 1481 static bool isFunctionDecl(clang::DeclContext &context) { 1482 return llvm::isa<clang::FunctionDecl>(&context); 1483 } 1484 1485 static bool isBlockDecl(clang::DeclContext &context) { 1486 return llvm::isa<clang::BlockDecl>(&context); 1487 } 1488 1489 void PdbAstBuilder::ParseAllNamespacesPlusChildrenOf( 1490 llvm::Optional<llvm::StringRef> parent) { 1491 TypeIndex ti{m_index.tpi().TypeIndexBegin()}; 1492 for (const CVType &cvt : m_index.tpi().typeArray()) { 1493 PdbTypeSymId tid{ti}; 1494 ++ti; 1495 1496 if (!IsTagRecord(cvt)) 1497 continue; 1498 1499 CVTagRecord tag = CVTagRecord::create(cvt); 1500 1501 if (!parent) { 1502 clang::QualType qt = GetOrCreateType(tid); 1503 CompleteType(qt); 1504 continue; 1505 } 1506 1507 // Call CreateDeclInfoForType unconditionally so that the namespace info 1508 // gets created. But only call CreateRecordType if the namespace name 1509 // matches. 1510 clang::DeclContext *context = nullptr; 1511 std::string uname; 1512 std::tie(context, uname) = CreateDeclInfoForType(tag.asTag(), tid.index); 1513 if (!context || !context->isNamespace()) 1514 continue; 1515 1516 clang::NamespaceDecl *ns = llvm::cast<clang::NamespaceDecl>(context); 1517 std::string actual_ns = ns->getQualifiedNameAsString(); 1518 if (llvm::StringRef(actual_ns).startswith(*parent)) { 1519 clang::QualType qt = GetOrCreateType(tid); 1520 CompleteType(qt); 1521 continue; 1522 } 1523 } 1524 1525 uint32_t module_count = m_index.dbi().modules().getModuleCount(); 1526 for (uint16_t modi = 0; modi < module_count; ++modi) { 1527 CompilandIndexItem &cii = m_index.compilands().GetOrCreateCompiland(modi); 1528 const CVSymbolArray &symbols = cii.m_debug_stream.getSymbolArray(); 1529 auto iter = symbols.begin(); 1530 while (iter != symbols.end()) { 1531 PdbCompilandSymId sym_id{modi, iter.offset()}; 1532 1533 switch (iter->kind()) { 1534 case S_GPROC32: 1535 case S_LPROC32: 1536 GetOrCreateFunctionDecl(sym_id); 1537 iter = symbols.at(getScopeEndOffset(*iter)); 1538 break; 1539 case S_GDATA32: 1540 case S_GTHREAD32: 1541 case S_LDATA32: 1542 case S_LTHREAD32: 1543 GetOrCreateVariableDecl(PdbCompilandSymId(modi, 0), sym_id); 1544 ++iter; 1545 break; 1546 default: 1547 ++iter; 1548 continue; 1549 } 1550 } 1551 } 1552 } 1553 1554 static CVSymbolArray skipFunctionParameters(clang::Decl &decl, 1555 const CVSymbolArray &symbols) { 1556 clang::FunctionDecl *func_decl = llvm::dyn_cast<clang::FunctionDecl>(&decl); 1557 if (!func_decl) 1558 return symbols; 1559 unsigned int params = func_decl->getNumParams(); 1560 if (params == 0) 1561 return symbols; 1562 1563 CVSymbolArray result = symbols; 1564 1565 while (!result.empty()) { 1566 if (params == 0) 1567 return result; 1568 1569 CVSymbol sym = *result.begin(); 1570 result.drop_front(); 1571 1572 if (!isLocalVariableType(sym.kind())) 1573 continue; 1574 1575 --params; 1576 } 1577 return result; 1578 } 1579 1580 void PdbAstBuilder::ParseBlockChildren(PdbCompilandSymId block_id) { 1581 CVSymbol sym = m_index.ReadSymbolRecord(block_id); 1582 lldbassert(sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32 || 1583 sym.kind() == S_BLOCK32 || sym.kind() == S_INLINESITE); 1584 CompilandIndexItem &cii = 1585 m_index.compilands().GetOrCreateCompiland(block_id.modi); 1586 CVSymbolArray symbols = 1587 cii.m_debug_stream.getSymbolArrayForScope(block_id.offset); 1588 1589 // Function parameters should already have been created when the function was 1590 // parsed. 1591 if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32) 1592 symbols = 1593 skipFunctionParameters(*m_uid_to_decl[toOpaqueUid(block_id)], symbols); 1594 1595 symbols.drop_front(); 1596 auto begin = symbols.begin(); 1597 while (begin != symbols.end()) { 1598 PdbCompilandSymId child_sym_id(block_id.modi, begin.offset()); 1599 GetOrCreateSymbolForId(child_sym_id); 1600 if (begin->kind() == S_BLOCK32 || begin->kind() == S_INLINESITE) { 1601 ParseBlockChildren(child_sym_id); 1602 begin = symbols.at(getScopeEndOffset(*begin)); 1603 } 1604 ++begin; 1605 } 1606 } 1607 1608 void PdbAstBuilder::ParseDeclsForSimpleContext(clang::DeclContext &context) { 1609 1610 clang::Decl *decl = clang::Decl::castFromDeclContext(&context); 1611 lldbassert(decl); 1612 1613 auto iter = m_decl_to_status.find(decl); 1614 lldbassert(iter != m_decl_to_status.end()); 1615 1616 if (auto *tag = llvm::dyn_cast<clang::TagDecl>(&context)) { 1617 CompleteTagDecl(*tag); 1618 return; 1619 } 1620 1621 if (isFunctionDecl(context) || isBlockDecl(context)) { 1622 PdbCompilandSymId block_id = PdbSymUid(iter->second.uid).asCompilandSym(); 1623 ParseBlockChildren(block_id); 1624 } 1625 } 1626 1627 void PdbAstBuilder::ParseDeclsForContext(clang::DeclContext &context) { 1628 // Namespaces aren't explicitly represented in the debug info, and the only 1629 // way to parse them is to parse all type info, demangling every single type 1630 // and trying to reconstruct the DeclContext hierarchy this way. Since this 1631 // is an expensive operation, we have to special case it so that we do other 1632 // work (such as parsing the items that appear within the namespaces) at the 1633 // same time. 1634 if (context.isTranslationUnit()) { 1635 ParseAllNamespacesPlusChildrenOf(llvm::None); 1636 return; 1637 } 1638 1639 if (context.isNamespace()) { 1640 clang::NamespaceDecl &ns = *llvm::dyn_cast<clang::NamespaceDecl>(&context); 1641 std::string qname = ns.getQualifiedNameAsString(); 1642 ParseAllNamespacesPlusChildrenOf(llvm::StringRef{qname}); 1643 return; 1644 } 1645 1646 if (isTagDecl(context) || isFunctionDecl(context) || isBlockDecl(context)) { 1647 ParseDeclsForSimpleContext(context); 1648 return; 1649 } 1650 } 1651 1652 CompilerDecl PdbAstBuilder::ToCompilerDecl(clang::Decl &decl) { 1653 return m_clang.GetCompilerDecl(&decl); 1654 } 1655 1656 CompilerType PdbAstBuilder::ToCompilerType(clang::QualType qt) { 1657 return {&m_clang, qt.getAsOpaquePtr()}; 1658 } 1659 1660 CompilerDeclContext 1661 PdbAstBuilder::ToCompilerDeclContext(clang::DeclContext &context) { 1662 return m_clang.CreateDeclContext(&context); 1663 } 1664 1665 clang::Decl * PdbAstBuilder::FromCompilerDecl(CompilerDecl decl) { 1666 return ClangUtil::GetDecl(decl); 1667 } 1668 1669 clang::DeclContext * 1670 PdbAstBuilder::FromCompilerDeclContext(CompilerDeclContext context) { 1671 return static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext()); 1672 } 1673 1674 void PdbAstBuilder::Dump(Stream &stream) { 1675 m_clang.Dump(stream.AsRawOstream()); 1676 } 1677