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 327 context = clang::TagDecl::castToDeclContext(parent_qt->getAsTagDecl()); 328 return {context, uname}; 329 } 330 331 void PdbAstBuilder::BuildParentMap() { 332 LazyRandomTypeCollection &types = m_index.tpi().typeCollection(); 333 334 llvm::DenseMap<TypeIndex, TypeIndex> forward_to_full; 335 llvm::DenseMap<TypeIndex, TypeIndex> full_to_forward; 336 337 struct RecordIndices { 338 TypeIndex forward; 339 TypeIndex full; 340 }; 341 342 llvm::StringMap<RecordIndices> record_indices; 343 344 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) { 345 CVType type = types.getType(*ti); 346 if (!IsTagRecord(type)) 347 continue; 348 349 CVTagRecord tag = CVTagRecord::create(type); 350 351 RecordIndices &indices = record_indices[tag.asTag().getUniqueName()]; 352 if (tag.asTag().isForwardRef()) 353 indices.forward = *ti; 354 else 355 indices.full = *ti; 356 357 if (indices.full != TypeIndex::None() && 358 indices.forward != TypeIndex::None()) { 359 forward_to_full[indices.forward] = indices.full; 360 full_to_forward[indices.full] = indices.forward; 361 } 362 363 // We're looking for LF_NESTTYPE records in the field list, so ignore 364 // forward references (no field list), and anything without a nested class 365 // (since there won't be any LF_NESTTYPE records). 366 if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass()) 367 continue; 368 369 struct ProcessTpiStream : public TypeVisitorCallbacks { 370 ProcessTpiStream(PdbIndex &index, TypeIndex parent, 371 const CVTagRecord &parent_cvt, 372 llvm::DenseMap<TypeIndex, TypeIndex> &parents) 373 : index(index), parents(parents), parent(parent), 374 parent_cvt(parent_cvt) {} 375 376 PdbIndex &index; 377 llvm::DenseMap<TypeIndex, TypeIndex> &parents; 378 379 unsigned unnamed_type_index = 1; 380 TypeIndex parent; 381 const CVTagRecord &parent_cvt; 382 383 llvm::Error visitKnownMember(CVMemberRecord &CVR, 384 NestedTypeRecord &Record) override { 385 std::string unnamed_type_name; 386 if (Record.Name.empty()) { 387 unnamed_type_name = 388 llvm::formatv("<unnamed-type-$S{0}>", unnamed_type_index).str(); 389 Record.Name = unnamed_type_name; 390 ++unnamed_type_index; 391 } 392 llvm::Optional<CVTagRecord> tag = 393 GetNestedTagDefinition(Record, parent_cvt, index.tpi()); 394 if (!tag) 395 return llvm::ErrorSuccess(); 396 397 parents[Record.Type] = parent; 398 return llvm::ErrorSuccess(); 399 } 400 }; 401 402 CVType field_list = m_index.tpi().getType(tag.asTag().FieldList); 403 ProcessTpiStream process(m_index, *ti, tag, m_parent_types); 404 llvm::Error error = visitMemberRecordStream(field_list.data(), process); 405 if (error) 406 llvm::consumeError(std::move(error)); 407 } 408 409 // Now that we know the forward -> full mapping of all type indices, we can 410 // re-write all the indices. At the end of this process, we want a mapping 411 // consisting of fwd -> full and full -> full for all child -> parent indices. 412 // We can re-write the values in place, but for the keys, we must save them 413 // off so that we don't modify the map in place while also iterating it. 414 std::vector<TypeIndex> full_keys; 415 std::vector<TypeIndex> fwd_keys; 416 for (auto &entry : m_parent_types) { 417 TypeIndex key = entry.first; 418 TypeIndex value = entry.second; 419 420 auto iter = forward_to_full.find(value); 421 if (iter != forward_to_full.end()) 422 entry.second = iter->second; 423 424 iter = forward_to_full.find(key); 425 if (iter != forward_to_full.end()) 426 fwd_keys.push_back(key); 427 else 428 full_keys.push_back(key); 429 } 430 for (TypeIndex fwd : fwd_keys) { 431 TypeIndex full = forward_to_full[fwd]; 432 m_parent_types[full] = m_parent_types[fwd]; 433 } 434 for (TypeIndex full : full_keys) { 435 TypeIndex fwd = full_to_forward[full]; 436 m_parent_types[fwd] = m_parent_types[full]; 437 } 438 439 // Now that 440 } 441 442 static bool isLocalVariableType(SymbolKind K) { 443 switch (K) { 444 case S_REGISTER: 445 case S_REGREL32: 446 case S_LOCAL: 447 return true; 448 default: 449 break; 450 } 451 return false; 452 } 453 454 static std::string 455 RenderScopeList(llvm::ArrayRef<llvm::ms_demangle::Node *> nodes) { 456 lldbassert(!nodes.empty()); 457 458 std::string result = nodes.front()->toString(); 459 nodes = nodes.drop_front(); 460 while (!nodes.empty()) { 461 result += "::"; 462 result += nodes.front()->toString(llvm::ms_demangle::OF_NoTagSpecifier); 463 nodes = nodes.drop_front(); 464 } 465 return result; 466 } 467 468 static llvm::Optional<PublicSym32> FindPublicSym(const SegmentOffset &addr, 469 SymbolStream &syms, 470 PublicsStream &publics) { 471 llvm::FixedStreamArray<ulittle32_t> addr_map = publics.getAddressMap(); 472 auto iter = std::lower_bound( 473 addr_map.begin(), addr_map.end(), addr, 474 [&](const ulittle32_t &x, const SegmentOffset &y) { 475 CVSymbol s1 = syms.readRecord(x); 476 lldbassert(s1.kind() == S_PUB32); 477 PublicSym32 p1; 478 llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(s1, p1)); 479 if (p1.Segment < y.segment) 480 return true; 481 return p1.Offset < y.offset; 482 }); 483 if (iter == addr_map.end()) 484 return llvm::None; 485 CVSymbol sym = syms.readRecord(*iter); 486 lldbassert(sym.kind() == S_PUB32); 487 PublicSym32 p; 488 llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(sym, p)); 489 if (p.Segment == addr.segment && p.Offset == addr.offset) 490 return p; 491 return llvm::None; 492 } 493 494 clang::Decl *PdbAstBuilder::GetOrCreateSymbolForId(PdbCompilandSymId id) { 495 CVSymbol cvs = m_index.ReadSymbolRecord(id); 496 497 if (isLocalVariableType(cvs.kind())) { 498 clang::DeclContext *scope = GetParentDeclContext(id); 499 clang::Decl *scope_decl = clang::Decl::castFromDeclContext(scope); 500 PdbCompilandSymId scope_id = 501 PdbSymUid(m_decl_to_status[scope_decl].uid).asCompilandSym(); 502 return GetOrCreateVariableDecl(scope_id, id); 503 } 504 505 switch (cvs.kind()) { 506 case S_GPROC32: 507 case S_LPROC32: 508 return GetOrCreateFunctionDecl(id); 509 case S_GDATA32: 510 case S_LDATA32: 511 case S_GTHREAD32: 512 case S_CONSTANT: 513 // global variable 514 return nullptr; 515 case S_BLOCK32: 516 return GetOrCreateBlockDecl(id); 517 default: 518 return nullptr; 519 } 520 } 521 522 llvm::Optional<CompilerDecl> PdbAstBuilder::GetOrCreateDeclForUid(PdbSymUid uid) { 523 if (clang::Decl *result = TryGetDecl(uid)) 524 return ToCompilerDecl(*result); 525 526 clang::Decl *result = nullptr; 527 switch (uid.kind()) { 528 case PdbSymUidKind::CompilandSym: 529 result = GetOrCreateSymbolForId(uid.asCompilandSym()); 530 break; 531 case PdbSymUidKind::Type: { 532 clang::QualType qt = GetOrCreateType(uid.asTypeSym()); 533 if (auto *tag = qt->getAsTagDecl()) { 534 result = tag; 535 break; 536 } 537 return llvm::None; 538 } 539 default: 540 return llvm::None; 541 } 542 m_uid_to_decl[toOpaqueUid(uid)] = result; 543 return ToCompilerDecl(*result); 544 } 545 546 clang::DeclContext *PdbAstBuilder::GetOrCreateDeclContextForUid(PdbSymUid uid) { 547 if (uid.kind() == PdbSymUidKind::CompilandSym) { 548 if (uid.asCompilandSym().offset == 0) 549 return FromCompilerDeclContext(GetTranslationUnitDecl()); 550 } 551 auto option = GetOrCreateDeclForUid(uid); 552 if (!option) 553 return nullptr; 554 clang::Decl *decl = FromCompilerDecl(option.getValue()); 555 if (!decl) 556 return nullptr; 557 558 return clang::Decl::castToDeclContext(decl); 559 } 560 561 std::pair<clang::DeclContext *, std::string> 562 PdbAstBuilder::CreateDeclInfoForUndecoratedName(llvm::StringRef name) { 563 MSVCUndecoratedNameParser parser(name); 564 llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers(); 565 566 auto context = FromCompilerDeclContext(GetTranslationUnitDecl()); 567 568 llvm::StringRef uname = specs.back().GetBaseName(); 569 specs = specs.drop_back(); 570 if (specs.empty()) 571 return {context, std::string(name)}; 572 573 llvm::StringRef scope_name = specs.back().GetFullName(); 574 575 // It might be a class name, try that first. 576 std::vector<TypeIndex> types = m_index.tpi().findRecordsByName(scope_name); 577 while (!types.empty()) { 578 clang::QualType qt = GetOrCreateType(types.back()); 579 clang::TagDecl *tag = qt->getAsTagDecl(); 580 if (tag) 581 return {clang::TagDecl::castToDeclContext(tag), std::string(uname)}; 582 types.pop_back(); 583 } 584 585 // If that fails, treat it as a series of namespaces. 586 for (const MSVCUndecoratedNameSpecifier &spec : specs) { 587 std::string ns_name = spec.GetBaseName().str(); 588 context = GetOrCreateNamespaceDecl(ns_name.c_str(), *context); 589 } 590 return {context, std::string(uname)}; 591 } 592 593 clang::DeclContext * 594 PdbAstBuilder::GetParentDeclContextForSymbol(const CVSymbol &sym) { 595 if (!SymbolHasAddress(sym)) 596 return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first; 597 SegmentOffset addr = GetSegmentAndOffset(sym); 598 llvm::Optional<PublicSym32> pub = 599 FindPublicSym(addr, m_index.symrecords(), m_index.publics()); 600 if (!pub) 601 return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first; 602 603 llvm::ms_demangle::Demangler demangler; 604 StringView name{pub->Name.begin(), pub->Name.size()}; 605 llvm::ms_demangle::SymbolNode *node = demangler.parse(name); 606 if (!node) 607 return FromCompilerDeclContext(GetTranslationUnitDecl()); 608 llvm::ArrayRef<llvm::ms_demangle::Node *> name_components{ 609 node->Name->Components->Nodes, node->Name->Components->Count - 1}; 610 611 if (!name_components.empty()) { 612 // Render the current list of scope nodes as a fully qualified name, and 613 // look it up in the debug info as a type name. If we find something, 614 // this is a type (which may itself be prefixed by a namespace). If we 615 // don't, this is a list of namespaces. 616 std::string qname = RenderScopeList(name_components); 617 std::vector<TypeIndex> matches = m_index.tpi().findRecordsByName(qname); 618 while (!matches.empty()) { 619 clang::QualType qt = GetOrCreateType(matches.back()); 620 clang::TagDecl *tag = qt->getAsTagDecl(); 621 if (tag) 622 return clang::TagDecl::castToDeclContext(tag); 623 matches.pop_back(); 624 } 625 } 626 627 // It's not a type. It must be a series of namespaces. 628 auto context = FromCompilerDeclContext(GetTranslationUnitDecl()); 629 while (!name_components.empty()) { 630 std::string ns = name_components.front()->toString(); 631 context = GetOrCreateNamespaceDecl(ns.c_str(), *context); 632 name_components = name_components.drop_front(); 633 } 634 return context; 635 } 636 637 clang::DeclContext *PdbAstBuilder::GetParentDeclContext(PdbSymUid uid) { 638 // We must do this *without* calling GetOrCreate on the current uid, as 639 // that would be an infinite recursion. 640 switch (uid.kind()) { 641 case PdbSymUidKind::CompilandSym: { 642 llvm::Optional<PdbCompilandSymId> scope = 643 FindSymbolScope(m_index, uid.asCompilandSym()); 644 if (scope) 645 return GetOrCreateDeclContextForUid(*scope); 646 647 CVSymbol sym = m_index.ReadSymbolRecord(uid.asCompilandSym()); 648 return GetParentDeclContextForSymbol(sym); 649 } 650 case PdbSymUidKind::Type: { 651 // It could be a namespace, class, or global. We don't support nested 652 // functions yet. Anyway, we just need to consult the parent type map. 653 PdbTypeSymId type_id = uid.asTypeSym(); 654 auto iter = m_parent_types.find(type_id.index); 655 if (iter == m_parent_types.end()) 656 return FromCompilerDeclContext(GetTranslationUnitDecl()); 657 return GetOrCreateDeclContextForUid(PdbTypeSymId(iter->second)); 658 } 659 case PdbSymUidKind::FieldListMember: 660 // In this case the parent DeclContext is the one for the class that this 661 // member is inside of. 662 break; 663 case PdbSymUidKind::GlobalSym: { 664 // If this refers to a compiland symbol, just recurse in with that symbol. 665 // The only other possibilities are S_CONSTANT and S_UDT, in which case we 666 // need to parse the undecorated name to figure out the scope, then look 667 // that up in the TPI stream. If it's found, it's a type, othewrise it's 668 // a series of namespaces. 669 // FIXME: do this. 670 CVSymbol global = m_index.ReadSymbolRecord(uid.asGlobalSym()); 671 switch (global.kind()) { 672 case SymbolKind::S_GDATA32: 673 case SymbolKind::S_LDATA32: 674 return GetParentDeclContextForSymbol(global); 675 case SymbolKind::S_PROCREF: 676 case SymbolKind::S_LPROCREF: { 677 ProcRefSym ref{global.kind()}; 678 llvm::cantFail( 679 SymbolDeserializer::deserializeAs<ProcRefSym>(global, ref)); 680 PdbCompilandSymId cu_sym_id{ref.modi(), ref.SymOffset}; 681 return GetParentDeclContext(cu_sym_id); 682 } 683 case SymbolKind::S_CONSTANT: 684 case SymbolKind::S_UDT: 685 return CreateDeclInfoForUndecoratedName(getSymbolName(global)).first; 686 default: 687 break; 688 } 689 break; 690 } 691 default: 692 break; 693 } 694 return FromCompilerDeclContext(GetTranslationUnitDecl()); 695 } 696 697 bool PdbAstBuilder::CompleteType(clang::QualType qt) { 698 clang::TagDecl *tag = qt->getAsTagDecl(); 699 if (!tag) 700 return false; 701 702 return CompleteTagDecl(*tag); 703 } 704 705 bool PdbAstBuilder::CompleteTagDecl(clang::TagDecl &tag) { 706 // If this is not in our map, it's an error. 707 auto status_iter = m_decl_to_status.find(&tag); 708 lldbassert(status_iter != m_decl_to_status.end()); 709 710 // If it's already complete, just return. 711 DeclStatus &status = status_iter->second; 712 if (status.resolved) 713 return true; 714 715 PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym(); 716 717 lldbassert(IsTagRecord(type_id, m_index.tpi())); 718 719 clang::QualType tag_qt = m_clang.getASTContext().getTypeDeclType(&tag); 720 TypeSystemClang::SetHasExternalStorage(tag_qt.getAsOpaquePtr(), false); 721 722 TypeIndex tag_ti = type_id.index; 723 CVType cvt = m_index.tpi().getType(tag_ti); 724 if (cvt.kind() == LF_MODIFIER) 725 tag_ti = LookThroughModifierRecord(cvt); 726 727 PdbTypeSymId best_ti = GetBestPossibleDecl(tag_ti, m_index.tpi()); 728 cvt = m_index.tpi().getType(best_ti.index); 729 lldbassert(IsTagRecord(cvt)); 730 731 if (IsForwardRefUdt(cvt)) { 732 // If we can't find a full decl for this forward ref anywhere in the debug 733 // info, then we have no way to complete it. 734 return false; 735 } 736 737 TypeIndex field_list_ti = GetFieldListIndex(cvt); 738 CVType field_list_cvt = m_index.tpi().getType(field_list_ti); 739 if (field_list_cvt.kind() != LF_FIELDLIST) 740 return false; 741 742 // Visit all members of this class, then perform any finalization necessary 743 // to complete the class. 744 CompilerType ct = ToCompilerType(tag_qt); 745 UdtRecordCompleter completer(best_ti, ct, tag, *this, m_index, 746 m_cxx_record_map); 747 auto error = 748 llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer); 749 completer.complete(); 750 751 status.resolved = true; 752 if (!error) 753 return true; 754 755 llvm::consumeError(std::move(error)); 756 return false; 757 } 758 759 clang::QualType PdbAstBuilder::CreateSimpleType(TypeIndex ti) { 760 if (ti == TypeIndex::NullptrT()) 761 return GetBasicType(lldb::eBasicTypeNullPtr); 762 763 if (ti.getSimpleMode() != SimpleTypeMode::Direct) { 764 clang::QualType direct_type = GetOrCreateType(ti.makeDirect()); 765 return m_clang.getASTContext().getPointerType(direct_type); 766 } 767 768 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated) 769 return {}; 770 771 lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind()); 772 if (bt == lldb::eBasicTypeInvalid) 773 return {}; 774 775 return GetBasicType(bt); 776 } 777 778 clang::QualType PdbAstBuilder::CreatePointerType(const PointerRecord &pointer) { 779 clang::QualType pointee_type = GetOrCreateType(pointer.ReferentType); 780 781 // This can happen for pointers to LF_VTSHAPE records, which we shouldn't 782 // create in the AST. 783 if (pointee_type.isNull()) 784 return {}; 785 786 if (pointer.isPointerToMember()) { 787 MemberPointerInfo mpi = pointer.getMemberInfo(); 788 clang::QualType class_type = GetOrCreateType(mpi.ContainingType); 789 790 return m_clang.getASTContext().getMemberPointerType( 791 pointee_type, class_type.getTypePtr()); 792 } 793 794 clang::QualType pointer_type; 795 if (pointer.getMode() == PointerMode::LValueReference) 796 pointer_type = m_clang.getASTContext().getLValueReferenceType(pointee_type); 797 else if (pointer.getMode() == PointerMode::RValueReference) 798 pointer_type = m_clang.getASTContext().getRValueReferenceType(pointee_type); 799 else 800 pointer_type = m_clang.getASTContext().getPointerType(pointee_type); 801 802 if ((pointer.getOptions() & PointerOptions::Const) != PointerOptions::None) 803 pointer_type.addConst(); 804 805 if ((pointer.getOptions() & PointerOptions::Volatile) != PointerOptions::None) 806 pointer_type.addVolatile(); 807 808 if ((pointer.getOptions() & PointerOptions::Restrict) != PointerOptions::None) 809 pointer_type.addRestrict(); 810 811 return pointer_type; 812 } 813 814 clang::QualType 815 PdbAstBuilder::CreateModifierType(const ModifierRecord &modifier) { 816 clang::QualType unmodified_type = GetOrCreateType(modifier.ModifiedType); 817 if (unmodified_type.isNull()) 818 return {}; 819 820 if ((modifier.Modifiers & ModifierOptions::Const) != ModifierOptions::None) 821 unmodified_type.addConst(); 822 if ((modifier.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None) 823 unmodified_type.addVolatile(); 824 825 return unmodified_type; 826 } 827 828 clang::QualType PdbAstBuilder::CreateRecordType(PdbTypeSymId id, 829 const TagRecord &record) { 830 clang::DeclContext *context = nullptr; 831 std::string uname; 832 std::tie(context, uname) = CreateDeclInfoForType(record, id.index); 833 clang::TagTypeKind ttk = TranslateUdtKind(record); 834 lldb::AccessType access = 835 (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic; 836 837 ClangASTMetadata metadata; 838 metadata.SetUserID(toOpaqueUid(id)); 839 metadata.SetIsDynamicCXXType(false); 840 841 CompilerType ct = 842 m_clang.CreateRecordType(context, OptionalClangModuleID(), access, uname, 843 ttk, lldb::eLanguageTypeC_plus_plus, &metadata); 844 845 lldbassert(ct.IsValid()); 846 847 TypeSystemClang::StartTagDeclarationDefinition(ct); 848 849 // Even if it's possible, don't complete it at this point. Just mark it 850 // forward resolved, and if/when LLDB needs the full definition, it can 851 // ask us. 852 clang::QualType result = 853 clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType()); 854 855 TypeSystemClang::SetHasExternalStorage(result.getAsOpaquePtr(), true); 856 return result; 857 } 858 859 clang::Decl *PdbAstBuilder::TryGetDecl(PdbSymUid uid) const { 860 auto iter = m_uid_to_decl.find(toOpaqueUid(uid)); 861 if (iter != m_uid_to_decl.end()) 862 return iter->second; 863 return nullptr; 864 } 865 866 clang::NamespaceDecl * 867 PdbAstBuilder::GetOrCreateNamespaceDecl(const char *name, 868 clang::DeclContext &context) { 869 return m_clang.GetUniqueNamespaceDeclaration( 870 IsAnonymousNamespaceName(name) ? nullptr : name, &context, 871 OptionalClangModuleID()); 872 } 873 874 clang::BlockDecl * 875 PdbAstBuilder::GetOrCreateBlockDecl(PdbCompilandSymId block_id) { 876 if (clang::Decl *decl = TryGetDecl(block_id)) 877 return llvm::dyn_cast<clang::BlockDecl>(decl); 878 879 clang::DeclContext *scope = GetParentDeclContext(block_id); 880 881 clang::BlockDecl *block_decl = 882 m_clang.CreateBlockDeclaration(scope, OptionalClangModuleID()); 883 m_uid_to_decl.insert({toOpaqueUid(block_id), block_decl}); 884 885 DeclStatus status; 886 status.resolved = true; 887 status.uid = toOpaqueUid(block_id); 888 m_decl_to_status.insert({block_decl, status}); 889 890 return block_decl; 891 } 892 893 clang::VarDecl *PdbAstBuilder::CreateVariableDecl(PdbSymUid uid, CVSymbol sym, 894 clang::DeclContext &scope) { 895 VariableInfo var_info = GetVariableNameInfo(sym); 896 clang::QualType qt = GetOrCreateType(var_info.type); 897 898 clang::VarDecl *var_decl = m_clang.CreateVariableDeclaration( 899 &scope, OptionalClangModuleID(), var_info.name.str().c_str(), qt); 900 901 m_uid_to_decl[toOpaqueUid(uid)] = var_decl; 902 DeclStatus status; 903 status.resolved = true; 904 status.uid = toOpaqueUid(uid); 905 m_decl_to_status.insert({var_decl, status}); 906 return var_decl; 907 } 908 909 clang::VarDecl * 910 PdbAstBuilder::GetOrCreateVariableDecl(PdbCompilandSymId scope_id, 911 PdbCompilandSymId var_id) { 912 if (clang::Decl *decl = TryGetDecl(var_id)) 913 return llvm::dyn_cast<clang::VarDecl>(decl); 914 915 clang::DeclContext *scope = GetOrCreateDeclContextForUid(scope_id); 916 917 CVSymbol sym = m_index.ReadSymbolRecord(var_id); 918 return CreateVariableDecl(PdbSymUid(var_id), sym, *scope); 919 } 920 921 clang::VarDecl *PdbAstBuilder::GetOrCreateVariableDecl(PdbGlobalSymId var_id) { 922 if (clang::Decl *decl = TryGetDecl(var_id)) 923 return llvm::dyn_cast<clang::VarDecl>(decl); 924 925 CVSymbol sym = m_index.ReadSymbolRecord(var_id); 926 auto context = FromCompilerDeclContext(GetTranslationUnitDecl()); 927 return CreateVariableDecl(PdbSymUid(var_id), sym, *context); 928 } 929 930 clang::TypedefNameDecl * 931 PdbAstBuilder::GetOrCreateTypedefDecl(PdbGlobalSymId id) { 932 if (clang::Decl *decl = TryGetDecl(id)) 933 return llvm::dyn_cast<clang::TypedefNameDecl>(decl); 934 935 CVSymbol sym = m_index.ReadSymbolRecord(id); 936 lldbassert(sym.kind() == S_UDT); 937 UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym)); 938 939 clang::DeclContext *scope = GetParentDeclContext(id); 940 941 PdbTypeSymId real_type_id{udt.Type, false}; 942 clang::QualType qt = GetOrCreateType(real_type_id); 943 944 std::string uname = std::string(DropNameScope(udt.Name)); 945 946 CompilerType ct = ToCompilerType(qt).CreateTypedef( 947 uname.c_str(), ToCompilerDeclContext(*scope), 0); 948 clang::TypedefNameDecl *tnd = m_clang.GetAsTypedefDecl(ct); 949 DeclStatus status; 950 status.resolved = true; 951 status.uid = toOpaqueUid(id); 952 m_decl_to_status.insert({tnd, status}); 953 return tnd; 954 } 955 956 clang::QualType PdbAstBuilder::GetBasicType(lldb::BasicType type) { 957 CompilerType ct = m_clang.GetBasicType(type); 958 return clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType()); 959 } 960 961 clang::QualType PdbAstBuilder::CreateType(PdbTypeSymId type) { 962 if (type.index.isSimple()) 963 return CreateSimpleType(type.index); 964 965 CVType cvt = m_index.tpi().getType(type.index); 966 967 if (cvt.kind() == LF_MODIFIER) { 968 ModifierRecord modifier; 969 llvm::cantFail( 970 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier)); 971 return CreateModifierType(modifier); 972 } 973 974 if (cvt.kind() == LF_POINTER) { 975 PointerRecord pointer; 976 llvm::cantFail( 977 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer)); 978 return CreatePointerType(pointer); 979 } 980 981 if (IsTagRecord(cvt)) { 982 CVTagRecord tag = CVTagRecord::create(cvt); 983 if (tag.kind() == CVTagRecord::Union) 984 return CreateRecordType(type.index, tag.asUnion()); 985 if (tag.kind() == CVTagRecord::Enum) 986 return CreateEnumType(type.index, tag.asEnum()); 987 return CreateRecordType(type.index, tag.asClass()); 988 } 989 990 if (cvt.kind() == LF_ARRAY) { 991 ArrayRecord ar; 992 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar)); 993 return CreateArrayType(ar); 994 } 995 996 if (cvt.kind() == LF_PROCEDURE) { 997 ProcedureRecord pr; 998 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr)); 999 return CreateFunctionType(pr.ArgumentList, pr.ReturnType, pr.CallConv); 1000 } 1001 1002 if (cvt.kind() == LF_MFUNCTION) { 1003 MemberFunctionRecord mfr; 1004 llvm::cantFail( 1005 TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr)); 1006 return CreateFunctionType(mfr.ArgumentList, mfr.ReturnType, mfr.CallConv); 1007 } 1008 1009 return {}; 1010 } 1011 1012 clang::QualType PdbAstBuilder::GetOrCreateType(PdbTypeSymId type) { 1013 lldb::user_id_t uid = toOpaqueUid(type); 1014 auto iter = m_uid_to_type.find(uid); 1015 if (iter != m_uid_to_type.end()) 1016 return iter->second; 1017 1018 PdbTypeSymId best_type = GetBestPossibleDecl(type, m_index.tpi()); 1019 1020 clang::QualType qt; 1021 if (best_type.index != type.index) { 1022 // This is a forward decl. Call GetOrCreate on the full decl, then map the 1023 // forward decl id to the full decl QualType. 1024 clang::QualType qt = GetOrCreateType(best_type); 1025 m_uid_to_type[toOpaqueUid(type)] = qt; 1026 return qt; 1027 } 1028 1029 // This is either a full decl, or a forward decl with no matching full decl 1030 // in the debug info. 1031 qt = CreateType(type); 1032 m_uid_to_type[toOpaqueUid(type)] = qt; 1033 if (IsTagRecord(type, m_index.tpi())) { 1034 clang::TagDecl *tag = qt->getAsTagDecl(); 1035 lldbassert(m_decl_to_status.count(tag) == 0); 1036 1037 DeclStatus &status = m_decl_to_status[tag]; 1038 status.uid = uid; 1039 status.resolved = false; 1040 } 1041 return qt; 1042 } 1043 1044 clang::FunctionDecl * 1045 PdbAstBuilder::GetOrCreateFunctionDecl(PdbCompilandSymId func_id) { 1046 if (clang::Decl *decl = TryGetDecl(func_id)) 1047 return llvm::dyn_cast<clang::FunctionDecl>(decl); 1048 1049 clang::DeclContext *parent = GetParentDeclContext(PdbSymUid(func_id)); 1050 std::string context_name; 1051 if (clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(parent)) { 1052 context_name = ns->getQualifiedNameAsString(); 1053 } else if (clang::TagDecl *tag = llvm::dyn_cast<clang::TagDecl>(parent)) { 1054 context_name = tag->getQualifiedNameAsString(); 1055 } 1056 1057 CVSymbol cvs = m_index.ReadSymbolRecord(func_id); 1058 ProcSym proc(static_cast<SymbolRecordKind>(cvs.kind())); 1059 llvm::cantFail(SymbolDeserializer::deserializeAs<ProcSym>(cvs, proc)); 1060 1061 PdbTypeSymId type_id(proc.FunctionType); 1062 clang::QualType qt = GetOrCreateType(type_id); 1063 if (qt.isNull()) 1064 return nullptr; 1065 1066 clang::StorageClass storage = clang::SC_None; 1067 if (proc.Kind == SymbolRecordKind::ProcSym) 1068 storage = clang::SC_Static; 1069 1070 const clang::FunctionProtoType *func_type = 1071 llvm::dyn_cast<clang::FunctionProtoType>(qt); 1072 1073 CompilerType func_ct = ToCompilerType(qt); 1074 1075 llvm::StringRef proc_name = proc.Name; 1076 proc_name.consume_front(context_name); 1077 proc_name.consume_front("::"); 1078 1079 clang::FunctionDecl *function_decl = nullptr; 1080 if (parent->isRecord()) { 1081 clang::QualType parent_qt = llvm::cast<clang::TypeDecl>(parent) 1082 ->getTypeForDecl() 1083 ->getCanonicalTypeInternal(); 1084 lldb::opaque_compiler_type_t parent_opaque_ty = 1085 ToCompilerType(parent_qt).GetOpaqueQualType(); 1086 1087 auto iter = m_cxx_record_map.find(parent_opaque_ty); 1088 if (iter != m_cxx_record_map.end()) { 1089 if (iter->getSecond().contains({proc_name, func_ct})) { 1090 return nullptr; 1091 } 1092 } 1093 1094 CVType cvt = m_index.tpi().getType(type_id.index); 1095 MemberFunctionRecord func_record(static_cast<TypeRecordKind>(cvt.kind())); 1096 llvm::cantFail(TypeDeserializer::deserializeAs<MemberFunctionRecord>( 1097 cvt, func_record)); 1098 TypeIndex class_index = func_record.getClassType(); 1099 CVType parent_cvt = m_index.tpi().getType(class_index); 1100 ClassRecord class_record = CVTagRecord::create(parent_cvt).asClass(); 1101 // If it's a forward reference, try to get the real TypeIndex. 1102 if (class_record.isForwardRef()) { 1103 llvm::Expected<TypeIndex> eti = 1104 m_index.tpi().findFullDeclForForwardRef(class_index); 1105 if (eti) { 1106 class_record = 1107 CVTagRecord::create(m_index.tpi().getType(*eti)).asClass(); 1108 } 1109 } 1110 if (!class_record.FieldList.isSimple()) { 1111 CVType field_list = m_index.tpi().getType(class_record.FieldList); 1112 CreateMethodDecl process(m_index, m_clang, type_id.index, function_decl, 1113 parent_opaque_ty, proc_name, func_ct); 1114 if (llvm::Error err = visitMemberRecordStream(field_list.data(), process)) 1115 llvm::consumeError(std::move(err)); 1116 } 1117 1118 if (!function_decl) { 1119 function_decl = m_clang.AddMethodToCXXRecordType( 1120 parent_opaque_ty, proc_name, 1121 /*mangled_name=*/nullptr, func_ct, 1122 /*access=*/lldb::AccessType::eAccessPublic, 1123 /*is_virtual=*/false, /*is_static=*/false, 1124 /*is_inline=*/false, /*is_explicit=*/false, 1125 /*is_attr_used=*/false, /*is_artificial=*/false); 1126 } 1127 1128 m_cxx_record_map[parent_opaque_ty].insert({proc_name, func_ct}); 1129 } else { 1130 function_decl = m_clang.CreateFunctionDeclaration( 1131 parent, OptionalClangModuleID(), proc_name, func_ct, storage, false); 1132 CreateFunctionParameters(func_id, *function_decl, 1133 func_type->getNumParams()); 1134 } 1135 1136 lldbassert(m_uid_to_decl.count(toOpaqueUid(func_id)) == 0); 1137 m_uid_to_decl[toOpaqueUid(func_id)] = function_decl; 1138 DeclStatus status; 1139 status.resolved = true; 1140 status.uid = toOpaqueUid(func_id); 1141 m_decl_to_status.insert({function_decl, status}); 1142 1143 return function_decl; 1144 } 1145 1146 void PdbAstBuilder::CreateFunctionParameters(PdbCompilandSymId func_id, 1147 clang::FunctionDecl &function_decl, 1148 uint32_t param_count) { 1149 CompilandIndexItem *cii = m_index.compilands().GetCompiland(func_id.modi); 1150 CVSymbolArray scope = 1151 cii->m_debug_stream.getSymbolArrayForScope(func_id.offset); 1152 1153 auto begin = scope.begin(); 1154 auto end = scope.end(); 1155 std::vector<clang::ParmVarDecl *> params; 1156 while (begin != end && param_count > 0) { 1157 uint32_t record_offset = begin.offset(); 1158 CVSymbol sym = *begin++; 1159 1160 TypeIndex param_type; 1161 llvm::StringRef param_name; 1162 switch (sym.kind()) { 1163 case S_REGREL32: { 1164 RegRelativeSym reg(SymbolRecordKind::RegRelativeSym); 1165 cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg)); 1166 param_type = reg.Type; 1167 param_name = reg.Name; 1168 break; 1169 } 1170 case S_REGISTER: { 1171 RegisterSym reg(SymbolRecordKind::RegisterSym); 1172 cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg)); 1173 param_type = reg.Index; 1174 param_name = reg.Name; 1175 break; 1176 } 1177 case S_LOCAL: { 1178 LocalSym local(SymbolRecordKind::LocalSym); 1179 cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local)); 1180 if ((local.Flags & LocalSymFlags::IsParameter) == LocalSymFlags::None) 1181 continue; 1182 param_type = local.Type; 1183 param_name = local.Name; 1184 break; 1185 } 1186 case S_BLOCK32: 1187 // All parameters should come before the first block. If that isn't the 1188 // case, then perhaps this is bad debug info that doesn't contain 1189 // information about all parameters. 1190 return; 1191 default: 1192 continue; 1193 } 1194 1195 PdbCompilandSymId param_uid(func_id.modi, record_offset); 1196 clang::QualType qt = GetOrCreateType(param_type); 1197 1198 CompilerType param_type_ct = m_clang.GetType(qt); 1199 clang::ParmVarDecl *param = m_clang.CreateParameterDeclaration( 1200 &function_decl, OptionalClangModuleID(), param_name.str().c_str(), 1201 param_type_ct, clang::SC_None, true); 1202 lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0); 1203 1204 m_uid_to_decl[toOpaqueUid(param_uid)] = param; 1205 params.push_back(param); 1206 --param_count; 1207 } 1208 1209 if (!params.empty()) 1210 m_clang.SetFunctionParameters(&function_decl, params); 1211 } 1212 1213 clang::QualType PdbAstBuilder::CreateEnumType(PdbTypeSymId id, 1214 const EnumRecord &er) { 1215 clang::DeclContext *decl_context = nullptr; 1216 std::string uname; 1217 std::tie(decl_context, uname) = CreateDeclInfoForType(er, id.index); 1218 clang::QualType underlying_type = GetOrCreateType(er.UnderlyingType); 1219 1220 Declaration declaration; 1221 CompilerType enum_ct = m_clang.CreateEnumerationType( 1222 uname, decl_context, OptionalClangModuleID(), declaration, 1223 ToCompilerType(underlying_type), er.isScoped()); 1224 1225 TypeSystemClang::StartTagDeclarationDefinition(enum_ct); 1226 TypeSystemClang::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true); 1227 1228 return clang::QualType::getFromOpaquePtr(enum_ct.GetOpaqueQualType()); 1229 } 1230 1231 clang::QualType PdbAstBuilder::CreateArrayType(const ArrayRecord &ar) { 1232 clang::QualType element_type = GetOrCreateType(ar.ElementType); 1233 1234 uint64_t element_size = GetSizeOfType({ar.ElementType}, m_index.tpi()); 1235 if (element_size == 0) 1236 return {}; 1237 uint64_t element_count = ar.Size / element_size; 1238 1239 CompilerType array_ct = m_clang.CreateArrayType(ToCompilerType(element_type), 1240 element_count, false); 1241 return clang::QualType::getFromOpaquePtr(array_ct.GetOpaqueQualType()); 1242 } 1243 1244 clang::QualType PdbAstBuilder::CreateFunctionType( 1245 TypeIndex args_type_idx, TypeIndex return_type_idx, 1246 llvm::codeview::CallingConvention calling_convention) { 1247 TpiStream &stream = m_index.tpi(); 1248 CVType args_cvt = stream.getType(args_type_idx); 1249 ArgListRecord args; 1250 llvm::cantFail( 1251 TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args)); 1252 1253 llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices); 1254 bool is_variadic = IsCVarArgsFunction(arg_indices); 1255 if (is_variadic) 1256 arg_indices = arg_indices.drop_back(); 1257 1258 std::vector<CompilerType> arg_types; 1259 arg_types.reserve(arg_indices.size()); 1260 1261 for (TypeIndex arg_index : arg_indices) { 1262 clang::QualType arg_type = GetOrCreateType(arg_index); 1263 arg_types.push_back(ToCompilerType(arg_type)); 1264 } 1265 1266 clang::QualType return_type = GetOrCreateType(return_type_idx); 1267 1268 llvm::Optional<clang::CallingConv> cc = 1269 TranslateCallingConvention(calling_convention); 1270 if (!cc) 1271 return {}; 1272 1273 CompilerType return_ct = ToCompilerType(return_type); 1274 CompilerType func_sig_ast_type = m_clang.CreateFunctionType( 1275 return_ct, arg_types.data(), arg_types.size(), is_variadic, 0, *cc); 1276 1277 return clang::QualType::getFromOpaquePtr( 1278 func_sig_ast_type.GetOpaqueQualType()); 1279 } 1280 1281 static bool isTagDecl(clang::DeclContext &context) { 1282 return llvm::isa<clang::TagDecl>(&context); 1283 } 1284 1285 static bool isFunctionDecl(clang::DeclContext &context) { 1286 return llvm::isa<clang::FunctionDecl>(&context); 1287 } 1288 1289 static bool isBlockDecl(clang::DeclContext &context) { 1290 return llvm::isa<clang::BlockDecl>(&context); 1291 } 1292 1293 void PdbAstBuilder::ParseAllNamespacesPlusChildrenOf( 1294 llvm::Optional<llvm::StringRef> parent) { 1295 TypeIndex ti{m_index.tpi().TypeIndexBegin()}; 1296 for (const CVType &cvt : m_index.tpi().typeArray()) { 1297 PdbTypeSymId tid{ti}; 1298 ++ti; 1299 1300 if (!IsTagRecord(cvt)) 1301 continue; 1302 1303 CVTagRecord tag = CVTagRecord::create(cvt); 1304 1305 if (!parent.hasValue()) { 1306 clang::QualType qt = GetOrCreateType(tid); 1307 CompleteType(qt); 1308 continue; 1309 } 1310 1311 // Call CreateDeclInfoForType unconditionally so that the namespace info 1312 // gets created. But only call CreateRecordType if the namespace name 1313 // matches. 1314 clang::DeclContext *context = nullptr; 1315 std::string uname; 1316 std::tie(context, uname) = CreateDeclInfoForType(tag.asTag(), tid.index); 1317 if (!context->isNamespace()) 1318 continue; 1319 1320 clang::NamespaceDecl *ns = llvm::cast<clang::NamespaceDecl>(context); 1321 std::string actual_ns = ns->getQualifiedNameAsString(); 1322 if (llvm::StringRef(actual_ns).startswith(*parent)) { 1323 clang::QualType qt = GetOrCreateType(tid); 1324 CompleteType(qt); 1325 continue; 1326 } 1327 } 1328 1329 uint32_t module_count = m_index.dbi().modules().getModuleCount(); 1330 for (uint16_t modi = 0; modi < module_count; ++modi) { 1331 CompilandIndexItem &cii = m_index.compilands().GetOrCreateCompiland(modi); 1332 const CVSymbolArray &symbols = cii.m_debug_stream.getSymbolArray(); 1333 auto iter = symbols.begin(); 1334 while (iter != symbols.end()) { 1335 PdbCompilandSymId sym_id{modi, iter.offset()}; 1336 1337 switch (iter->kind()) { 1338 case S_GPROC32: 1339 case S_LPROC32: 1340 GetOrCreateFunctionDecl(sym_id); 1341 iter = symbols.at(getScopeEndOffset(*iter)); 1342 break; 1343 case S_GDATA32: 1344 case S_GTHREAD32: 1345 case S_LDATA32: 1346 case S_LTHREAD32: 1347 GetOrCreateVariableDecl(PdbCompilandSymId(modi, 0), sym_id); 1348 ++iter; 1349 break; 1350 default: 1351 ++iter; 1352 continue; 1353 } 1354 } 1355 } 1356 } 1357 1358 static CVSymbolArray skipFunctionParameters(clang::Decl &decl, 1359 const CVSymbolArray &symbols) { 1360 clang::FunctionDecl *func_decl = llvm::dyn_cast<clang::FunctionDecl>(&decl); 1361 if (!func_decl) 1362 return symbols; 1363 unsigned int params = func_decl->getNumParams(); 1364 if (params == 0) 1365 return symbols; 1366 1367 CVSymbolArray result = symbols; 1368 1369 while (!result.empty()) { 1370 if (params == 0) 1371 return result; 1372 1373 CVSymbol sym = *result.begin(); 1374 result.drop_front(); 1375 1376 if (!isLocalVariableType(sym.kind())) 1377 continue; 1378 1379 --params; 1380 } 1381 return result; 1382 } 1383 1384 void PdbAstBuilder::ParseBlockChildren(PdbCompilandSymId block_id) { 1385 CVSymbol sym = m_index.ReadSymbolRecord(block_id); 1386 lldbassert(sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32 || 1387 sym.kind() == S_BLOCK32); 1388 CompilandIndexItem &cii = 1389 m_index.compilands().GetOrCreateCompiland(block_id.modi); 1390 CVSymbolArray symbols = 1391 cii.m_debug_stream.getSymbolArrayForScope(block_id.offset); 1392 1393 // Function parameters should already have been created when the function was 1394 // parsed. 1395 if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32) 1396 symbols = 1397 skipFunctionParameters(*m_uid_to_decl[toOpaqueUid(block_id)], symbols); 1398 1399 auto begin = symbols.begin(); 1400 while (begin != symbols.end()) { 1401 PdbCompilandSymId child_sym_id(block_id.modi, begin.offset()); 1402 GetOrCreateSymbolForId(child_sym_id); 1403 if (begin->kind() == S_BLOCK32) { 1404 ParseBlockChildren(child_sym_id); 1405 begin = symbols.at(getScopeEndOffset(*begin)); 1406 } 1407 ++begin; 1408 } 1409 } 1410 1411 void PdbAstBuilder::ParseDeclsForSimpleContext(clang::DeclContext &context) { 1412 1413 clang::Decl *decl = clang::Decl::castFromDeclContext(&context); 1414 lldbassert(decl); 1415 1416 auto iter = m_decl_to_status.find(decl); 1417 lldbassert(iter != m_decl_to_status.end()); 1418 1419 if (auto *tag = llvm::dyn_cast<clang::TagDecl>(&context)) { 1420 CompleteTagDecl(*tag); 1421 return; 1422 } 1423 1424 if (isFunctionDecl(context) || isBlockDecl(context)) { 1425 PdbCompilandSymId block_id = PdbSymUid(iter->second.uid).asCompilandSym(); 1426 ParseBlockChildren(block_id); 1427 } 1428 } 1429 1430 void PdbAstBuilder::ParseDeclsForContext(clang::DeclContext &context) { 1431 // Namespaces aren't explicitly represented in the debug info, and the only 1432 // way to parse them is to parse all type info, demangling every single type 1433 // and trying to reconstruct the DeclContext hierarchy this way. Since this 1434 // is an expensive operation, we have to special case it so that we do other 1435 // work (such as parsing the items that appear within the namespaces) at the 1436 // same time. 1437 if (context.isTranslationUnit()) { 1438 ParseAllNamespacesPlusChildrenOf(llvm::None); 1439 return; 1440 } 1441 1442 if (context.isNamespace()) { 1443 clang::NamespaceDecl &ns = *llvm::dyn_cast<clang::NamespaceDecl>(&context); 1444 std::string qname = ns.getQualifiedNameAsString(); 1445 ParseAllNamespacesPlusChildrenOf(llvm::StringRef{qname}); 1446 return; 1447 } 1448 1449 if (isTagDecl(context) || isFunctionDecl(context) || isBlockDecl(context)) { 1450 ParseDeclsForSimpleContext(context); 1451 return; 1452 } 1453 } 1454 1455 CompilerDecl PdbAstBuilder::ToCompilerDecl(clang::Decl &decl) { 1456 return m_clang.GetCompilerDecl(&decl); 1457 } 1458 1459 CompilerType PdbAstBuilder::ToCompilerType(clang::QualType qt) { 1460 return {&m_clang, qt.getAsOpaquePtr()}; 1461 } 1462 1463 CompilerDeclContext 1464 PdbAstBuilder::ToCompilerDeclContext(clang::DeclContext &context) { 1465 return m_clang.CreateDeclContext(&context); 1466 } 1467 1468 clang::Decl * PdbAstBuilder::FromCompilerDecl(CompilerDecl decl) { 1469 return ClangUtil::GetDecl(decl); 1470 } 1471 1472 clang::DeclContext * 1473 PdbAstBuilder::FromCompilerDeclContext(CompilerDeclContext context) { 1474 return static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext()); 1475 } 1476 1477 void PdbAstBuilder::Dump(Stream &stream) { 1478 m_clang.Dump(stream.AsRawOstream()); 1479 } 1480