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