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