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