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