xref: /freebsd-src/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.cpp (revision 9dba64be9536c28e4800e06512b7f29b43ade345)
1 //===-- PDBASTParser.cpp ----------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "PDBASTParser.h"
10 
11 #include "SymbolFilePDB.h"
12 
13 #include "clang/AST/CharUnits.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 
17 #include "lldb/Core/Module.h"
18 #include "lldb/Symbol/ClangASTContext.h"
19 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
20 #include "lldb/Symbol/ClangUtil.h"
21 #include "lldb/Symbol/Declaration.h"
22 #include "lldb/Symbol/SymbolFile.h"
23 #include "lldb/Symbol/TypeMap.h"
24 #include "lldb/Symbol/TypeSystem.h"
25 
26 #include "llvm/DebugInfo/PDB/IPDBLineNumber.h"
27 #include "llvm/DebugInfo/PDB/IPDBSourceFile.h"
28 #include "llvm/DebugInfo/PDB/PDBSymbol.h"
29 #include "llvm/DebugInfo/PDB/PDBSymbolData.h"
30 #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
31 #include "llvm/DebugInfo/PDB/PDBSymbolTypeArray.h"
32 #include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h"
33 #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
34 #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h"
35 #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h"
36 #include "llvm/DebugInfo/PDB/PDBSymbolTypePointer.h"
37 #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
38 #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
39 
40 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
41 
42 using namespace lldb;
43 using namespace lldb_private;
44 using namespace llvm::pdb;
45 
46 static int TranslateUdtKind(PDB_UdtType pdb_kind) {
47   switch (pdb_kind) {
48   case PDB_UdtType::Class:
49     return clang::TTK_Class;
50   case PDB_UdtType::Struct:
51     return clang::TTK_Struct;
52   case PDB_UdtType::Union:
53     return clang::TTK_Union;
54   case PDB_UdtType::Interface:
55     return clang::TTK_Interface;
56   }
57   llvm_unreachable("unsuported PDB UDT type");
58 }
59 
60 static lldb::Encoding TranslateBuiltinEncoding(PDB_BuiltinType type) {
61   switch (type) {
62   case PDB_BuiltinType::Float:
63     return lldb::eEncodingIEEE754;
64   case PDB_BuiltinType::Int:
65   case PDB_BuiltinType::Long:
66   case PDB_BuiltinType::Char:
67     return lldb::eEncodingSint;
68   case PDB_BuiltinType::Bool:
69   case PDB_BuiltinType::Char16:
70   case PDB_BuiltinType::Char32:
71   case PDB_BuiltinType::UInt:
72   case PDB_BuiltinType::ULong:
73   case PDB_BuiltinType::HResult:
74   case PDB_BuiltinType::WCharT:
75     return lldb::eEncodingUint;
76   default:
77     return lldb::eEncodingInvalid;
78   }
79 }
80 
81 static lldb::Encoding TranslateEnumEncoding(PDB_VariantType type) {
82   switch (type) {
83   case PDB_VariantType::Int8:
84   case PDB_VariantType::Int16:
85   case PDB_VariantType::Int32:
86   case PDB_VariantType::Int64:
87     return lldb::eEncodingSint;
88 
89   case PDB_VariantType::UInt8:
90   case PDB_VariantType::UInt16:
91   case PDB_VariantType::UInt32:
92   case PDB_VariantType::UInt64:
93     return lldb::eEncodingUint;
94 
95   default:
96     break;
97   }
98 
99   return lldb::eEncodingSint;
100 }
101 
102 static CompilerType
103 GetBuiltinTypeForPDBEncodingAndBitSize(ClangASTContext &clang_ast,
104                                        const PDBSymbolTypeBuiltin &pdb_type,
105                                        Encoding encoding, uint32_t width) {
106   auto *ast = clang_ast.getASTContext();
107   if (!ast)
108     return CompilerType();
109 
110   switch (pdb_type.getBuiltinType()) {
111   default:
112     break;
113   case PDB_BuiltinType::None:
114     return CompilerType();
115   case PDB_BuiltinType::Void:
116     return clang_ast.GetBasicType(eBasicTypeVoid);
117   case PDB_BuiltinType::Char:
118     return clang_ast.GetBasicType(eBasicTypeChar);
119   case PDB_BuiltinType::Bool:
120     return clang_ast.GetBasicType(eBasicTypeBool);
121   case PDB_BuiltinType::Long:
122     if (width == ast->getTypeSize(ast->LongTy))
123       return CompilerType(ClangASTContext::GetASTContext(ast),
124                           ast->LongTy.getAsOpaquePtr());
125     if (width == ast->getTypeSize(ast->LongLongTy))
126       return CompilerType(ClangASTContext::GetASTContext(ast),
127                           ast->LongLongTy.getAsOpaquePtr());
128     break;
129   case PDB_BuiltinType::ULong:
130     if (width == ast->getTypeSize(ast->UnsignedLongTy))
131       return CompilerType(ClangASTContext::GetASTContext(ast),
132                           ast->UnsignedLongTy.getAsOpaquePtr());
133     if (width == ast->getTypeSize(ast->UnsignedLongLongTy))
134       return CompilerType(ClangASTContext::GetASTContext(ast),
135                           ast->UnsignedLongLongTy.getAsOpaquePtr());
136     break;
137   case PDB_BuiltinType::WCharT:
138     if (width == ast->getTypeSize(ast->WCharTy))
139       return CompilerType(ClangASTContext::GetASTContext(ast),
140                           ast->WCharTy.getAsOpaquePtr());
141     break;
142   case PDB_BuiltinType::Char16:
143     return CompilerType(ClangASTContext::GetASTContext(ast),
144                         ast->Char16Ty.getAsOpaquePtr());
145   case PDB_BuiltinType::Char32:
146     return CompilerType(ClangASTContext::GetASTContext(ast),
147                         ast->Char32Ty.getAsOpaquePtr());
148   case PDB_BuiltinType::Float:
149     // Note: types `long double` and `double` have same bit size in MSVC and
150     // there is no information in the PDB to distinguish them. So when falling
151     // back to default search, the compiler type of `long double` will be
152     // represented by the one generated for `double`.
153     break;
154   }
155   // If there is no match on PDB_BuiltinType, fall back to default search by
156   // encoding and width only
157   return clang_ast.GetBuiltinTypeForEncodingAndBitSize(encoding, width);
158 }
159 
160 static ConstString GetPDBBuiltinTypeName(const PDBSymbolTypeBuiltin &pdb_type,
161                                          CompilerType &compiler_type) {
162   PDB_BuiltinType kind = pdb_type.getBuiltinType();
163   switch (kind) {
164   default:
165     break;
166   case PDB_BuiltinType::Currency:
167     return ConstString("CURRENCY");
168   case PDB_BuiltinType::Date:
169     return ConstString("DATE");
170   case PDB_BuiltinType::Variant:
171     return ConstString("VARIANT");
172   case PDB_BuiltinType::Complex:
173     return ConstString("complex");
174   case PDB_BuiltinType::Bitfield:
175     return ConstString("bitfield");
176   case PDB_BuiltinType::BSTR:
177     return ConstString("BSTR");
178   case PDB_BuiltinType::HResult:
179     return ConstString("HRESULT");
180   case PDB_BuiltinType::BCD:
181     return ConstString("BCD");
182   case PDB_BuiltinType::Char16:
183     return ConstString("char16_t");
184   case PDB_BuiltinType::Char32:
185     return ConstString("char32_t");
186   case PDB_BuiltinType::None:
187     return ConstString("...");
188   }
189   return compiler_type.GetTypeName();
190 }
191 
192 static bool GetDeclarationForSymbol(const PDBSymbol &symbol,
193                                     Declaration &decl) {
194   auto &raw_sym = symbol.getRawSymbol();
195   auto first_line_up = raw_sym.getSrcLineOnTypeDefn();
196 
197   if (!first_line_up) {
198     auto lines_up = symbol.getSession().findLineNumbersByAddress(
199         raw_sym.getVirtualAddress(), raw_sym.getLength());
200     if (!lines_up)
201       return false;
202     first_line_up = lines_up->getNext();
203     if (!first_line_up)
204       return false;
205   }
206   uint32_t src_file_id = first_line_up->getSourceFileId();
207   auto src_file_up = symbol.getSession().getSourceFileById(src_file_id);
208   if (!src_file_up)
209     return false;
210 
211   FileSpec spec(src_file_up->getFileName());
212   decl.SetFile(spec);
213   decl.SetColumn(first_line_up->getColumnNumber());
214   decl.SetLine(first_line_up->getLineNumber());
215   return true;
216 }
217 
218 static AccessType TranslateMemberAccess(PDB_MemberAccess access) {
219   switch (access) {
220   case PDB_MemberAccess::Private:
221     return eAccessPrivate;
222   case PDB_MemberAccess::Protected:
223     return eAccessProtected;
224   case PDB_MemberAccess::Public:
225     return eAccessPublic;
226   }
227   return eAccessNone;
228 }
229 
230 static AccessType GetDefaultAccessibilityForUdtKind(PDB_UdtType udt_kind) {
231   switch (udt_kind) {
232   case PDB_UdtType::Struct:
233   case PDB_UdtType::Union:
234     return eAccessPublic;
235   case PDB_UdtType::Class:
236   case PDB_UdtType::Interface:
237     return eAccessPrivate;
238   }
239   llvm_unreachable("unsupported PDB UDT type");
240 }
241 
242 static AccessType GetAccessibilityForUdt(const PDBSymbolTypeUDT &udt) {
243   AccessType access = TranslateMemberAccess(udt.getAccess());
244   if (access != lldb::eAccessNone || !udt.isNested())
245     return access;
246 
247   auto parent = udt.getClassParent();
248   if (!parent)
249     return lldb::eAccessNone;
250 
251   auto parent_udt = llvm::dyn_cast<PDBSymbolTypeUDT>(parent.get());
252   if (!parent_udt)
253     return lldb::eAccessNone;
254 
255   return GetDefaultAccessibilityForUdtKind(parent_udt->getUdtKind());
256 }
257 
258 static clang::MSInheritanceAttr::Spelling
259 GetMSInheritance(const PDBSymbolTypeUDT &udt) {
260   int base_count = 0;
261   bool has_virtual = false;
262 
263   auto bases_enum = udt.findAllChildren<PDBSymbolTypeBaseClass>();
264   if (bases_enum) {
265     while (auto base = bases_enum->getNext()) {
266       base_count++;
267       has_virtual |= base->isVirtualBaseClass();
268     }
269   }
270 
271   if (has_virtual)
272     return clang::MSInheritanceAttr::Keyword_virtual_inheritance;
273   if (base_count > 1)
274     return clang::MSInheritanceAttr::Keyword_multiple_inheritance;
275   return clang::MSInheritanceAttr::Keyword_single_inheritance;
276 }
277 
278 static std::unique_ptr<llvm::pdb::PDBSymbol>
279 GetClassOrFunctionParent(const llvm::pdb::PDBSymbol &symbol) {
280   const IPDBSession &session = symbol.getSession();
281   const IPDBRawSymbol &raw = symbol.getRawSymbol();
282   auto tag = symbol.getSymTag();
283 
284   // For items that are nested inside of a class, return the class that it is
285   // nested inside of.
286   // Note that only certain items can be nested inside of classes.
287   switch (tag) {
288   case PDB_SymType::Function:
289   case PDB_SymType::Data:
290   case PDB_SymType::UDT:
291   case PDB_SymType::Enum:
292   case PDB_SymType::FunctionSig:
293   case PDB_SymType::Typedef:
294   case PDB_SymType::BaseClass:
295   case PDB_SymType::VTable: {
296     auto class_parent_id = raw.getClassParentId();
297     if (auto class_parent = session.getSymbolById(class_parent_id))
298       return class_parent;
299     break;
300   }
301   default:
302     break;
303   }
304 
305   // Otherwise, if it is nested inside of a function, return the function.
306   // Note that only certain items can be nested inside of functions.
307   switch (tag) {
308   case PDB_SymType::Block:
309   case PDB_SymType::Data: {
310     auto lexical_parent_id = raw.getLexicalParentId();
311     auto lexical_parent = session.getSymbolById(lexical_parent_id);
312     if (!lexical_parent)
313       return nullptr;
314 
315     auto lexical_parent_tag = lexical_parent->getSymTag();
316     if (lexical_parent_tag == PDB_SymType::Function)
317       return lexical_parent;
318     if (lexical_parent_tag == PDB_SymType::Exe)
319       return nullptr;
320 
321     return GetClassOrFunctionParent(*lexical_parent);
322   }
323   default:
324     return nullptr;
325   }
326 }
327 
328 static clang::NamedDecl *
329 GetDeclFromContextByName(const clang::ASTContext &ast,
330                          const clang::DeclContext &decl_context,
331                          llvm::StringRef name) {
332   clang::IdentifierInfo &ident = ast.Idents.get(name);
333   clang::DeclarationName decl_name = ast.DeclarationNames.getIdentifier(&ident);
334   clang::DeclContext::lookup_result result = decl_context.lookup(decl_name);
335   if (result.empty())
336     return nullptr;
337 
338   return result[0];
339 }
340 
341 static bool IsAnonymousNamespaceName(llvm::StringRef name) {
342   return name == "`anonymous namespace'" || name == "`anonymous-namespace'";
343 }
344 
345 static clang::CallingConv TranslateCallingConvention(PDB_CallingConv pdb_cc) {
346   switch (pdb_cc) {
347   case llvm::codeview::CallingConvention::NearC:
348     return clang::CC_C;
349   case llvm::codeview::CallingConvention::NearStdCall:
350     return clang::CC_X86StdCall;
351   case llvm::codeview::CallingConvention::NearFast:
352     return clang::CC_X86FastCall;
353   case llvm::codeview::CallingConvention::ThisCall:
354     return clang::CC_X86ThisCall;
355   case llvm::codeview::CallingConvention::NearVector:
356     return clang::CC_X86VectorCall;
357   case llvm::codeview::CallingConvention::NearPascal:
358     return clang::CC_X86Pascal;
359   default:
360     assert(false && "Unknown calling convention");
361     return clang::CC_C;
362   }
363 }
364 
365 PDBASTParser::PDBASTParser(lldb_private::ClangASTContext &ast) : m_ast(ast) {}
366 
367 PDBASTParser::~PDBASTParser() {}
368 
369 // DebugInfoASTParser interface
370 
371 lldb::TypeSP PDBASTParser::CreateLLDBTypeFromPDBType(const PDBSymbol &type) {
372   Declaration decl;
373   switch (type.getSymTag()) {
374   case PDB_SymType::BaseClass: {
375     auto symbol_file = m_ast.GetSymbolFile();
376     if (!symbol_file)
377       return nullptr;
378 
379     auto ty = symbol_file->ResolveTypeUID(type.getRawSymbol().getTypeId());
380     return ty ? ty->shared_from_this() : nullptr;
381   } break;
382   case PDB_SymType::UDT: {
383     auto udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&type);
384     assert(udt);
385 
386     // Note that, unnamed UDT being typedef-ed is generated as a UDT symbol
387     // other than a Typedef symbol in PDB. For example,
388     //    typedef union { short Row; short Col; } Union;
389     // is generated as a named UDT in PDB:
390     //    union Union { short Row; short Col; }
391     // Such symbols will be handled here.
392 
393     // Some UDT with trival ctor has zero length. Just ignore.
394     if (udt->getLength() == 0)
395       return nullptr;
396 
397     // Ignore unnamed-tag UDTs.
398     std::string name = MSVCUndecoratedNameParser::DropScope(udt->getName());
399     if (name.empty())
400       return nullptr;
401 
402     auto decl_context = GetDeclContextContainingSymbol(type);
403 
404     // Check if such an UDT already exists in the current context.
405     // This may occur with const or volatile types. There are separate type
406     // symbols in PDB for types with const or volatile modifiers, but we need
407     // to create only one declaration for them all.
408     Type::ResolveStateTag type_resolve_state_tag;
409     CompilerType clang_type = m_ast.GetTypeForIdentifier<clang::CXXRecordDecl>(
410         ConstString(name), decl_context);
411     if (!clang_type.IsValid()) {
412       auto access = GetAccessibilityForUdt(*udt);
413 
414       auto tag_type_kind = TranslateUdtKind(udt->getUdtKind());
415 
416       ClangASTMetadata metadata;
417       metadata.SetUserID(type.getSymIndexId());
418       metadata.SetIsDynamicCXXType(false);
419 
420       clang_type = m_ast.CreateRecordType(
421           decl_context, access, name.c_str(), tag_type_kind,
422           lldb::eLanguageTypeC_plus_plus, &metadata);
423       assert(clang_type.IsValid());
424 
425       auto record_decl =
426           m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
427       assert(record_decl);
428       m_uid_to_decl[type.getSymIndexId()] = record_decl;
429 
430       auto inheritance_attr = clang::MSInheritanceAttr::CreateImplicit(
431           *m_ast.getASTContext(), GetMSInheritance(*udt));
432       record_decl->addAttr(inheritance_attr);
433 
434       ClangASTContext::StartTagDeclarationDefinition(clang_type);
435 
436       auto children = udt->findAllChildren();
437       if (!children || children->getChildCount() == 0) {
438         // PDB does not have symbol of forwarder. We assume we get an udt w/o
439         // any fields. Just complete it at this point.
440         ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
441 
442         ClangASTContext::SetHasExternalStorage(clang_type.GetOpaqueQualType(),
443                                                false);
444 
445         type_resolve_state_tag = Type::eResolveStateFull;
446       } else {
447         // Add the type to the forward declarations. It will help us to avoid
448         // an endless recursion in CompleteTypeFromUdt function.
449         m_forward_decl_to_uid[record_decl] = type.getSymIndexId();
450 
451         ClangASTContext::SetHasExternalStorage(clang_type.GetOpaqueQualType(),
452                                                true);
453 
454         type_resolve_state_tag = Type::eResolveStateForward;
455       }
456     } else
457       type_resolve_state_tag = Type::eResolveStateForward;
458 
459     if (udt->isConstType())
460       clang_type = clang_type.AddConstModifier();
461 
462     if (udt->isVolatileType())
463       clang_type = clang_type.AddVolatileModifier();
464 
465     GetDeclarationForSymbol(type, decl);
466     return std::make_shared<lldb_private::Type>(
467         type.getSymIndexId(), m_ast.GetSymbolFile(), ConstString(name),
468         udt->getLength(), nullptr, LLDB_INVALID_UID,
469         lldb_private::Type::eEncodingIsUID, decl, clang_type,
470         type_resolve_state_tag);
471   } break;
472   case PDB_SymType::Enum: {
473     auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(&type);
474     assert(enum_type);
475 
476     std::string name =
477         MSVCUndecoratedNameParser::DropScope(enum_type->getName());
478     auto decl_context = GetDeclContextContainingSymbol(type);
479     uint64_t bytes = enum_type->getLength();
480 
481     // Check if such an enum already exists in the current context
482     CompilerType ast_enum = m_ast.GetTypeForIdentifier<clang::EnumDecl>(
483         ConstString(name), decl_context);
484     if (!ast_enum.IsValid()) {
485       auto underlying_type_up = enum_type->getUnderlyingType();
486       if (!underlying_type_up)
487         return nullptr;
488 
489       lldb::Encoding encoding =
490           TranslateBuiltinEncoding(underlying_type_up->getBuiltinType());
491       // FIXME: Type of underlying builtin is always `Int`. We correct it with
492       // the very first enumerator's encoding if any.
493       auto first_child = enum_type->findOneChild<PDBSymbolData>();
494       if (first_child)
495         encoding = TranslateEnumEncoding(first_child->getValue().Type);
496 
497       CompilerType builtin_type;
498       if (bytes > 0)
499         builtin_type = GetBuiltinTypeForPDBEncodingAndBitSize(
500             m_ast, *underlying_type_up, encoding, bytes * 8);
501       else
502         builtin_type = m_ast.GetBasicType(eBasicTypeInt);
503 
504       // FIXME: PDB does not have information about scoped enumeration (Enum
505       // Class). Set it false for now.
506       bool isScoped = false;
507 
508       ast_enum = m_ast.CreateEnumerationType(name.c_str(), decl_context, decl,
509                                              builtin_type, isScoped);
510 
511       auto enum_decl = ClangASTContext::GetAsEnumDecl(ast_enum);
512       assert(enum_decl);
513       m_uid_to_decl[type.getSymIndexId()] = enum_decl;
514 
515       auto enum_values = enum_type->findAllChildren<PDBSymbolData>();
516       if (enum_values) {
517         while (auto enum_value = enum_values->getNext()) {
518           if (enum_value->getDataKind() != PDB_DataKind::Constant)
519             continue;
520           AddEnumValue(ast_enum, *enum_value);
521         }
522       }
523 
524       if (ClangASTContext::StartTagDeclarationDefinition(ast_enum))
525         ClangASTContext::CompleteTagDeclarationDefinition(ast_enum);
526     }
527 
528     if (enum_type->isConstType())
529       ast_enum = ast_enum.AddConstModifier();
530 
531     if (enum_type->isVolatileType())
532       ast_enum = ast_enum.AddVolatileModifier();
533 
534     GetDeclarationForSymbol(type, decl);
535     return std::make_shared<lldb_private::Type>(
536         type.getSymIndexId(), m_ast.GetSymbolFile(), ConstString(name), bytes,
537         nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
538         ast_enum, lldb_private::Type::eResolveStateFull);
539   } break;
540   case PDB_SymType::Typedef: {
541     auto type_def = llvm::dyn_cast<PDBSymbolTypeTypedef>(&type);
542     assert(type_def);
543 
544     lldb_private::Type *target_type =
545         m_ast.GetSymbolFile()->ResolveTypeUID(type_def->getTypeId());
546     if (!target_type)
547       return nullptr;
548 
549     std::string name =
550         MSVCUndecoratedNameParser::DropScope(type_def->getName());
551     auto decl_ctx = GetDeclContextContainingSymbol(type);
552 
553     // Check if such a typedef already exists in the current context
554     CompilerType ast_typedef =
555         m_ast.GetTypeForIdentifier<clang::TypedefNameDecl>(ConstString(name),
556                                                            decl_ctx);
557     if (!ast_typedef.IsValid()) {
558       CompilerType target_ast_type = target_type->GetFullCompilerType();
559 
560       ast_typedef = m_ast.CreateTypedefType(
561           target_ast_type, name.c_str(), CompilerDeclContext(&m_ast, decl_ctx));
562       if (!ast_typedef)
563         return nullptr;
564 
565       auto typedef_decl = ClangASTContext::GetAsTypedefDecl(ast_typedef);
566       assert(typedef_decl);
567       m_uid_to_decl[type.getSymIndexId()] = typedef_decl;
568     }
569 
570     if (type_def->isConstType())
571       ast_typedef = ast_typedef.AddConstModifier();
572 
573     if (type_def->isVolatileType())
574       ast_typedef = ast_typedef.AddVolatileModifier();
575 
576     GetDeclarationForSymbol(type, decl);
577     llvm::Optional<uint64_t> size;
578     if (type_def->getLength())
579       size = type_def->getLength();
580     return std::make_shared<lldb_private::Type>(
581         type_def->getSymIndexId(), m_ast.GetSymbolFile(), ConstString(name),
582         size, nullptr, target_type->GetID(),
583         lldb_private::Type::eEncodingIsTypedefUID, decl, ast_typedef,
584         lldb_private::Type::eResolveStateFull);
585   } break;
586   case PDB_SymType::Function:
587   case PDB_SymType::FunctionSig: {
588     std::string name;
589     PDBSymbolTypeFunctionSig *func_sig = nullptr;
590     if (auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(&type)) {
591       if (pdb_func->isCompilerGenerated())
592         return nullptr;
593 
594       auto sig = pdb_func->getSignature();
595       if (!sig)
596         return nullptr;
597       func_sig = sig.release();
598       // Function type is named.
599       name = MSVCUndecoratedNameParser::DropScope(pdb_func->getName());
600     } else if (auto pdb_func_sig =
601                    llvm::dyn_cast<PDBSymbolTypeFunctionSig>(&type)) {
602       func_sig = const_cast<PDBSymbolTypeFunctionSig *>(pdb_func_sig);
603     } else
604       llvm_unreachable("Unexpected PDB symbol!");
605 
606     auto arg_enum = func_sig->getArguments();
607     uint32_t num_args = arg_enum->getChildCount();
608     std::vector<CompilerType> arg_list;
609 
610     bool is_variadic = func_sig->isCVarArgs();
611     // Drop last variadic argument.
612     if (is_variadic)
613       --num_args;
614     for (uint32_t arg_idx = 0; arg_idx < num_args; arg_idx++) {
615       auto arg = arg_enum->getChildAtIndex(arg_idx);
616       if (!arg)
617         break;
618       lldb_private::Type *arg_type =
619           m_ast.GetSymbolFile()->ResolveTypeUID(arg->getSymIndexId());
620       // If there's some error looking up one of the dependent types of this
621       // function signature, bail.
622       if (!arg_type)
623         return nullptr;
624       CompilerType arg_ast_type = arg_type->GetFullCompilerType();
625       arg_list.push_back(arg_ast_type);
626     }
627     lldbassert(arg_list.size() <= num_args);
628 
629     auto pdb_return_type = func_sig->getReturnType();
630     lldb_private::Type *return_type =
631         m_ast.GetSymbolFile()->ResolveTypeUID(pdb_return_type->getSymIndexId());
632     // If there's some error looking up one of the dependent types of this
633     // function signature, bail.
634     if (!return_type)
635       return nullptr;
636     CompilerType return_ast_type = return_type->GetFullCompilerType();
637     uint32_t type_quals = 0;
638     if (func_sig->isConstType())
639       type_quals |= clang::Qualifiers::Const;
640     if (func_sig->isVolatileType())
641       type_quals |= clang::Qualifiers::Volatile;
642     auto cc = TranslateCallingConvention(func_sig->getCallingConvention());
643     CompilerType func_sig_ast_type =
644         m_ast.CreateFunctionType(return_ast_type, arg_list.data(),
645                                  arg_list.size(), is_variadic, type_quals, cc);
646 
647     GetDeclarationForSymbol(type, decl);
648     return std::make_shared<lldb_private::Type>(
649         type.getSymIndexId(), m_ast.GetSymbolFile(), ConstString(name),
650         llvm::None, nullptr, LLDB_INVALID_UID,
651         lldb_private::Type::eEncodingIsUID, decl, func_sig_ast_type,
652         lldb_private::Type::eResolveStateFull);
653   } break;
654   case PDB_SymType::ArrayType: {
655     auto array_type = llvm::dyn_cast<PDBSymbolTypeArray>(&type);
656     assert(array_type);
657     uint32_t num_elements = array_type->getCount();
658     uint32_t element_uid = array_type->getElementTypeId();
659     llvm::Optional<uint64_t> bytes;
660     if (uint64_t size = array_type->getLength())
661       bytes = size;
662 
663     // If array rank > 0, PDB gives the element type at N=0. So element type
664     // will parsed in the order N=0, N=1,..., N=rank sequentially.
665     lldb_private::Type *element_type =
666         m_ast.GetSymbolFile()->ResolveTypeUID(element_uid);
667     if (!element_type)
668       return nullptr;
669 
670     CompilerType element_ast_type = element_type->GetForwardCompilerType();
671     // If element type is UDT, it needs to be complete.
672     if (ClangASTContext::IsCXXClassType(element_ast_type) &&
673         !element_ast_type.GetCompleteType()) {
674       if (ClangASTContext::StartTagDeclarationDefinition(element_ast_type)) {
675         ClangASTContext::CompleteTagDeclarationDefinition(element_ast_type);
676       } else {
677         // We are not able to start defintion.
678         return nullptr;
679       }
680     }
681     CompilerType array_ast_type = m_ast.CreateArrayType(
682         element_ast_type, num_elements, /*is_gnu_vector*/ false);
683     TypeSP type_sp = std::make_shared<lldb_private::Type>(
684         array_type->getSymIndexId(), m_ast.GetSymbolFile(), ConstString(),
685         bytes, nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID,
686         decl, array_ast_type, lldb_private::Type::eResolveStateFull);
687     type_sp->SetEncodingType(element_type);
688     return type_sp;
689   } break;
690   case PDB_SymType::BuiltinType: {
691     auto *builtin_type = llvm::dyn_cast<PDBSymbolTypeBuiltin>(&type);
692     assert(builtin_type);
693     PDB_BuiltinType builtin_kind = builtin_type->getBuiltinType();
694     if (builtin_kind == PDB_BuiltinType::None)
695       return nullptr;
696 
697     llvm::Optional<uint64_t> bytes;
698     if (uint64_t size = builtin_type->getLength())
699       bytes = size;
700     Encoding encoding = TranslateBuiltinEncoding(builtin_kind);
701     CompilerType builtin_ast_type = GetBuiltinTypeForPDBEncodingAndBitSize(
702         m_ast, *builtin_type, encoding, bytes.getValueOr(0) * 8);
703 
704     if (builtin_type->isConstType())
705       builtin_ast_type = builtin_ast_type.AddConstModifier();
706 
707     if (builtin_type->isVolatileType())
708       builtin_ast_type = builtin_ast_type.AddVolatileModifier();
709 
710     auto type_name = GetPDBBuiltinTypeName(*builtin_type, builtin_ast_type);
711 
712     return std::make_shared<lldb_private::Type>(
713         builtin_type->getSymIndexId(), m_ast.GetSymbolFile(), type_name, bytes,
714         nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
715         builtin_ast_type, lldb_private::Type::eResolveStateFull);
716   } break;
717   case PDB_SymType::PointerType: {
718     auto *pointer_type = llvm::dyn_cast<PDBSymbolTypePointer>(&type);
719     assert(pointer_type);
720     Type *pointee_type = m_ast.GetSymbolFile()->ResolveTypeUID(
721         pointer_type->getPointeeType()->getSymIndexId());
722     if (!pointee_type)
723       return nullptr;
724 
725     if (pointer_type->isPointerToDataMember() ||
726         pointer_type->isPointerToMemberFunction()) {
727       auto class_parent_uid = pointer_type->getRawSymbol().getClassParentId();
728       auto class_parent_type =
729           m_ast.GetSymbolFile()->ResolveTypeUID(class_parent_uid);
730       assert(class_parent_type);
731 
732       CompilerType pointer_ast_type;
733       pointer_ast_type = ClangASTContext::CreateMemberPointerType(
734           class_parent_type->GetLayoutCompilerType(),
735           pointee_type->GetForwardCompilerType());
736       assert(pointer_ast_type);
737 
738       return std::make_shared<lldb_private::Type>(
739           pointer_type->getSymIndexId(), m_ast.GetSymbolFile(), ConstString(),
740           pointer_type->getLength(), nullptr, LLDB_INVALID_UID,
741           lldb_private::Type::eEncodingIsUID, decl, pointer_ast_type,
742           lldb_private::Type::eResolveStateForward);
743     }
744 
745     CompilerType pointer_ast_type;
746     pointer_ast_type = pointee_type->GetFullCompilerType();
747     if (pointer_type->isReference())
748       pointer_ast_type = pointer_ast_type.GetLValueReferenceType();
749     else if (pointer_type->isRValueReference())
750       pointer_ast_type = pointer_ast_type.GetRValueReferenceType();
751     else
752       pointer_ast_type = pointer_ast_type.GetPointerType();
753 
754     if (pointer_type->isConstType())
755       pointer_ast_type = pointer_ast_type.AddConstModifier();
756 
757     if (pointer_type->isVolatileType())
758       pointer_ast_type = pointer_ast_type.AddVolatileModifier();
759 
760     if (pointer_type->isRestrictedType())
761       pointer_ast_type = pointer_ast_type.AddRestrictModifier();
762 
763     return std::make_shared<lldb_private::Type>(
764         pointer_type->getSymIndexId(), m_ast.GetSymbolFile(), ConstString(),
765         pointer_type->getLength(), nullptr, LLDB_INVALID_UID,
766         lldb_private::Type::eEncodingIsUID, decl, pointer_ast_type,
767         lldb_private::Type::eResolveStateFull);
768   } break;
769   default:
770     break;
771   }
772   return nullptr;
773 }
774 
775 bool PDBASTParser::CompleteTypeFromPDB(
776     lldb_private::CompilerType &compiler_type) {
777   if (GetClangASTImporter().CanImport(compiler_type))
778     return GetClangASTImporter().CompleteType(compiler_type);
779 
780   // Remove the type from the forward declarations to avoid
781   // an endless recursion for types like a linked list.
782   clang::CXXRecordDecl *record_decl =
783       m_ast.GetAsCXXRecordDecl(compiler_type.GetOpaqueQualType());
784   auto uid_it = m_forward_decl_to_uid.find(record_decl);
785   if (uid_it == m_forward_decl_to_uid.end())
786     return true;
787 
788   auto symbol_file = static_cast<SymbolFilePDB *>(m_ast.GetSymbolFile());
789   if (!symbol_file)
790     return false;
791 
792   std::unique_ptr<PDBSymbol> symbol =
793       symbol_file->GetPDBSession().getSymbolById(uid_it->getSecond());
794   if (!symbol)
795     return false;
796 
797   m_forward_decl_to_uid.erase(uid_it);
798 
799   ClangASTContext::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),
800                                          false);
801 
802   switch (symbol->getSymTag()) {
803   case PDB_SymType::UDT: {
804     auto udt = llvm::dyn_cast<PDBSymbolTypeUDT>(symbol.get());
805     if (!udt)
806       return false;
807 
808     return CompleteTypeFromUDT(*symbol_file, compiler_type, *udt);
809   }
810   default:
811     llvm_unreachable("not a forward clang type decl!");
812   }
813 }
814 
815 clang::Decl *
816 PDBASTParser::GetDeclForSymbol(const llvm::pdb::PDBSymbol &symbol) {
817   uint32_t sym_id = symbol.getSymIndexId();
818   auto it = m_uid_to_decl.find(sym_id);
819   if (it != m_uid_to_decl.end())
820     return it->second;
821 
822   auto symbol_file = static_cast<SymbolFilePDB *>(m_ast.GetSymbolFile());
823   if (!symbol_file)
824     return nullptr;
825 
826   // First of all, check if the symbol is a member of a class. Resolve the full
827   // class type and return the declaration from the cache if so.
828   auto tag = symbol.getSymTag();
829   if (tag == PDB_SymType::Data || tag == PDB_SymType::Function) {
830     const IPDBSession &session = symbol.getSession();
831     const IPDBRawSymbol &raw = symbol.getRawSymbol();
832 
833     auto class_parent_id = raw.getClassParentId();
834     if (std::unique_ptr<PDBSymbol> class_parent =
835             session.getSymbolById(class_parent_id)) {
836       auto class_parent_type = symbol_file->ResolveTypeUID(class_parent_id);
837       if (!class_parent_type)
838         return nullptr;
839 
840       CompilerType class_parent_ct = class_parent_type->GetFullCompilerType();
841 
842       // Look a declaration up in the cache after completing the class
843       clang::Decl *decl = m_uid_to_decl.lookup(sym_id);
844       if (decl)
845         return decl;
846 
847       // A declaration was not found in the cache. It means that the symbol
848       // has the class parent, but the class doesn't have the symbol in its
849       // children list.
850       if (auto func = llvm::dyn_cast_or_null<PDBSymbolFunc>(&symbol)) {
851         // Try to find a class child method with the same RVA and use its
852         // declaration if found.
853         if (uint32_t rva = func->getRelativeVirtualAddress()) {
854           if (std::unique_ptr<ConcreteSymbolEnumerator<PDBSymbolFunc>>
855                   methods_enum =
856                       class_parent->findAllChildren<PDBSymbolFunc>()) {
857             while (std::unique_ptr<PDBSymbolFunc> method =
858                        methods_enum->getNext()) {
859               if (method->getRelativeVirtualAddress() == rva) {
860                 decl = m_uid_to_decl.lookup(method->getSymIndexId());
861                 if (decl)
862                   break;
863               }
864             }
865           }
866         }
867 
868         // If no class methods with the same RVA were found, then create a new
869         // method. It is possible for template methods.
870         if (!decl)
871           decl = AddRecordMethod(*symbol_file, class_parent_ct, *func);
872       }
873 
874       if (decl)
875         m_uid_to_decl[sym_id] = decl;
876 
877       return decl;
878     }
879   }
880 
881   // If we are here, then the symbol is not belonging to a class and is not
882   // contained in the cache. So create a declaration for it.
883   switch (symbol.getSymTag()) {
884   case PDB_SymType::Data: {
885     auto data = llvm::dyn_cast<PDBSymbolData>(&symbol);
886     assert(data);
887 
888     auto decl_context = GetDeclContextContainingSymbol(symbol);
889     assert(decl_context);
890 
891     // May be the current context is a class really, but we haven't found
892     // any class parent. This happens e.g. in the case of class static
893     // variables - they has two symbols, one is a child of the class when
894     // another is a child of the exe. So always complete the parent and use
895     // an existing declaration if possible.
896     if (auto parent_decl = llvm::dyn_cast_or_null<clang::TagDecl>(decl_context))
897       m_ast.GetCompleteDecl(parent_decl);
898 
899     std::string name = MSVCUndecoratedNameParser::DropScope(data->getName());
900 
901     // Check if the current context already contains the symbol with the name.
902     clang::Decl *decl =
903         GetDeclFromContextByName(*m_ast.getASTContext(), *decl_context, name);
904     if (!decl) {
905       auto type = symbol_file->ResolveTypeUID(data->getTypeId());
906       if (!type)
907         return nullptr;
908 
909       decl = m_ast.CreateVariableDeclaration(
910           decl_context, name.c_str(),
911           ClangUtil::GetQualType(type->GetLayoutCompilerType()));
912     }
913 
914     m_uid_to_decl[sym_id] = decl;
915 
916     return decl;
917   }
918   case PDB_SymType::Function: {
919     auto func = llvm::dyn_cast<PDBSymbolFunc>(&symbol);
920     assert(func);
921 
922     auto decl_context = GetDeclContextContainingSymbol(symbol);
923     assert(decl_context);
924 
925     std::string name = MSVCUndecoratedNameParser::DropScope(func->getName());
926 
927     Type *type = symbol_file->ResolveTypeUID(sym_id);
928     if (!type)
929       return nullptr;
930 
931     auto storage = func->isStatic() ? clang::StorageClass::SC_Static
932                                     : clang::StorageClass::SC_None;
933 
934     auto decl = m_ast.CreateFunctionDeclaration(
935         decl_context, name.c_str(), type->GetForwardCompilerType(), storage,
936         func->hasInlineAttribute());
937 
938     std::vector<clang::ParmVarDecl *> params;
939     if (std::unique_ptr<PDBSymbolTypeFunctionSig> sig = func->getSignature()) {
940       if (std::unique_ptr<ConcreteSymbolEnumerator<PDBSymbolTypeFunctionArg>>
941               arg_enum = sig->findAllChildren<PDBSymbolTypeFunctionArg>()) {
942         while (std::unique_ptr<PDBSymbolTypeFunctionArg> arg =
943                    arg_enum->getNext()) {
944           Type *arg_type = symbol_file->ResolveTypeUID(arg->getTypeId());
945           if (!arg_type)
946             continue;
947 
948           clang::ParmVarDecl *param = m_ast.CreateParameterDeclaration(
949               decl, nullptr, arg_type->GetForwardCompilerType(),
950               clang::SC_None, true);
951           if (param)
952             params.push_back(param);
953         }
954       }
955     }
956     if (params.size())
957       m_ast.SetFunctionParameters(decl, params.data(), params.size());
958 
959     m_uid_to_decl[sym_id] = decl;
960 
961     return decl;
962   }
963   default: {
964     // It's not a variable and not a function, check if it's a type
965     Type *type = symbol_file->ResolveTypeUID(sym_id);
966     if (!type)
967       return nullptr;
968 
969     return m_uid_to_decl.lookup(sym_id);
970   }
971   }
972 }
973 
974 clang::DeclContext *
975 PDBASTParser::GetDeclContextForSymbol(const llvm::pdb::PDBSymbol &symbol) {
976   if (symbol.getSymTag() == PDB_SymType::Function) {
977     clang::DeclContext *result =
978         llvm::dyn_cast_or_null<clang::FunctionDecl>(GetDeclForSymbol(symbol));
979 
980     if (result)
981       m_decl_context_to_uid[result] = symbol.getSymIndexId();
982 
983     return result;
984   }
985 
986   auto symbol_file = static_cast<SymbolFilePDB *>(m_ast.GetSymbolFile());
987   if (!symbol_file)
988     return nullptr;
989 
990   auto type = symbol_file->ResolveTypeUID(symbol.getSymIndexId());
991   if (!type)
992     return nullptr;
993 
994   clang::DeclContext *result =
995       m_ast.GetDeclContextForType(type->GetForwardCompilerType());
996 
997   if (result)
998     m_decl_context_to_uid[result] = symbol.getSymIndexId();
999 
1000   return result;
1001 }
1002 
1003 clang::DeclContext *PDBASTParser::GetDeclContextContainingSymbol(
1004     const llvm::pdb::PDBSymbol &symbol) {
1005   auto parent = GetClassOrFunctionParent(symbol);
1006   while (parent) {
1007     if (auto parent_context = GetDeclContextForSymbol(*parent))
1008       return parent_context;
1009 
1010     parent = GetClassOrFunctionParent(*parent);
1011   }
1012 
1013   // We can't find any class or function parent of the symbol. So analyze
1014   // the full symbol name. The symbol may be belonging to a namespace
1015   // or function (or even to a class if it's e.g. a static variable symbol).
1016 
1017   // TODO: Make clang to emit full names for variables in namespaces
1018   // (as MSVC does)
1019 
1020   std::string name(symbol.getRawSymbol().getName());
1021   MSVCUndecoratedNameParser parser(name);
1022   llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers();
1023   if (specs.empty())
1024     return m_ast.GetTranslationUnitDecl();
1025 
1026   auto symbol_file = static_cast<SymbolFilePDB *>(m_ast.GetSymbolFile());
1027   if (!symbol_file)
1028     return m_ast.GetTranslationUnitDecl();
1029 
1030   auto global = symbol_file->GetPDBSession().getGlobalScope();
1031   if (!global)
1032     return m_ast.GetTranslationUnitDecl();
1033 
1034   bool has_type_or_function_parent = false;
1035   clang::DeclContext *curr_context = m_ast.GetTranslationUnitDecl();
1036   for (std::size_t i = 0; i < specs.size() - 1; i++) {
1037     // Check if there is a function or a type with the current context's name.
1038     if (std::unique_ptr<IPDBEnumSymbols> children_enum = global->findChildren(
1039             PDB_SymType::None, specs[i].GetFullName(), NS_CaseSensitive)) {
1040       while (IPDBEnumChildren<PDBSymbol>::ChildTypePtr child =
1041                  children_enum->getNext()) {
1042         if (clang::DeclContext *child_context =
1043                 GetDeclContextForSymbol(*child)) {
1044           // Note that `GetDeclContextForSymbol' retrieves
1045           // a declaration context for functions and types only,
1046           // so if we are here then `child_context' is guaranteed
1047           // a function or a type declaration context.
1048           has_type_or_function_parent = true;
1049           curr_context = child_context;
1050         }
1051       }
1052     }
1053 
1054     // If there were no functions or types above then retrieve a namespace with
1055     // the current context's name. There can be no namespaces inside a function
1056     // or a type. We check it to avoid fake namespaces such as `__l2':
1057     // `N0::N1::CClass::PrivateFunc::__l2::InnerFuncStruct'
1058     if (!has_type_or_function_parent) {
1059       std::string namespace_name = specs[i].GetBaseName();
1060       const char *namespace_name_c_str =
1061           IsAnonymousNamespaceName(namespace_name) ? nullptr
1062                                                    : namespace_name.data();
1063       clang::NamespaceDecl *namespace_decl =
1064           m_ast.GetUniqueNamespaceDeclaration(namespace_name_c_str,
1065                                               curr_context);
1066 
1067       m_parent_to_namespaces[curr_context].insert(namespace_decl);
1068       m_namespaces.insert(namespace_decl);
1069 
1070       curr_context = namespace_decl;
1071     }
1072   }
1073 
1074   return curr_context;
1075 }
1076 
1077 void PDBASTParser::ParseDeclsForDeclContext(
1078     const clang::DeclContext *decl_context) {
1079   auto symbol_file = static_cast<SymbolFilePDB *>(m_ast.GetSymbolFile());
1080   if (!symbol_file)
1081     return;
1082 
1083   IPDBSession &session = symbol_file->GetPDBSession();
1084   auto symbol_up =
1085       session.getSymbolById(m_decl_context_to_uid.lookup(decl_context));
1086   auto global_up = session.getGlobalScope();
1087 
1088   PDBSymbol *symbol;
1089   if (symbol_up)
1090     symbol = symbol_up.get();
1091   else if (global_up)
1092     symbol = global_up.get();
1093   else
1094     return;
1095 
1096   if (auto children = symbol->findAllChildren())
1097     while (auto child = children->getNext())
1098       GetDeclForSymbol(*child);
1099 }
1100 
1101 clang::NamespaceDecl *
1102 PDBASTParser::FindNamespaceDecl(const clang::DeclContext *parent,
1103                                 llvm::StringRef name) {
1104   NamespacesSet *set;
1105   if (parent) {
1106     auto pit = m_parent_to_namespaces.find(parent);
1107     if (pit == m_parent_to_namespaces.end())
1108       return nullptr;
1109 
1110     set = &pit->second;
1111   } else {
1112     set = &m_namespaces;
1113   }
1114   assert(set);
1115 
1116   for (clang::NamespaceDecl *namespace_decl : *set)
1117     if (namespace_decl->getName().equals(name))
1118       return namespace_decl;
1119 
1120   for (clang::NamespaceDecl *namespace_decl : *set)
1121     if (namespace_decl->isAnonymousNamespace())
1122       return FindNamespaceDecl(namespace_decl, name);
1123 
1124   return nullptr;
1125 }
1126 
1127 bool PDBASTParser::AddEnumValue(CompilerType enum_type,
1128                                 const PDBSymbolData &enum_value) {
1129   Declaration decl;
1130   Variant v = enum_value.getValue();
1131   std::string name = MSVCUndecoratedNameParser::DropScope(enum_value.getName());
1132   int64_t raw_value;
1133   switch (v.Type) {
1134   case PDB_VariantType::Int8:
1135     raw_value = v.Value.Int8;
1136     break;
1137   case PDB_VariantType::Int16:
1138     raw_value = v.Value.Int16;
1139     break;
1140   case PDB_VariantType::Int32:
1141     raw_value = v.Value.Int32;
1142     break;
1143   case PDB_VariantType::Int64:
1144     raw_value = v.Value.Int64;
1145     break;
1146   case PDB_VariantType::UInt8:
1147     raw_value = v.Value.UInt8;
1148     break;
1149   case PDB_VariantType::UInt16:
1150     raw_value = v.Value.UInt16;
1151     break;
1152   case PDB_VariantType::UInt32:
1153     raw_value = v.Value.UInt32;
1154     break;
1155   case PDB_VariantType::UInt64:
1156     raw_value = v.Value.UInt64;
1157     break;
1158   default:
1159     return false;
1160   }
1161   CompilerType underlying_type =
1162       m_ast.GetEnumerationIntegerType(enum_type.GetOpaqueQualType());
1163   uint32_t byte_size = m_ast.getASTContext()->getTypeSize(
1164       ClangUtil::GetQualType(underlying_type));
1165   auto enum_constant_decl = m_ast.AddEnumerationValueToEnumerationType(
1166       enum_type, decl, name.c_str(), raw_value, byte_size * 8);
1167   if (!enum_constant_decl)
1168     return false;
1169 
1170   m_uid_to_decl[enum_value.getSymIndexId()] = enum_constant_decl;
1171 
1172   return true;
1173 }
1174 
1175 bool PDBASTParser::CompleteTypeFromUDT(
1176     lldb_private::SymbolFile &symbol_file,
1177     lldb_private::CompilerType &compiler_type,
1178     llvm::pdb::PDBSymbolTypeUDT &udt) {
1179   ClangASTImporter::LayoutInfo layout_info;
1180   layout_info.bit_size = udt.getLength() * 8;
1181 
1182   auto nested_enums = udt.findAllChildren<PDBSymbolTypeUDT>();
1183   if (nested_enums)
1184     while (auto nested = nested_enums->getNext())
1185       symbol_file.ResolveTypeUID(nested->getSymIndexId());
1186 
1187   auto bases_enum = udt.findAllChildren<PDBSymbolTypeBaseClass>();
1188   if (bases_enum)
1189     AddRecordBases(symbol_file, compiler_type,
1190                    TranslateUdtKind(udt.getUdtKind()), *bases_enum,
1191                    layout_info);
1192 
1193   auto members_enum = udt.findAllChildren<PDBSymbolData>();
1194   if (members_enum)
1195     AddRecordMembers(symbol_file, compiler_type, *members_enum, layout_info);
1196 
1197   auto methods_enum = udt.findAllChildren<PDBSymbolFunc>();
1198   if (methods_enum)
1199     AddRecordMethods(symbol_file, compiler_type, *methods_enum);
1200 
1201   m_ast.AddMethodOverridesForCXXRecordType(compiler_type.GetOpaqueQualType());
1202   ClangASTContext::BuildIndirectFields(compiler_type);
1203   ClangASTContext::CompleteTagDeclarationDefinition(compiler_type);
1204 
1205   clang::CXXRecordDecl *record_decl =
1206       m_ast.GetAsCXXRecordDecl(compiler_type.GetOpaqueQualType());
1207   if (!record_decl)
1208     return static_cast<bool>(compiler_type);
1209 
1210   GetClangASTImporter().InsertRecordDecl(record_decl, layout_info);
1211 
1212   return static_cast<bool>(compiler_type);
1213 }
1214 
1215 void PDBASTParser::AddRecordMembers(
1216     lldb_private::SymbolFile &symbol_file,
1217     lldb_private::CompilerType &record_type,
1218     PDBDataSymbolEnumerator &members_enum,
1219     lldb_private::ClangASTImporter::LayoutInfo &layout_info) {
1220   while (auto member = members_enum.getNext()) {
1221     if (member->isCompilerGenerated())
1222       continue;
1223 
1224     auto member_name = member->getName();
1225 
1226     auto member_type = symbol_file.ResolveTypeUID(member->getTypeId());
1227     if (!member_type)
1228       continue;
1229 
1230     auto member_comp_type = member_type->GetLayoutCompilerType();
1231     if (!member_comp_type.GetCompleteType()) {
1232       symbol_file.GetObjectFile()->GetModule()->ReportError(
1233           ":: Class '%s' has a member '%s' of type '%s' "
1234           "which does not have a complete definition.",
1235           record_type.GetTypeName().GetCString(), member_name.c_str(),
1236           member_comp_type.GetTypeName().GetCString());
1237       if (ClangASTContext::StartTagDeclarationDefinition(member_comp_type))
1238         ClangASTContext::CompleteTagDeclarationDefinition(member_comp_type);
1239     }
1240 
1241     auto access = TranslateMemberAccess(member->getAccess());
1242 
1243     switch (member->getDataKind()) {
1244     case PDB_DataKind::Member: {
1245       auto location_type = member->getLocationType();
1246 
1247       auto bit_size = member->getLength();
1248       if (location_type == PDB_LocType::ThisRel)
1249         bit_size *= 8;
1250 
1251       auto decl = ClangASTContext::AddFieldToRecordType(
1252           record_type, member_name.c_str(), member_comp_type, access, bit_size);
1253       if (!decl)
1254         continue;
1255 
1256       m_uid_to_decl[member->getSymIndexId()] = decl;
1257 
1258       auto offset = member->getOffset() * 8;
1259       if (location_type == PDB_LocType::BitField)
1260         offset += member->getBitPosition();
1261 
1262       layout_info.field_offsets.insert(std::make_pair(decl, offset));
1263 
1264       break;
1265     }
1266     case PDB_DataKind::StaticMember: {
1267       auto decl = ClangASTContext::AddVariableToRecordType(
1268           record_type, member_name.c_str(), member_comp_type, access);
1269       if (!decl)
1270         continue;
1271 
1272       m_uid_to_decl[member->getSymIndexId()] = decl;
1273 
1274       break;
1275     }
1276     default:
1277       llvm_unreachable("unsupported PDB data kind");
1278     }
1279   }
1280 }
1281 
1282 void PDBASTParser::AddRecordBases(
1283     lldb_private::SymbolFile &symbol_file,
1284     lldb_private::CompilerType &record_type, int record_kind,
1285     PDBBaseClassSymbolEnumerator &bases_enum,
1286     lldb_private::ClangASTImporter::LayoutInfo &layout_info) const {
1287   std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> base_classes;
1288 
1289   while (auto base = bases_enum.getNext()) {
1290     auto base_type = symbol_file.ResolveTypeUID(base->getTypeId());
1291     if (!base_type)
1292       continue;
1293 
1294     auto base_comp_type = base_type->GetFullCompilerType();
1295     if (!base_comp_type.GetCompleteType()) {
1296       symbol_file.GetObjectFile()->GetModule()->ReportError(
1297           ":: Class '%s' has a base class '%s' "
1298           "which does not have a complete definition.",
1299           record_type.GetTypeName().GetCString(),
1300           base_comp_type.GetTypeName().GetCString());
1301       if (ClangASTContext::StartTagDeclarationDefinition(base_comp_type))
1302         ClangASTContext::CompleteTagDeclarationDefinition(base_comp_type);
1303     }
1304 
1305     auto access = TranslateMemberAccess(base->getAccess());
1306 
1307     auto is_virtual = base->isVirtualBaseClass();
1308 
1309     std::unique_ptr<clang::CXXBaseSpecifier> base_spec =
1310         m_ast.CreateBaseClassSpecifier(base_comp_type.GetOpaqueQualType(),
1311                                        access, is_virtual,
1312                                        record_kind == clang::TTK_Class);
1313     lldbassert(base_spec);
1314 
1315     base_classes.push_back(std::move(base_spec));
1316 
1317     if (is_virtual)
1318       continue;
1319 
1320     auto decl = m_ast.GetAsCXXRecordDecl(base_comp_type.GetOpaqueQualType());
1321     if (!decl)
1322       continue;
1323 
1324     auto offset = clang::CharUnits::fromQuantity(base->getOffset());
1325     layout_info.base_offsets.insert(std::make_pair(decl, offset));
1326   }
1327 
1328   m_ast.TransferBaseClasses(record_type.GetOpaqueQualType(),
1329                             std::move(base_classes));
1330 }
1331 
1332 void PDBASTParser::AddRecordMethods(lldb_private::SymbolFile &symbol_file,
1333                                     lldb_private::CompilerType &record_type,
1334                                     PDBFuncSymbolEnumerator &methods_enum) {
1335   while (std::unique_ptr<PDBSymbolFunc> method = methods_enum.getNext())
1336     if (clang::CXXMethodDecl *decl =
1337             AddRecordMethod(symbol_file, record_type, *method))
1338       m_uid_to_decl[method->getSymIndexId()] = decl;
1339 }
1340 
1341 clang::CXXMethodDecl *
1342 PDBASTParser::AddRecordMethod(lldb_private::SymbolFile &symbol_file,
1343                               lldb_private::CompilerType &record_type,
1344                               const llvm::pdb::PDBSymbolFunc &method) const {
1345   std::string name = MSVCUndecoratedNameParser::DropScope(method.getName());
1346 
1347   Type *method_type = symbol_file.ResolveTypeUID(method.getSymIndexId());
1348   // MSVC specific __vecDelDtor.
1349   if (!method_type)
1350     return nullptr;
1351 
1352   CompilerType method_comp_type = method_type->GetFullCompilerType();
1353   if (!method_comp_type.GetCompleteType()) {
1354     symbol_file.GetObjectFile()->GetModule()->ReportError(
1355         ":: Class '%s' has a method '%s' whose type cannot be completed.",
1356         record_type.GetTypeName().GetCString(),
1357         method_comp_type.GetTypeName().GetCString());
1358     if (ClangASTContext::StartTagDeclarationDefinition(method_comp_type))
1359       ClangASTContext::CompleteTagDeclarationDefinition(method_comp_type);
1360   }
1361 
1362   AccessType access = TranslateMemberAccess(method.getAccess());
1363   if (access == eAccessNone)
1364     access = eAccessPublic;
1365 
1366   // TODO: get mangled name for the method.
1367   return m_ast.AddMethodToCXXRecordType(
1368       record_type.GetOpaqueQualType(), name.c_str(),
1369       /*mangled_name*/ nullptr, method_comp_type, access, method.isVirtual(),
1370       method.isStatic(), method.hasInlineAttribute(),
1371       /*is_explicit*/ false, // FIXME: Need this field in CodeView.
1372       /*is_attr_used*/ false,
1373       /*is_artificial*/ method.isCompilerGenerated());
1374 }
1375