LLDB mainline
PdbAstBuilder.cpp
Go to the documentation of this file.
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 "PdbUtil.h"
22#include "SymbolFileNativePDB.h"
23#include "UdtRecordCompleter.h"
24#include "lldb/Core/Module.h"
27#include <optional>
28#include <string_view>
29
30using namespace lldb_private;
31using namespace lldb_private::npdb;
32using namespace llvm::codeview;
33using namespace llvm::pdb;
34
35namespace {
36struct CreateMethodDecl : public TypeVisitorCallbacks {
37 CreateMethodDecl(PdbIndex &m_index, TypeSystemClang &m_clang,
38 TypeIndex func_type_index,
39 clang::FunctionDecl *&function_decl,
41 llvm::StringRef proc_name, ConstString mangled_name,
42 CompilerType func_ct)
43 : m_index(m_index), m_clang(m_clang), func_type_index(func_type_index),
44 function_decl(function_decl), parent_ty(parent_ty),
45 proc_name(proc_name), mangled_name(mangled_name), func_ct(func_ct) {}
46 PdbIndex &m_index;
47 TypeSystemClang &m_clang;
48 TypeIndex func_type_index;
49 clang::FunctionDecl *&function_decl;
51 llvm::StringRef proc_name;
52 ConstString mangled_name;
53 CompilerType func_ct;
54
55 llvm::Error visitKnownMember(CVMemberRecord &cvr,
56 OverloadedMethodRecord &overloaded) override {
57 TypeIndex method_list_idx = overloaded.MethodList;
58
59 CVType method_list_type = m_index.tpi().getType(method_list_idx);
60 assert(method_list_type.kind() == LF_METHODLIST);
61
62 MethodOverloadListRecord method_list;
63 llvm::cantFail(TypeDeserializer::deserializeAs<MethodOverloadListRecord>(
64 method_list_type, method_list));
65
66 for (const OneMethodRecord &method : method_list.Methods) {
67 if (method.getType().getIndex() == func_type_index.getIndex())
68 AddMethod(overloaded.Name, method.getAccess(), method.getOptions(),
69 method.Attrs);
70 }
71
72 return llvm::Error::success();
73 }
74
75 llvm::Error visitKnownMember(CVMemberRecord &cvr,
76 OneMethodRecord &record) override {
77 AddMethod(record.getName(), record.getAccess(), record.getOptions(),
78 record.Attrs);
79 return llvm::Error::success();
80 }
81
82 void AddMethod(llvm::StringRef name, MemberAccess access,
83 MethodOptions options, MemberAttributes attrs) {
84 if (name != proc_name || function_decl)
85 return;
86 lldb::AccessType access_type = TranslateMemberAccess(access);
87 bool is_virtual = attrs.isVirtual();
88 bool is_static = attrs.isStatic();
89 bool is_artificial = (options & MethodOptions::CompilerGenerated) ==
90 MethodOptions::CompilerGenerated;
91 function_decl = m_clang.AddMethodToCXXRecordType(
92 parent_ty, proc_name, mangled_name, func_ct, /*access=*/access_type,
93 /*is_virtual=*/is_virtual, /*is_static=*/is_static,
94 /*is_inline=*/false, /*is_explicit=*/false,
95 /*is_attr_used=*/false, /*is_artificial=*/is_artificial);
96 }
97};
98} // namespace
99
100static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) {
101 switch (cr.Kind) {
102 case TypeRecordKind::Class:
103 return clang::TagTypeKind::Class;
104 case TypeRecordKind::Struct:
105 return clang::TagTypeKind::Struct;
106 case TypeRecordKind::Union:
107 return clang::TagTypeKind::Union;
108 case TypeRecordKind::Interface:
109 return clang::TagTypeKind::Interface;
110 case TypeRecordKind::Enum:
111 return clang::TagTypeKind::Enum;
112 default:
113 lldbassert(false && "Invalid tag record kind!");
114 return clang::TagTypeKind::Struct;
115 }
116}
117
118static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) {
119 if (args.empty())
120 return false;
121 return args.back() == TypeIndex::None();
122}
123
124static bool
125AnyScopesHaveTemplateParams(llvm::ArrayRef<llvm::ms_demangle::Node *> scopes) {
126 for (llvm::ms_demangle::Node *n : scopes) {
127 auto *idn = static_cast<llvm::ms_demangle::IdentifierNode *>(n);
128 if (idn->TemplateParams)
129 return true;
130 }
131 return false;
132}
133
134static std::optional<clang::CallingConv>
135TranslateCallingConvention(llvm::codeview::CallingConvention conv) {
136 using CC = llvm::codeview::CallingConvention;
137 switch (conv) {
138
139 case CC::NearC:
140 case CC::FarC:
141 return clang::CallingConv::CC_C;
142 case CC::NearPascal:
143 case CC::FarPascal:
144 return clang::CallingConv::CC_X86Pascal;
145 case CC::NearFast:
146 case CC::FarFast:
147 return clang::CallingConv::CC_X86FastCall;
148 case CC::NearStdCall:
149 case CC::FarStdCall:
150 return clang::CallingConv::CC_X86StdCall;
151 case CC::ThisCall:
152 return clang::CallingConv::CC_X86ThisCall;
153 case CC::NearVector:
154 return clang::CallingConv::CC_X86VectorCall;
155 default:
156 return std::nullopt;
157 }
158}
159
160static bool IsAnonymousNamespaceName(llvm::StringRef name) {
161 return name == "`anonymous namespace'" || name == "`anonymous-namespace'";
162}
163
165
169
170std::pair<clang::DeclContext *, std::string>
173 m_clang.GetSymbolFile()->GetBackingSymbolFile());
174 // FIXME: Move this to GetDeclContextContainingUID.
175 if (!record.hasUniqueName())
176 return CreateDeclInfoForUndecoratedName(record.Name);
177
178 llvm::ms_demangle::Demangler demangler;
179 std::string_view sv(record.UniqueName.begin(), record.UniqueName.size());
180 llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
181 if (demangler.Error)
182 return CreateDeclInfoForUndecoratedName(record.Name);
183
184 llvm::ms_demangle::IdentifierNode *idn =
185 ttn->QualifiedName->getUnqualifiedIdentifier();
186 std::string uname = idn->toString(llvm::ms_demangle::OF_NoTagSpecifier);
187
188 llvm::ms_demangle::NodeArrayNode *name_components =
189 ttn->QualifiedName->Components;
190 llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes,
191 name_components->Count - 1);
192
193 clang::DeclContext *context = m_clang.GetTranslationUnitDecl();
194
195 // If this type doesn't have a parent type in the debug info, then the best we
196 // can do is to say that it's either a series of namespaces (if the scope is
197 // non-empty), or the translation unit (if the scope is empty).
198 std::optional<TypeIndex> parent_index = pdb->GetParentType(ti);
199 if (!parent_index) {
200 if (scopes.empty())
201 return {context, uname};
202
203 // If there is no parent in the debug info, but some of the scopes have
204 // template params, then this is a case of bad debug info. See, for
205 // example, llvm.org/pr39607. We don't want to create an ambiguity between
206 // a NamespaceDecl and a CXXRecordDecl, so instead we create a class at
207 // global scope with the fully qualified name.
208 if (AnyScopesHaveTemplateParams(scopes))
209 return {context, std::string(record.Name)};
210
211 for (llvm::ms_demangle::Node *scope : scopes) {
212 auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope);
213 std::string str = nii->toString();
214 context = GetOrCreateNamespaceDecl(str.c_str(), *context);
215 }
216 return {context, uname};
217 }
218
219 // Otherwise, all we need to do is get the parent type of this type and
220 // recurse into our lazy type creation / AST reconstruction logic to get an
221 // LLDB TypeSP for the parent. This will cause the AST to automatically get
222 // the right DeclContext created for any parent.
223 clang::QualType parent_qt = GetOrCreateClangType(*parent_index);
224 if (parent_qt.isNull())
225 return {nullptr, ""};
226
227 context = clang::TagDecl::castToDeclContext(parent_qt->getAsTagDecl());
228 return {context, uname};
229}
230
231static bool isLocalVariableType(SymbolKind K) {
232 switch (K) {
233 case S_REGISTER:
234 case S_REGREL32:
235 case S_LOCAL:
236 return true;
237 default:
238 break;
239 }
240 return false;
241}
242
245 m_clang.GetSymbolFile()->GetBackingSymbolFile());
246 PdbIndex &index = pdb->GetIndex();
247 CVSymbol cvs = index.ReadSymbolRecord(id);
248
249 if (isLocalVariableType(cvs.kind())) {
250 clang::DeclContext *scope = GetParentClangDeclContext(id);
251 if (!scope)
252 return nullptr;
253 clang::Decl *scope_decl = clang::Decl::castFromDeclContext(scope);
254 PdbCompilandSymId scope_id =
255 PdbSymUid(m_decl_to_status[scope_decl].uid).asCompilandSym();
256 return GetOrCreateVariableDecl(scope_id, id);
257 }
258
259 switch (cvs.kind()) {
260 case S_GPROC32:
261 case S_LPROC32:
262 return GetOrCreateFunctionDecl(id);
263 case S_GDATA32:
264 case S_LDATA32:
265 case S_GTHREAD32:
266 case S_CONSTANT:
267 // global variable
268 return nullptr;
269 case S_BLOCK32:
270 return GetOrCreateBlockDecl(id);
271 case S_INLINESITE:
273 default:
274 return nullptr;
275 }
276}
277
278std::optional<CompilerDecl>
280 if (clang::Decl *result = TryGetDecl(uid))
281 return ToCompilerDecl(result);
282
283 clang::Decl *result = nullptr;
284 switch (uid.kind()) {
287 break;
288 case PdbSymUidKind::Type: {
289 clang::QualType qt = GetOrCreateClangType(uid.asTypeSym());
290 if (qt.isNull())
291 return std::nullopt;
292 if (auto *tag = qt->getAsTagDecl()) {
293 result = tag;
294 break;
295 }
296 return std::nullopt;
297 }
298 default:
299 return std::nullopt;
300 }
301
302 if (!result)
303 return std::nullopt;
304 m_uid_to_decl[toOpaqueUid(uid)] = result;
305 return ToCompilerDecl(result);
306}
307
308clang::DeclContext *
310 if (uid.kind() == PdbSymUidKind::CompilandSym) {
311 if (uid.asCompilandSym().offset == 0)
313 }
314 auto option = GetOrCreateDeclForUid(uid);
315 if (!option)
316 return nullptr;
317 clang::Decl *decl = FromCompilerDecl(*option);
318 if (!decl)
319 return nullptr;
320
321 return clang::Decl::castToDeclContext(decl);
322}
323
327
328std::pair<clang::DeclContext *, std::string>
331 m_clang.GetSymbolFile()->GetBackingSymbolFile());
332 PdbIndex &index = pdb->GetIndex();
333 MSVCUndecoratedNameParser parser(name);
334 llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers();
335
337
338 llvm::StringRef uname = specs.back().GetBaseName();
339 specs = specs.drop_back();
340 if (specs.empty())
341 return {context, std::string(name)};
342
343 llvm::StringRef scope_name = specs.back().GetFullName();
344
345 // It might be a class name, try that first.
346 std::vector<TypeIndex> types = index.tpi().findRecordsByName(scope_name);
347 while (!types.empty()) {
348 clang::QualType qt = GetOrCreateClangType(types.back());
349 if (qt.isNull())
350 continue;
351 clang::TagDecl *tag = qt->getAsTagDecl();
352 if (tag)
353 return {clang::TagDecl::castToDeclContext(tag), std::string(uname)};
354 types.pop_back();
355 }
356
357 // If that fails, treat it as a series of namespaces.
358 for (const MSVCUndecoratedNameSpecifier &spec : specs) {
359 std::string ns_name = spec.GetBaseName().str();
360 context = GetOrCreateNamespaceDecl(ns_name.c_str(), *context);
361 }
362 return {context, std::string(uname)};
363}
364
366 // We must do this *without* calling GetOrCreate on the current uid, as
367 // that would be an infinite recursion.
369 m_clang.GetSymbolFile()->GetBackingSymbolFile());
370 PdbIndex& index = pdb->GetIndex();
371 switch (uid.kind()) {
373 std::optional<PdbCompilandSymId> scope =
374 pdb->FindSymbolScope(uid.asCompilandSym());
375 if (scope)
377
378 CVSymbol sym = index.ReadSymbolRecord(uid.asCompilandSym());
379 return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first;
380 }
381 case PdbSymUidKind::Type: {
382 // It could be a namespace, class, or global. We don't support nested
383 // functions yet. Anyway, we just need to consult the parent type map.
384 PdbTypeSymId type_id = uid.asTypeSym();
385 std::optional<TypeIndex> parent_index = pdb->GetParentType(type_id.index);
386 if (!parent_index)
388 return GetOrCreateClangDeclContextForUid(PdbTypeSymId(*parent_index));
389 }
391 // In this case the parent DeclContext is the one for the class that this
392 // member is inside of.
393 break;
395 // If this refers to a compiland symbol, just recurse in with that symbol.
396 // The only other possibilities are S_CONSTANT and S_UDT, in which case we
397 // need to parse the undecorated name to figure out the scope, then look
398 // that up in the TPI stream. If it's found, it's a type, othewrise it's
399 // a series of namespaces.
400 // FIXME: do this.
401 CVSymbol global = index.ReadSymbolRecord(uid.asGlobalSym());
402 switch (global.kind()) {
403 case SymbolKind::S_GDATA32:
404 case SymbolKind::S_LDATA32:
405 return CreateDeclInfoForUndecoratedName(getSymbolName(global)).first;;
406 case SymbolKind::S_PROCREF:
407 case SymbolKind::S_LPROCREF: {
408 ProcRefSym ref{global.kind()};
409 llvm::cantFail(
410 SymbolDeserializer::deserializeAs<ProcRefSym>(global, ref));
411 PdbCompilandSymId cu_sym_id{ref.modi(), ref.SymOffset};
412 return GetParentClangDeclContext(cu_sym_id);
413 }
414 case SymbolKind::S_CONSTANT:
415 case SymbolKind::S_UDT:
416 return CreateDeclInfoForUndecoratedName(getSymbolName(global)).first;
417 default:
418 break;
419 }
420 break;
421 }
422 default:
423 break;
424 }
426}
427
431
433 if (GetClangASTImporter().CanImport(ct))
435
436 clang::QualType qt = FromCompilerType(ct);
437 if (qt.isNull())
438 return false;
439 clang::TagDecl *tag = qt->getAsTagDecl();
440 if (qt->isArrayType()) {
441 const clang::Type *element_type = qt->getArrayElementTypeNoTypeQual();
442 tag = element_type->getAsTagDecl();
443 }
444 if (!tag)
445 return false;
446
447 return CompleteTagDecl(*tag);
448}
449
450bool PdbAstBuilder::CompleteTagDecl(clang::TagDecl &tag) {
451 // If this is not in our map, it's an error.
452 auto status_iter = m_decl_to_status.find(&tag);
453 lldbassert(status_iter != m_decl_to_status.end());
454
455 // If it's already complete, just return.
456 DeclStatus &status = status_iter->second;
457 if (status.resolved)
458 return true;
459
460 PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym();
461 PdbIndex &index = static_cast<SymbolFileNativePDB *>(
462 m_clang.GetSymbolFile()->GetBackingSymbolFile())
463 ->GetIndex();
464 lldbassert(IsTagRecord(type_id, index.tpi()));
465
466 clang::QualType tag_qt = m_clang.getASTContext().getCanonicalTagType(&tag);
467 TypeSystemClang::SetHasExternalStorage(tag_qt.getAsOpaquePtr(), false);
468
469 TypeIndex tag_ti = type_id.index;
470 CVType cvt = index.tpi().getType(tag_ti);
471 if (cvt.kind() == LF_MODIFIER)
472 tag_ti = LookThroughModifierRecord(cvt);
473
474 PdbTypeSymId best_ti = GetBestPossibleDecl(tag_ti, index.tpi());
475 cvt = index.tpi().getType(best_ti.index);
477
478 if (IsForwardRefUdt(cvt)) {
479 // If we can't find a full decl for this forward ref anywhere in the debug
480 // info, then we have no way to complete it.
481 return false;
482 }
483
484 TypeIndex field_list_ti = GetFieldListIndex(cvt);
485 CVType field_list_cvt = index.tpi().getType(field_list_ti);
486 if (field_list_cvt.kind() != LF_FIELDLIST)
487 return false;
488 FieldListRecord field_list;
489 if (llvm::Error error = TypeDeserializer::deserializeAs<FieldListRecord>(
490 field_list_cvt, field_list))
491 llvm::consumeError(std::move(error));
492
493 // Visit all members of this class, then perform any finalization necessary
494 // to complete the class.
495 CompilerType ct = ToCompilerType(tag_qt);
496 UdtRecordCompleter completer(best_ti, ct, tag, *this, index, m_decl_to_status,
498 llvm::Error error =
499 llvm::codeview::visitMemberRecordStream(field_list.Data, completer);
500 completer.complete();
501
502 m_decl_to_status[&tag].resolved = true;
503 if (error) {
504 llvm::consumeError(std::move(error));
505 return false;
506 }
507 return true;
508}
509
511 if (ti == TypeIndex::NullptrT())
513
514 if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
515 clang::QualType direct_type = GetOrCreateClangType(ti.makeDirect());
516 if (direct_type.isNull())
517 return {};
518 return m_clang.getASTContext().getPointerType(direct_type);
519 }
520
521 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
522 return {};
523
524 lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind());
525 if (bt == lldb::eBasicTypeInvalid)
526 return {};
527
528 return GetBasicType(bt);
529}
530
531clang::QualType PdbAstBuilder::CreatePointerType(const PointerRecord &pointer) {
532 clang::QualType pointee_type = GetOrCreateClangType(pointer.ReferentType);
533
534 // This can happen for pointers to LF_VTSHAPE records, which we shouldn't
535 // create in the AST.
536 if (pointee_type.isNull())
537 return {};
538
539 if (pointer.isPointerToMember()) {
540 MemberPointerInfo mpi = pointer.getMemberInfo();
541 clang::QualType class_type = GetOrCreateClangType(mpi.ContainingType);
542 if (class_type.isNull())
543 return {};
544 if (clang::TagDecl *tag = class_type->getAsTagDecl()) {
545 clang::MSInheritanceAttr::Spelling spelling;
546 switch (mpi.Representation) {
547 case llvm::codeview::PointerToMemberRepresentation::SingleInheritanceData:
548 case llvm::codeview::PointerToMemberRepresentation::
549 SingleInheritanceFunction:
550 spelling =
551 clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance;
552 break;
553 case llvm::codeview::PointerToMemberRepresentation::
554 MultipleInheritanceData:
555 case llvm::codeview::PointerToMemberRepresentation::
556 MultipleInheritanceFunction:
557 spelling =
558 clang::MSInheritanceAttr::Spelling::Keyword_multiple_inheritance;
559 break;
560 case llvm::codeview::PointerToMemberRepresentation::
561 VirtualInheritanceData:
562 case llvm::codeview::PointerToMemberRepresentation::
563 VirtualInheritanceFunction:
564 spelling =
565 clang::MSInheritanceAttr::Spelling::Keyword_virtual_inheritance;
566 break;
567 case llvm::codeview::PointerToMemberRepresentation::Unknown:
568 spelling =
569 clang::MSInheritanceAttr::Spelling::Keyword_unspecified_inheritance;
570 break;
571 default:
572 spelling = clang::MSInheritanceAttr::Spelling::SpellingNotCalculated;
573 break;
574 }
575 tag->addAttr(clang::MSInheritanceAttr::CreateImplicit(
576 m_clang.getASTContext(), spelling));
577 }
578 return m_clang.getASTContext().getMemberPointerType(
579 pointee_type, /*Qualifier=*/std::nullopt,
580 class_type->getAsCXXRecordDecl());
581 }
582
583 clang::QualType pointer_type;
584 if (pointer.getMode() == PointerMode::LValueReference)
585 pointer_type = m_clang.getASTContext().getLValueReferenceType(pointee_type);
586 else if (pointer.getMode() == PointerMode::RValueReference)
587 pointer_type = m_clang.getASTContext().getRValueReferenceType(pointee_type);
588 else
589 pointer_type = m_clang.getASTContext().getPointerType(pointee_type);
590
591 if ((pointer.getOptions() & PointerOptions::Const) != PointerOptions::None)
592 pointer_type.addConst();
593
594 if ((pointer.getOptions() & PointerOptions::Volatile) != PointerOptions::None)
595 pointer_type.addVolatile();
596
597 if ((pointer.getOptions() & PointerOptions::Restrict) != PointerOptions::None)
598 pointer_type.addRestrict();
599
600 return pointer_type;
601}
602
603clang::QualType
604PdbAstBuilder::CreateModifierType(const ModifierRecord &modifier) {
605 clang::QualType unmodified_type = GetOrCreateClangType(modifier.ModifiedType);
606 if (unmodified_type.isNull())
607 return {};
608
609 if ((modifier.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
610 unmodified_type.addConst();
611 if ((modifier.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
612 unmodified_type.addVolatile();
613
614 return unmodified_type;
615}
616
618 const TagRecord &record) {
619 clang::DeclContext *context = nullptr;
620 std::string uname;
621 std::tie(context, uname) = CreateDeclInfoForType(record, id.index);
622 if (!context)
623 return {};
624
625 clang::TagTypeKind ttk = TranslateUdtKind(record);
626 lldb::AccessType access = (ttk == clang::TagTypeKind::Class)
629
630 ClangASTMetadata metadata;
631 metadata.SetUserID(toOpaqueUid(id));
632 metadata.SetIsDynamicCXXType(false);
633
634 CompilerType ct = m_clang.CreateRecordType(
635 context, OptionalClangModuleID(), access, uname, llvm::to_underlying(ttk),
637
638 lldbassert(ct.IsValid());
639
641
642 // Even if it's possible, don't complete it at this point. Just mark it
643 // forward resolved, and if/when LLDB needs the full definition, it can
644 // ask us.
645 clang::QualType result =
646 clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType());
647
648 TypeSystemClang::SetHasExternalStorage(result.getAsOpaquePtr(), true);
649 return result;
650}
651
652clang::Decl *PdbAstBuilder::TryGetDecl(PdbSymUid uid) const {
653 auto iter = m_uid_to_decl.find(toOpaqueUid(uid));
654 if (iter != m_uid_to_decl.end())
655 return iter->second;
656 return nullptr;
657}
658
659clang::NamespaceDecl *
661 clang::DeclContext &context) {
662 clang::NamespaceDecl *ns = m_clang.GetUniqueNamespaceDeclaration(
663 IsAnonymousNamespaceName(name) ? nullptr : name, &context,
665 m_known_namespaces.insert(ns);
666 m_parent_to_namespaces[&context].insert(ns);
667 return ns;
668}
669
670clang::BlockDecl *
672 if (clang::Decl *decl = TryGetDecl(block_id))
673 return llvm::dyn_cast<clang::BlockDecl>(decl);
674
675 clang::DeclContext *scope = GetParentClangDeclContext(block_id);
676
677 clang::BlockDecl *block_decl =
678 m_clang.CreateBlockDeclaration(scope, OptionalClangModuleID());
679 m_uid_to_decl.insert({toOpaqueUid(block_id), block_decl});
680
681 DeclStatus status;
682 status.resolved = true;
683 status.uid = toOpaqueUid(block_id);
684 m_decl_to_status.insert({block_decl, status});
685
686 return block_decl;
687}
688
689clang::VarDecl *PdbAstBuilder::CreateVariableDecl(PdbSymUid uid, CVSymbol sym,
690 clang::DeclContext &scope) {
691 VariableInfo var_info = GetVariableNameInfo(sym);
692 clang::QualType qt = GetOrCreateClangType(var_info.type);
693 if (qt.isNull())
694 return nullptr;
695
696 clang::VarDecl *var_decl = m_clang.CreateVariableDeclaration(
697 &scope, OptionalClangModuleID(), var_info.name.str().c_str(), qt);
698
699 m_uid_to_decl[toOpaqueUid(uid)] = var_decl;
700 DeclStatus status;
701 status.resolved = true;
702 status.uid = toOpaqueUid(uid);
703 m_decl_to_status.insert({var_decl, status});
704 return var_decl;
705}
706
707clang::VarDecl *
709 PdbCompilandSymId var_id) {
710 if (clang::Decl *decl = TryGetDecl(var_id))
711 return llvm::dyn_cast<clang::VarDecl>(decl);
712
713 clang::DeclContext *scope = GetOrCreateClangDeclContextForUid(scope_id);
714 if (!scope)
715 return nullptr;
716
718 m_clang.GetSymbolFile()->GetBackingSymbolFile());
719 PdbIndex &index = pdb->GetIndex();
720 CVSymbol sym = index.ReadSymbolRecord(var_id);
721 return CreateVariableDecl(PdbSymUid(var_id), sym, *scope);
722}
723
725 if (clang::Decl *decl = TryGetDecl(var_id))
726 return llvm::dyn_cast<clang::VarDecl>(decl);
727
729 m_clang.GetSymbolFile()->GetBackingSymbolFile());
730 PdbIndex &index = pdb->GetIndex();
731 CVSymbol sym = index.ReadSymbolRecord(var_id);
733 return CreateVariableDecl(PdbSymUid(var_id), sym, *context);
734}
735
736clang::TypedefNameDecl *
738 if (clang::Decl *decl = TryGetDecl(id))
739 return llvm::dyn_cast<clang::TypedefNameDecl>(decl);
740
742 m_clang.GetSymbolFile()->GetBackingSymbolFile());
743 PdbIndex &index = pdb->GetIndex();
744 CVSymbol sym = index.ReadSymbolRecord(id);
745 lldbassert(sym.kind() == S_UDT);
746 UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
747
748 clang::DeclContext *scope = GetParentClangDeclContext(id);
749
750 PdbTypeSymId real_type_id{udt.Type, false};
751 clang::QualType qt = GetOrCreateClangType(real_type_id);
752 if (qt.isNull() || !scope)
753 return nullptr;
754
755 std::string uname = std::string(DropNameScope(udt.Name));
756
758 uname.c_str(), ToCompilerDeclContext(scope), 0);
759 clang::TypedefNameDecl *tnd = m_clang.GetAsTypedefDecl(ct);
760 DeclStatus status;
761 status.resolved = true;
762 status.uid = toOpaqueUid(id);
763 m_decl_to_status.insert({tnd, status});
764 return tnd;
765}
766
768 CompilerType ct = m_clang.GetBasicType(type);
769 return clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType());
770}
771
773 if (type.index.isSimple())
774 return CreateSimpleType(type.index);
775
777 m_clang.GetSymbolFile()->GetBackingSymbolFile());
778 PdbIndex &index = pdb->GetIndex();
779 CVType cvt = index.tpi().getType(type.index);
780
781 if (cvt.kind() == LF_MODIFIER) {
782 ModifierRecord modifier;
783 llvm::cantFail(
784 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
785 return CreateModifierType(modifier);
786 }
787
788 if (cvt.kind() == LF_POINTER) {
789 PointerRecord pointer;
790 llvm::cantFail(
791 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
792 return CreatePointerType(pointer);
793 }
794
795 if (IsTagRecord(cvt)) {
797 if (tag.kind() == CVTagRecord::Union)
798 return CreateRecordType(type.index, tag.asUnion());
799 if (tag.kind() == CVTagRecord::Enum)
800 return CreateEnumType(type.index, tag.asEnum());
801 return CreateRecordType(type.index, tag.asClass());
802 }
803
804 if (cvt.kind() == LF_ARRAY) {
805 ArrayRecord ar;
806 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
807 return CreateArrayType(ar);
808 }
809
810 if (cvt.kind() == LF_PROCEDURE) {
811 ProcedureRecord pr;
812 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
813 return CreateFunctionType(pr.ArgumentList, pr.ReturnType, pr.CallConv);
814 }
815
816 if (cvt.kind() == LF_MFUNCTION) {
817 MemberFunctionRecord mfr;
818 llvm::cantFail(
819 TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr));
820 return CreateFunctionType(mfr.ArgumentList, mfr.ReturnType, mfr.CallConv);
821 }
822
823 return {};
824}
825
827 if (type.index.isNoneType())
828 return {};
829
830 lldb::user_id_t uid = toOpaqueUid(type);
831 auto iter = m_uid_to_type.find(uid);
832 if (iter != m_uid_to_type.end())
833 return iter->second;
834
836 m_clang.GetSymbolFile()->GetBackingSymbolFile());
837 PdbIndex &index = pdb->GetIndex();
838 PdbTypeSymId best_type = GetBestPossibleDecl(type, index.tpi());
839
840 clang::QualType qt;
841 if (best_type.index != type.index) {
842 // This is a forward decl. Call GetOrCreate on the full decl, then map the
843 // forward decl id to the full decl QualType.
844 clang::QualType qt = GetOrCreateClangType(best_type);
845 if (qt.isNull())
846 return {};
847 m_uid_to_type[toOpaqueUid(type)] = qt;
848 return qt;
849 }
850
851 // This is either a full decl, or a forward decl with no matching full decl
852 // in the debug info.
853 qt = CreateType(type);
854 if (qt.isNull())
855 return {};
856
857 m_uid_to_type[toOpaqueUid(type)] = qt;
858 if (IsTagRecord(type, index.tpi())) {
859 clang::TagDecl *tag = qt->getAsTagDecl();
860 lldbassert(m_decl_to_status.count(tag) == 0);
861
862 DeclStatus &status = m_decl_to_status[tag];
863 status.uid = uid;
864 status.resolved = false;
865 }
866 return qt;
867}
868
870 clang::QualType qt = GetOrCreateClangType(type);
871 if (qt.isNull())
872 return {};
873 return ToCompilerType(qt);
874}
875
876clang::FunctionDecl *
878 llvm::StringRef func_name, TypeIndex func_ti,
879 CompilerType func_ct, uint32_t param_count,
880 clang::StorageClass func_storage,
881 bool is_inline, clang::DeclContext *parent) {
882 clang::FunctionDecl *function_decl = nullptr;
883 if (parent->isRecord()) {
885 m_clang.GetSymbolFile()->GetBackingSymbolFile());
886 PdbIndex &index = pdb->GetIndex();
887 clang::CanQualType parent_qt =
888 m_clang.getASTContext().getCanonicalTypeDeclType(
889 llvm::cast<clang::TypeDecl>(parent));
890 lldb::opaque_compiler_type_t parent_opaque_ty =
892 // FIXME: Remove this workaround.
893 auto iter = m_cxx_record_map.find(parent_opaque_ty);
894 if (iter != m_cxx_record_map.end()) {
895 if (iter->getSecond().contains({func_name, func_ct})) {
896 return nullptr;
897 }
898 }
899
900 CVType cvt = index.tpi().getType(func_ti);
901 MemberFunctionRecord func_record(static_cast<TypeRecordKind>(cvt.kind()));
902 llvm::cantFail(TypeDeserializer::deserializeAs<MemberFunctionRecord>(
903 cvt, func_record));
904 TypeIndex class_index = func_record.getClassType();
905
906 CVType parent_cvt = index.tpi().getType(class_index);
907 TagRecord tag_record = CVTagRecord::create(parent_cvt).asTag();
908 // If it's a forward reference, try to get the real TypeIndex.
909 if (tag_record.isForwardRef()) {
910 llvm::Expected<TypeIndex> eti =
911 index.tpi().findFullDeclForForwardRef(class_index);
912 if (eti) {
913 tag_record = CVTagRecord::create(index.tpi().getType(*eti)).asTag();
914 }
915 }
916
917 ConstString mangled_name(
918 pdb->FindMangledFunctionName(func_id).value_or(llvm::StringRef()));
919
920 if (!tag_record.FieldList.isSimple()) {
921 CVType field_list_cvt = index.tpi().getType(tag_record.FieldList);
922 FieldListRecord field_list;
923 if (llvm::Error error = TypeDeserializer::deserializeAs<FieldListRecord>(
924 field_list_cvt, field_list))
925 llvm::consumeError(std::move(error));
926 CreateMethodDecl process(index, m_clang, func_ti, function_decl,
927 parent_opaque_ty, func_name, mangled_name,
928 func_ct);
929 if (llvm::Error err = visitMemberRecordStream(field_list.Data, process))
930 llvm::consumeError(std::move(err));
931 }
932
933 if (!function_decl) {
934 function_decl = m_clang.AddMethodToCXXRecordType(
935 parent_opaque_ty, func_name, mangled_name, func_ct,
937 /*is_virtual=*/false, /*is_static=*/false,
938 /*is_inline=*/false, /*is_explicit=*/false,
939 /*is_attr_used=*/false, /*is_artificial=*/false);
940 }
941 m_cxx_record_map[parent_opaque_ty].insert({func_name, func_ct});
942 } else {
943 function_decl = m_clang.CreateFunctionDeclaration(
944 parent, OptionalClangModuleID(), func_name, func_ct, func_storage,
945 is_inline, /*asm_label=*/{});
946 CreateFunctionParameters(func_id, *function_decl, param_count);
947 }
948 return function_decl;
949}
950
951clang::FunctionDecl *
954 m_clang.GetSymbolFile()->GetBackingSymbolFile());
955 PdbIndex &index = pdb->GetIndex();
956 CompilandIndexItem *cii =
957 index.compilands().GetCompiland(inlinesite_id.modi);
958 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(inlinesite_id.offset);
959 InlineSiteSym inline_site(static_cast<SymbolRecordKind>(sym.kind()));
960 cantFail(SymbolDeserializer::deserializeAs<InlineSiteSym>(sym, inline_site));
961
962 // Inlinee is the id index to the function id record that is inlined.
963 PdbTypeSymId func_id(inline_site.Inlinee, true);
964 // Look up the function decl by the id index to see if we have created a
965 // function decl for a different inlinesite that refers the same function.
966 if (clang::Decl *decl = TryGetDecl(func_id))
967 return llvm::dyn_cast<clang::FunctionDecl>(decl);
968 clang::FunctionDecl *function_decl =
969 CreateFunctionDeclFromId(func_id, inlinesite_id);
970 if (function_decl == nullptr)
971 return nullptr;
972
973 // Use inline site id in m_decl_to_status because it's expected to be a
974 // PdbCompilandSymId so that we can parse local variables info after it.
975 uint64_t inlinesite_uid = toOpaqueUid(inlinesite_id);
976 DeclStatus status;
977 status.resolved = true;
978 status.uid = inlinesite_uid;
979 m_decl_to_status.insert({function_decl, status});
980 // Use the index in IPI stream as uid in m_uid_to_decl, because index in IPI
981 // stream are unique and there could be multiple inline sites (different ids)
982 // referring the same inline function. This avoid creating multiple same
983 // inline function delcs.
984 uint64_t func_uid = toOpaqueUid(func_id);
985 lldbassert(m_uid_to_decl.count(func_uid) == 0);
986 m_uid_to_decl[func_uid] = function_decl;
987 return function_decl;
988}
989
990clang::FunctionDecl *
992 PdbCompilandSymId func_sid) {
993 lldbassert(func_tid.is_ipi);
995 m_clang.GetSymbolFile()->GetBackingSymbolFile());
996 PdbIndex &index = pdb->GetIndex();
997 CVType func_cvt = index.ipi().getType(func_tid.index);
998 llvm::StringRef func_name;
999 TypeIndex func_ti;
1000 clang::DeclContext *parent = nullptr;
1001 switch (func_cvt.kind()) {
1002 case LF_MFUNC_ID: {
1003 MemberFuncIdRecord mfr;
1004 cantFail(
1005 TypeDeserializer::deserializeAs<MemberFuncIdRecord>(func_cvt, mfr));
1006 func_name = mfr.getName();
1007 func_ti = mfr.getFunctionType();
1008 PdbTypeSymId class_type_id(mfr.ClassType, false);
1009 parent = GetOrCreateClangDeclContextForUid(class_type_id);
1010 break;
1011 }
1012 case LF_FUNC_ID: {
1013 FuncIdRecord fir;
1014 cantFail(TypeDeserializer::deserializeAs<FuncIdRecord>(func_cvt, fir));
1015 func_name = fir.getName();
1016 func_ti = fir.getFunctionType();
1018 if (!fir.ParentScope.isNoneType()) {
1019 CVType parent_cvt = index.ipi().getType(fir.ParentScope);
1020 if (parent_cvt.kind() == LF_STRING_ID) {
1021 StringIdRecord sir;
1022 cantFail(
1023 TypeDeserializer::deserializeAs<StringIdRecord>(parent_cvt, sir));
1024 parent = GetOrCreateNamespaceDecl(sir.String.data(), *parent);
1025 }
1026 }
1027 break;
1028 }
1029 default:
1030 lldbassert(false && "Invalid function id type!");
1031 }
1032 clang::QualType func_qt = GetOrCreateClangType(func_ti);
1033 if (func_qt.isNull() || !parent)
1034 return nullptr;
1035 CompilerType func_ct = ToCompilerType(func_qt);
1036 uint32_t param_count =
1037 llvm::cast<clang::FunctionProtoType>(func_qt)->getNumParams();
1038 return CreateFunctionDecl(func_sid, func_name, func_ti, func_ct, param_count,
1039 clang::SC_None, true, parent);
1040}
1041
1042clang::FunctionDecl *
1044 if (clang::Decl *decl = TryGetDecl(func_id))
1045 return llvm::dyn_cast<clang::FunctionDecl>(decl);
1046
1047 clang::DeclContext *parent = GetParentClangDeclContext(PdbSymUid(func_id));
1048 if (!parent)
1049 return nullptr;
1050 std::string context_name;
1051 if (clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(parent)) {
1052 context_name = ns->getQualifiedNameAsString();
1053 } else if (clang::TagDecl *tag = llvm::dyn_cast<clang::TagDecl>(parent)) {
1054 context_name = tag->getQualifiedNameAsString();
1055 }
1056
1058 m_clang.GetSymbolFile()->GetBackingSymbolFile());
1059 PdbIndex &index = pdb->GetIndex();
1060 CVSymbol cvs = index.ReadSymbolRecord(func_id);
1061 ProcSym proc(static_cast<SymbolRecordKind>(cvs.kind()));
1062 llvm::cantFail(SymbolDeserializer::deserializeAs<ProcSym>(cvs, proc));
1063
1064 PdbTypeSymId type_id(proc.FunctionType);
1065 clang::QualType qt = GetOrCreateClangType(type_id);
1066 if (qt.isNull())
1067 return nullptr;
1068
1069 clang::StorageClass storage = clang::SC_None;
1070 if (proc.Kind == SymbolRecordKind::ProcSym)
1071 storage = clang::SC_Static;
1072
1073 const clang::FunctionProtoType *func_type =
1074 llvm::dyn_cast<clang::FunctionProtoType>(qt);
1075
1076 CompilerType func_ct = ToCompilerType(qt);
1077
1078 llvm::StringRef proc_name = proc.Name;
1079 proc_name.consume_front(context_name);
1080 proc_name.consume_front("::");
1081 clang::FunctionDecl *function_decl =
1082 CreateFunctionDecl(func_id, proc_name, proc.FunctionType, func_ct,
1083 func_type->getNumParams(), storage, false, parent);
1084 if (function_decl == nullptr)
1085 return nullptr;
1086
1087 lldbassert(m_uid_to_decl.count(toOpaqueUid(func_id)) == 0);
1088 m_uid_to_decl[toOpaqueUid(func_id)] = function_decl;
1089 DeclStatus status;
1090 status.resolved = true;
1091 status.uid = toOpaqueUid(func_id);
1092 m_decl_to_status.insert({function_decl, status});
1093
1094 return function_decl;
1095}
1096
1098 clang::FunctionDecl &function_decl,
1099 uint32_t param_count) {
1101 m_clang.GetSymbolFile()->GetBackingSymbolFile());
1102 PdbIndex &index = pdb->GetIndex();
1103 CompilandIndexItem *cii = index.compilands().GetCompiland(func_id.modi);
1104 CVSymbolArray scope =
1105 cii->m_debug_stream.getSymbolArrayForScope(func_id.offset);
1106
1107 scope.drop_front();
1108 auto begin = scope.begin();
1109 auto end = scope.end();
1110 std::vector<clang::ParmVarDecl *> params;
1111 for (uint32_t i = 0; i < param_count && begin != end;) {
1112 uint32_t record_offset = begin.offset();
1113 CVSymbol sym = *begin++;
1114
1115 TypeIndex param_type;
1116 llvm::StringRef param_name;
1117 switch (sym.kind()) {
1118 case S_REGREL32: {
1119 RegRelativeSym reg(SymbolRecordKind::RegRelativeSym);
1120 cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg));
1121 param_type = reg.Type;
1122 param_name = reg.Name;
1123 break;
1124 }
1125 case S_REGISTER: {
1126 RegisterSym reg(SymbolRecordKind::RegisterSym);
1127 cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg));
1128 param_type = reg.Index;
1129 param_name = reg.Name;
1130 break;
1131 }
1132 case S_LOCAL: {
1133 LocalSym local(SymbolRecordKind::LocalSym);
1134 cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local));
1135 if ((local.Flags & LocalSymFlags::IsParameter) == LocalSymFlags::None)
1136 continue;
1137 param_type = local.Type;
1138 param_name = local.Name;
1139 break;
1140 }
1141 case S_BLOCK32:
1142 case S_INLINESITE:
1143 case S_INLINESITE2:
1144 // All parameters should come before the first block/inlinesite. If that
1145 // isn't the case, then perhaps this is bad debug info that doesn't
1146 // contain information about all parameters.
1147 return;
1148 default:
1149 continue;
1150 }
1151
1152 PdbCompilandSymId param_uid(func_id.modi, record_offset);
1153 clang::QualType qt = GetOrCreateClangType(param_type);
1154 if (qt.isNull())
1155 return;
1156
1157 CompilerType param_type_ct = m_clang.GetType(qt);
1158 clang::ParmVarDecl *param = m_clang.CreateParameterDeclaration(
1159 &function_decl, OptionalClangModuleID(), param_name.str().c_str(),
1160 param_type_ct, clang::SC_None, true);
1161 lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0);
1162
1163 m_uid_to_decl[toOpaqueUid(param_uid)] = param;
1164 params.push_back(param);
1165 ++i;
1166 }
1167
1168 if (!params.empty() && params.size() == param_count)
1169 function_decl.setParams(params);
1170}
1171
1173 const EnumRecord &er) {
1174 clang::DeclContext *decl_context = nullptr;
1175 std::string uname;
1176 std::tie(decl_context, uname) = CreateDeclInfoForType(er, id.index);
1177 if (!decl_context)
1178 return {};
1179
1180 clang::QualType underlying_type = GetOrCreateClangType(er.UnderlyingType);
1181 if (underlying_type.isNull())
1182 return {};
1183
1184 Declaration declaration;
1185 CompilerType enum_ct = m_clang.CreateEnumerationType(
1186 uname, decl_context, OptionalClangModuleID(), declaration,
1187 ToCompilerType(underlying_type), er.isScoped());
1188
1191
1192 return clang::QualType::getFromOpaquePtr(enum_ct.GetOpaqueQualType());
1193}
1194
1195clang::QualType PdbAstBuilder::CreateArrayType(const ArrayRecord &ar) {
1196 clang::QualType element_type = GetOrCreateClangType(ar.ElementType);
1198
1200 m_clang.GetSymbolFile()->GetBackingSymbolFile());
1201 PdbIndex &index = pdb->GetIndex();
1202 uint64_t element_size = GetSizeOfType({ar.ElementType}, index.tpi());
1203 if (element_type.isNull() || element_size == 0)
1204 return {};
1205 uint64_t element_count = ar.Size / element_size;
1206
1207 CompilerType array_ct = m_clang.CreateArrayType(ToCompilerType(element_type),
1208 element_count, false);
1209 return clang::QualType::getFromOpaquePtr(array_ct.GetOpaqueQualType());
1210}
1211
1213 TypeIndex args_type_idx, TypeIndex return_type_idx,
1214 llvm::codeview::CallingConvention calling_convention) {
1216 m_clang.GetSymbolFile()->GetBackingSymbolFile());
1217 PdbIndex &index = pdb->GetIndex();
1218 TpiStream &stream = index.tpi();
1219 CVType args_cvt = stream.getType(args_type_idx);
1220 ArgListRecord args;
1221 llvm::cantFail(
1222 TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args));
1223
1224 llvm::ArrayRef<TypeIndex> arg_indices = llvm::ArrayRef(args.ArgIndices);
1225 bool is_variadic = IsCVarArgsFunction(arg_indices);
1226 if (is_variadic)
1227 arg_indices = arg_indices.drop_back();
1228
1229 std::vector<CompilerType> arg_types;
1230 arg_types.reserve(arg_indices.size());
1231
1232 for (TypeIndex arg_index : arg_indices) {
1233 clang::QualType arg_type = GetOrCreateClangType(arg_index);
1234 if (arg_type.isNull())
1235 continue;
1236 arg_types.push_back(ToCompilerType(arg_type));
1237 }
1238
1239 clang::QualType return_type = GetOrCreateClangType(return_type_idx);
1240 if (return_type.isNull())
1241 return {};
1242
1243 std::optional<clang::CallingConv> cc =
1244 TranslateCallingConvention(calling_convention);
1245 if (!cc)
1246 return {};
1247
1248 CompilerType return_ct = ToCompilerType(return_type);
1249 CompilerType func_sig_ast_type =
1250 m_clang.CreateFunctionType(return_ct, arg_types, is_variadic, 0, *cc);
1251
1252 return clang::QualType::getFromOpaquePtr(
1253 func_sig_ast_type.GetOpaqueQualType());
1254}
1255
1256static bool isTagDecl(clang::DeclContext &context) {
1257 return llvm::isa<clang::TagDecl>(&context);
1258}
1259
1260static bool isFunctionDecl(clang::DeclContext &context) {
1261 return llvm::isa<clang::FunctionDecl>(&context);
1262}
1263
1264static bool isBlockDecl(clang::DeclContext &context) {
1265 return llvm::isa<clang::BlockDecl>(&context);
1266}
1267
1268void PdbAstBuilder::ParseNamespace(clang::DeclContext &context) {
1269 clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(&context);
1270 if (m_parsed_namespaces.contains(ns))
1271 return;
1272 std::string qname = ns->getQualifiedNameAsString();
1274 m_clang.GetSymbolFile()->GetBackingSymbolFile());
1275 PdbIndex &index = pdb->GetIndex();
1276 TypeIndex ti{index.tpi().TypeIndexBegin()};
1277 for (const CVType &cvt : index.tpi().typeArray()) {
1278 PdbTypeSymId tid{ti};
1279 ++ti;
1280
1281 if (!IsTagRecord(cvt))
1282 continue;
1283
1285
1286 // Call CreateDeclInfoForType unconditionally so that the namespace info
1287 // gets created. But only call CreateRecordType if the namespace name
1288 // matches.
1289 clang::DeclContext *context = nullptr;
1290 std::string uname;
1291 std::tie(context, uname) = CreateDeclInfoForType(tag.asTag(), tid.index);
1292 if (!context || !context->isNamespace())
1293 continue;
1294
1295 clang::NamespaceDecl *ns = llvm::cast<clang::NamespaceDecl>(context);
1296 llvm::StringRef ns_name = ns->getName();
1297 if (ns_name.starts_with(qname)) {
1298 ns_name = ns_name.drop_front(qname.size());
1299 if (ns_name.starts_with("::"))
1301 }
1302 }
1304 m_parsed_namespaces.insert(ns);
1305}
1306
1308 llvm::call_once(m_parse_all_types, [this]() {
1310 m_clang.GetSymbolFile()->GetBackingSymbolFile());
1311 PdbIndex &index = pdb->GetIndex();
1312 TypeIndex ti{index.tpi().TypeIndexBegin()};
1313 for (const CVType &cvt : index.tpi().typeArray()) {
1314 PdbTypeSymId tid{ti};
1315 ++ti;
1316
1317 if (!IsTagRecord(cvt))
1318 continue;
1319
1321 }
1322 });
1323}
1324
1326 llvm::call_once(m_parse_functions_and_non_local_vars, [this]() {
1328 m_clang.GetSymbolFile()->GetBackingSymbolFile());
1329 PdbIndex &index = pdb->GetIndex();
1330 uint32_t module_count = index.dbi().modules().getModuleCount();
1331 for (uint16_t modi = 0; modi < module_count; ++modi) {
1333 const CVSymbolArray &symbols = cii.m_debug_stream.getSymbolArray();
1334 auto iter = symbols.begin();
1335 while (iter != symbols.end()) {
1336 PdbCompilandSymId sym_id{modi, iter.offset()};
1337
1338 switch (iter->kind()) {
1339 case S_GPROC32:
1340 case S_LPROC32:
1342 iter = symbols.at(getScopeEndOffset(*iter));
1343 break;
1344 case S_GDATA32:
1345 case S_GTHREAD32:
1346 case S_LDATA32:
1347 case S_LTHREAD32:
1349 ++iter;
1350 break;
1351 default:
1352 ++iter;
1353 continue;
1354 }
1355 }
1356 }
1357 });
1358}
1359
1360static CVSymbolArray skipFunctionParameters(clang::Decl &decl,
1361 const CVSymbolArray &symbols) {
1362 clang::FunctionDecl *func_decl = llvm::dyn_cast<clang::FunctionDecl>(&decl);
1363 if (!func_decl)
1364 return symbols;
1365 unsigned int params = func_decl->getNumParams();
1366 if (params == 0)
1367 return symbols;
1368
1369 CVSymbolArray result = symbols;
1370
1371 while (!result.empty()) {
1372 if (params == 0)
1373 return result;
1374
1375 CVSymbol sym = *result.begin();
1376 result.drop_front();
1377
1378 if (!isLocalVariableType(sym.kind()))
1379 continue;
1380
1381 --params;
1382 }
1383 return result;
1384}
1385
1388 m_clang.GetSymbolFile()->GetBackingSymbolFile());
1389 PdbIndex &index = pdb->GetIndex();
1390 CVSymbol sym = index.ReadSymbolRecord(block_id);
1391 lldbassert(sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32 ||
1392 sym.kind() == S_BLOCK32 || sym.kind() == S_INLINESITE);
1393 CompilandIndexItem &cii =
1394 index.compilands().GetOrCreateCompiland(block_id.modi);
1395 CVSymbolArray symbols =
1396 cii.m_debug_stream.getSymbolArrayForScope(block_id.offset);
1397
1398 // Function parameters should already have been created when the function was
1399 // parsed.
1400 if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32)
1401 symbols =
1402 skipFunctionParameters(*m_uid_to_decl[toOpaqueUid(block_id)], symbols);
1403
1404 symbols.drop_front();
1405 auto begin = symbols.begin();
1406 while (begin != symbols.end()) {
1407 PdbCompilandSymId child_sym_id(block_id.modi, begin.offset());
1408 GetOrCreateSymbolForId(child_sym_id);
1409 if (begin->kind() == S_BLOCK32 || begin->kind() == S_INLINESITE) {
1410 ParseBlockChildren(child_sym_id);
1411 begin = symbols.at(getScopeEndOffset(*begin));
1412 }
1413 ++begin;
1414 }
1415}
1416
1417void PdbAstBuilder::ParseDeclsForSimpleContext(clang::DeclContext &context) {
1418
1419 clang::Decl *decl = clang::Decl::castFromDeclContext(&context);
1420 lldbassert(decl);
1421
1422 auto iter = m_decl_to_status.find(decl);
1423 lldbassert(iter != m_decl_to_status.end());
1424
1425 if (auto *tag = llvm::dyn_cast<clang::TagDecl>(&context)) {
1426 CompleteTagDecl(*tag);
1427 return;
1428 }
1429
1430 if (isFunctionDecl(context) || isBlockDecl(context)) {
1431 PdbCompilandSymId block_id = PdbSymUid(iter->second.uid).asCompilandSym();
1432 ParseBlockChildren(block_id);
1433 }
1434}
1435
1437 clang::DeclContext *dc = FromCompilerDeclContext(context);
1438 if (!dc)
1439 return;
1440
1441 // Namespaces aren't explicitly represented in the debug info, and the only
1442 // way to parse them is to parse all type info, demangling every single type
1443 // and trying to reconstruct the DeclContext hierarchy this way. Since this
1444 // is an expensive operation, we have to special case it so that we do other
1445 // work (such as parsing the items that appear within the namespaces) at the
1446 // same time.
1447 if (dc->isTranslationUnit()) {
1448 ParseAllTypes();
1450 return;
1451 }
1452
1453 if (dc->isNamespace()) {
1454 ParseNamespace(*dc);
1455 return;
1456 }
1457
1458 if (isTagDecl(*dc) || isFunctionDecl(*dc) || isBlockDecl(*dc)) {
1460 return;
1461 }
1462}
1463
1465 return m_clang.GetCompilerDecl(decl);
1466}
1467
1469 return {m_clang.weak_from_this(), qt.getAsOpaquePtr()};
1470}
1471
1473 return ClangUtil::GetQualType(ct);
1474}
1475
1477PdbAstBuilder::ToCompilerDeclContext(clang::DeclContext *context) {
1478 return m_clang.CreateDeclContext(context);
1479}
1480
1482 return ClangUtil::GetDecl(decl);
1483}
1484
1485clang::DeclContext *
1487 return static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext());
1488}
1489
1490void PdbAstBuilder::Dump(Stream &stream, llvm::StringRef filter,
1491 bool show_color) {
1492 m_clang.Dump(stream.AsRawOstream(), filter, show_color);
1493}
1494
1497 llvm::StringRef name) {
1498 clang::DeclContext *parent = FromCompilerDeclContext(parent_ctx);
1499 NamespaceSet *set;
1500
1501 if (parent) {
1502 auto it = m_parent_to_namespaces.find(parent);
1503 if (it == m_parent_to_namespaces.end())
1504 return {};
1505
1506 set = &it->second;
1507 } else {
1508 // In this case, search through all known namespaces
1509 set = &m_known_namespaces;
1510 }
1511 assert(set);
1512
1513 for (clang::NamespaceDecl *namespace_decl : *set)
1514 if (namespace_decl->getName() == name)
1515 return ToCompilerDeclContext(namespace_decl);
1516
1517 for (clang::NamespaceDecl *namespace_decl : *set)
1518 if (namespace_decl->isAnonymousNamespace())
1519 return FindNamespaceDecl(ToCompilerDeclContext(namespace_decl), name);
1520
1521 return {};
1522}
static llvm::raw_ostream & error(Stream &strm)
#define lldbassert(x)
Definition LLDBAssert.h:16
static bool isFunctionDecl(clang::DeclContext &context)
static bool isBlockDecl(clang::DeclContext &context)
static CVSymbolArray skipFunctionParameters(clang::Decl &decl, const CVSymbolArray &symbols)
static std::optional< clang::CallingConv > TranslateCallingConvention(llvm::codeview::CallingConvention conv)
static bool isTagDecl(clang::DeclContext &context)
static bool isLocalVariableType(SymbolKind K)
static bool IsAnonymousNamespaceName(llvm::StringRef name)
static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr)
static bool IsCVarArgsFunction(llvm::ArrayRef< TypeIndex > args)
static bool AnyScopesHaveTemplateParams(llvm::ArrayRef< llvm::ms_demangle::Node * > scopes)
llvm::ArrayRef< MSVCUndecoratedNameSpecifier > GetSpecifiers() const
bool CompleteType(const CompilerType &compiler_type)
void SetUserID(lldb::user_id_t user_id)
void SetIsDynamicCXXType(std::optional< bool > b)
Represents a generic declaration context in a program.
Represents a generic declaration such as a function declaration.
Generic representation of a type in a programming language.
lldb::opaque_compiler_type_t GetOpaqueQualType() const
CompilerType CreateTypedef(const char *name, const CompilerDeclContext &decl_ctx, uint32_t payload) const
Create a typedef to this type using "name" as the name of the typedef this type is valid and the type...
A uniqued constant string class.
Definition ConstString.h:40
A class that describes the declaration location of a lldb object.
Definition Declaration.h:24
A stream class that can stream formatted output to a file.
Definition Stream.h:28
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:406
A TypeSystem implementation based on Clang.
static bool SetHasExternalStorage(lldb::opaque_compiler_type_t type, bool has_extern)
static bool StartTagDeclarationDefinition(const CompilerType &type)
static void RequireCompleteType(CompilerType type)
Complete a type from debug info, or mark it as forcefully completed if there is no definition of the ...
CompilandIndexItem & GetOrCreateCompiland(uint16_t modi)
const CompilandIndexItem * GetCompiland(uint16_t modi) const
clang::QualType CreatePointerType(const llvm::codeview::PointerRecord &pointer)
bool CompleteTagDecl(clang::TagDecl &tag)
clang::QualType FromCompilerType(CompilerType ct)
void ParseBlockChildren(PdbCompilandSymId block_id)
ClangASTImporter & GetClangASTImporter()
llvm::DenseMap< lldb::opaque_compiler_type_t, llvm::SmallSet< std::pair< llvm::StringRef, CompilerType >, 8 > > m_cxx_record_map
clang::FunctionDecl * CreateFunctionDecl(PdbCompilandSymId func_id, llvm::StringRef func_name, TypeIndex func_ti, CompilerType func_ct, uint32_t param_count, clang::StorageClass func_storage, bool is_inline, clang::DeclContext *parent)
lldb_private::CompilerDeclContext GetTranslationUnitDecl()
lldb_private::CompilerDeclContext GetParentDeclContext(PdbSymUid uid)
CompilerDecl ToCompilerDecl(clang::Decl *decl)
clang::QualType CreateModifierType(const llvm::codeview::ModifierRecord &modifier)
CompilerType GetOrCreateType(PdbTypeSymId type)
void ParseDeclsForSimpleContext(clang::DeclContext &context)
void ParseDeclsForContext(lldb_private::CompilerDeclContext context)
llvm::DenseMap< lldb::user_id_t, clang::QualType > m_uid_to_type
clang::QualType CreateFunctionType(TypeIndex args_type_idx, TypeIndex return_type_idx, llvm::codeview::CallingConvention calling_convention)
void Dump(Stream &stream, llvm::StringRef filter, bool show_color)
void ParseNamespace(clang::DeclContext &parent)
llvm::codeview::TypeIndex TypeIndex
std::pair< clang::DeclContext *, std::string > CreateDeclInfoForUndecoratedName(llvm::StringRef uname)
clang::Decl * TryGetDecl(PdbSymUid uid) const
clang::DeclContext * FromCompilerDeclContext(CompilerDeclContext context)
clang::VarDecl * GetOrCreateVariableDecl(PdbCompilandSymId scope_id, PdbCompilandSymId var_id)
clang::Decl * GetOrCreateSymbolForId(PdbCompilandSymId id)
CompilerType ToCompilerType(clang::QualType qt)
clang::NamespaceDecl * GetOrCreateNamespaceDecl(const char *name, clang::DeclContext &context)
PdbAstBuilder(TypeSystemClang &clang)
std::pair< clang::DeclContext *, std::string > CreateDeclInfoForType(const llvm::codeview::TagRecord &record, TypeIndex ti)
clang::QualType GetBasicType(lldb::BasicType type)
llvm::DenseMap< clang::Decl *, DeclStatus > m_decl_to_status
CompilerDeclContext ToCompilerDeclContext(clang::DeclContext *context)
clang::DeclContext * GetOrCreateClangDeclContextForUid(PdbSymUid uid)
llvm::DenseMap< lldb::user_id_t, clang::Decl * > m_uid_to_decl
clang::BlockDecl * GetOrCreateBlockDecl(PdbCompilandSymId block_id)
clang::Decl * FromCompilerDecl(CompilerDecl decl)
clang::QualType CreateSimpleType(TypeIndex ti)
void CreateFunctionParameters(PdbCompilandSymId func_id, clang::FunctionDecl &function_decl, uint32_t param_count)
clang::FunctionDecl * GetOrCreateFunctionDecl(PdbCompilandSymId func_id)
clang::QualType CreateArrayType(const llvm::codeview::ArrayRecord &array)
clang::QualType GetOrCreateClangType(PdbTypeSymId type)
clang::QualType CreateRecordType(PdbTypeSymId id, const llvm::codeview::TagRecord &record)
clang::FunctionDecl * CreateFunctionDeclFromId(PdbTypeSymId func_tid, PdbCompilandSymId func_sid)
lldb_private::CompilerDeclContext GetOrCreateDeclContextForUid(PdbSymUid uid)
llvm::once_flag m_parse_functions_and_non_local_vars
clang::VarDecl * CreateVariableDecl(PdbSymUid uid, llvm::codeview::CVSymbol sym, clang::DeclContext &scope)
clang::QualType CreateEnumType(PdbTypeSymId id, const llvm::codeview::EnumRecord &record)
clang::FunctionDecl * GetOrCreateInlinedFunctionDecl(PdbCompilandSymId inlinesite_id)
clang::DeclContext * GetParentClangDeclContext(PdbSymUid uid)
std::optional< lldb_private::CompilerDecl > GetOrCreateDeclForUid(PdbSymUid uid)
llvm::DenseSet< clang::NamespaceDecl * > NamespaceSet
lldb_private::CompilerDeclContext FindNamespaceDecl(lldb_private::CompilerDeclContext parent_ctx, llvm::StringRef name)
clang::QualType CreateType(PdbTypeSymId type)
clang::TypedefNameDecl * GetOrCreateTypedefDecl(PdbGlobalSymId id)
llvm::DenseMap< clang::DeclContext *, NamespaceSet > m_parent_to_namespaces
PdbIndex - Lazy access to the important parts of a PDB file.
Definition PdbIndex.h:47
llvm::pdb::TpiStream & ipi()
Definition PdbIndex.h:127
CompileUnitIndex & compilands()
Definition PdbIndex.h:142
llvm::pdb::DbiStream & dbi()
Definition PdbIndex.h:121
llvm::codeview::CVSymbol ReadSymbolRecord(PdbCompilandSymId cu_sym) const
Definition PdbIndex.cpp:187
llvm::pdb::TpiStream & tpi()
Definition PdbIndex.h:124
PdbGlobalSymId asGlobalSym() const
PdbCompilandSymId asCompilandSym() const
PdbTypeSymId asTypeSym() const
PdbSymUidKind kind() const
llvm::StringRef DropNameScope(llvm::StringRef name)
Definition PdbUtil.cpp:599
uint64_t toOpaqueUid(const T &cid)
Definition PdbSymUid.h:114
lldb::BasicType GetCompilerTypeForSimpleKind(llvm::codeview::SimpleTypeKind kind)
VariableInfo GetVariableNameInfo(llvm::codeview::CVSymbol symbol)
bool IsTagRecord(llvm::codeview::CVType cvt)
Definition PdbUtil.cpp:517
llvm::codeview::TypeIndex LookThroughModifierRecord(llvm::codeview::CVType modifier)
bool IsForwardRefUdt(llvm::codeview::CVType cvt)
lldb::AccessType TranslateMemberAccess(llvm::codeview::MemberAccess access)
llvm::codeview::TypeIndex GetFieldListIndex(llvm::codeview::CVType cvt)
size_t GetSizeOfType(PdbTypeSymId id, llvm::pdb::TpiStream &tpi)
Definition PdbUtil.cpp:1094
PdbTypeSymId GetBestPossibleDecl(PdbTypeSymId id, llvm::pdb::TpiStream &tpi)
A class that represents a running process on the host machine.
void * opaque_compiler_type_t
Definition lldb-types.h:89
BasicType
Basic types enumeration for the public API SBType::GetBasicType().
@ eLanguageTypeC_plus_plus
ISO C++:1998.
uint64_t user_id_t
Definition lldb-types.h:82
static clang::QualType GetQualType(const CompilerType &ct)
Definition ClangUtil.cpp:36
static clang::Decl * GetDecl(const CompilerDecl &decl)
Returns the clang::Decl of the given CompilerDecl.
Definition ClangUtil.cpp:31
const llvm::codeview::UnionRecord & asUnion() const
Definition PdbUtil.h:62
static CVTagRecord create(llvm::codeview::CVType type)
Definition PdbUtil.cpp:198
const llvm::codeview::ClassRecord & asClass() const
Definition PdbUtil.h:52
const llvm::codeview::EnumRecord & asEnum() const
Definition PdbUtil.h:57
const llvm::codeview::TagRecord & asTag() const
Definition PdbUtil.h:44
Represents a single compile unit.
llvm::pdb::ModuleDebugStreamRef m_debug_stream
llvm::codeview::TypeIndex index
Definition PdbSymUid.h:76
llvm::codeview::TypeIndex type
Definition PdbUtil.h:114