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