1 //===-- PDBASTParser.cpp ----------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "PDBASTParser.h"
11 
12 #include "SymbolFilePDB.h"
13 
14 #include "clang/AST/CharUnits.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclCXX.h"
17 
18 #include "lldb/Core/Module.h"
19 #include "lldb/Symbol/ClangASTContext.h"
20 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
21 #include "lldb/Symbol/ClangUtil.h"
22 #include "lldb/Symbol/Declaration.h"
23 #include "lldb/Symbol/SymbolFile.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 using namespace lldb;
41 using namespace lldb_private;
42 using namespace llvm::pdb;
43 
44 namespace {
45 int TranslateUdtKind(PDB_UdtType pdb_kind) {
46   switch (pdb_kind) {
47   case PDB_UdtType::Class:
48     return clang::TTK_Class;
49   case PDB_UdtType::Struct:
50     return clang::TTK_Struct;
51   case PDB_UdtType::Union:
52     return clang::TTK_Union;
53   case PDB_UdtType::Interface:
54     return clang::TTK_Interface;
55   default:
56     llvm_unreachable("unsuported PDB UDT type");
57   }
58 }
59 
60 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 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 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::Bool:
118     return clang_ast.GetBasicType(eBasicTypeBool);
119   case PDB_BuiltinType::Long:
120     if (width == ast->getTypeSize(ast->LongTy))
121       return CompilerType(ast, ast->LongTy);
122     if (width == ast->getTypeSize(ast->LongLongTy))
123       return CompilerType(ast, ast->LongLongTy);
124     break;
125   case PDB_BuiltinType::ULong:
126     if (width == ast->getTypeSize(ast->UnsignedLongTy))
127       return CompilerType(ast, ast->UnsignedLongTy);
128     if (width == ast->getTypeSize(ast->UnsignedLongLongTy))
129       return CompilerType(ast, ast->UnsignedLongLongTy);
130     break;
131   case PDB_BuiltinType::WCharT:
132     if (width == ast->getTypeSize(ast->WCharTy))
133       return CompilerType(ast, ast->WCharTy);
134     break;
135   case PDB_BuiltinType::Char16:
136     return CompilerType(ast, ast->Char16Ty);
137   case PDB_BuiltinType::Char32:
138     return CompilerType(ast, ast->Char32Ty);
139   case PDB_BuiltinType::Float:
140     // Note: types `long double` and `double` have same bit size in MSVC and
141     // there is no information in the PDB to distinguish them. So when falling
142     // back to default search, the compiler type of `long double` will be
143     // represented by the one generated for `double`.
144     break;
145   }
146   // If there is no match on PDB_BuiltinType, fall back to default search by
147   // encoding and width only
148   return clang_ast.GetBuiltinTypeForEncodingAndBitSize(encoding, width);
149 }
150 
151 ConstString GetPDBBuiltinTypeName(const PDBSymbolTypeBuiltin &pdb_type,
152                                   CompilerType &compiler_type) {
153   PDB_BuiltinType kind = pdb_type.getBuiltinType();
154   switch (kind) {
155   default:
156     break;
157   case PDB_BuiltinType::Currency:
158     return ConstString("CURRENCY");
159   case PDB_BuiltinType::Date:
160     return ConstString("DATE");
161   case PDB_BuiltinType::Variant:
162     return ConstString("VARIANT");
163   case PDB_BuiltinType::Complex:
164     return ConstString("complex");
165   case PDB_BuiltinType::Bitfield:
166     return ConstString("bitfield");
167   case PDB_BuiltinType::BSTR:
168     return ConstString("BSTR");
169   case PDB_BuiltinType::HResult:
170     return ConstString("HRESULT");
171   case PDB_BuiltinType::BCD:
172     return ConstString("BCD");
173   case PDB_BuiltinType::Char16:
174     return ConstString("char16_t");
175   case PDB_BuiltinType::Char32:
176     return ConstString("char32_t");
177   case PDB_BuiltinType::None:
178     return ConstString("...");
179   }
180   return compiler_type.GetTypeName();
181 }
182 
183 bool GetDeclarationForSymbol(const PDBSymbol &symbol, Declaration &decl) {
184   auto &raw_sym = symbol.getRawSymbol();
185   auto first_line_up = raw_sym.getSrcLineOnTypeDefn();
186 
187   if (!first_line_up) {
188     auto lines_up = symbol.getSession().findLineNumbersByAddress(
189         raw_sym.getVirtualAddress(), raw_sym.getLength());
190     if (!lines_up)
191       return false;
192     first_line_up = lines_up->getNext();
193     if (!first_line_up)
194       return false;
195   }
196   uint32_t src_file_id = first_line_up->getSourceFileId();
197   auto src_file_up = symbol.getSession().getSourceFileById(src_file_id);
198   if (!src_file_up)
199     return false;
200 
201   FileSpec spec(src_file_up->getFileName(), /*resolve_path*/ false);
202   decl.SetFile(spec);
203   decl.SetColumn(first_line_up->getColumnNumber());
204   decl.SetLine(first_line_up->getLineNumber());
205   return true;
206 }
207 
208 AccessType TranslateMemberAccess(PDB_MemberAccess access) {
209   switch (access) {
210   case PDB_MemberAccess::Private:
211     return eAccessPrivate;
212   case PDB_MemberAccess::Protected:
213     return eAccessProtected;
214   case PDB_MemberAccess::Public:
215     return eAccessPublic;
216   default:
217     return eAccessNone;
218   }
219 }
220 
221 AccessType GetDefaultAccessibilityForUdtKind(PDB_UdtType udt_kind) {
222   switch (udt_kind) {
223   case PDB_UdtType::Struct:
224   case PDB_UdtType::Union:
225     return eAccessPublic;
226   case PDB_UdtType::Class:
227   case PDB_UdtType::Interface:
228     return eAccessPrivate;
229   default:
230     llvm_unreachable("unsupported PDB UDT type");
231   }
232 }
233 
234 AccessType GetAccessibilityForUdt(const PDBSymbolTypeUDT &udt) {
235   AccessType access = TranslateMemberAccess(udt.getAccess());
236   if (access != lldb::eAccessNone || !udt.isNested())
237     return access;
238 
239   auto parent = udt.getClassParent();
240   if (!parent)
241     return lldb::eAccessNone;
242 
243   auto parent_udt = llvm::dyn_cast<PDBSymbolTypeUDT>(parent.get());
244   if (!parent_udt)
245     return lldb::eAccessNone;
246 
247   return GetDefaultAccessibilityForUdtKind(parent_udt->getUdtKind());
248 }
249 
250 clang::MSInheritanceAttr::Spelling GetMSInheritance(
251     const PDBSymbolTypeUDT &udt) {
252   int base_count = 0;
253   bool has_virtual = false;
254 
255   auto bases_enum = udt.findAllChildren<PDBSymbolTypeBaseClass>();
256   if (bases_enum) {
257     while (auto base = bases_enum->getNext()) {
258       base_count++;
259       has_virtual |= base->isVirtualBaseClass();
260     }
261   }
262 
263   if (has_virtual)
264     return clang::MSInheritanceAttr::Keyword_virtual_inheritance;
265   if (base_count > 1)
266     return clang::MSInheritanceAttr::Keyword_multiple_inheritance;
267   return clang::MSInheritanceAttr::Keyword_single_inheritance;
268 }
269 } // namespace
270 
271 PDBASTParser::PDBASTParser(lldb_private::ClangASTContext &ast) : m_ast(ast) {}
272 
273 PDBASTParser::~PDBASTParser() {}
274 
275 // DebugInfoASTParser interface
276 
277 lldb::TypeSP PDBASTParser::CreateLLDBTypeFromPDBType(const PDBSymbol &type) {
278   // PDB doesn't maintain enough information to robustly rebuild the entire
279   // tree, and this is most problematic when it comes to figure out the right
280   // DeclContext to put a type in.  So for now, everything goes in the
281   // translation unit decl as a fully qualified type.
282   clang::DeclContext *tu_decl_ctx = m_ast.GetTranslationUnitDecl();
283   Declaration decl;
284 
285   switch (type.getSymTag()) {
286   case PDB_SymType::BaseClass: {
287     auto symbol_file = m_ast.GetSymbolFile();
288     if (!symbol_file)
289       return nullptr;
290 
291     auto ty = symbol_file->ResolveTypeUID(type.getRawSymbol().getTypeId());
292     return ty ? ty->shared_from_this() : nullptr;
293   } break;
294   case PDB_SymType::UDT: {
295     auto udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&type);
296     assert(udt);
297 
298     // Note that, unnamed UDT being typedef-ed is generated as a UDT symbol
299     // other than a Typedef symbol in PDB. For example,
300     //    typedef union { short Row; short Col; } Union;
301     // is generated as a named UDT in PDB:
302     //    union Union { short Row; short Col; }
303     // Such symbols will be handled here.
304 
305     // Some UDT with trival ctor has zero length. Just ignore.
306     if (udt->getLength() == 0)
307       return nullptr;
308 
309     // Ignore unnamed-tag UDTs.
310     if (udt->getName().empty())
311       return nullptr;
312 
313     auto access = GetAccessibilityForUdt(*udt);
314 
315     auto tag_type_kind = TranslateUdtKind(udt->getUdtKind());
316 
317     ClangASTMetadata metadata;
318     metadata.SetUserID(type.getSymIndexId());
319     metadata.SetIsDynamicCXXType(false);
320 
321     CompilerType clang_type = m_ast.CreateRecordType(
322         tu_decl_ctx, access, udt->getName().c_str(), tag_type_kind,
323         lldb::eLanguageTypeC_plus_plus, &metadata);
324     assert(clang_type.IsValid());
325 
326     if (udt->isConstType())
327       clang_type = clang_type.AddConstModifier();
328 
329     if (udt->isVolatileType())
330       clang_type = clang_type.AddVolatileModifier();
331 
332     clang::CXXRecordDecl *record_decl =
333       m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
334     assert(record_decl);
335     auto inheritance_attr = clang::MSInheritanceAttr::CreateImplicit(
336         *m_ast.getASTContext(), GetMSInheritance(*udt));
337     record_decl->addAttr(inheritance_attr);
338 
339     ClangASTContext::StartTagDeclarationDefinition(clang_type);
340 
341     Type::ResolveStateTag type_resolve_state_tag;
342     auto children = udt->findAllChildren();
343     if (!children || children->getChildCount() == 0) {
344       // PDB does not have symbol of forwarder. We assume we get an udt w/o any
345       // fields. Just complete it at this point.
346       ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
347 
348       m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), false);
349 
350       type_resolve_state_tag = Type::eResolveStateFull;
351     } else {
352       // Add the type to the forward declarations. It will help us to avoid
353       // an endless recursion in CompleteTypeFromUdt function.
354       auto clang_type_removed_fast_quals =
355           ClangUtil::RemoveFastQualifiers(clang_type).GetOpaqueQualType();
356       m_forward_decl_clang_type_to_uid[clang_type_removed_fast_quals] =
357           type.getSymIndexId();
358 
359       m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), true);
360 
361       type_resolve_state_tag = Type::eResolveStateForward;
362     }
363 
364     GetDeclarationForSymbol(type, decl);
365     return std::make_shared<lldb_private::Type>(
366         type.getSymIndexId(), m_ast.GetSymbolFile(),
367         ConstString(udt->getName()), udt->getLength(), nullptr,
368         LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, clang_type,
369         type_resolve_state_tag);
370   } break;
371   case PDB_SymType::Enum: {
372     auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(&type);
373     assert(enum_type);
374     auto underlying_type_up = enum_type->getUnderlyingType();
375     if (!underlying_type_up)
376       return nullptr;
377     lldb::Encoding encoding =
378         TranslateBuiltinEncoding(underlying_type_up->getBuiltinType());
379     // FIXME: Type of underlying builtin is always `Int`. We correct it with
380     // the very first enumerator's encoding if any.
381     auto first_child = enum_type->findOneChild<PDBSymbolData>();
382     if (first_child) {
383       encoding = TranslateEnumEncoding(first_child->getValue().Type);
384     }
385     std::string name = enum_type->getName();
386     uint64_t bytes = enum_type->getLength();
387     CompilerType builtin_type;
388     if (bytes > 0)
389       builtin_type = GetBuiltinTypeForPDBEncodingAndBitSize(
390           m_ast, *underlying_type_up, encoding, bytes * 8);
391     else
392       builtin_type = m_ast.GetBasicType(eBasicTypeInt);
393     // FIXME: PDB does not have information about scoped enumeration (Enum
394     // Class). Set it false for now.
395     bool isScoped = false;
396 
397     CompilerType ast_enum = m_ast.CreateEnumerationType(
398         name.c_str(), tu_decl_ctx, decl, builtin_type, isScoped);
399     auto enum_values = enum_type->findAllChildren<PDBSymbolData>();
400     if (enum_values) {
401       while (auto enum_value = enum_values->getNext()) {
402         if (enum_value->getDataKind() != PDB_DataKind::Constant)
403           continue;
404         AddEnumValue(ast_enum, *enum_value);
405       }
406     }
407     if (ClangASTContext::StartTagDeclarationDefinition(ast_enum))
408       ClangASTContext::CompleteTagDeclarationDefinition(ast_enum);
409 
410     GetDeclarationForSymbol(type, decl);
411     return std::make_shared<lldb_private::Type>(
412         type.getSymIndexId(), m_ast.GetSymbolFile(), ConstString(name), bytes,
413         nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
414         ast_enum, lldb_private::Type::eResolveStateFull);
415   } break;
416   case PDB_SymType::Typedef: {
417     auto type_def = llvm::dyn_cast<PDBSymbolTypeTypedef>(&type);
418     assert(type_def);
419     lldb_private::Type *target_type =
420         m_ast.GetSymbolFile()->ResolveTypeUID(type_def->getTypeId());
421     if (!target_type)
422       return nullptr;
423     std::string name = type_def->getName();
424     uint64_t bytes = type_def->getLength();
425     CompilerType target_ast_type = target_type->GetFullCompilerType();
426     CompilerDeclContext target_decl_ctx =
427         m_ast.GetSymbolFile()->GetDeclContextForUID(target_type->GetID());
428     CompilerType ast_typedef =
429         m_ast.CreateTypedefType(target_ast_type, name.c_str(), target_decl_ctx);
430     if (!ast_typedef)
431       return nullptr;
432 
433     return std::make_shared<lldb_private::Type>(
434         type_def->getSymIndexId(), m_ast.GetSymbolFile(), ConstString(name),
435         bytes, nullptr, target_type->GetID(),
436         lldb_private::Type::eEncodingIsTypedefUID, decl, ast_typedef,
437         lldb_private::Type::eResolveStateFull);
438   } break;
439   case PDB_SymType::Function:
440   case PDB_SymType::FunctionSig: {
441     std::string name;
442     PDBSymbolTypeFunctionSig *func_sig = nullptr;
443     if (auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(&type)) {
444       if (pdb_func->isCompilerGenerated())
445         return nullptr;
446 
447       auto sig = pdb_func->getSignature();
448       if (!sig)
449         return nullptr;
450       func_sig = sig.release();
451       // Function type is named.
452       name = pdb_func->getName();
453     } else if (auto pdb_func_sig =
454                    llvm::dyn_cast<PDBSymbolTypeFunctionSig>(&type)) {
455       func_sig = const_cast<PDBSymbolTypeFunctionSig *>(pdb_func_sig);
456     } else
457       llvm_unreachable("Unexpected PDB symbol!");
458 
459     auto arg_enum = func_sig->getArguments();
460     uint32_t num_args = arg_enum->getChildCount();
461     std::vector<CompilerType> arg_list;
462 
463     bool is_variadic = func_sig->isCVarArgs();
464     // Drop last variadic argument.
465     if (is_variadic)
466       --num_args;
467     for (uint32_t arg_idx = 0; arg_idx < num_args; arg_idx++) {
468       auto arg = arg_enum->getChildAtIndex(arg_idx);
469       if (!arg)
470         break;
471       lldb_private::Type *arg_type =
472           m_ast.GetSymbolFile()->ResolveTypeUID(arg->getSymIndexId());
473       // If there's some error looking up one of the dependent types of this
474       // function signature, bail.
475       if (!arg_type)
476         return nullptr;
477       CompilerType arg_ast_type = arg_type->GetFullCompilerType();
478       arg_list.push_back(arg_ast_type);
479     }
480     lldbassert(arg_list.size() <= num_args);
481 
482     auto pdb_return_type = func_sig->getReturnType();
483     lldb_private::Type *return_type =
484         m_ast.GetSymbolFile()->ResolveTypeUID(pdb_return_type->getSymIndexId());
485     // If there's some error looking up one of the dependent types of this
486     // function signature, bail.
487     if (!return_type)
488       return nullptr;
489     CompilerType return_ast_type = return_type->GetFullCompilerType();
490     uint32_t type_quals = 0;
491     if (func_sig->isConstType())
492       type_quals |= clang::Qualifiers::Const;
493     if (func_sig->isVolatileType())
494       type_quals |= clang::Qualifiers::Volatile;
495     CompilerType func_sig_ast_type =
496         m_ast.CreateFunctionType(return_ast_type, arg_list.data(),
497                                  arg_list.size(), is_variadic, type_quals);
498 
499     GetDeclarationForSymbol(type, decl);
500     return std::make_shared<lldb_private::Type>(
501         type.getSymIndexId(), m_ast.GetSymbolFile(), ConstString(name), 0,
502         nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
503         func_sig_ast_type, lldb_private::Type::eResolveStateFull);
504   } break;
505   case PDB_SymType::ArrayType: {
506     auto array_type = llvm::dyn_cast<PDBSymbolTypeArray>(&type);
507     assert(array_type);
508     uint32_t num_elements = array_type->getCount();
509     uint32_t element_uid = array_type->getElementTypeId();
510     uint32_t bytes = array_type->getLength();
511 
512     // If array rank > 0, PDB gives the element type at N=0. So element type
513     // will parsed in the order N=0, N=1,..., N=rank sequentially.
514     lldb_private::Type *element_type =
515         m_ast.GetSymbolFile()->ResolveTypeUID(element_uid);
516     if (!element_type)
517       return nullptr;
518 
519     CompilerType element_ast_type = element_type->GetForwardCompilerType();
520     // If element type is UDT, it needs to be complete.
521     if (ClangASTContext::IsCXXClassType(element_ast_type) &&
522         element_ast_type.GetCompleteType() == false) {
523       if (ClangASTContext::StartTagDeclarationDefinition(element_ast_type)) {
524         ClangASTContext::CompleteTagDeclarationDefinition(element_ast_type);
525       } else {
526         // We are not able to start defintion.
527         return nullptr;
528       }
529     }
530     CompilerType array_ast_type = m_ast.CreateArrayType(
531         element_ast_type, num_elements, /*is_gnu_vector*/ false);
532     TypeSP type_sp = std::make_shared<lldb_private::Type>(
533         array_type->getSymIndexId(), m_ast.GetSymbolFile(), ConstString(),
534         bytes, nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID,
535         decl, array_ast_type, lldb_private::Type::eResolveStateFull);
536     type_sp->SetEncodingType(element_type);
537     return type_sp;
538   } break;
539   case PDB_SymType::BuiltinType: {
540     auto *builtin_type = llvm::dyn_cast<PDBSymbolTypeBuiltin>(&type);
541     assert(builtin_type);
542     PDB_BuiltinType builtin_kind = builtin_type->getBuiltinType();
543     if (builtin_kind == PDB_BuiltinType::None)
544       return nullptr;
545 
546     uint64_t bytes = builtin_type->getLength();
547     Encoding encoding = TranslateBuiltinEncoding(builtin_kind);
548     CompilerType builtin_ast_type = GetBuiltinTypeForPDBEncodingAndBitSize(
549         m_ast, *builtin_type, encoding, bytes * 8);
550 
551     if (builtin_type->isConstType())
552       builtin_ast_type = builtin_ast_type.AddConstModifier();
553 
554     if (builtin_type->isVolatileType())
555       builtin_ast_type = builtin_ast_type.AddVolatileModifier();
556 
557     auto type_name = GetPDBBuiltinTypeName(*builtin_type, builtin_ast_type);
558 
559     return std::make_shared<lldb_private::Type>(
560         builtin_type->getSymIndexId(), m_ast.GetSymbolFile(), type_name, bytes,
561         nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
562         builtin_ast_type, lldb_private::Type::eResolveStateFull);
563   } break;
564   case PDB_SymType::PointerType: {
565     auto *pointer_type = llvm::dyn_cast<PDBSymbolTypePointer>(&type);
566     assert(pointer_type);
567     Type *pointee_type = m_ast.GetSymbolFile()->ResolveTypeUID(
568         pointer_type->getPointeeType()->getSymIndexId());
569     if (!pointee_type)
570       return nullptr;
571 
572     if (pointer_type->isPointerToDataMember() ||
573         pointer_type->isPointerToMemberFunction()) {
574       auto class_parent_uid = pointer_type->getRawSymbol().getClassParentId();
575       auto class_parent_type =
576           m_ast.GetSymbolFile()->ResolveTypeUID(class_parent_uid);
577       assert(class_parent_type);
578 
579       CompilerType pointer_ast_type;
580       pointer_ast_type = ClangASTContext::CreateMemberPointerType(
581           class_parent_type->GetLayoutCompilerType(),
582           pointee_type->GetForwardCompilerType());
583       assert(pointer_ast_type);
584 
585       return std::make_shared<lldb_private::Type>(
586           pointer_type->getSymIndexId(), m_ast.GetSymbolFile(), ConstString(),
587           pointer_type->getLength(), nullptr, LLDB_INVALID_UID,
588           lldb_private::Type::eEncodingIsUID, decl, pointer_ast_type,
589           lldb_private::Type::eResolveStateForward);
590     }
591 
592     CompilerType pointer_ast_type;
593     pointer_ast_type = pointee_type->GetFullCompilerType();
594     if (pointer_type->isReference())
595       pointer_ast_type = pointer_ast_type.GetLValueReferenceType();
596     else if (pointer_type->isRValueReference())
597       pointer_ast_type = pointer_ast_type.GetRValueReferenceType();
598     else
599       pointer_ast_type = pointer_ast_type.GetPointerType();
600 
601     if (pointer_type->isConstType())
602       pointer_ast_type = pointer_ast_type.AddConstModifier();
603 
604     if (pointer_type->isVolatileType())
605       pointer_ast_type = pointer_ast_type.AddVolatileModifier();
606 
607     if (pointer_type->isRestrictedType())
608       pointer_ast_type = pointer_ast_type.AddRestrictModifier();
609 
610     return std::make_shared<lldb_private::Type>(
611         pointer_type->getSymIndexId(), m_ast.GetSymbolFile(), ConstString(),
612         pointer_type->getLength(), nullptr, LLDB_INVALID_UID,
613         lldb_private::Type::eEncodingIsUID, decl, pointer_ast_type,
614         lldb_private::Type::eResolveStateFull);
615   } break;
616   default:
617     break;
618   }
619   return nullptr;
620 }
621 
622 bool PDBASTParser::CompleteTypeFromPDB(
623     lldb_private::CompilerType &compiler_type) {
624   if (GetClangASTImporter().CanImport(compiler_type))
625     return GetClangASTImporter().CompleteType(compiler_type);
626 
627   // Remove the type from the forward declarations to avoid
628   // an endless recursion for types like a linked list.
629   CompilerType compiler_type_no_qualifiers =
630       ClangUtil::RemoveFastQualifiers(compiler_type);
631   auto uid_it = m_forward_decl_clang_type_to_uid.find(
632       compiler_type_no_qualifiers.GetOpaqueQualType());
633   if (uid_it == m_forward_decl_clang_type_to_uid.end())
634     return true;
635 
636   auto symbol_file = static_cast<SymbolFilePDB *>(m_ast.GetSymbolFile());
637   if (!symbol_file)
638     return false;
639 
640   std::unique_ptr<PDBSymbol> symbol =
641       symbol_file->GetPDBSession().getSymbolById(uid_it->getSecond());
642   if (!symbol)
643     return false;
644 
645   m_forward_decl_clang_type_to_uid.erase(uid_it);
646 
647   ClangASTContext::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),
648                                          false);
649 
650   switch (symbol->getSymTag()) {
651   case PDB_SymType::UDT: {
652     auto udt = llvm::dyn_cast<PDBSymbolTypeUDT>(symbol.get());
653     if (!udt)
654       return false;
655 
656     return CompleteTypeFromUDT(*symbol_file, compiler_type, *udt);
657   }
658   default:
659     llvm_unreachable("not a forward clang type decl!");
660   }
661 }
662 
663 bool PDBASTParser::AddEnumValue(CompilerType enum_type,
664                                 const PDBSymbolData &enum_value) const {
665   Declaration decl;
666   Variant v = enum_value.getValue();
667   std::string name = enum_value.getName();
668   int64_t raw_value;
669   switch (v.Type) {
670   case PDB_VariantType::Int8:
671     raw_value = v.Value.Int8;
672     break;
673   case PDB_VariantType::Int16:
674     raw_value = v.Value.Int16;
675     break;
676   case PDB_VariantType::Int32:
677     raw_value = v.Value.Int32;
678     break;
679   case PDB_VariantType::Int64:
680     raw_value = v.Value.Int64;
681     break;
682   case PDB_VariantType::UInt8:
683     raw_value = v.Value.UInt8;
684     break;
685   case PDB_VariantType::UInt16:
686     raw_value = v.Value.UInt16;
687     break;
688   case PDB_VariantType::UInt32:
689     raw_value = v.Value.UInt32;
690     break;
691   case PDB_VariantType::UInt64:
692     raw_value = v.Value.UInt64;
693     break;
694   default:
695     return false;
696   }
697   CompilerType underlying_type =
698       m_ast.GetEnumerationIntegerType(enum_type.GetOpaqueQualType());
699   uint32_t byte_size = m_ast.getASTContext()->getTypeSize(
700       ClangUtil::GetQualType(underlying_type));
701   return m_ast.AddEnumerationValueToEnumerationType(
702       enum_type.GetOpaqueQualType(), underlying_type, decl, name.c_str(),
703       raw_value, byte_size * 8);
704 }
705 
706 bool PDBASTParser::CompleteTypeFromUDT(
707     lldb_private::SymbolFile &symbol_file,
708     lldb_private::CompilerType &compiler_type,
709     llvm::pdb::PDBSymbolTypeUDT &udt) {
710   ClangASTImporter::LayoutInfo layout_info;
711   layout_info.bit_size = udt.getLength() * 8;
712 
713   auto nested_enums = udt.findAllChildren<PDBSymbolTypeUDT>();
714   if (nested_enums)
715     while (auto nested = nested_enums->getNext())
716       symbol_file.ResolveTypeUID(nested->getSymIndexId());
717 
718   auto bases_enum = udt.findAllChildren<PDBSymbolTypeBaseClass>();
719   if (bases_enum)
720     AddRecordBases(symbol_file, compiler_type,
721                    TranslateUdtKind(udt.getUdtKind()), *bases_enum,
722                    layout_info);
723 
724   auto members_enum = udt.findAllChildren<PDBSymbolData>();
725   if (members_enum)
726     AddRecordMembers(symbol_file, compiler_type, *members_enum, layout_info);
727 
728   auto methods_enum = udt.findAllChildren<PDBSymbolFunc>();
729   if (methods_enum)
730     AddRecordMethods(symbol_file, compiler_type, *methods_enum);
731 
732   m_ast.AddMethodOverridesForCXXRecordType(compiler_type.GetOpaqueQualType());
733   ClangASTContext::BuildIndirectFields(compiler_type);
734   ClangASTContext::CompleteTagDeclarationDefinition(compiler_type);
735 
736   clang::CXXRecordDecl *record_decl =
737       m_ast.GetAsCXXRecordDecl(compiler_type.GetOpaqueQualType());
738   if (!record_decl)
739     return static_cast<bool>(compiler_type);
740 
741   GetClangASTImporter().InsertRecordDecl(record_decl, layout_info);
742 
743   return static_cast<bool>(compiler_type);
744 }
745 
746 void PDBASTParser::AddRecordMembers(
747     lldb_private::SymbolFile &symbol_file,
748     lldb_private::CompilerType &record_type,
749     PDBDataSymbolEnumerator &members_enum,
750     lldb_private::ClangASTImporter::LayoutInfo &layout_info) const {
751   while (auto member = members_enum.getNext()) {
752     if (member->isCompilerGenerated())
753         continue;
754 
755     auto member_name = member->getName();
756 
757     auto member_type = symbol_file.ResolveTypeUID(member->getTypeId());
758     if (!member_type)
759       continue;
760 
761     auto member_comp_type = member_type->GetLayoutCompilerType();
762     if (!member_comp_type.GetCompleteType()) {
763       symbol_file.GetObjectFile()->GetModule()->ReportError(
764           ":: Class '%s' has a member '%s' of type '%s' "
765           "which does not have a complete definition.",
766           record_type.GetTypeName().GetCString(), member_name.c_str(),
767           member_comp_type.GetTypeName().GetCString());
768       if (ClangASTContext::StartTagDeclarationDefinition(member_comp_type))
769         ClangASTContext::CompleteTagDeclarationDefinition(member_comp_type);
770     }
771 
772     auto access = TranslateMemberAccess(member->getAccess());
773 
774     switch (member->getDataKind()) {
775     case PDB_DataKind::Member: {
776       auto location_type = member->getLocationType();
777 
778       auto bit_size = member->getLength();
779       if (location_type == PDB_LocType::ThisRel)
780         bit_size *= 8;
781 
782       auto decl = ClangASTContext::AddFieldToRecordType(
783           record_type, member_name.c_str(), member_comp_type, access, bit_size);
784       if (!decl)
785         continue;
786 
787       auto offset = member->getOffset() * 8;
788       if (location_type == PDB_LocType::BitField)
789         offset += member->getBitPosition();
790 
791       layout_info.field_offsets.insert(std::make_pair(decl, offset));
792 
793       break;
794     }
795     case PDB_DataKind::StaticMember:
796       ClangASTContext::AddVariableToRecordType(record_type, member_name.c_str(),
797                                                member_comp_type, access);
798       break;
799     default:
800       llvm_unreachable("unsupported PDB data kind");
801     }
802   }
803 }
804 
805 void PDBASTParser::AddRecordBases(
806     lldb_private::SymbolFile &symbol_file,
807     lldb_private::CompilerType &record_type, int record_kind,
808     PDBBaseClassSymbolEnumerator &bases_enum,
809     lldb_private::ClangASTImporter::LayoutInfo &layout_info) const {
810   std::vector<clang::CXXBaseSpecifier *> base_classes;
811   while (auto base = bases_enum.getNext()) {
812     auto base_type = symbol_file.ResolveTypeUID(base->getTypeId());
813     if (!base_type)
814       continue;
815 
816     auto base_comp_type = base_type->GetFullCompilerType();
817     if (!base_comp_type.GetCompleteType()) {
818       symbol_file.GetObjectFile()->GetModule()->ReportError(
819           ":: Class '%s' has a base class '%s' "
820           "which does not have a complete definition.",
821           record_type.GetTypeName().GetCString(),
822           base_comp_type.GetTypeName().GetCString());
823       if (ClangASTContext::StartTagDeclarationDefinition(base_comp_type))
824         ClangASTContext::CompleteTagDeclarationDefinition(base_comp_type);
825     }
826 
827     auto access = TranslateMemberAccess(base->getAccess());
828 
829     auto is_virtual = base->isVirtualBaseClass();
830 
831     auto base_class_spec = m_ast.CreateBaseClassSpecifier(
832         base_comp_type.GetOpaqueQualType(), access, is_virtual,
833         record_kind == clang::TTK_Class);
834     if (!base_class_spec)
835         continue;
836 
837     base_classes.push_back(base_class_spec);
838 
839     if (is_virtual)
840         continue;
841 
842     auto decl = m_ast.GetAsCXXRecordDecl(base_comp_type.GetOpaqueQualType());
843     if (!decl)
844       continue;
845 
846     auto offset = clang::CharUnits::fromQuantity(base->getOffset());
847     layout_info.base_offsets.insert(std::make_pair(decl, offset));
848   }
849   if (!base_classes.empty()) {
850     m_ast.SetBaseClassesForClassType(record_type.GetOpaqueQualType(),
851                                      &base_classes.front(),
852                                      base_classes.size());
853     ClangASTContext::DeleteBaseClassSpecifiers(&base_classes.front(),
854                                                base_classes.size());
855   }
856 }
857 
858 void PDBASTParser::AddRecordMethods(
859     lldb_private::SymbolFile &symbol_file,
860     lldb_private::CompilerType &record_type,
861     PDBFuncSymbolEnumerator &methods_enum) const {
862   while (auto method = methods_enum.getNext()) {
863     auto method_type = symbol_file.ResolveTypeUID(method->getSymIndexId());
864     // MSVC specific __vecDelDtor.
865     if (!method_type)
866       break;
867 
868     auto method_comp_type = method_type->GetFullCompilerType();
869     if (!method_comp_type.GetCompleteType()) {
870       symbol_file.GetObjectFile()->GetModule()->ReportError(
871           ":: Class '%s' has a method '%s' whose type cannot be completed.",
872           record_type.GetTypeName().GetCString(),
873           method_comp_type.GetTypeName().GetCString());
874       if (ClangASTContext::StartTagDeclarationDefinition(method_comp_type))
875         ClangASTContext::CompleteTagDeclarationDefinition(method_comp_type);
876     }
877 
878     // TODO: get mangled name for the method.
879     m_ast.AddMethodToCXXRecordType(
880         record_type.GetOpaqueQualType(), method->getName().c_str(),
881         /*mangled_name*/ nullptr, method_comp_type,
882         TranslateMemberAccess(method->getAccess()), method->isVirtual(),
883         method->isStatic(), method->hasInlineAttribute(),
884         /*is_explicit*/ false, // FIXME: Need this field in CodeView.
885         /*is_attr_used*/ false,
886         /*is_artificial*/ method->isCompilerGenerated());
887   }
888 }
889