1 #include "PdbAstBuilder.h"
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"
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"
26 #include "UdtRecordCompleter.h"
28 using namespace lldb_private;
29 using namespace lldb_private::npdb;
30 using namespace llvm::codeview;
31 using namespace llvm::pdb;
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
39 id.offset = getScopeParentOffset(sym);
40 // Global symbols have parent offset of 0. Return llvm::None to indicate
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();
52 auto begin = syms.begin();
53 auto end = syms.at(id.offset);
54 std::vector<PdbCompilandSymId> scope_stack;
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())
61 return scope_stack.back();
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!");
69 // We haven't found the symbol yet. Check if we need to open or close the
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);
78 // The symbol we're looking for is somewhere in this scope.
79 scope_stack.emplace_back(id.modi, begin.offset());
81 } else if (symbolEndsScope(begin->kind())) {
82 scope_stack.pop_back();
90 static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) {
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;
103 lldbassert(false && "Invalid tag record kind!");
104 return clang::TTK_Struct;
108 static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) {
111 return args.back() == TypeIndex::None();
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)
124 static ClangASTContext &GetClangASTContext(ObjectFile &obj) {
126 obj.GetModule()->GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
128 return static_cast<ClangASTContext &>(*ts);
131 static llvm::Optional<clang::CallingConv>
132 TranslateCallingConvention(llvm::codeview::CallingConvention conv) {
133 using CC = llvm::codeview::CallingConvention;
138 return clang::CallingConv::CC_C;
141 return clang::CallingConv::CC_X86Pascal;
144 return clang::CallingConv::CC_X86FastCall;
145 case CC::NearStdCall:
147 return clang::CallingConv::CC_X86StdCall;
149 return clang::CallingConv::CC_X86ThisCall;
151 return clang::CallingConv::CC_X86VectorCall;
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:
167 // Then in the debug info, this will appear as:
168 // LF_STRUCTURE `A::B` [type index = N]
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.
175 // If it's a simple type, then this is something like `using foo = int`.
176 if (Record.Type.isSimple())
179 CVType cvt = tpi.getType(Record.Type);
181 if (!IsTagRecord(cvt))
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)
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];
199 piece += Record.Name;
200 piece.push_back('@');
201 qname.insert(4, std::move(piece));
202 if (qname != child.asTag().UniqueName)
205 return std::move(child);
208 PdbAstBuilder::PdbAstBuilder(ObjectFile &obj, PdbIndex &index)
209 : m_index(index), m_clang(GetClangASTContext(obj)) {
213 clang::DeclContext &PdbAstBuilder::GetTranslationUnitDecl() {
214 return *m_clang.GetTranslationUnitDecl();
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);
223 llvm::ms_demangle::Demangler demangler;
224 StringView sv(record.UniqueName.begin(), record.UniqueName.size());
225 llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
227 return {m_clang.GetTranslationUnitDecl(), record.UniqueName};
229 llvm::ms_demangle::IdentifierNode *idn =
230 ttn->QualifiedName->getUnqualifiedIdentifier();
231 std::string uname = idn->toString(llvm::ms_demangle::OF_NoTagSpecifier);
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);
238 clang::DeclContext *context = m_clang.GetTranslationUnitDecl();
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()) {
246 return {context, uname};
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};
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);
261 return {context, uname};
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);
270 context = clang::TagDecl::castToDeclContext(parent_qt->getAsTagDecl());
271 return {context, uname};
274 void PdbAstBuilder::BuildParentMap() {
275 LazyRandomTypeCollection &types = m_index.tpi().typeCollection();
277 llvm::DenseMap<TypeIndex, TypeIndex> forward_to_full;
278 llvm::DenseMap<TypeIndex, TypeIndex> full_to_forward;
280 struct RecordIndices {
285 llvm::StringMap<RecordIndices> record_indices;
287 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
288 CVType type = types.getType(*ti);
289 if (!IsTagRecord(type))
292 CVTagRecord tag = CVTagRecord::create(type);
294 RecordIndices &indices = record_indices[tag.asTag().getUniqueName()];
295 if (tag.asTag().isForwardRef())
296 indices.forward = *ti;
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;
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())
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) {}
320 llvm::DenseMap<TypeIndex, TypeIndex> &parents;
322 unsigned unnamed_type_index = 1;
324 const CVTagRecord &parent_cvt;
326 llvm::Error visitKnownMember(CVMemberRecord &CVR,
327 NestedTypeRecord &Record) override {
328 std::string unnamed_type_name;
329 if (Record.Name.empty()) {
331 llvm::formatv("<unnamed-type-$S{0}>", unnamed_type_index).str();
332 Record.Name = unnamed_type_name;
333 ++unnamed_type_index;
335 llvm::Optional<CVTagRecord> tag =
336 GetNestedTagDefinition(Record, parent_cvt, index.tpi());
338 return llvm::ErrorSuccess();
340 parents[Record.Type] = parent;
341 return llvm::ErrorSuccess();
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);
349 llvm::consumeError(std::move(error));
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;
363 auto iter = forward_to_full.find(value);
364 if (iter != forward_to_full.end())
365 entry.second = iter->second;
367 iter = forward_to_full.find(key);
368 if (iter != forward_to_full.end())
369 fwd_keys.push_back(key);
371 full_keys.push_back(key);
373 for (TypeIndex fwd : fwd_keys) {
374 TypeIndex full = forward_to_full[fwd];
375 m_parent_types[full] = m_parent_types[fwd];
377 for (TypeIndex full : full_keys) {
378 TypeIndex fwd = full_to_forward[full];
379 m_parent_types[fwd] = m_parent_types[full];
385 static bool isLocalVariableType(SymbolKind K) {
398 RenderScopeList(llvm::ArrayRef<llvm::ms_demangle::Node *> nodes) {
399 lldbassert(!nodes.empty());
401 std::string result = nodes.front()->toString();
402 nodes = nodes.drop_front();
403 while (!nodes.empty()) {
405 result += nodes.front()->toString(llvm::ms_demangle::OF_NoTagSpecifier);
406 nodes = nodes.drop_front();
411 static llvm::Optional<PublicSym32> FindPublicSym(const SegmentOffset &addr,
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);
421 llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(s1, p1));
422 if (p1.Segment < y.segment)
424 return p1.Offset < y.offset;
426 if (iter == addr_map.end())
428 CVSymbol sym = syms.readRecord(*iter);
429 lldbassert(sym.kind() == S_PUB32);
431 llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(sym, p));
432 if (p.Segment == addr.segment && p.Offset == addr.offset)
437 clang::Decl *PdbAstBuilder::GetOrCreateSymbolForId(PdbCompilandSymId id) {
438 CVSymbol cvs = m_index.ReadSymbolRecord(id);
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);
447 switch (cvs.kind()) {
450 return GetOrCreateFunctionDecl(id);
458 return GetOrCreateBlockDecl(id);
464 clang::Decl *PdbAstBuilder::GetOrCreateDeclForUid(PdbSymUid uid) {
465 if (clang::Decl *result = TryGetDecl(uid))
468 clang::Decl *result = nullptr;
469 switch (uid.kind()) {
470 case PdbSymUidKind::CompilandSym:
471 result = GetOrCreateSymbolForId(uid.asCompilandSym());
473 case PdbSymUidKind::Type: {
474 clang::QualType qt = GetOrCreateType(uid.asTypeSym());
475 if (auto *tag = qt->getAsTagDecl()) {
484 m_uid_to_decl[toOpaqueUid(uid)] = result;
488 clang::DeclContext *PdbAstBuilder::GetOrCreateDeclContextForUid(PdbSymUid uid) {
489 if (uid.kind() == PdbSymUidKind::CompilandSym) {
490 if (uid.asCompilandSym().offset == 0)
491 return &GetTranslationUnitDecl();
494 clang::Decl *decl = GetOrCreateDeclForUid(uid);
498 return clang::Decl::castToDeclContext(decl);
501 std::pair<clang::DeclContext *, std::string>
502 PdbAstBuilder::CreateDeclInfoForUndecoratedName(llvm::StringRef name) {
503 MSVCUndecoratedNameParser parser(name);
504 llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers();
506 clang::DeclContext *context = &GetTranslationUnitDecl();
508 llvm::StringRef uname = specs.back().GetBaseName();
509 specs = specs.drop_back();
511 return {context, name};
513 llvm::StringRef scope_name = specs.back().GetFullName();
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();
521 return {clang::TagDecl::castToDeclContext(tag), uname};
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);
530 return {context, uname};
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());
541 return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first;
543 llvm::ms_demangle::Demangler demangler;
544 StringView name{pub->Name.begin(), pub->Name.size()};
545 llvm::ms_demangle::SymbolNode *node = demangler.parse(name);
547 return &GetTranslationUnitDecl();
548 llvm::ArrayRef<llvm::ms_demangle::Node *> name_components{
549 node->Name->Components->Nodes, node->Name->Components->Count - 1};
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();
562 return clang::TagDecl::castToDeclContext(tag);
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();
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());
585 return GetOrCreateDeclContextForUid(*scope);
587 CVSymbol sym = m_index.ReadSymbolRecord(uid.asCompilandSym());
588 return GetParentDeclContextForSymbol(sym);
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));
599 case PdbSymUidKind::FieldListMember:
600 // In this case the parent DeclContext is the one for the class that this
601 // member is inside of.
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.
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()};
619 SymbolDeserializer::deserializeAs<ProcRefSym>(global, ref));
620 PdbCompilandSymId cu_sym_id{ref.modi(), ref.SymOffset};
621 return GetParentDeclContext(cu_sym_id);
623 case SymbolKind::S_CONSTANT:
624 case SymbolKind::S_UDT:
625 return CreateDeclInfoForUndecoratedName(getSymbolName(global)).first;
634 return &GetTranslationUnitDecl();
637 bool PdbAstBuilder::CompleteType(clang::QualType qt) {
638 clang::TagDecl *tag = qt->getAsTagDecl();
642 return CompleteTagDecl(*tag);
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());
650 // If it's already complete, just return.
651 DeclStatus &status = status_iter->second;
655 PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym();
657 lldbassert(IsTagRecord(type_id, m_index.tpi()));
659 clang::QualType tag_qt = m_clang.getASTContext()->getTypeDeclType(&tag);
660 ClangASTContext::SetHasExternalStorage(tag_qt.getAsOpaquePtr(), false);
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);
667 PdbTypeSymId best_ti = GetBestPossibleDecl(tag_ti, m_index.tpi());
668 cvt = m_index.tpi().getType(best_ti.index);
669 lldbassert(IsTagRecord(cvt));
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.
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)
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());
687 llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer);
688 completer.complete();
690 status.resolved = true;
694 llvm::consumeError(std::move(error));
698 clang::QualType PdbAstBuilder::CreateSimpleType(TypeIndex ti) {
699 if (ti == TypeIndex::NullptrT())
700 return GetBasicType(lldb::eBasicTypeNullPtr);
702 if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
703 clang::QualType direct_type = GetOrCreateType(ti.makeDirect());
704 return m_clang.getASTContext()->getPointerType(direct_type);
707 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
710 lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind());
711 if (bt == lldb::eBasicTypeInvalid)
714 return GetBasicType(bt);
717 clang::QualType PdbAstBuilder::CreatePointerType(const PointerRecord &pointer) {
718 clang::QualType pointee_type = GetOrCreateType(pointer.ReferentType);
720 // This can happen for pointers to LF_VTSHAPE records, which we shouldn't
721 // create in the AST.
722 if (pointee_type.isNull())
725 if (pointer.isPointerToMember()) {
726 MemberPointerInfo mpi = pointer.getMemberInfo();
727 clang::QualType class_type = GetOrCreateType(mpi.ContainingType);
729 return m_clang.getASTContext()->getMemberPointerType(
730 pointee_type, class_type.getTypePtr());
733 clang::QualType pointer_type;
734 if (pointer.getMode() == PointerMode::LValueReference)
736 m_clang.getASTContext()->getLValueReferenceType(pointee_type);
737 else if (pointer.getMode() == PointerMode::RValueReference)
739 m_clang.getASTContext()->getRValueReferenceType(pointee_type);
741 pointer_type = m_clang.getASTContext()->getPointerType(pointee_type);
743 if ((pointer.getOptions() & PointerOptions::Const) != PointerOptions::None)
744 pointer_type.addConst();
746 if ((pointer.getOptions() & PointerOptions::Volatile) != PointerOptions::None)
747 pointer_type.addVolatile();
749 if ((pointer.getOptions() & PointerOptions::Restrict) != PointerOptions::None)
750 pointer_type.addRestrict();
756 PdbAstBuilder::CreateModifierType(const ModifierRecord &modifier) {
757 clang::QualType unmodified_type = GetOrCreateType(modifier.ModifiedType);
758 if (unmodified_type.isNull())
761 if ((modifier.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
762 unmodified_type.addConst();
763 if ((modifier.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
764 unmodified_type.addVolatile();
766 return unmodified_type;
769 clang::QualType PdbAstBuilder::CreateRecordType(PdbTypeSymId id,
770 const TagRecord &record) {
771 clang::DeclContext *context = nullptr;
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;
778 ClangASTMetadata metadata;
779 metadata.SetUserID(toOpaqueUid(id));
780 metadata.SetIsDynamicCXXType(false);
783 m_clang.CreateRecordType(context, access, uname.c_str(), ttk,
784 lldb::eLanguageTypeC_plus_plus, &metadata);
786 lldbassert(ct.IsValid());
788 ClangASTContext::StartTagDeclarationDefinition(ct);
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
793 clang::QualType result =
794 clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType());
796 ClangASTContext::SetHasExternalStorage(result.getAsOpaquePtr(), true);
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())
807 clang::NamespaceDecl *
808 PdbAstBuilder::GetOrCreateNamespaceDecl(llvm::StringRef name,
809 clang::DeclContext &context) {
810 return m_clang.GetUniqueNamespaceDeclaration(name.str().c_str(), &context);
814 PdbAstBuilder::GetOrCreateBlockDecl(PdbCompilandSymId block_id) {
815 if (clang::Decl *decl = TryGetDecl(block_id))
816 return llvm::dyn_cast<clang::BlockDecl>(decl);
818 clang::DeclContext *scope = GetParentDeclContext(block_id);
820 clang::BlockDecl *block_decl = m_clang.CreateBlockDeclaration(scope);
821 m_uid_to_decl.insert({toOpaqueUid(block_id), block_decl});
824 status.resolved = true;
825 status.uid = toOpaqueUid(block_id);
826 m_decl_to_status.insert({block_decl, status});
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);
836 clang::VarDecl *var_decl = m_clang.CreateVariableDeclaration(
837 &scope, var_info.name.str().c_str(), qt);
839 m_uid_to_decl[toOpaqueUid(uid)] = var_decl;
841 status.resolved = true;
842 status.uid = toOpaqueUid(uid);
843 m_decl_to_status.insert({var_decl, status});
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);
853 clang::DeclContext *scope = GetOrCreateDeclContextForUid(scope_id);
855 CVSymbol sym = m_index.ReadSymbolRecord(var_id);
856 return CreateVariableDecl(PdbSymUid(var_id), sym, *scope);
859 clang::VarDecl *PdbAstBuilder::GetOrCreateVariableDecl(PdbGlobalSymId var_id) {
860 if (clang::Decl *decl = TryGetDecl(var_id))
861 return llvm::dyn_cast<clang::VarDecl>(decl);
863 CVSymbol sym = m_index.ReadSymbolRecord(var_id);
864 return CreateVariableDecl(PdbSymUid(var_id), sym, GetTranslationUnitDecl());
867 clang::TypedefNameDecl *
868 PdbAstBuilder::GetOrCreateTypedefDecl(PdbGlobalSymId id) {
869 if (clang::Decl *decl = TryGetDecl(id))
870 return llvm::dyn_cast<clang::TypedefNameDecl>(decl);
872 CVSymbol sym = m_index.ReadSymbolRecord(id);
873 lldbassert(sym.kind() == S_UDT);
874 UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
876 clang::DeclContext *scope = GetParentDeclContext(id);
878 PdbTypeSymId real_type_id{udt.Type, false};
879 clang::QualType qt = GetOrCreateType(real_type_id);
881 std::string uname = DropNameScope(udt.Name);
883 CompilerType ct = m_clang.CreateTypedefType(ToCompilerType(qt), uname.c_str(),
884 ToCompilerDeclContext(*scope));
885 clang::TypedefNameDecl *tnd = m_clang.GetAsTypedefDecl(ct);
887 status.resolved = true;
888 status.uid = toOpaqueUid(id);
889 m_decl_to_status.insert({tnd, status});
893 clang::QualType PdbAstBuilder::GetBasicType(lldb::BasicType type) {
894 CompilerType ct = m_clang.GetBasicType(type);
895 return clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType());
898 clang::QualType PdbAstBuilder::CreateType(PdbTypeSymId type) {
899 if (type.index.isSimple())
900 return CreateSimpleType(type.index);
902 CVType cvt = m_index.tpi().getType(type.index);
904 if (cvt.kind() == LF_MODIFIER) {
905 ModifierRecord modifier;
907 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
908 return CreateModifierType(modifier);
911 if (cvt.kind() == LF_POINTER) {
912 PointerRecord pointer;
914 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
915 return CreatePointerType(pointer);
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());
927 if (cvt.kind() == LF_ARRAY) {
929 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
930 return CreateArrayType(ar);
933 if (cvt.kind() == LF_PROCEDURE) {
935 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
936 return CreateProcedureType(pr);
942 clang::QualType PdbAstBuilder::GetOrCreateType(PdbTypeSymId type) {
943 lldb::user_id_t uid = toOpaqueUid(type);
944 auto iter = m_uid_to_type.find(uid);
945 if (iter != m_uid_to_type.end())
948 PdbTypeSymId best_type = GetBestPossibleDecl(type, m_index.tpi());
951 if (best_type.index != type.index) {
952 // This is a forward decl. Call GetOrCreate on the full decl, then map the
953 // forward decl id to the full decl QualType.
954 clang::QualType qt = GetOrCreateType(best_type);
955 m_uid_to_type[toOpaqueUid(type)] = qt;
959 // This is either a full decl, or a forward decl with no matching full decl
960 // in the debug info.
961 qt = CreateType(type);
962 m_uid_to_type[toOpaqueUid(type)] = qt;
963 if (IsTagRecord(type, m_index.tpi())) {
964 clang::TagDecl *tag = qt->getAsTagDecl();
965 lldbassert(m_decl_to_status.count(tag) == 0);
967 DeclStatus &status = m_decl_to_status[tag];
969 status.resolved = false;
974 clang::FunctionDecl *
975 PdbAstBuilder::GetOrCreateFunctionDecl(PdbCompilandSymId func_id) {
976 if (clang::Decl *decl = TryGetDecl(func_id))
977 return llvm::dyn_cast<clang::FunctionDecl>(decl);
979 clang::DeclContext *parent = GetParentDeclContext(PdbSymUid(func_id));
980 std::string context_name;
981 if (clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(parent)) {
982 context_name = ns->getQualifiedNameAsString();
983 } else if (clang::TagDecl *tag = llvm::dyn_cast<clang::TagDecl>(parent)) {
984 context_name = tag->getQualifiedNameAsString();
987 CVSymbol cvs = m_index.ReadSymbolRecord(func_id);
988 ProcSym proc(static_cast<SymbolRecordKind>(cvs.kind()));
989 llvm::cantFail(SymbolDeserializer::deserializeAs<ProcSym>(cvs, proc));
991 PdbTypeSymId type_id(proc.FunctionType);
992 clang::QualType qt = GetOrCreateType(type_id);
996 clang::StorageClass storage = clang::SC_None;
997 if (proc.Kind == SymbolRecordKind::ProcSym)
998 storage = clang::SC_Static;
1000 const clang::FunctionProtoType *func_type =
1001 llvm::dyn_cast<clang::FunctionProtoType>(qt);
1003 CompilerType func_ct = ToCompilerType(qt);
1005 llvm::StringRef proc_name = proc.Name;
1006 proc_name.consume_front(context_name);
1007 proc_name.consume_front("::");
1009 clang::FunctionDecl *function_decl = m_clang.CreateFunctionDeclaration(
1010 parent, proc_name.str().c_str(), func_ct, storage, false);
1012 lldbassert(m_uid_to_decl.count(toOpaqueUid(func_id)) == 0);
1013 m_uid_to_decl[toOpaqueUid(func_id)] = function_decl;
1015 status.resolved = true;
1016 status.uid = toOpaqueUid(func_id);
1017 m_decl_to_status.insert({function_decl, status});
1019 CreateFunctionParameters(func_id, *function_decl, func_type->getNumParams());
1021 return function_decl;
1024 void PdbAstBuilder::CreateFunctionParameters(PdbCompilandSymId func_id,
1025 clang::FunctionDecl &function_decl,
1026 uint32_t param_count) {
1027 CompilandIndexItem *cii = m_index.compilands().GetCompiland(func_id.modi);
1028 CVSymbolArray scope =
1029 cii->m_debug_stream.getSymbolArrayForScope(func_id.offset);
1031 auto begin = scope.begin();
1032 auto end = scope.end();
1033 std::vector<clang::ParmVarDecl *> params;
1034 while (begin != end && param_count > 0) {
1035 uint32_t record_offset = begin.offset();
1036 CVSymbol sym = *begin++;
1038 TypeIndex param_type;
1039 llvm::StringRef param_name;
1040 switch (sym.kind()) {
1042 RegRelativeSym reg(SymbolRecordKind::RegRelativeSym);
1043 cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg));
1044 param_type = reg.Type;
1045 param_name = reg.Name;
1049 RegisterSym reg(SymbolRecordKind::RegisterSym);
1050 cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg));
1051 param_type = reg.Index;
1052 param_name = reg.Name;
1056 LocalSym local(SymbolRecordKind::LocalSym);
1057 cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local));
1058 if ((local.Flags & LocalSymFlags::IsParameter) == LocalSymFlags::None)
1060 param_type = local.Type;
1061 param_name = local.Name;
1065 // All parameters should come before the first block. If that isn't the
1066 // case, then perhaps this is bad debug info that doesn't contain
1067 // information about all parameters.
1073 PdbCompilandSymId param_uid(func_id.modi, record_offset);
1074 clang::QualType qt = GetOrCreateType(param_type);
1076 CompilerType param_type_ct(&m_clang, qt.getAsOpaquePtr());
1077 clang::ParmVarDecl *param = m_clang.CreateParameterDeclaration(
1078 &function_decl, param_name.str().c_str(), param_type_ct,
1080 lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0);
1082 m_uid_to_decl[toOpaqueUid(param_uid)] = param;
1083 params.push_back(param);
1087 if (!params.empty())
1088 m_clang.SetFunctionParameters(&function_decl, params.data(), params.size());
1091 clang::QualType PdbAstBuilder::CreateEnumType(PdbTypeSymId id,
1092 const EnumRecord &er) {
1093 clang::DeclContext *decl_context = nullptr;
1095 std::tie(decl_context, uname) = CreateDeclInfoForType(er, id.index);
1096 clang::QualType underlying_type = GetOrCreateType(er.UnderlyingType);
1098 Declaration declaration;
1099 CompilerType enum_ct = m_clang.CreateEnumerationType(
1100 uname.c_str(), decl_context, declaration, ToCompilerType(underlying_type),
1103 ClangASTContext::StartTagDeclarationDefinition(enum_ct);
1104 ClangASTContext::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true);
1106 return clang::QualType::getFromOpaquePtr(enum_ct.GetOpaqueQualType());
1109 clang::QualType PdbAstBuilder::CreateArrayType(const ArrayRecord &ar) {
1110 clang::QualType element_type = GetOrCreateType(ar.ElementType);
1112 uint64_t element_count =
1113 ar.Size / GetSizeOfType({ar.ElementType}, m_index.tpi());
1115 CompilerType array_ct = m_clang.CreateArrayType(ToCompilerType(element_type),
1116 element_count, false);
1117 return clang::QualType::getFromOpaquePtr(array_ct.GetOpaqueQualType());
1121 PdbAstBuilder::CreateProcedureType(const ProcedureRecord &proc) {
1122 TpiStream &stream = m_index.tpi();
1123 CVType args_cvt = stream.getType(proc.ArgumentList);
1126 TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args));
1128 llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices);
1129 bool is_variadic = IsCVarArgsFunction(arg_indices);
1131 arg_indices = arg_indices.drop_back();
1133 std::vector<CompilerType> arg_types;
1134 arg_types.reserve(arg_indices.size());
1136 for (TypeIndex arg_index : arg_indices) {
1137 clang::QualType arg_type = GetOrCreateType(arg_index);
1138 arg_types.push_back(ToCompilerType(arg_type));
1141 clang::QualType return_type = GetOrCreateType(proc.ReturnType);
1143 llvm::Optional<clang::CallingConv> cc =
1144 TranslateCallingConvention(proc.CallConv);
1148 CompilerType return_ct = ToCompilerType(return_type);
1149 CompilerType func_sig_ast_type = m_clang.CreateFunctionType(
1150 return_ct, arg_types.data(), arg_types.size(), is_variadic, 0, *cc);
1152 return clang::QualType::getFromOpaquePtr(
1153 func_sig_ast_type.GetOpaqueQualType());
1156 static bool isTagDecl(clang::DeclContext &context) {
1157 return !!llvm::dyn_cast<clang::TagDecl>(&context);
1160 static bool isFunctionDecl(clang::DeclContext &context) {
1161 return !!llvm::dyn_cast<clang::FunctionDecl>(&context);
1164 static bool isBlockDecl(clang::DeclContext &context) {
1165 return !!llvm::dyn_cast<clang::BlockDecl>(&context);
1168 void PdbAstBuilder::ParseAllNamespacesPlusChildrenOf(
1169 llvm::Optional<llvm::StringRef> parent) {
1170 TypeIndex ti{m_index.tpi().TypeIndexBegin()};
1171 for (const CVType &cvt : m_index.tpi().typeArray()) {
1172 PdbTypeSymId tid{ti};
1175 if (!IsTagRecord(cvt))
1178 CVTagRecord tag = CVTagRecord::create(cvt);
1180 if (!parent.hasValue()) {
1181 clang::QualType qt = GetOrCreateType(tid);
1186 // Call CreateDeclInfoForType unconditionally so that the namespace info
1187 // gets created. But only call CreateRecordType if the namespace name
1189 clang::DeclContext *context = nullptr;
1191 std::tie(context, uname) = CreateDeclInfoForType(tag.asTag(), tid.index);
1192 if (!context->isNamespace())
1195 clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(context);
1196 std::string actual_ns = ns->getQualifiedNameAsString();
1197 if (llvm::StringRef(actual_ns).startswith(*parent)) {
1198 clang::QualType qt = GetOrCreateType(tid);
1204 uint32_t module_count = m_index.dbi().modules().getModuleCount();
1205 for (uint16_t modi = 0; modi < module_count; ++modi) {
1206 CompilandIndexItem &cii = m_index.compilands().GetOrCreateCompiland(modi);
1207 const CVSymbolArray &symbols = cii.m_debug_stream.getSymbolArray();
1208 auto iter = symbols.begin();
1209 while (iter != symbols.end()) {
1210 PdbCompilandSymId sym_id{modi, iter.offset()};
1212 switch (iter->kind()) {
1215 GetOrCreateFunctionDecl(sym_id);
1216 iter = symbols.at(getScopeEndOffset(*iter));
1222 GetOrCreateVariableDecl(PdbCompilandSymId(modi, 0), sym_id);
1233 static CVSymbolArray skipFunctionParameters(clang::Decl &decl,
1234 const CVSymbolArray &symbols) {
1235 clang::FunctionDecl *func_decl = llvm::dyn_cast<clang::FunctionDecl>(&decl);
1238 unsigned int params = func_decl->getNumParams();
1242 CVSymbolArray result = symbols;
1244 while (!result.empty()) {
1248 CVSymbol sym = *result.begin();
1249 result.drop_front();
1251 if (!isLocalVariableType(sym.kind()))
1259 void PdbAstBuilder::ParseBlockChildren(PdbCompilandSymId block_id) {
1260 CVSymbol sym = m_index.ReadSymbolRecord(block_id);
1261 lldbassert(sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32 ||
1262 sym.kind() == S_BLOCK32);
1263 CompilandIndexItem &cii =
1264 m_index.compilands().GetOrCreateCompiland(block_id.modi);
1265 CVSymbolArray symbols =
1266 cii.m_debug_stream.getSymbolArrayForScope(block_id.offset);
1268 // Function parameters should already have been created when the function was
1270 if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32)
1272 skipFunctionParameters(*m_uid_to_decl[toOpaqueUid(block_id)], symbols);
1274 auto begin = symbols.begin();
1275 while (begin != symbols.end()) {
1276 PdbCompilandSymId child_sym_id(block_id.modi, begin.offset());
1277 GetOrCreateSymbolForId(child_sym_id);
1278 if (begin->kind() == S_BLOCK32) {
1279 ParseBlockChildren(child_sym_id);
1280 begin = symbols.at(getScopeEndOffset(*begin));
1286 void PdbAstBuilder::ParseDeclsForSimpleContext(clang::DeclContext &context) {
1288 clang::Decl *decl = clang::Decl::castFromDeclContext(&context);
1291 auto iter = m_decl_to_status.find(decl);
1292 lldbassert(iter != m_decl_to_status.end());
1294 if (auto *tag = llvm::dyn_cast<clang::TagDecl>(&context)) {
1295 CompleteTagDecl(*tag);
1299 if (isFunctionDecl(context) || isBlockDecl(context)) {
1300 PdbCompilandSymId block_id = PdbSymUid(iter->second.uid).asCompilandSym();
1301 ParseBlockChildren(block_id);
1305 void PdbAstBuilder::ParseDeclsForContext(clang::DeclContext &context) {
1306 // Namespaces aren't explicitly represented in the debug info, and the only
1307 // way to parse them is to parse all type info, demangling every single type
1308 // and trying to reconstruct the DeclContext hierarchy this way. Since this
1309 // is an expensive operation, we have to special case it so that we do other
1310 // work (such as parsing the items that appear within the namespaces) at the
1312 if (context.isTranslationUnit()) {
1313 ParseAllNamespacesPlusChildrenOf(llvm::None);
1317 if (context.isNamespace()) {
1318 clang::NamespaceDecl &ns = *llvm::dyn_cast<clang::NamespaceDecl>(&context);
1319 std::string qname = ns.getQualifiedNameAsString();
1320 ParseAllNamespacesPlusChildrenOf(llvm::StringRef{qname});
1324 if (isTagDecl(context) || isFunctionDecl(context) || isBlockDecl(context)) {
1325 ParseDeclsForSimpleContext(context);
1330 CompilerDecl PdbAstBuilder::ToCompilerDecl(clang::Decl &decl) {
1331 return {&m_clang, &decl};
1334 CompilerType PdbAstBuilder::ToCompilerType(clang::QualType qt) {
1335 return {&m_clang, qt.getAsOpaquePtr()};
1339 PdbAstBuilder::ToCompilerDeclContext(clang::DeclContext &context) {
1340 return {&m_clang, &context};
1343 clang::DeclContext *
1344 PdbAstBuilder::FromCompilerDeclContext(CompilerDeclContext context) {
1345 return static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext());
1348 void PdbAstBuilder::Dump(Stream &stream) { m_clang.Dump(stream); }