1 //===-- DWARFASTParserClang.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 <cstdlib>
10
11 #include "DWARFASTParser.h"
12 #include "DWARFASTParserClang.h"
13 #include "DWARFDebugInfo.h"
14 #include "DWARFDeclContext.h"
15 #include "DWARFDefines.h"
16 #include "SymbolFileDWARF.h"
17 #include "SymbolFileDWARFDebugMap.h"
18 #include "SymbolFileDWARFDwo.h"
19 #include "UniqueDWARFASTType.h"
20
21 #include "Plugins/ExpressionParser/Clang/ClangASTImporter.h"
22 #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
23 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
24 #include "Plugins/Language/ObjC/ObjCLanguage.h"
25 #include "lldb/Core/Module.h"
26 #include "lldb/Core/Value.h"
27 #include "lldb/Host/Host.h"
28 #include "lldb/Symbol/CompileUnit.h"
29 #include "lldb/Symbol/Function.h"
30 #include "lldb/Symbol/ObjectFile.h"
31 #include "lldb/Symbol/SymbolFile.h"
32 #include "lldb/Symbol/TypeList.h"
33 #include "lldb/Symbol/TypeMap.h"
34 #include "lldb/Target/Language.h"
35 #include "lldb/Utility/LLDBAssert.h"
36 #include "lldb/Utility/Log.h"
37 #include "lldb/Utility/StreamString.h"
38
39 #include "llvm/Demangle/Demangle.h"
40
41 #include "clang/AST/CXXInheritance.h"
42 #include "clang/AST/DeclCXX.h"
43 #include "clang/AST/DeclObjC.h"
44 #include "clang/AST/DeclTemplate.h"
45
46 #include <map>
47 #include <memory>
48 #include <vector>
49
50 //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
51
52 #ifdef ENABLE_DEBUG_PRINTF
53 #include <cstdio>
54 #define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
55 #else
56 #define DEBUG_PRINTF(fmt, ...)
57 #endif
58
59 using namespace lldb;
60 using namespace lldb_private;
61 using namespace lldb_private::dwarf;
DWARFASTParserClang(TypeSystemClang & ast)62 DWARFASTParserClang::DWARFASTParserClang(TypeSystemClang &ast)
63 : m_ast(ast), m_die_to_decl_ctx(), m_decl_ctx_to_die() {}
64
65 DWARFASTParserClang::~DWARFASTParserClang() = default;
66
DeclKindIsCXXClass(clang::Decl::Kind decl_kind)67 static bool DeclKindIsCXXClass(clang::Decl::Kind decl_kind) {
68 switch (decl_kind) {
69 case clang::Decl::CXXRecord:
70 case clang::Decl::ClassTemplateSpecialization:
71 return true;
72 default:
73 break;
74 }
75 return false;
76 }
77
78
GetClangASTImporter()79 ClangASTImporter &DWARFASTParserClang::GetClangASTImporter() {
80 if (!m_clang_ast_importer_up) {
81 m_clang_ast_importer_up = std::make_unique<ClangASTImporter>();
82 }
83 return *m_clang_ast_importer_up;
84 }
85
86 /// Detect a forward declaration that is nested in a DW_TAG_module.
IsClangModuleFwdDecl(const DWARFDIE & Die)87 static bool IsClangModuleFwdDecl(const DWARFDIE &Die) {
88 if (!Die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0))
89 return false;
90 auto Parent = Die.GetParent();
91 while (Parent.IsValid()) {
92 if (Parent.Tag() == DW_TAG_module)
93 return true;
94 Parent = Parent.GetParent();
95 }
96 return false;
97 }
98
GetContainingClangModuleDIE(const DWARFDIE & die)99 static DWARFDIE GetContainingClangModuleDIE(const DWARFDIE &die) {
100 if (die.IsValid()) {
101 DWARFDIE top_module_die;
102 // Now make sure this DIE is scoped in a DW_TAG_module tag and return true
103 // if so
104 for (DWARFDIE parent = die.GetParent(); parent.IsValid();
105 parent = parent.GetParent()) {
106 const dw_tag_t tag = parent.Tag();
107 if (tag == DW_TAG_module)
108 top_module_die = parent;
109 else if (tag == DW_TAG_compile_unit || tag == DW_TAG_partial_unit)
110 break;
111 }
112
113 return top_module_die;
114 }
115 return DWARFDIE();
116 }
117
GetContainingClangModule(const DWARFDIE & die)118 static lldb::ModuleSP GetContainingClangModule(const DWARFDIE &die) {
119 if (die.IsValid()) {
120 DWARFDIE clang_module_die = GetContainingClangModuleDIE(die);
121
122 if (clang_module_die) {
123 const char *module_name = clang_module_die.GetName();
124 if (module_name)
125 return die.GetDWARF()->GetExternalModule(
126 lldb_private::ConstString(module_name));
127 }
128 }
129 return lldb::ModuleSP();
130 }
131
ParseTypeFromClangModule(const SymbolContext & sc,const DWARFDIE & die,Log * log)132 TypeSP DWARFASTParserClang::ParseTypeFromClangModule(const SymbolContext &sc,
133 const DWARFDIE &die,
134 Log *log) {
135 ModuleSP clang_module_sp = GetContainingClangModule(die);
136 if (!clang_module_sp)
137 return TypeSP();
138
139 // If this type comes from a Clang module, recursively look in the
140 // DWARF section of the .pcm file in the module cache. Clang
141 // generates DWO skeleton units as breadcrumbs to find them.
142 llvm::SmallVector<CompilerContext, 4> decl_context;
143 die.GetDeclContext(decl_context);
144 TypeMap pcm_types;
145
146 // The type in the Clang module must have the same language as the current CU.
147 LanguageSet languages;
148 languages.Insert(SymbolFileDWARF::GetLanguageFamily(*die.GetCU()));
149 llvm::DenseSet<SymbolFile *> searched_symbol_files;
150 clang_module_sp->GetSymbolFile()->FindTypes(decl_context, languages,
151 searched_symbol_files, pcm_types);
152 if (pcm_types.Empty()) {
153 // Since this type is defined in one of the Clang modules imported
154 // by this symbol file, search all of them. Instead of calling
155 // sym_file->FindTypes(), which would return this again, go straight
156 // to the imported modules.
157 auto &sym_file = die.GetCU()->GetSymbolFileDWARF();
158
159 // Well-formed clang modules never form cycles; guard against corrupted
160 // ones by inserting the current file.
161 searched_symbol_files.insert(&sym_file);
162 sym_file.ForEachExternalModule(
163 *sc.comp_unit, searched_symbol_files, [&](Module &module) {
164 module.GetSymbolFile()->FindTypes(decl_context, languages,
165 searched_symbol_files, pcm_types);
166 return pcm_types.GetSize();
167 });
168 }
169
170 if (!pcm_types.GetSize())
171 return TypeSP();
172
173 // We found a real definition for this type in the Clang module, so lets use
174 // it and cache the fact that we found a complete type for this die.
175 TypeSP pcm_type_sp = pcm_types.GetTypeAtIndex(0);
176 if (!pcm_type_sp)
177 return TypeSP();
178
179 lldb_private::CompilerType pcm_type = pcm_type_sp->GetForwardCompilerType();
180 lldb_private::CompilerType type =
181 GetClangASTImporter().CopyType(m_ast, pcm_type);
182
183 if (!type)
184 return TypeSP();
185
186 // Under normal operation pcm_type is a shallow forward declaration
187 // that gets completed later. This is necessary to support cyclic
188 // data structures. If, however, pcm_type is already complete (for
189 // example, because it was loaded for a different target before),
190 // the definition needs to be imported right away, too.
191 // Type::ResolveClangType() effectively ignores the ResolveState
192 // inside type_sp and only looks at IsDefined(), so it never calls
193 // ClangASTImporter::ASTImporterDelegate::ImportDefinitionTo(),
194 // which does extra work for Objective-C classes. This would result
195 // in only the forward declaration to be visible.
196 if (pcm_type.IsDefined())
197 GetClangASTImporter().RequireCompleteType(ClangUtil::GetQualType(type));
198
199 SymbolFileDWARF *dwarf = die.GetDWARF();
200 TypeSP type_sp(new Type(die.GetID(), dwarf, pcm_type_sp->GetName(),
201 pcm_type_sp->GetByteSize(nullptr), nullptr,
202 LLDB_INVALID_UID, Type::eEncodingInvalid,
203 &pcm_type_sp->GetDeclaration(), type,
204 Type::ResolveState::Forward,
205 TypePayloadClang(GetOwningClangModule(die))));
206
207 dwarf->GetTypeList().Insert(type_sp);
208 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
209 clang::TagDecl *tag_decl = TypeSystemClang::GetAsTagDecl(type);
210 if (tag_decl) {
211 LinkDeclContextToDIE(tag_decl, die);
212 } else {
213 clang::DeclContext *defn_decl_ctx = GetCachedClangDeclContextForDIE(die);
214 if (defn_decl_ctx)
215 LinkDeclContextToDIE(defn_decl_ctx, die);
216 }
217
218 return type_sp;
219 }
220
ForcefullyCompleteType(CompilerType type)221 static void ForcefullyCompleteType(CompilerType type) {
222 bool started = TypeSystemClang::StartTagDeclarationDefinition(type);
223 lldbassert(started && "Unable to start a class type definition.");
224 TypeSystemClang::CompleteTagDeclarationDefinition(type);
225 const clang::TagDecl *td = ClangUtil::GetAsTagDecl(type);
226 auto &ts = llvm::cast<TypeSystemClang>(*type.GetTypeSystem());
227 ts.GetMetadata(td)->SetIsForcefullyCompleted();
228 }
229
230 /// Complete a type from debug info, or mark it as forcefully completed if
231 /// there is no definition of the type in the current Module. Call this function
232 /// in contexts where the usual C++ rules require a type to be complete (base
233 /// class, member, etc.).
RequireCompleteType(CompilerType type)234 static void RequireCompleteType(CompilerType type) {
235 // Technically, enums can be incomplete too, but we don't handle those as they
236 // are emitted even under -flimit-debug-info.
237 if (!TypeSystemClang::IsCXXClassType(type))
238 return;
239
240 if (type.GetCompleteType())
241 return;
242
243 // No complete definition in this module. Mark the class as complete to
244 // satisfy local ast invariants, but make a note of the fact that
245 // it is not _really_ complete so we can later search for a definition in a
246 // different module.
247 // Since we provide layout assistance, layouts of types containing this class
248 // will be correct even if we are not able to find the definition elsewhere.
249 ForcefullyCompleteType(type);
250 }
251
252 /// This function serves a similar purpose as RequireCompleteType above, but it
253 /// avoids completing the type if it is not immediately necessary. It only
254 /// ensures we _can_ complete the type later.
PrepareContextToReceiveMembers(TypeSystemClang & ast,ClangASTImporter & ast_importer,clang::DeclContext * decl_ctx,DWARFDIE die,const char * type_name_cstr)255 static void PrepareContextToReceiveMembers(TypeSystemClang &ast,
256 ClangASTImporter &ast_importer,
257 clang::DeclContext *decl_ctx,
258 DWARFDIE die,
259 const char *type_name_cstr) {
260 auto *tag_decl_ctx = clang::dyn_cast<clang::TagDecl>(decl_ctx);
261 if (!tag_decl_ctx)
262 return; // Non-tag context are always ready.
263
264 // We have already completed the type, or we have found its definition and are
265 // ready to complete it later (cf. ParseStructureLikeDIE).
266 if (tag_decl_ctx->isCompleteDefinition() || tag_decl_ctx->isBeingDefined())
267 return;
268
269 // We reach this point of the tag was present in the debug info as a
270 // declaration only. If it was imported from another AST context (in the
271 // gmodules case), we can complete the type by doing a full import.
272
273 // If this type was not imported from an external AST, there's nothing to do.
274 CompilerType type = ast.GetTypeForDecl(tag_decl_ctx);
275 if (type && ast_importer.CanImport(type)) {
276 auto qual_type = ClangUtil::GetQualType(type);
277 if (ast_importer.RequireCompleteType(qual_type))
278 return;
279 die.GetDWARF()->GetObjectFile()->GetModule()->ReportError(
280 "Unable to complete the Decl context for DIE '%s' at offset "
281 "0x%8.8x.\nPlease file a bug report.",
282 type_name_cstr ? type_name_cstr : "", die.GetOffset());
283 }
284
285 // We don't have a type definition and/or the import failed. We must
286 // forcefully complete the type to avoid crashes.
287 ForcefullyCompleteType(type);
288 }
289
ParsedDWARFTypeAttributes(const DWARFDIE & die)290 ParsedDWARFTypeAttributes::ParsedDWARFTypeAttributes(const DWARFDIE &die) {
291 DWARFAttributes attributes;
292 size_t num_attributes = die.GetAttributes(attributes);
293 for (size_t i = 0; i < num_attributes; ++i) {
294 dw_attr_t attr = attributes.AttributeAtIndex(i);
295 DWARFFormValue form_value;
296 if (!attributes.ExtractFormValueAtIndex(i, form_value))
297 continue;
298 switch (attr) {
299 case DW_AT_abstract_origin:
300 abstract_origin = form_value;
301 break;
302
303 case DW_AT_accessibility:
304 accessibility = DWARFASTParser::GetAccessTypeFromDWARF(form_value.Unsigned());
305 break;
306
307 case DW_AT_artificial:
308 is_artificial = form_value.Boolean();
309 break;
310
311 case DW_AT_bit_stride:
312 bit_stride = form_value.Unsigned();
313 break;
314
315 case DW_AT_byte_size:
316 byte_size = form_value.Unsigned();
317 break;
318
319 case DW_AT_byte_stride:
320 byte_stride = form_value.Unsigned();
321 break;
322
323 case DW_AT_calling_convention:
324 calling_convention = form_value.Unsigned();
325 break;
326
327 case DW_AT_containing_type:
328 containing_type = form_value;
329 break;
330
331 case DW_AT_decl_file:
332 // die.GetCU() can differ if DW_AT_specification uses DW_FORM_ref_addr.
333 decl.SetFile(
334 attributes.CompileUnitAtIndex(i)->GetFile(form_value.Unsigned()));
335 break;
336 case DW_AT_decl_line:
337 decl.SetLine(form_value.Unsigned());
338 break;
339 case DW_AT_decl_column:
340 decl.SetColumn(form_value.Unsigned());
341 break;
342
343 case DW_AT_declaration:
344 is_forward_declaration = form_value.Boolean();
345 break;
346
347 case DW_AT_encoding:
348 encoding = form_value.Unsigned();
349 break;
350
351 case DW_AT_enum_class:
352 is_scoped_enum = form_value.Boolean();
353 break;
354
355 case DW_AT_explicit:
356 is_explicit = form_value.Boolean();
357 break;
358
359 case DW_AT_external:
360 if (form_value.Unsigned())
361 storage = clang::SC_Extern;
362 break;
363
364 case DW_AT_inline:
365 is_inline = form_value.Boolean();
366 break;
367
368 case DW_AT_linkage_name:
369 case DW_AT_MIPS_linkage_name:
370 mangled_name = form_value.AsCString();
371 break;
372
373 case DW_AT_name:
374 name.SetCString(form_value.AsCString());
375 break;
376
377 case DW_AT_object_pointer:
378 object_pointer = form_value.Reference();
379 break;
380
381 case DW_AT_signature:
382 signature = form_value;
383 break;
384
385 case DW_AT_specification:
386 specification = form_value;
387 break;
388
389 case DW_AT_type:
390 type = form_value;
391 break;
392
393 case DW_AT_virtuality:
394 is_virtual = form_value.Boolean();
395 break;
396
397 case DW_AT_APPLE_objc_complete_type:
398 is_complete_objc_class = form_value.Signed();
399 break;
400
401 case DW_AT_APPLE_objc_direct:
402 is_objc_direct_call = true;
403 break;
404
405 case DW_AT_APPLE_runtime_class:
406 class_language = (LanguageType)form_value.Signed();
407 break;
408
409 case DW_AT_GNU_vector:
410 is_vector = form_value.Boolean();
411 break;
412 case DW_AT_export_symbols:
413 exports_symbols = form_value.Boolean();
414 break;
415 }
416 }
417 }
418
GetUnitName(const DWARFDIE & die)419 static std::string GetUnitName(const DWARFDIE &die) {
420 if (DWARFUnit *unit = die.GetCU())
421 return unit->GetAbsolutePath().GetPath();
422 return "<missing DWARF unit path>";
423 }
424
ParseTypeFromDWARF(const SymbolContext & sc,const DWARFDIE & die,bool * type_is_new_ptr)425 TypeSP DWARFASTParserClang::ParseTypeFromDWARF(const SymbolContext &sc,
426 const DWARFDIE &die,
427 bool *type_is_new_ptr) {
428 if (type_is_new_ptr)
429 *type_is_new_ptr = false;
430
431 if (!die)
432 return nullptr;
433
434 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups);
435
436 SymbolFileDWARF *dwarf = die.GetDWARF();
437 if (log) {
438 DWARFDIE context_die;
439 clang::DeclContext *context =
440 GetClangDeclContextContainingDIE(die, &context_die);
441
442 dwarf->GetObjectFile()->GetModule()->LogMessage(
443 log,
444 "DWARFASTParserClang::ParseTypeFromDWARF "
445 "(die = 0x%8.8x, decl_ctx = %p (die 0x%8.8x)) %s name = '%s')",
446 die.GetOffset(), static_cast<void *>(context), context_die.GetOffset(),
447 die.GetTagAsCString(), die.GetName());
448 }
449
450 Type *type_ptr = dwarf->GetDIEToType().lookup(die.GetDIE());
451 if (type_ptr == DIE_IS_BEING_PARSED)
452 return nullptr;
453 if (type_ptr)
454 return type_ptr->shared_from_this();
455 // Set a bit that lets us know that we are currently parsing this
456 dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
457
458 ParsedDWARFTypeAttributes attrs(die);
459
460 if (DWARFDIE signature_die = attrs.signature.Reference()) {
461 if (TypeSP type_sp =
462 ParseTypeFromDWARF(sc, signature_die, type_is_new_ptr)) {
463 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
464 if (clang::DeclContext *decl_ctx =
465 GetCachedClangDeclContextForDIE(signature_die))
466 LinkDeclContextToDIE(decl_ctx, die);
467 return type_sp;
468 }
469 return nullptr;
470 }
471
472 if (type_is_new_ptr)
473 *type_is_new_ptr = true;
474
475 const dw_tag_t tag = die.Tag();
476
477 TypeSP type_sp;
478
479 switch (tag) {
480 case DW_TAG_typedef:
481 case DW_TAG_base_type:
482 case DW_TAG_pointer_type:
483 case DW_TAG_reference_type:
484 case DW_TAG_rvalue_reference_type:
485 case DW_TAG_const_type:
486 case DW_TAG_restrict_type:
487 case DW_TAG_volatile_type:
488 case DW_TAG_atomic_type:
489 case DW_TAG_unspecified_type: {
490 type_sp = ParseTypeModifier(sc, die, attrs);
491 break;
492 }
493
494 case DW_TAG_structure_type:
495 case DW_TAG_union_type:
496 case DW_TAG_class_type: {
497 type_sp = ParseStructureLikeDIE(sc, die, attrs);
498 break;
499 }
500
501 case DW_TAG_enumeration_type: {
502 type_sp = ParseEnum(sc, die, attrs);
503 break;
504 }
505
506 case DW_TAG_inlined_subroutine:
507 case DW_TAG_subprogram:
508 case DW_TAG_subroutine_type: {
509 type_sp = ParseSubroutine(die, attrs);
510 break;
511 }
512 case DW_TAG_array_type: {
513 type_sp = ParseArrayType(die, attrs);
514 break;
515 }
516 case DW_TAG_ptr_to_member_type: {
517 type_sp = ParsePointerToMemberType(die, attrs);
518 break;
519 }
520 default:
521 dwarf->GetObjectFile()->GetModule()->ReportError(
522 "{0x%8.8x}: unhandled type tag 0x%4.4x (%s), please file a bug and "
523 "attach the file at the start of this error message",
524 die.GetOffset(), tag, DW_TAG_value_to_name(tag));
525 break;
526 }
527
528 // TODO: We should consider making the switch above exhaustive to simplify
529 // control flow in ParseTypeFromDWARF. Then, we could simply replace this
530 // return statement with a call to llvm_unreachable.
531 return UpdateSymbolContextScopeForType(sc, die, type_sp);
532 }
533
534 lldb::TypeSP
ParseTypeModifier(const SymbolContext & sc,const DWARFDIE & die,ParsedDWARFTypeAttributes & attrs)535 DWARFASTParserClang::ParseTypeModifier(const SymbolContext &sc,
536 const DWARFDIE &die,
537 ParsedDWARFTypeAttributes &attrs) {
538 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups);
539 SymbolFileDWARF *dwarf = die.GetDWARF();
540 const dw_tag_t tag = die.Tag();
541 LanguageType cu_language = SymbolFileDWARF::GetLanguage(*die.GetCU());
542 Type::ResolveState resolve_state = Type::ResolveState::Unresolved;
543 Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID;
544 TypeSP type_sp;
545 CompilerType clang_type;
546
547 if (tag == DW_TAG_typedef) {
548 // DeclContext will be populated when the clang type is materialized in
549 // Type::ResolveCompilerType.
550 PrepareContextToReceiveMembers(
551 m_ast, GetClangASTImporter(),
552 GetClangDeclContextContainingDIE(die, nullptr), die,
553 attrs.name.GetCString());
554
555 if (attrs.type.IsValid()) {
556 // Try to parse a typedef from the (DWARF embedded in the) Clang
557 // module file first as modules can contain typedef'ed
558 // structures that have no names like:
559 //
560 // typedef struct { int a; } Foo;
561 //
562 // In this case we will have a structure with no name and a
563 // typedef named "Foo" that points to this unnamed
564 // structure. The name in the typedef is the only identifier for
565 // the struct, so always try to get typedefs from Clang modules
566 // if possible.
567 //
568 // The type_sp returned will be empty if the typedef doesn't
569 // exist in a module file, so it is cheap to call this function
570 // just to check.
571 //
572 // If we don't do this we end up creating a TypeSP that says
573 // this is a typedef to type 0x123 (the DW_AT_type value would
574 // be 0x123 in the DW_TAG_typedef), and this is the unnamed
575 // structure type. We will have a hard time tracking down an
576 // unnammed structure type in the module debug info, so we make
577 // sure we don't get into this situation by always resolving
578 // typedefs from the module.
579 const DWARFDIE encoding_die = attrs.type.Reference();
580
581 // First make sure that the die that this is typedef'ed to _is_
582 // just a declaration (DW_AT_declaration == 1), not a full
583 // definition since template types can't be represented in
584 // modules since only concrete instances of templates are ever
585 // emitted and modules won't contain those
586 if (encoding_die &&
587 encoding_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) == 1) {
588 type_sp = ParseTypeFromClangModule(sc, die, log);
589 if (type_sp)
590 return type_sp;
591 }
592 }
593 }
594
595 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\") type => 0x%8.8lx\n", die.GetID(),
596 DW_TAG_value_to_name(tag), type_name_cstr,
597 encoding_uid.Reference());
598
599 switch (tag) {
600 default:
601 break;
602
603 case DW_TAG_unspecified_type:
604 if (attrs.name == "nullptr_t" || attrs.name == "decltype(nullptr)") {
605 resolve_state = Type::ResolveState::Full;
606 clang_type = m_ast.GetBasicType(eBasicTypeNullPtr);
607 break;
608 }
609 // Fall through to base type below in case we can handle the type
610 // there...
611 LLVM_FALLTHROUGH;
612
613 case DW_TAG_base_type:
614 resolve_state = Type::ResolveState::Full;
615 clang_type = m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize(
616 attrs.name.GetStringRef(), attrs.encoding,
617 attrs.byte_size.value_or(0) * 8);
618 break;
619
620 case DW_TAG_pointer_type:
621 encoding_data_type = Type::eEncodingIsPointerUID;
622 break;
623 case DW_TAG_reference_type:
624 encoding_data_type = Type::eEncodingIsLValueReferenceUID;
625 break;
626 case DW_TAG_rvalue_reference_type:
627 encoding_data_type = Type::eEncodingIsRValueReferenceUID;
628 break;
629 case DW_TAG_typedef:
630 encoding_data_type = Type::eEncodingIsTypedefUID;
631 break;
632 case DW_TAG_const_type:
633 encoding_data_type = Type::eEncodingIsConstUID;
634 break;
635 case DW_TAG_restrict_type:
636 encoding_data_type = Type::eEncodingIsRestrictUID;
637 break;
638 case DW_TAG_volatile_type:
639 encoding_data_type = Type::eEncodingIsVolatileUID;
640 break;
641 case DW_TAG_atomic_type:
642 encoding_data_type = Type::eEncodingIsAtomicUID;
643 break;
644 }
645
646 if (!clang_type && (encoding_data_type == Type::eEncodingIsPointerUID ||
647 encoding_data_type == Type::eEncodingIsTypedefUID)) {
648 if (tag == DW_TAG_pointer_type) {
649 DWARFDIE target_die = die.GetReferencedDIE(DW_AT_type);
650
651 if (target_die.GetAttributeValueAsUnsigned(DW_AT_APPLE_block, 0)) {
652 // Blocks have a __FuncPtr inside them which is a pointer to a
653 // function of the proper type.
654
655 for (DWARFDIE child_die : target_die.children()) {
656 if (!strcmp(child_die.GetAttributeValueAsString(DW_AT_name, ""),
657 "__FuncPtr")) {
658 DWARFDIE function_pointer_type =
659 child_die.GetReferencedDIE(DW_AT_type);
660
661 if (function_pointer_type) {
662 DWARFDIE function_type =
663 function_pointer_type.GetReferencedDIE(DW_AT_type);
664
665 bool function_type_is_new_pointer;
666 TypeSP lldb_function_type_sp = ParseTypeFromDWARF(
667 sc, function_type, &function_type_is_new_pointer);
668
669 if (lldb_function_type_sp) {
670 clang_type = m_ast.CreateBlockPointerType(
671 lldb_function_type_sp->GetForwardCompilerType());
672 encoding_data_type = Type::eEncodingIsUID;
673 attrs.type.Clear();
674 resolve_state = Type::ResolveState::Full;
675 }
676 }
677
678 break;
679 }
680 }
681 }
682 }
683
684 if (cu_language == eLanguageTypeObjC ||
685 cu_language == eLanguageTypeObjC_plus_plus) {
686 if (attrs.name) {
687 if (attrs.name == "id") {
688 if (log)
689 dwarf->GetObjectFile()->GetModule()->LogMessage(
690 log,
691 "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' "
692 "is Objective-C 'id' built-in type.",
693 die.GetOffset(), die.GetTagAsCString(), die.GetName());
694 clang_type = m_ast.GetBasicType(eBasicTypeObjCID);
695 encoding_data_type = Type::eEncodingIsUID;
696 attrs.type.Clear();
697 resolve_state = Type::ResolveState::Full;
698 } else if (attrs.name == "Class") {
699 if (log)
700 dwarf->GetObjectFile()->GetModule()->LogMessage(
701 log,
702 "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' "
703 "is Objective-C 'Class' built-in type.",
704 die.GetOffset(), die.GetTagAsCString(), die.GetName());
705 clang_type = m_ast.GetBasicType(eBasicTypeObjCClass);
706 encoding_data_type = Type::eEncodingIsUID;
707 attrs.type.Clear();
708 resolve_state = Type::ResolveState::Full;
709 } else if (attrs.name == "SEL") {
710 if (log)
711 dwarf->GetObjectFile()->GetModule()->LogMessage(
712 log,
713 "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' "
714 "is Objective-C 'selector' built-in type.",
715 die.GetOffset(), die.GetTagAsCString(), die.GetName());
716 clang_type = m_ast.GetBasicType(eBasicTypeObjCSel);
717 encoding_data_type = Type::eEncodingIsUID;
718 attrs.type.Clear();
719 resolve_state = Type::ResolveState::Full;
720 }
721 } else if (encoding_data_type == Type::eEncodingIsPointerUID &&
722 attrs.type.IsValid()) {
723 // Clang sometimes erroneously emits id as objc_object*. In that
724 // case we fix up the type to "id".
725
726 const DWARFDIE encoding_die = attrs.type.Reference();
727
728 if (encoding_die && encoding_die.Tag() == DW_TAG_structure_type) {
729 llvm::StringRef struct_name = encoding_die.GetName();
730 if (struct_name == "objc_object") {
731 if (log)
732 dwarf->GetObjectFile()->GetModule()->LogMessage(
733 log,
734 "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s "
735 "'%s' is 'objc_object*', which we overrode to "
736 "'id'.",
737 die.GetOffset(), die.GetTagAsCString(), die.GetName());
738 clang_type = m_ast.GetBasicType(eBasicTypeObjCID);
739 encoding_data_type = Type::eEncodingIsUID;
740 attrs.type.Clear();
741 resolve_state = Type::ResolveState::Full;
742 }
743 }
744 }
745 }
746 }
747
748 type_sp = std::make_shared<Type>(
749 die.GetID(), dwarf, attrs.name, attrs.byte_size, nullptr,
750 dwarf->GetUID(attrs.type.Reference()), encoding_data_type, &attrs.decl,
751 clang_type, resolve_state, TypePayloadClang(GetOwningClangModule(die)));
752
753 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
754 return type_sp;
755 }
756
ParseEnum(const SymbolContext & sc,const DWARFDIE & die,ParsedDWARFTypeAttributes & attrs)757 TypeSP DWARFASTParserClang::ParseEnum(const SymbolContext &sc,
758 const DWARFDIE &die,
759 ParsedDWARFTypeAttributes &attrs) {
760 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups);
761 SymbolFileDWARF *dwarf = die.GetDWARF();
762 const dw_tag_t tag = die.Tag();
763 TypeSP type_sp;
764
765 if (attrs.is_forward_declaration) {
766 type_sp = ParseTypeFromClangModule(sc, die, log);
767 if (type_sp)
768 return type_sp;
769
770 DWARFDeclContext die_decl_ctx = SymbolFileDWARF::GetDWARFDeclContext(die);
771
772 type_sp = dwarf->FindDefinitionTypeForDWARFDeclContext(die_decl_ctx);
773
774 if (!type_sp) {
775 SymbolFileDWARFDebugMap *debug_map_symfile = dwarf->GetDebugMapSymfile();
776 if (debug_map_symfile) {
777 // We weren't able to find a full declaration in this DWARF,
778 // see if we have a declaration anywhere else...
779 type_sp = debug_map_symfile->FindDefinitionTypeForDWARFDeclContext(
780 die_decl_ctx);
781 }
782 }
783
784 if (type_sp) {
785 if (log) {
786 dwarf->GetObjectFile()->GetModule()->LogMessage(
787 log,
788 "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a "
789 "forward declaration, complete type is 0x%8.8" PRIx64,
790 static_cast<void *>(this), die.GetOffset(),
791 DW_TAG_value_to_name(tag), attrs.name.GetCString(),
792 type_sp->GetID());
793 }
794
795 // We found a real definition for this type elsewhere so lets use
796 // it and cache the fact that we found a complete type for this
797 // die
798 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
799 clang::DeclContext *defn_decl_ctx =
800 GetCachedClangDeclContextForDIE(dwarf->GetDIE(type_sp->GetID()));
801 if (defn_decl_ctx)
802 LinkDeclContextToDIE(defn_decl_ctx, die);
803 return type_sp;
804 }
805 }
806 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
807 DW_TAG_value_to_name(tag), type_name_cstr);
808
809 CompilerType enumerator_clang_type;
810 CompilerType clang_type;
811 clang_type.SetCompilerType(
812 &m_ast, dwarf->GetForwardDeclDieToClangType().lookup(die.GetDIE()));
813 if (!clang_type) {
814 if (attrs.type.IsValid()) {
815 Type *enumerator_type =
816 dwarf->ResolveTypeUID(attrs.type.Reference(), true);
817 if (enumerator_type)
818 enumerator_clang_type = enumerator_type->GetFullCompilerType();
819 }
820
821 if (!enumerator_clang_type) {
822 if (attrs.byte_size) {
823 enumerator_clang_type = m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize(
824 "", DW_ATE_signed, *attrs.byte_size * 8);
825 } else {
826 enumerator_clang_type = m_ast.GetBasicType(eBasicTypeInt);
827 }
828 }
829
830 clang_type = m_ast.CreateEnumerationType(
831 attrs.name.GetStringRef(),
832 GetClangDeclContextContainingDIE(die, nullptr),
833 GetOwningClangModule(die), attrs.decl, enumerator_clang_type,
834 attrs.is_scoped_enum);
835 } else {
836 enumerator_clang_type = m_ast.GetEnumerationIntegerType(clang_type);
837 }
838
839 LinkDeclContextToDIE(TypeSystemClang::GetDeclContextForType(clang_type), die);
840
841 type_sp = std::make_shared<Type>(
842 die.GetID(), dwarf, attrs.name, attrs.byte_size, nullptr,
843 dwarf->GetUID(attrs.type.Reference()), Type::eEncodingIsUID, &attrs.decl,
844 clang_type, Type::ResolveState::Forward,
845 TypePayloadClang(GetOwningClangModule(die)));
846
847 if (TypeSystemClang::StartTagDeclarationDefinition(clang_type)) {
848 if (die.HasChildren()) {
849 bool is_signed = false;
850 enumerator_clang_type.IsIntegerType(is_signed);
851 ParseChildEnumerators(clang_type, is_signed,
852 type_sp->GetByteSize(nullptr).value_or(0), die);
853 }
854 TypeSystemClang::CompleteTagDeclarationDefinition(clang_type);
855 } else {
856 dwarf->GetObjectFile()->GetModule()->ReportError(
857 "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its "
858 "definition.\nPlease file a bug and attach the file at the "
859 "start of this error message",
860 die.GetOffset(), attrs.name.GetCString());
861 }
862 return type_sp;
863 }
864
865 static clang::CallingConv
ConvertDWARFCallingConventionToClang(const ParsedDWARFTypeAttributes & attrs)866 ConvertDWARFCallingConventionToClang(const ParsedDWARFTypeAttributes &attrs) {
867 switch (attrs.calling_convention) {
868 case llvm::dwarf::DW_CC_normal:
869 return clang::CC_C;
870 case llvm::dwarf::DW_CC_BORLAND_stdcall:
871 return clang::CC_X86StdCall;
872 case llvm::dwarf::DW_CC_BORLAND_msfastcall:
873 return clang::CC_X86FastCall;
874 case llvm::dwarf::DW_CC_LLVM_vectorcall:
875 return clang::CC_X86VectorCall;
876 case llvm::dwarf::DW_CC_BORLAND_pascal:
877 return clang::CC_X86Pascal;
878 case llvm::dwarf::DW_CC_LLVM_Win64:
879 return clang::CC_Win64;
880 case llvm::dwarf::DW_CC_LLVM_X86_64SysV:
881 return clang::CC_X86_64SysV;
882 case llvm::dwarf::DW_CC_LLVM_X86RegCall:
883 return clang::CC_X86RegCall;
884 default:
885 break;
886 }
887
888 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups);
889 LLDB_LOG(log, "Unsupported DW_AT_calling_convention value: {0}",
890 attrs.calling_convention);
891 // Use the default calling convention as a fallback.
892 return clang::CC_C;
893 }
894
ParseSubroutine(const DWARFDIE & die,ParsedDWARFTypeAttributes & attrs)895 TypeSP DWARFASTParserClang::ParseSubroutine(const DWARFDIE &die,
896 ParsedDWARFTypeAttributes &attrs) {
897 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups);
898
899 SymbolFileDWARF *dwarf = die.GetDWARF();
900 const dw_tag_t tag = die.Tag();
901
902 bool is_variadic = false;
903 bool is_static = false;
904 bool has_template_params = false;
905
906 unsigned type_quals = 0;
907
908 std::string object_pointer_name;
909 if (attrs.object_pointer) {
910 const char *object_pointer_name_cstr = attrs.object_pointer.GetName();
911 if (object_pointer_name_cstr)
912 object_pointer_name = object_pointer_name_cstr;
913 }
914
915 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
916 DW_TAG_value_to_name(tag), type_name_cstr);
917
918 CompilerType return_clang_type;
919 Type *func_type = nullptr;
920
921 if (attrs.type.IsValid())
922 func_type = dwarf->ResolveTypeUID(attrs.type.Reference(), true);
923
924 if (func_type)
925 return_clang_type = func_type->GetForwardCompilerType();
926 else
927 return_clang_type = m_ast.GetBasicType(eBasicTypeVoid);
928
929 std::vector<CompilerType> function_param_types;
930 std::vector<clang::ParmVarDecl *> function_param_decls;
931
932 // Parse the function children for the parameters
933
934 DWARFDIE decl_ctx_die;
935 clang::DeclContext *containing_decl_ctx =
936 GetClangDeclContextContainingDIE(die, &decl_ctx_die);
937 const clang::Decl::Kind containing_decl_kind =
938 containing_decl_ctx->getDeclKind();
939
940 bool is_cxx_method = DeclKindIsCXXClass(containing_decl_kind);
941 // Start off static. This will be set to false in
942 // ParseChildParameters(...) if we find a "this" parameters as the
943 // first parameter
944 if (is_cxx_method) {
945 is_static = true;
946 }
947
948 if (die.HasChildren()) {
949 bool skip_artificial = true;
950 ParseChildParameters(containing_decl_ctx, die, skip_artificial, is_static,
951 is_variadic, has_template_params,
952 function_param_types, function_param_decls,
953 type_quals);
954 }
955
956 bool ignore_containing_context = false;
957 // Check for templatized class member functions. If we had any
958 // DW_TAG_template_type_parameter or DW_TAG_template_value_parameter
959 // the DW_TAG_subprogram DIE, then we can't let this become a method in
960 // a class. Why? Because templatized functions are only emitted if one
961 // of the templatized methods is used in the current compile unit and
962 // we will end up with classes that may or may not include these member
963 // functions and this means one class won't match another class
964 // definition and it affects our ability to use a class in the clang
965 // expression parser. So for the greater good, we currently must not
966 // allow any template member functions in a class definition.
967 if (is_cxx_method && has_template_params) {
968 ignore_containing_context = true;
969 is_cxx_method = false;
970 }
971
972 clang::CallingConv calling_convention =
973 ConvertDWARFCallingConventionToClang(attrs);
974
975 // clang_type will get the function prototype clang type after this
976 // call
977 CompilerType clang_type = m_ast.CreateFunctionType(
978 return_clang_type, function_param_types.data(),
979 function_param_types.size(), is_variadic, type_quals, calling_convention);
980
981 if (attrs.name) {
982 bool type_handled = false;
983 if (tag == DW_TAG_subprogram || tag == DW_TAG_inlined_subroutine) {
984 ObjCLanguage::MethodName objc_method(attrs.name.GetStringRef(), true);
985 if (objc_method.IsValid(true)) {
986 CompilerType class_opaque_type;
987 ConstString class_name(objc_method.GetClassName());
988 if (class_name) {
989 TypeSP complete_objc_class_type_sp(
990 dwarf->FindCompleteObjCDefinitionTypeForDIE(DWARFDIE(),
991 class_name, false));
992
993 if (complete_objc_class_type_sp) {
994 CompilerType type_clang_forward_type =
995 complete_objc_class_type_sp->GetForwardCompilerType();
996 if (TypeSystemClang::IsObjCObjectOrInterfaceType(
997 type_clang_forward_type))
998 class_opaque_type = type_clang_forward_type;
999 }
1000 }
1001
1002 if (class_opaque_type) {
1003 // If accessibility isn't set to anything valid, assume public
1004 // for now...
1005 if (attrs.accessibility == eAccessNone)
1006 attrs.accessibility = eAccessPublic;
1007
1008 clang::ObjCMethodDecl *objc_method_decl =
1009 m_ast.AddMethodToObjCObjectType(
1010 class_opaque_type, attrs.name.GetCString(), clang_type,
1011 attrs.accessibility, attrs.is_artificial, is_variadic,
1012 attrs.is_objc_direct_call);
1013 type_handled = objc_method_decl != nullptr;
1014 if (type_handled) {
1015 LinkDeclContextToDIE(objc_method_decl, die);
1016 m_ast.SetMetadataAsUserID(objc_method_decl, die.GetID());
1017 } else {
1018 dwarf->GetObjectFile()->GetModule()->ReportError(
1019 "{0x%8.8x}: invalid Objective-C method 0x%4.4x (%s), "
1020 "please file a bug and attach the file at the start of "
1021 "this error message",
1022 die.GetOffset(), tag, DW_TAG_value_to_name(tag));
1023 }
1024 }
1025 } else if (is_cxx_method) {
1026 // Look at the parent of this DIE and see if is is a class or
1027 // struct and see if this is actually a C++ method
1028 Type *class_type = dwarf->ResolveType(decl_ctx_die);
1029 if (class_type) {
1030 if (class_type->GetID() != decl_ctx_die.GetID() ||
1031 IsClangModuleFwdDecl(decl_ctx_die)) {
1032
1033 // We uniqued the parent class of this function to another
1034 // class so we now need to associate all dies under
1035 // "decl_ctx_die" to DIEs in the DIE for "class_type"...
1036 DWARFDIE class_type_die = dwarf->GetDIE(class_type->GetID());
1037
1038 if (class_type_die) {
1039 std::vector<DWARFDIE> failures;
1040
1041 CopyUniqueClassMethodTypes(decl_ctx_die, class_type_die,
1042 class_type, failures);
1043
1044 // FIXME do something with these failures that's
1045 // smarter than just dropping them on the ground.
1046 // Unfortunately classes don't like having stuff added
1047 // to them after their definitions are complete...
1048
1049 Type *type_ptr = dwarf->GetDIEToType()[die.GetDIE()];
1050 if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) {
1051 return type_ptr->shared_from_this();
1052 }
1053 }
1054 }
1055
1056 if (attrs.specification.IsValid()) {
1057 // We have a specification which we are going to base our
1058 // function prototype off of, so we need this type to be
1059 // completed so that the m_die_to_decl_ctx for the method in
1060 // the specification has a valid clang decl context.
1061 class_type->GetForwardCompilerType();
1062 // If we have a specification, then the function type should
1063 // have been made with the specification and not with this
1064 // die.
1065 DWARFDIE spec_die = attrs.specification.Reference();
1066 clang::DeclContext *spec_clang_decl_ctx =
1067 GetClangDeclContextForDIE(spec_die);
1068 if (spec_clang_decl_ctx) {
1069 LinkDeclContextToDIE(spec_clang_decl_ctx, die);
1070 } else {
1071 dwarf->GetObjectFile()->GetModule()->ReportWarning(
1072 "0x%8.8" PRIx64 ": DW_AT_specification(0x%8.8x"
1073 ") has no decl\n",
1074 die.GetID(), spec_die.GetOffset());
1075 }
1076 type_handled = true;
1077 } else if (attrs.abstract_origin.IsValid()) {
1078 // We have a specification which we are going to base our
1079 // function prototype off of, so we need this type to be
1080 // completed so that the m_die_to_decl_ctx for the method in
1081 // the abstract origin has a valid clang decl context.
1082 class_type->GetForwardCompilerType();
1083
1084 DWARFDIE abs_die = attrs.abstract_origin.Reference();
1085 clang::DeclContext *abs_clang_decl_ctx =
1086 GetClangDeclContextForDIE(abs_die);
1087 if (abs_clang_decl_ctx) {
1088 LinkDeclContextToDIE(abs_clang_decl_ctx, die);
1089 } else {
1090 dwarf->GetObjectFile()->GetModule()->ReportWarning(
1091 "0x%8.8" PRIx64 ": DW_AT_abstract_origin(0x%8.8x"
1092 ") has no decl\n",
1093 die.GetID(), abs_die.GetOffset());
1094 }
1095 type_handled = true;
1096 } else {
1097 CompilerType class_opaque_type =
1098 class_type->GetForwardCompilerType();
1099 if (TypeSystemClang::IsCXXClassType(class_opaque_type)) {
1100 if (class_opaque_type.IsBeingDefined()) {
1101 if (!is_static && !die.HasChildren()) {
1102 // We have a C++ member function with no children (this
1103 // pointer!) and clang will get mad if we try and make
1104 // a function that isn't well formed in the DWARF, so
1105 // we will just skip it...
1106 type_handled = true;
1107 } else {
1108 llvm::PrettyStackTraceFormat stack_trace(
1109 "SymbolFileDWARF::ParseType() is adding a method "
1110 "%s to class %s in DIE 0x%8.8" PRIx64 " from %s",
1111 attrs.name.GetCString(),
1112 class_type->GetName().GetCString(), die.GetID(),
1113 dwarf->GetObjectFile()->GetFileSpec().GetPath().c_str());
1114
1115 const bool is_attr_used = false;
1116 // Neither GCC 4.2 nor clang++ currently set a valid
1117 // accessibility in the DWARF for C++ methods...
1118 // Default to public for now...
1119 if (attrs.accessibility == eAccessNone)
1120 attrs.accessibility = eAccessPublic;
1121
1122 clang::CXXMethodDecl *cxx_method_decl =
1123 m_ast.AddMethodToCXXRecordType(
1124 class_opaque_type.GetOpaqueQualType(),
1125 attrs.name.GetCString(), attrs.mangled_name,
1126 clang_type, attrs.accessibility, attrs.is_virtual,
1127 is_static, attrs.is_inline, attrs.is_explicit,
1128 is_attr_used, attrs.is_artificial);
1129
1130 type_handled = cxx_method_decl != nullptr;
1131 // Artificial methods are always handled even when we
1132 // don't create a new declaration for them.
1133 type_handled |= attrs.is_artificial;
1134
1135 if (cxx_method_decl) {
1136 LinkDeclContextToDIE(cxx_method_decl, die);
1137
1138 ClangASTMetadata metadata;
1139 metadata.SetUserID(die.GetID());
1140
1141 if (!object_pointer_name.empty()) {
1142 metadata.SetObjectPtrName(object_pointer_name.c_str());
1143 LLDB_LOGF(log,
1144 "Setting object pointer name: %s on method "
1145 "object %p.\n",
1146 object_pointer_name.c_str(),
1147 static_cast<void *>(cxx_method_decl));
1148 }
1149 m_ast.SetMetadata(cxx_method_decl, metadata);
1150 } else {
1151 ignore_containing_context = true;
1152 }
1153 }
1154 } else {
1155 // We were asked to parse the type for a method in a
1156 // class, yet the class hasn't been asked to complete
1157 // itself through the clang::ExternalASTSource protocol,
1158 // so we need to just have the class complete itself and
1159 // do things the right way, then our
1160 // DIE should then have an entry in the
1161 // dwarf->GetDIEToType() map. First
1162 // we need to modify the dwarf->GetDIEToType() so it
1163 // doesn't think we are trying to parse this DIE
1164 // anymore...
1165 dwarf->GetDIEToType()[die.GetDIE()] = NULL;
1166
1167 // Now we get the full type to force our class type to
1168 // complete itself using the clang::ExternalASTSource
1169 // protocol which will parse all base classes and all
1170 // methods (including the method for this DIE).
1171 class_type->GetFullCompilerType();
1172
1173 // The type for this DIE should have been filled in the
1174 // function call above
1175 Type *type_ptr = dwarf->GetDIEToType()[die.GetDIE()];
1176 if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) {
1177 return type_ptr->shared_from_this();
1178 }
1179
1180 // FIXME This is fixing some even uglier behavior but we
1181 // really need to
1182 // uniq the methods of each class as well as the class
1183 // itself. <rdar://problem/11240464>
1184 type_handled = true;
1185 }
1186 }
1187 }
1188 }
1189 }
1190 }
1191
1192 if (!type_handled) {
1193 clang::FunctionDecl *function_decl = nullptr;
1194 clang::FunctionDecl *template_function_decl = nullptr;
1195
1196 if (attrs.abstract_origin.IsValid()) {
1197 DWARFDIE abs_die = attrs.abstract_origin.Reference();
1198
1199 if (dwarf->ResolveType(abs_die)) {
1200 function_decl = llvm::dyn_cast_or_null<clang::FunctionDecl>(
1201 GetCachedClangDeclContextForDIE(abs_die));
1202
1203 if (function_decl) {
1204 LinkDeclContextToDIE(function_decl, die);
1205 }
1206 }
1207 }
1208
1209 if (!function_decl) {
1210 char *name_buf = nullptr;
1211 llvm::StringRef name = attrs.name.GetStringRef();
1212
1213 // We currently generate function templates with template parameters in
1214 // their name. In order to get closer to the AST that clang generates
1215 // we want to strip these from the name when creating the AST.
1216 if (attrs.mangled_name) {
1217 llvm::ItaniumPartialDemangler D;
1218 if (!D.partialDemangle(attrs.mangled_name)) {
1219 name_buf = D.getFunctionBaseName(nullptr, nullptr);
1220 name = name_buf;
1221 }
1222 }
1223
1224 // We just have a function that isn't part of a class
1225 function_decl = m_ast.CreateFunctionDeclaration(
1226 ignore_containing_context ? m_ast.GetTranslationUnitDecl()
1227 : containing_decl_ctx,
1228 GetOwningClangModule(die), name, clang_type, attrs.storage,
1229 attrs.is_inline);
1230 std::free(name_buf);
1231
1232 if (has_template_params) {
1233 TypeSystemClang::TemplateParameterInfos template_param_infos;
1234 ParseTemplateParameterInfos(die, template_param_infos);
1235 template_function_decl = m_ast.CreateFunctionDeclaration(
1236 ignore_containing_context ? m_ast.GetTranslationUnitDecl()
1237 : containing_decl_ctx,
1238 GetOwningClangModule(die), attrs.name.GetStringRef(), clang_type,
1239 attrs.storage, attrs.is_inline);
1240 clang::FunctionTemplateDecl *func_template_decl =
1241 m_ast.CreateFunctionTemplateDecl(
1242 containing_decl_ctx, GetOwningClangModule(die),
1243 template_function_decl, template_param_infos);
1244 m_ast.CreateFunctionTemplateSpecializationInfo(
1245 template_function_decl, func_template_decl, template_param_infos);
1246 }
1247
1248 lldbassert(function_decl);
1249
1250 if (function_decl) {
1251 LinkDeclContextToDIE(function_decl, die);
1252
1253 if (!function_param_decls.empty()) {
1254 m_ast.SetFunctionParameters(function_decl, function_param_decls);
1255 if (template_function_decl)
1256 m_ast.SetFunctionParameters(template_function_decl,
1257 function_param_decls);
1258 }
1259
1260 ClangASTMetadata metadata;
1261 metadata.SetUserID(die.GetID());
1262
1263 if (!object_pointer_name.empty()) {
1264 metadata.SetObjectPtrName(object_pointer_name.c_str());
1265 LLDB_LOGF(log,
1266 "Setting object pointer name: %s on function "
1267 "object %p.",
1268 object_pointer_name.c_str(),
1269 static_cast<void *>(function_decl));
1270 }
1271 m_ast.SetMetadata(function_decl, metadata);
1272 }
1273 }
1274 }
1275 }
1276 return std::make_shared<Type>(
1277 die.GetID(), dwarf, attrs.name, llvm::None, nullptr, LLDB_INVALID_UID,
1278 Type::eEncodingIsUID, &attrs.decl, clang_type, Type::ResolveState::Full);
1279 }
1280
ParseArrayType(const DWARFDIE & die,ParsedDWARFTypeAttributes & attrs)1281 TypeSP DWARFASTParserClang::ParseArrayType(const DWARFDIE &die,
1282 ParsedDWARFTypeAttributes &attrs) {
1283 SymbolFileDWARF *dwarf = die.GetDWARF();
1284
1285 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
1286 DW_TAG_value_to_name(tag), type_name_cstr);
1287
1288 DWARFDIE type_die = attrs.type.Reference();
1289 Type *element_type = dwarf->ResolveTypeUID(type_die, true);
1290
1291 if (!element_type)
1292 return nullptr;
1293
1294 llvm::Optional<SymbolFile::ArrayInfo> array_info = ParseChildArrayInfo(die);
1295 if (array_info) {
1296 attrs.byte_stride = array_info->byte_stride;
1297 attrs.bit_stride = array_info->bit_stride;
1298 }
1299 if (attrs.byte_stride == 0 && attrs.bit_stride == 0)
1300 attrs.byte_stride = element_type->GetByteSize(nullptr).value_or(0);
1301 CompilerType array_element_type = element_type->GetForwardCompilerType();
1302 RequireCompleteType(array_element_type);
1303
1304 uint64_t array_element_bit_stride =
1305 attrs.byte_stride * 8 + attrs.bit_stride;
1306 CompilerType clang_type;
1307 if (array_info && array_info->element_orders.size() > 0) {
1308 uint64_t num_elements = 0;
1309 auto end = array_info->element_orders.rend();
1310 for (auto pos = array_info->element_orders.rbegin(); pos != end; ++pos) {
1311 num_elements = *pos;
1312 clang_type = m_ast.CreateArrayType(array_element_type, num_elements,
1313 attrs.is_vector);
1314 array_element_type = clang_type;
1315 array_element_bit_stride = num_elements
1316 ? array_element_bit_stride * num_elements
1317 : array_element_bit_stride;
1318 }
1319 } else {
1320 clang_type =
1321 m_ast.CreateArrayType(array_element_type, 0, attrs.is_vector);
1322 }
1323 ConstString empty_name;
1324 TypeSP type_sp = std::make_shared<Type>(
1325 die.GetID(), dwarf, empty_name, array_element_bit_stride / 8, nullptr,
1326 dwarf->GetUID(type_die), Type::eEncodingIsUID, &attrs.decl, clang_type,
1327 Type::ResolveState::Full);
1328 type_sp->SetEncodingType(element_type);
1329 const clang::Type *type = ClangUtil::GetQualType(clang_type).getTypePtr();
1330 m_ast.SetMetadataAsUserID(type, die.GetID());
1331 return type_sp;
1332 }
1333
ParsePointerToMemberType(const DWARFDIE & die,const ParsedDWARFTypeAttributes & attrs)1334 TypeSP DWARFASTParserClang::ParsePointerToMemberType(
1335 const DWARFDIE &die, const ParsedDWARFTypeAttributes &attrs) {
1336 SymbolFileDWARF *dwarf = die.GetDWARF();
1337 Type *pointee_type = dwarf->ResolveTypeUID(attrs.type.Reference(), true);
1338 Type *class_type =
1339 dwarf->ResolveTypeUID(attrs.containing_type.Reference(), true);
1340
1341 CompilerType pointee_clang_type = pointee_type->GetForwardCompilerType();
1342 CompilerType class_clang_type = class_type->GetForwardCompilerType();
1343
1344 CompilerType clang_type = TypeSystemClang::CreateMemberPointerType(
1345 class_clang_type, pointee_clang_type);
1346
1347 if (llvm::Optional<uint64_t> clang_type_size =
1348 clang_type.GetByteSize(nullptr)) {
1349 return std::make_shared<Type>(die.GetID(), dwarf, attrs.name,
1350 *clang_type_size, nullptr, LLDB_INVALID_UID,
1351 Type::eEncodingIsUID, nullptr, clang_type,
1352 Type::ResolveState::Forward);
1353 }
1354 return nullptr;
1355 }
1356
ParseInheritance(const DWARFDIE & die,const DWARFDIE & parent_die,const CompilerType class_clang_type,const AccessType default_accessibility,const lldb::ModuleSP & module_sp,std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> & base_classes,ClangASTImporter::LayoutInfo & layout_info)1357 void DWARFASTParserClang::ParseInheritance(
1358 const DWARFDIE &die, const DWARFDIE &parent_die,
1359 const CompilerType class_clang_type, const AccessType default_accessibility,
1360 const lldb::ModuleSP &module_sp,
1361 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> &base_classes,
1362 ClangASTImporter::LayoutInfo &layout_info) {
1363
1364 TypeSystemClang *ast =
1365 llvm::dyn_cast_or_null<TypeSystemClang>(class_clang_type.GetTypeSystem());
1366 if (ast == nullptr)
1367 return;
1368
1369 // TODO: implement DW_TAG_inheritance type parsing.
1370 DWARFAttributes attributes;
1371 const size_t num_attributes = die.GetAttributes(attributes);
1372 if (num_attributes == 0)
1373 return;
1374
1375 DWARFFormValue encoding_form;
1376 AccessType accessibility = default_accessibility;
1377 bool is_virtual = false;
1378 bool is_base_of_class = true;
1379 off_t member_byte_offset = 0;
1380
1381 for (uint32_t i = 0; i < num_attributes; ++i) {
1382 const dw_attr_t attr = attributes.AttributeAtIndex(i);
1383 DWARFFormValue form_value;
1384 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1385 switch (attr) {
1386 case DW_AT_type:
1387 encoding_form = form_value;
1388 break;
1389 case DW_AT_data_member_location:
1390 if (form_value.BlockData()) {
1391 Value initialValue(0);
1392 Value memberOffset(0);
1393 const DWARFDataExtractor &debug_info_data = die.GetData();
1394 uint32_t block_length = form_value.Unsigned();
1395 uint32_t block_offset =
1396 form_value.BlockData() - debug_info_data.GetDataStart();
1397 if (DWARFExpression::Evaluate(
1398 nullptr, nullptr, module_sp,
1399 DataExtractor(debug_info_data, block_offset, block_length),
1400 die.GetCU(), eRegisterKindDWARF, &initialValue, nullptr,
1401 memberOffset, nullptr)) {
1402 member_byte_offset = memberOffset.ResolveValue(nullptr).UInt();
1403 }
1404 } else {
1405 // With DWARF 3 and later, if the value is an integer constant,
1406 // this form value is the offset in bytes from the beginning of
1407 // the containing entity.
1408 member_byte_offset = form_value.Unsigned();
1409 }
1410 break;
1411
1412 case DW_AT_accessibility:
1413 accessibility = DWARFASTParser::GetAccessTypeFromDWARF(form_value.Unsigned());
1414 break;
1415
1416 case DW_AT_virtuality:
1417 is_virtual = form_value.Boolean();
1418 break;
1419
1420 default:
1421 break;
1422 }
1423 }
1424 }
1425
1426 Type *base_class_type = die.ResolveTypeUID(encoding_form.Reference());
1427 if (base_class_type == nullptr) {
1428 module_sp->ReportError("0x%8.8x: DW_TAG_inheritance failed to "
1429 "resolve the base class at 0x%8.8x"
1430 " from enclosing type 0x%8.8x. \nPlease file "
1431 "a bug and attach the file at the start of "
1432 "this error message",
1433 die.GetOffset(),
1434 encoding_form.Reference().GetOffset(),
1435 parent_die.GetOffset());
1436 return;
1437 }
1438
1439 CompilerType base_class_clang_type = base_class_type->GetFullCompilerType();
1440 assert(base_class_clang_type);
1441 if (TypeSystemClang::IsObjCObjectOrInterfaceType(class_clang_type)) {
1442 ast->SetObjCSuperClass(class_clang_type, base_class_clang_type);
1443 return;
1444 }
1445 std::unique_ptr<clang::CXXBaseSpecifier> result =
1446 ast->CreateBaseClassSpecifier(base_class_clang_type.GetOpaqueQualType(),
1447 accessibility, is_virtual,
1448 is_base_of_class);
1449 if (!result)
1450 return;
1451
1452 base_classes.push_back(std::move(result));
1453
1454 if (is_virtual) {
1455 // Do not specify any offset for virtual inheritance. The DWARF
1456 // produced by clang doesn't give us a constant offset, but gives
1457 // us a DWARF expressions that requires an actual object in memory.
1458 // the DW_AT_data_member_location for a virtual base class looks
1459 // like:
1460 // DW_AT_data_member_location( DW_OP_dup, DW_OP_deref,
1461 // DW_OP_constu(0x00000018), DW_OP_minus, DW_OP_deref,
1462 // DW_OP_plus )
1463 // Given this, there is really no valid response we can give to
1464 // clang for virtual base class offsets, and this should eventually
1465 // be removed from LayoutRecordType() in the external
1466 // AST source in clang.
1467 } else {
1468 layout_info.base_offsets.insert(std::make_pair(
1469 ast->GetAsCXXRecordDecl(base_class_clang_type.GetOpaqueQualType()),
1470 clang::CharUnits::fromQuantity(member_byte_offset)));
1471 }
1472 }
1473
UpdateSymbolContextScopeForType(const SymbolContext & sc,const DWARFDIE & die,TypeSP type_sp)1474 TypeSP DWARFASTParserClang::UpdateSymbolContextScopeForType(
1475 const SymbolContext &sc, const DWARFDIE &die, TypeSP type_sp) {
1476 if (!type_sp)
1477 return type_sp;
1478
1479 SymbolFileDWARF *dwarf = die.GetDWARF();
1480 DWARFDIE sc_parent_die = SymbolFileDWARF::GetParentSymbolContextDIE(die);
1481 dw_tag_t sc_parent_tag = sc_parent_die.Tag();
1482
1483 SymbolContextScope *symbol_context_scope = nullptr;
1484 if (sc_parent_tag == DW_TAG_compile_unit ||
1485 sc_parent_tag == DW_TAG_partial_unit) {
1486 symbol_context_scope = sc.comp_unit;
1487 } else if (sc.function != nullptr && sc_parent_die) {
1488 symbol_context_scope =
1489 sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID());
1490 if (symbol_context_scope == nullptr)
1491 symbol_context_scope = sc.function;
1492 } else {
1493 symbol_context_scope = sc.module_sp.get();
1494 }
1495
1496 if (symbol_context_scope != nullptr)
1497 type_sp->SetSymbolContextScope(symbol_context_scope);
1498
1499 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1500 return type_sp;
1501 }
1502
1503 TypeSP
ParseStructureLikeDIE(const SymbolContext & sc,const DWARFDIE & die,ParsedDWARFTypeAttributes & attrs)1504 DWARFASTParserClang::ParseStructureLikeDIE(const SymbolContext &sc,
1505 const DWARFDIE &die,
1506 ParsedDWARFTypeAttributes &attrs) {
1507 TypeSP type_sp;
1508 CompilerType clang_type;
1509 const dw_tag_t tag = die.Tag();
1510 SymbolFileDWARF *dwarf = die.GetDWARF();
1511 LanguageType cu_language = SymbolFileDWARF::GetLanguage(*die.GetCU());
1512 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups);
1513
1514 // UniqueDWARFASTType is large, so don't create a local variables on the
1515 // stack, put it on the heap. This function is often called recursively and
1516 // clang isn't good at sharing the stack space for variables in different
1517 // blocks.
1518 auto unique_ast_entry_up = std::make_unique<UniqueDWARFASTType>();
1519
1520 ConstString unique_typename(attrs.name);
1521 Declaration unique_decl(attrs.decl);
1522
1523 if (attrs.name) {
1524 if (Language::LanguageIsCPlusPlus(cu_language)) {
1525 // For C++, we rely solely upon the one definition rule that says
1526 // only one thing can exist at a given decl context. We ignore the
1527 // file and line that things are declared on.
1528 std::string qualified_name;
1529 if (die.GetQualifiedName(qualified_name))
1530 unique_typename = ConstString(qualified_name);
1531 unique_decl.Clear();
1532 }
1533
1534 if (dwarf->GetUniqueDWARFASTTypeMap().Find(
1535 unique_typename, die, unique_decl, attrs.byte_size.value_or(-1),
1536 *unique_ast_entry_up)) {
1537 type_sp = unique_ast_entry_up->m_type_sp;
1538 if (type_sp) {
1539 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1540 LinkDeclContextToDIE(
1541 GetCachedClangDeclContextForDIE(unique_ast_entry_up->m_die), die);
1542 return type_sp;
1543 }
1544 }
1545 }
1546
1547 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
1548 DW_TAG_value_to_name(tag), type_name_cstr);
1549
1550 int tag_decl_kind = -1;
1551 AccessType default_accessibility = eAccessNone;
1552 if (tag == DW_TAG_structure_type) {
1553 tag_decl_kind = clang::TTK_Struct;
1554 default_accessibility = eAccessPublic;
1555 } else if (tag == DW_TAG_union_type) {
1556 tag_decl_kind = clang::TTK_Union;
1557 default_accessibility = eAccessPublic;
1558 } else if (tag == DW_TAG_class_type) {
1559 tag_decl_kind = clang::TTK_Class;
1560 default_accessibility = eAccessPrivate;
1561 }
1562
1563 if (attrs.byte_size && *attrs.byte_size == 0 && attrs.name &&
1564 !die.HasChildren() && cu_language == eLanguageTypeObjC) {
1565 // Work around an issue with clang at the moment where forward
1566 // declarations for objective C classes are emitted as:
1567 // DW_TAG_structure_type [2]
1568 // DW_AT_name( "ForwardObjcClass" )
1569 // DW_AT_byte_size( 0x00 )
1570 // DW_AT_decl_file( "..." )
1571 // DW_AT_decl_line( 1 )
1572 //
1573 // Note that there is no DW_AT_declaration and there are no children,
1574 // and the byte size is zero.
1575 attrs.is_forward_declaration = true;
1576 }
1577
1578 if (attrs.class_language == eLanguageTypeObjC ||
1579 attrs.class_language == eLanguageTypeObjC_plus_plus) {
1580 if (!attrs.is_complete_objc_class &&
1581 die.Supports_DW_AT_APPLE_objc_complete_type()) {
1582 // We have a valid eSymbolTypeObjCClass class symbol whose name
1583 // matches the current objective C class that we are trying to find
1584 // and this DIE isn't the complete definition (we checked
1585 // is_complete_objc_class above and know it is false), so the real
1586 // definition is in here somewhere
1587 type_sp =
1588 dwarf->FindCompleteObjCDefinitionTypeForDIE(die, attrs.name, true);
1589
1590 if (!type_sp) {
1591 SymbolFileDWARFDebugMap *debug_map_symfile =
1592 dwarf->GetDebugMapSymfile();
1593 if (debug_map_symfile) {
1594 // We weren't able to find a full declaration in this DWARF,
1595 // see if we have a declaration anywhere else...
1596 type_sp = debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE(
1597 die, attrs.name, true);
1598 }
1599 }
1600
1601 if (type_sp) {
1602 if (log) {
1603 dwarf->GetObjectFile()->GetModule()->LogMessage(
1604 log,
1605 "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is an "
1606 "incomplete objc type, complete type is 0x%8.8" PRIx64,
1607 static_cast<void *>(this), die.GetOffset(),
1608 DW_TAG_value_to_name(tag), attrs.name.GetCString(),
1609 type_sp->GetID());
1610 }
1611
1612 // We found a real definition for this type elsewhere so lets use
1613 // it and cache the fact that we found a complete type for this
1614 // die
1615 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1616 return type_sp;
1617 }
1618 }
1619 }
1620
1621 if (attrs.is_forward_declaration) {
1622 // We have a forward declaration to a type and we need to try and
1623 // find a full declaration. We look in the current type index just in
1624 // case we have a forward declaration followed by an actual
1625 // declarations in the DWARF. If this fails, we need to look
1626 // elsewhere...
1627 if (log) {
1628 dwarf->GetObjectFile()->GetModule()->LogMessage(
1629 log,
1630 "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a "
1631 "forward declaration, trying to find complete type",
1632 static_cast<void *>(this), die.GetOffset(), DW_TAG_value_to_name(tag),
1633 attrs.name.GetCString());
1634 }
1635
1636 // See if the type comes from a Clang module and if so, track down
1637 // that type.
1638 type_sp = ParseTypeFromClangModule(sc, die, log);
1639 if (type_sp)
1640 return type_sp;
1641
1642 DWARFDeclContext die_decl_ctx = SymbolFileDWARF::GetDWARFDeclContext(die);
1643
1644 // type_sp = FindDefinitionTypeForDIE (dwarf_cu, die,
1645 // type_name_const_str);
1646 type_sp = dwarf->FindDefinitionTypeForDWARFDeclContext(die_decl_ctx);
1647
1648 if (!type_sp) {
1649 SymbolFileDWARFDebugMap *debug_map_symfile = dwarf->GetDebugMapSymfile();
1650 if (debug_map_symfile) {
1651 // We weren't able to find a full declaration in this DWARF, see
1652 // if we have a declaration anywhere else...
1653 type_sp = debug_map_symfile->FindDefinitionTypeForDWARFDeclContext(
1654 die_decl_ctx);
1655 }
1656 }
1657
1658 if (type_sp) {
1659 if (log) {
1660 dwarf->GetObjectFile()->GetModule()->LogMessage(
1661 log,
1662 "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a "
1663 "forward declaration, complete type is 0x%8.8" PRIx64,
1664 static_cast<void *>(this), die.GetOffset(),
1665 DW_TAG_value_to_name(tag), attrs.name.GetCString(),
1666 type_sp->GetID());
1667 }
1668
1669 // We found a real definition for this type elsewhere so lets use
1670 // it and cache the fact that we found a complete type for this die
1671 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1672 clang::DeclContext *defn_decl_ctx =
1673 GetCachedClangDeclContextForDIE(dwarf->GetDIE(type_sp->GetID()));
1674 if (defn_decl_ctx)
1675 LinkDeclContextToDIE(defn_decl_ctx, die);
1676 return type_sp;
1677 }
1678 }
1679 assert(tag_decl_kind != -1);
1680 (void)tag_decl_kind;
1681 bool clang_type_was_created = false;
1682 clang_type.SetCompilerType(
1683 &m_ast, dwarf->GetForwardDeclDieToClangType().lookup(die.GetDIE()));
1684 if (!clang_type) {
1685 clang::DeclContext *decl_ctx =
1686 GetClangDeclContextContainingDIE(die, nullptr);
1687
1688 PrepareContextToReceiveMembers(m_ast, GetClangASTImporter(), decl_ctx, die,
1689 attrs.name.GetCString());
1690
1691 if (attrs.accessibility == eAccessNone && decl_ctx) {
1692 // Check the decl context that contains this class/struct/union. If
1693 // it is a class we must give it an accessibility.
1694 const clang::Decl::Kind containing_decl_kind = decl_ctx->getDeclKind();
1695 if (DeclKindIsCXXClass(containing_decl_kind))
1696 attrs.accessibility = default_accessibility;
1697 }
1698
1699 ClangASTMetadata metadata;
1700 metadata.SetUserID(die.GetID());
1701 metadata.SetIsDynamicCXXType(dwarf->ClassOrStructIsVirtual(die));
1702
1703 if (attrs.name.GetStringRef().contains('<')) {
1704 TypeSystemClang::TemplateParameterInfos template_param_infos;
1705 if (ParseTemplateParameterInfos(die, template_param_infos)) {
1706 clang::ClassTemplateDecl *class_template_decl =
1707 m_ast.ParseClassTemplateDecl(
1708 decl_ctx, GetOwningClangModule(die), attrs.accessibility,
1709 attrs.name.GetCString(), tag_decl_kind, template_param_infos);
1710 if (!class_template_decl) {
1711 if (log) {
1712 dwarf->GetObjectFile()->GetModule()->LogMessage(
1713 log,
1714 "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" "
1715 "clang::ClassTemplateDecl failed to return a decl.",
1716 static_cast<void *>(this), die.GetOffset(),
1717 DW_TAG_value_to_name(tag), attrs.name.GetCString());
1718 }
1719 return TypeSP();
1720 }
1721
1722 clang::ClassTemplateSpecializationDecl *class_specialization_decl =
1723 m_ast.CreateClassTemplateSpecializationDecl(
1724 decl_ctx, GetOwningClangModule(die), class_template_decl,
1725 tag_decl_kind, template_param_infos);
1726 clang_type = m_ast.CreateClassTemplateSpecializationType(
1727 class_specialization_decl);
1728 clang_type_was_created = true;
1729
1730 m_ast.SetMetadata(class_template_decl, metadata);
1731 m_ast.SetMetadata(class_specialization_decl, metadata);
1732 }
1733 }
1734
1735 if (!clang_type_was_created) {
1736 clang_type_was_created = true;
1737 clang_type = m_ast.CreateRecordType(
1738 decl_ctx, GetOwningClangModule(die), attrs.accessibility,
1739 attrs.name.GetCString(), tag_decl_kind, attrs.class_language,
1740 &metadata, attrs.exports_symbols);
1741 }
1742 }
1743
1744 // Store a forward declaration to this class type in case any
1745 // parameters in any class methods need it for the clang types for
1746 // function prototypes.
1747 LinkDeclContextToDIE(m_ast.GetDeclContextForType(clang_type), die);
1748 type_sp = std::make_shared<Type>(
1749 die.GetID(), dwarf, attrs.name, attrs.byte_size, nullptr,
1750 LLDB_INVALID_UID, Type::eEncodingIsUID, &attrs.decl, clang_type,
1751 Type::ResolveState::Forward,
1752 TypePayloadClang(OptionalClangModuleID(), attrs.is_complete_objc_class));
1753
1754 // Add our type to the unique type map so we don't end up creating many
1755 // copies of the same type over and over in the ASTContext for our
1756 // module
1757 unique_ast_entry_up->m_type_sp = type_sp;
1758 unique_ast_entry_up->m_die = die;
1759 unique_ast_entry_up->m_declaration = unique_decl;
1760 unique_ast_entry_up->m_byte_size = attrs.byte_size.value_or(0);
1761 dwarf->GetUniqueDWARFASTTypeMap().Insert(unique_typename,
1762 *unique_ast_entry_up);
1763
1764 if (!attrs.is_forward_declaration) {
1765 // Always start the definition for a class type so that if the class
1766 // has child classes or types that require the class to be created
1767 // for use as their decl contexts the class will be ready to accept
1768 // these child definitions.
1769 if (!die.HasChildren()) {
1770 // No children for this struct/union/class, lets finish it
1771 if (TypeSystemClang::StartTagDeclarationDefinition(clang_type)) {
1772 TypeSystemClang::CompleteTagDeclarationDefinition(clang_type);
1773 } else {
1774 dwarf->GetObjectFile()->GetModule()->ReportError(
1775 "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its "
1776 "definition.\nPlease file a bug and attach the file at the "
1777 "start of this error message",
1778 die.GetOffset(), attrs.name.GetCString());
1779 }
1780
1781 // If the byte size of the record is specified then overwrite the size
1782 // that would be computed by Clang. This is only needed as LLDB's
1783 // TypeSystemClang is always in C++ mode, but some compilers such as
1784 // GCC and Clang give empty structs a size of 0 in C mode (in contrast to
1785 // the size of 1 for empty structs that would be computed in C++ mode).
1786 if (attrs.byte_size) {
1787 clang::RecordDecl *record_decl =
1788 TypeSystemClang::GetAsRecordDecl(clang_type);
1789 if (record_decl) {
1790 ClangASTImporter::LayoutInfo layout;
1791 layout.bit_size = *attrs.byte_size * 8;
1792 GetClangASTImporter().SetRecordLayout(record_decl, layout);
1793 }
1794 }
1795 } else if (clang_type_was_created) {
1796 // Start the definition if the class is not objective C since the
1797 // underlying decls respond to isCompleteDefinition(). Objective
1798 // C decls don't respond to isCompleteDefinition() so we can't
1799 // start the declaration definition right away. For C++
1800 // class/union/structs we want to start the definition in case the
1801 // class is needed as the declaration context for a contained class
1802 // or type without the need to complete that type..
1803
1804 if (attrs.class_language != eLanguageTypeObjC &&
1805 attrs.class_language != eLanguageTypeObjC_plus_plus)
1806 TypeSystemClang::StartTagDeclarationDefinition(clang_type);
1807
1808 // Leave this as a forward declaration until we need to know the
1809 // details of the type. lldb_private::Type will automatically call
1810 // the SymbolFile virtual function
1811 // "SymbolFileDWARF::CompleteType(Type *)" When the definition
1812 // needs to be defined.
1813 assert(!dwarf->GetForwardDeclClangTypeToDie().count(
1814 ClangUtil::RemoveFastQualifiers(clang_type)
1815 .GetOpaqueQualType()) &&
1816 "Type already in the forward declaration map!");
1817 // Can't assume m_ast.GetSymbolFile() is actually a
1818 // SymbolFileDWARF, it can be a SymbolFileDWARFDebugMap for Apple
1819 // binaries.
1820 dwarf->GetForwardDeclDieToClangType()[die.GetDIE()] =
1821 clang_type.GetOpaqueQualType();
1822 dwarf->GetForwardDeclClangTypeToDie().try_emplace(
1823 ClangUtil::RemoveFastQualifiers(clang_type).GetOpaqueQualType(),
1824 *die.GetDIERef());
1825 m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), true);
1826 }
1827 }
1828
1829 // If we made a clang type, set the trivial abi if applicable: We only
1830 // do this for pass by value - which implies the Trivial ABI. There
1831 // isn't a way to assert that something that would normally be pass by
1832 // value is pass by reference, so we ignore that attribute if set.
1833 if (attrs.calling_convention == llvm::dwarf::DW_CC_pass_by_value) {
1834 clang::CXXRecordDecl *record_decl =
1835 m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
1836 if (record_decl && record_decl->getDefinition()) {
1837 record_decl->setHasTrivialSpecialMemberForCall();
1838 }
1839 }
1840
1841 if (attrs.calling_convention == llvm::dwarf::DW_CC_pass_by_reference) {
1842 clang::CXXRecordDecl *record_decl =
1843 m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
1844 if (record_decl)
1845 record_decl->setArgPassingRestrictions(
1846 clang::RecordDecl::APK_CannotPassInRegs);
1847 }
1848 return type_sp;
1849 }
1850
1851 // DWARF parsing functions
1852
1853 class DWARFASTParserClang::DelayedAddObjCClassProperty {
1854 public:
DelayedAddObjCClassProperty(const CompilerType & class_opaque_type,const char * property_name,const CompilerType & property_opaque_type,const char * property_setter_name,const char * property_getter_name,uint32_t property_attributes,const ClangASTMetadata * metadata)1855 DelayedAddObjCClassProperty(
1856 const CompilerType &class_opaque_type, const char *property_name,
1857 const CompilerType &property_opaque_type, // The property type is only
1858 // required if you don't have an
1859 // ivar decl
1860 const char *property_setter_name, const char *property_getter_name,
1861 uint32_t property_attributes, const ClangASTMetadata *metadata)
1862 : m_class_opaque_type(class_opaque_type), m_property_name(property_name),
1863 m_property_opaque_type(property_opaque_type),
1864 m_property_setter_name(property_setter_name),
1865 m_property_getter_name(property_getter_name),
1866 m_property_attributes(property_attributes) {
1867 if (metadata != nullptr) {
1868 m_metadata_up = std::make_unique<ClangASTMetadata>();
1869 *m_metadata_up = *metadata;
1870 }
1871 }
1872
DelayedAddObjCClassProperty(const DelayedAddObjCClassProperty & rhs)1873 DelayedAddObjCClassProperty(const DelayedAddObjCClassProperty &rhs) {
1874 *this = rhs;
1875 }
1876
1877 DelayedAddObjCClassProperty &
operator =(const DelayedAddObjCClassProperty & rhs)1878 operator=(const DelayedAddObjCClassProperty &rhs) {
1879 m_class_opaque_type = rhs.m_class_opaque_type;
1880 m_property_name = rhs.m_property_name;
1881 m_property_opaque_type = rhs.m_property_opaque_type;
1882 m_property_setter_name = rhs.m_property_setter_name;
1883 m_property_getter_name = rhs.m_property_getter_name;
1884 m_property_attributes = rhs.m_property_attributes;
1885
1886 if (rhs.m_metadata_up) {
1887 m_metadata_up = std::make_unique<ClangASTMetadata>();
1888 *m_metadata_up = *rhs.m_metadata_up;
1889 }
1890 return *this;
1891 }
1892
Finalize()1893 bool Finalize() {
1894 return TypeSystemClang::AddObjCClassProperty(
1895 m_class_opaque_type, m_property_name, m_property_opaque_type,
1896 /*ivar_decl=*/nullptr, m_property_setter_name, m_property_getter_name,
1897 m_property_attributes, m_metadata_up.get());
1898 }
1899
1900 private:
1901 CompilerType m_class_opaque_type;
1902 const char *m_property_name;
1903 CompilerType m_property_opaque_type;
1904 const char *m_property_setter_name;
1905 const char *m_property_getter_name;
1906 uint32_t m_property_attributes;
1907 std::unique_ptr<ClangASTMetadata> m_metadata_up;
1908 };
1909
ParseTemplateDIE(const DWARFDIE & die,TypeSystemClang::TemplateParameterInfos & template_param_infos)1910 bool DWARFASTParserClang::ParseTemplateDIE(
1911 const DWARFDIE &die,
1912 TypeSystemClang::TemplateParameterInfos &template_param_infos) {
1913 const dw_tag_t tag = die.Tag();
1914 bool is_template_template_argument = false;
1915
1916 switch (tag) {
1917 case DW_TAG_GNU_template_parameter_pack: {
1918 template_param_infos.packed_args =
1919 std::make_unique<TypeSystemClang::TemplateParameterInfos>();
1920 for (DWARFDIE child_die : die.children()) {
1921 if (!ParseTemplateDIE(child_die, *template_param_infos.packed_args))
1922 return false;
1923 }
1924 if (const char *name = die.GetName()) {
1925 template_param_infos.pack_name = name;
1926 }
1927 return true;
1928 }
1929 case DW_TAG_GNU_template_template_param:
1930 is_template_template_argument = true;
1931 LLVM_FALLTHROUGH;
1932 case DW_TAG_template_type_parameter:
1933 case DW_TAG_template_value_parameter: {
1934 DWARFAttributes attributes;
1935 const size_t num_attributes = die.GetAttributes(attributes);
1936 const char *name = nullptr;
1937 const char *template_name = nullptr;
1938 CompilerType clang_type;
1939 uint64_t uval64 = 0;
1940 bool uval64_valid = false;
1941 if (num_attributes > 0) {
1942 DWARFFormValue form_value;
1943 for (size_t i = 0; i < num_attributes; ++i) {
1944 const dw_attr_t attr = attributes.AttributeAtIndex(i);
1945
1946 switch (attr) {
1947 case DW_AT_name:
1948 if (attributes.ExtractFormValueAtIndex(i, form_value))
1949 name = form_value.AsCString();
1950 break;
1951
1952 case DW_AT_GNU_template_name:
1953 if (attributes.ExtractFormValueAtIndex(i, form_value))
1954 template_name = form_value.AsCString();
1955 break;
1956
1957 case DW_AT_type:
1958 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1959 Type *lldb_type = die.ResolveTypeUID(form_value.Reference());
1960 if (lldb_type)
1961 clang_type = lldb_type->GetForwardCompilerType();
1962 }
1963 break;
1964
1965 case DW_AT_const_value:
1966 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1967 uval64_valid = true;
1968 uval64 = form_value.Unsigned();
1969 }
1970 break;
1971 default:
1972 break;
1973 }
1974 }
1975
1976 clang::ASTContext &ast = m_ast.getASTContext();
1977 if (!clang_type)
1978 clang_type = m_ast.GetBasicType(eBasicTypeVoid);
1979
1980 if (!is_template_template_argument) {
1981 bool is_signed = false;
1982 if (name && name[0])
1983 template_param_infos.names.push_back(name);
1984 else
1985 template_param_infos.names.push_back(nullptr);
1986
1987 // Get the signed value for any integer or enumeration if available
1988 clang_type.IsIntegerOrEnumerationType(is_signed);
1989
1990 if (tag == DW_TAG_template_value_parameter && uval64_valid) {
1991 llvm::Optional<uint64_t> size = clang_type.GetBitSize(nullptr);
1992 if (!size)
1993 return false;
1994 llvm::APInt apint(*size, uval64, is_signed);
1995 template_param_infos.args.push_back(
1996 clang::TemplateArgument(ast, llvm::APSInt(apint, !is_signed),
1997 ClangUtil::GetQualType(clang_type)));
1998 } else {
1999 template_param_infos.args.push_back(
2000 clang::TemplateArgument(ClangUtil::GetQualType(clang_type)));
2001 }
2002 } else {
2003 auto *tplt_type = m_ast.CreateTemplateTemplateParmDecl(template_name);
2004 template_param_infos.names.push_back(name);
2005 template_param_infos.args.push_back(
2006 clang::TemplateArgument(clang::TemplateName(tplt_type)));
2007 }
2008 }
2009 }
2010 return true;
2011
2012 default:
2013 break;
2014 }
2015 return false;
2016 }
2017
ParseTemplateParameterInfos(const DWARFDIE & parent_die,TypeSystemClang::TemplateParameterInfos & template_param_infos)2018 bool DWARFASTParserClang::ParseTemplateParameterInfos(
2019 const DWARFDIE &parent_die,
2020 TypeSystemClang::TemplateParameterInfos &template_param_infos) {
2021
2022 if (!parent_die)
2023 return false;
2024
2025 for (DWARFDIE die : parent_die.children()) {
2026 const dw_tag_t tag = die.Tag();
2027
2028 switch (tag) {
2029 case DW_TAG_template_type_parameter:
2030 case DW_TAG_template_value_parameter:
2031 case DW_TAG_GNU_template_parameter_pack:
2032 case DW_TAG_GNU_template_template_param:
2033 ParseTemplateDIE(die, template_param_infos);
2034 break;
2035
2036 default:
2037 break;
2038 }
2039 }
2040 return template_param_infos.args.size() == template_param_infos.names.size();
2041 }
2042
CompleteRecordType(const DWARFDIE & die,lldb_private::Type * type,CompilerType & clang_type)2043 bool DWARFASTParserClang::CompleteRecordType(const DWARFDIE &die,
2044 lldb_private::Type *type,
2045 CompilerType &clang_type) {
2046 const dw_tag_t tag = die.Tag();
2047 SymbolFileDWARF *dwarf = die.GetDWARF();
2048
2049 ClangASTImporter::LayoutInfo layout_info;
2050
2051 if (die.HasChildren()) {
2052 const bool type_is_objc_object_or_interface =
2053 TypeSystemClang::IsObjCObjectOrInterfaceType(clang_type);
2054 if (type_is_objc_object_or_interface) {
2055 // For objective C we don't start the definition when the class is
2056 // created.
2057 TypeSystemClang::StartTagDeclarationDefinition(clang_type);
2058 }
2059
2060 AccessType default_accessibility = eAccessNone;
2061 if (tag == DW_TAG_structure_type) {
2062 default_accessibility = eAccessPublic;
2063 } else if (tag == DW_TAG_union_type) {
2064 default_accessibility = eAccessPublic;
2065 } else if (tag == DW_TAG_class_type) {
2066 default_accessibility = eAccessPrivate;
2067 }
2068
2069 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases;
2070 // Parse members and base classes first
2071 std::vector<DWARFDIE> member_function_dies;
2072
2073 DelayedPropertyList delayed_properties;
2074 ParseChildMembers(die, clang_type, bases, member_function_dies,
2075 delayed_properties, default_accessibility, layout_info);
2076
2077 // Now parse any methods if there were any...
2078 for (const DWARFDIE &die : member_function_dies)
2079 dwarf->ResolveType(die);
2080
2081 if (type_is_objc_object_or_interface) {
2082 ConstString class_name(clang_type.GetTypeName());
2083 if (class_name) {
2084 dwarf->GetObjCMethods(class_name, [&](DWARFDIE method_die) {
2085 method_die.ResolveType();
2086 return true;
2087 });
2088
2089 for (DelayedAddObjCClassProperty &property : delayed_properties)
2090 property.Finalize();
2091 }
2092 }
2093
2094 if (!bases.empty()) {
2095 // Make sure all base classes refer to complete types and not forward
2096 // declarations. If we don't do this, clang will crash with an
2097 // assertion in the call to clang_type.TransferBaseClasses()
2098 for (const auto &base_class : bases) {
2099 clang::TypeSourceInfo *type_source_info =
2100 base_class->getTypeSourceInfo();
2101 if (type_source_info)
2102 RequireCompleteType(m_ast.GetType(type_source_info->getType()));
2103 }
2104
2105 m_ast.TransferBaseClasses(clang_type.GetOpaqueQualType(),
2106 std::move(bases));
2107 }
2108 }
2109
2110 m_ast.AddMethodOverridesForCXXRecordType(clang_type.GetOpaqueQualType());
2111 TypeSystemClang::BuildIndirectFields(clang_type);
2112 TypeSystemClang::CompleteTagDeclarationDefinition(clang_type);
2113
2114 if (!layout_info.field_offsets.empty() || !layout_info.base_offsets.empty() ||
2115 !layout_info.vbase_offsets.empty()) {
2116 if (type)
2117 layout_info.bit_size = type->GetByteSize(nullptr).value_or(0) * 8;
2118 if (layout_info.bit_size == 0)
2119 layout_info.bit_size =
2120 die.GetAttributeValueAsUnsigned(DW_AT_byte_size, 0) * 8;
2121
2122 clang::CXXRecordDecl *record_decl =
2123 m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
2124 if (record_decl)
2125 GetClangASTImporter().SetRecordLayout(record_decl, layout_info);
2126 }
2127
2128 return (bool)clang_type;
2129 }
2130
CompleteEnumType(const DWARFDIE & die,lldb_private::Type * type,CompilerType & clang_type)2131 bool DWARFASTParserClang::CompleteEnumType(const DWARFDIE &die,
2132 lldb_private::Type *type,
2133 CompilerType &clang_type) {
2134 if (TypeSystemClang::StartTagDeclarationDefinition(clang_type)) {
2135 if (die.HasChildren()) {
2136 bool is_signed = false;
2137 clang_type.IsIntegerType(is_signed);
2138 ParseChildEnumerators(clang_type, is_signed,
2139 type->GetByteSize(nullptr).value_or(0), die);
2140 }
2141 TypeSystemClang::CompleteTagDeclarationDefinition(clang_type);
2142 }
2143 return (bool)clang_type;
2144 }
2145
CompleteTypeFromDWARF(const DWARFDIE & die,lldb_private::Type * type,CompilerType & clang_type)2146 bool DWARFASTParserClang::CompleteTypeFromDWARF(const DWARFDIE &die,
2147 lldb_private::Type *type,
2148 CompilerType &clang_type) {
2149 SymbolFileDWARF *dwarf = die.GetDWARF();
2150
2151 std::lock_guard<std::recursive_mutex> guard(
2152 dwarf->GetObjectFile()->GetModule()->GetMutex());
2153
2154 // Disable external storage for this type so we don't get anymore
2155 // clang::ExternalASTSource queries for this type.
2156 m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), false);
2157
2158 if (!die)
2159 return false;
2160
2161 const dw_tag_t tag = die.Tag();
2162
2163 assert(clang_type);
2164 DWARFAttributes attributes;
2165 switch (tag) {
2166 case DW_TAG_structure_type:
2167 case DW_TAG_union_type:
2168 case DW_TAG_class_type:
2169 return CompleteRecordType(die, type, clang_type);
2170 case DW_TAG_enumeration_type:
2171 return CompleteEnumType(die, type, clang_type);
2172 default:
2173 assert(false && "not a forward clang type decl!");
2174 break;
2175 }
2176
2177 return false;
2178 }
2179
EnsureAllDIEsInDeclContextHaveBeenParsed(lldb_private::CompilerDeclContext decl_context)2180 void DWARFASTParserClang::EnsureAllDIEsInDeclContextHaveBeenParsed(
2181 lldb_private::CompilerDeclContext decl_context) {
2182 auto opaque_decl_ctx =
2183 (clang::DeclContext *)decl_context.GetOpaqueDeclContext();
2184 for (auto it = m_decl_ctx_to_die.find(opaque_decl_ctx);
2185 it != m_decl_ctx_to_die.end() && it->first == opaque_decl_ctx;
2186 it = m_decl_ctx_to_die.erase(it))
2187 for (DWARFDIE decl : it->second.children())
2188 GetClangDeclForDIE(decl);
2189 }
2190
GetDeclForUIDFromDWARF(const DWARFDIE & die)2191 CompilerDecl DWARFASTParserClang::GetDeclForUIDFromDWARF(const DWARFDIE &die) {
2192 clang::Decl *clang_decl = GetClangDeclForDIE(die);
2193 if (clang_decl != nullptr)
2194 return m_ast.GetCompilerDecl(clang_decl);
2195 return CompilerDecl();
2196 }
2197
2198 CompilerDeclContext
GetDeclContextForUIDFromDWARF(const DWARFDIE & die)2199 DWARFASTParserClang::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) {
2200 clang::DeclContext *clang_decl_ctx = GetClangDeclContextForDIE(die);
2201 if (clang_decl_ctx)
2202 return m_ast.CreateDeclContext(clang_decl_ctx);
2203 return CompilerDeclContext();
2204 }
2205
2206 CompilerDeclContext
GetDeclContextContainingUIDFromDWARF(const DWARFDIE & die)2207 DWARFASTParserClang::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) {
2208 clang::DeclContext *clang_decl_ctx =
2209 GetClangDeclContextContainingDIE(die, nullptr);
2210 if (clang_decl_ctx)
2211 return m_ast.CreateDeclContext(clang_decl_ctx);
2212 return CompilerDeclContext();
2213 }
2214
ParseChildEnumerators(lldb_private::CompilerType & clang_type,bool is_signed,uint32_t enumerator_byte_size,const DWARFDIE & parent_die)2215 size_t DWARFASTParserClang::ParseChildEnumerators(
2216 lldb_private::CompilerType &clang_type, bool is_signed,
2217 uint32_t enumerator_byte_size, const DWARFDIE &parent_die) {
2218 if (!parent_die)
2219 return 0;
2220
2221 size_t enumerators_added = 0;
2222
2223 for (DWARFDIE die : parent_die.children()) {
2224 const dw_tag_t tag = die.Tag();
2225 if (tag == DW_TAG_enumerator) {
2226 DWARFAttributes attributes;
2227 const size_t num_child_attributes = die.GetAttributes(attributes);
2228 if (num_child_attributes > 0) {
2229 const char *name = nullptr;
2230 bool got_value = false;
2231 int64_t enum_value = 0;
2232 Declaration decl;
2233
2234 uint32_t i;
2235 for (i = 0; i < num_child_attributes; ++i) {
2236 const dw_attr_t attr = attributes.AttributeAtIndex(i);
2237 DWARFFormValue form_value;
2238 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2239 switch (attr) {
2240 case DW_AT_const_value:
2241 got_value = true;
2242 if (is_signed)
2243 enum_value = form_value.Signed();
2244 else
2245 enum_value = form_value.Unsigned();
2246 break;
2247
2248 case DW_AT_name:
2249 name = form_value.AsCString();
2250 break;
2251
2252 case DW_AT_description:
2253 default:
2254 case DW_AT_decl_file:
2255 decl.SetFile(attributes.CompileUnitAtIndex(i)->GetFile(
2256 form_value.Unsigned()));
2257 break;
2258 case DW_AT_decl_line:
2259 decl.SetLine(form_value.Unsigned());
2260 break;
2261 case DW_AT_decl_column:
2262 decl.SetColumn(form_value.Unsigned());
2263 break;
2264 case DW_AT_sibling:
2265 break;
2266 }
2267 }
2268 }
2269
2270 if (name && name[0] && got_value) {
2271 m_ast.AddEnumerationValueToEnumerationType(
2272 clang_type, decl, name, enum_value, enumerator_byte_size * 8);
2273 ++enumerators_added;
2274 }
2275 }
2276 }
2277 }
2278 return enumerators_added;
2279 }
2280
2281 Function *
ParseFunctionFromDWARF(CompileUnit & comp_unit,const DWARFDIE & die,const AddressRange & func_range)2282 DWARFASTParserClang::ParseFunctionFromDWARF(CompileUnit &comp_unit,
2283 const DWARFDIE &die,
2284 const AddressRange &func_range) {
2285 assert(func_range.GetBaseAddress().IsValid());
2286 DWARFRangeList func_ranges;
2287 const char *name = nullptr;
2288 const char *mangled = nullptr;
2289 int decl_file = 0;
2290 int decl_line = 0;
2291 int decl_column = 0;
2292 int call_file = 0;
2293 int call_line = 0;
2294 int call_column = 0;
2295 DWARFExpressionList frame_base;
2296
2297 const dw_tag_t tag = die.Tag();
2298
2299 if (tag != DW_TAG_subprogram)
2300 return nullptr;
2301
2302 if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line,
2303 decl_column, call_file, call_line, call_column,
2304 &frame_base)) {
2305 Mangled func_name;
2306 if (mangled)
2307 func_name.SetValue(ConstString(mangled), true);
2308 else if ((die.GetParent().Tag() == DW_TAG_compile_unit ||
2309 die.GetParent().Tag() == DW_TAG_partial_unit) &&
2310 Language::LanguageIsCPlusPlus(
2311 SymbolFileDWARF::GetLanguage(*die.GetCU())) &&
2312 !Language::LanguageIsObjC(
2313 SymbolFileDWARF::GetLanguage(*die.GetCU())) &&
2314 name && strcmp(name, "main") != 0) {
2315 // If the mangled name is not present in the DWARF, generate the
2316 // demangled name using the decl context. We skip if the function is
2317 // "main" as its name is never mangled.
2318 bool is_static = false;
2319 bool is_variadic = false;
2320 bool has_template_params = false;
2321 unsigned type_quals = 0;
2322 std::vector<CompilerType> param_types;
2323 std::vector<clang::ParmVarDecl *> param_decls;
2324 StreamString sstr;
2325
2326 DWARFDeclContext decl_ctx = SymbolFileDWARF::GetDWARFDeclContext(die);
2327 sstr << decl_ctx.GetQualifiedName();
2328
2329 clang::DeclContext *containing_decl_ctx =
2330 GetClangDeclContextContainingDIE(die, nullptr);
2331 ParseChildParameters(containing_decl_ctx, die, true, is_static,
2332 is_variadic, has_template_params, param_types,
2333 param_decls, type_quals);
2334 sstr << "(";
2335 for (size_t i = 0; i < param_types.size(); i++) {
2336 if (i > 0)
2337 sstr << ", ";
2338 sstr << param_types[i].GetTypeName();
2339 }
2340 if (is_variadic)
2341 sstr << ", ...";
2342 sstr << ")";
2343 if (type_quals & clang::Qualifiers::Const)
2344 sstr << " const";
2345
2346 func_name.SetValue(ConstString(sstr.GetString()), false);
2347 } else
2348 func_name.SetValue(ConstString(name), false);
2349
2350 FunctionSP func_sp;
2351 std::unique_ptr<Declaration> decl_up;
2352 if (decl_file != 0 || decl_line != 0 || decl_column != 0)
2353 decl_up = std::make_unique<Declaration>(die.GetCU()->GetFile(decl_file),
2354 decl_line, decl_column);
2355
2356 SymbolFileDWARF *dwarf = die.GetDWARF();
2357 // Supply the type _only_ if it has already been parsed
2358 Type *func_type = dwarf->GetDIEToType().lookup(die.GetDIE());
2359
2360 assert(func_type == nullptr || func_type != DIE_IS_BEING_PARSED);
2361
2362 const user_id_t func_user_id = die.GetID();
2363 func_sp =
2364 std::make_shared<Function>(&comp_unit,
2365 func_user_id, // UserID is the DIE offset
2366 func_user_id, func_name, func_type,
2367 func_range); // first address range
2368
2369 if (func_sp.get() != nullptr) {
2370 if (frame_base.IsValid())
2371 func_sp->GetFrameBaseExpression() = frame_base;
2372 comp_unit.AddFunction(func_sp);
2373 return func_sp.get();
2374 }
2375 }
2376 return nullptr;
2377 }
2378
2379 namespace {
2380 /// Parsed form of all attributes that are relevant for parsing type members.
2381 struct MemberAttributes {
2382 explicit MemberAttributes(const DWARFDIE &die, const DWARFDIE &parent_die,
2383 ModuleSP module_sp);
2384 const char *name = nullptr;
2385 /// Indicates how many bits into the word (according to the host endianness)
2386 /// the low-order bit of the field starts. Can be negative.
2387 int64_t bit_offset = 0;
2388 /// Indicates the size of the field in bits.
2389 size_t bit_size = 0;
2390 uint64_t data_bit_offset = UINT64_MAX;
2391 AccessType accessibility = eAccessNone;
2392 llvm::Optional<uint64_t> byte_size;
2393 llvm::Optional<DWARFFormValue> const_value_form;
2394 DWARFFormValue encoding_form;
2395 /// Indicates the byte offset of the word from the base address of the
2396 /// structure.
2397 uint32_t member_byte_offset;
2398 bool is_artificial = false;
2399 };
2400
2401 /// Parsed form of all attributes that are relevant for parsing Objective-C
2402 /// properties.
2403 struct PropertyAttributes {
2404 explicit PropertyAttributes(const DWARFDIE &die);
2405 const char *prop_name = nullptr;
2406 const char *prop_getter_name = nullptr;
2407 const char *prop_setter_name = nullptr;
2408 /// \see clang::ObjCPropertyAttribute
2409 uint32_t prop_attributes = 0;
2410 };
2411 } // namespace
2412
MemberAttributes(const DWARFDIE & die,const DWARFDIE & parent_die,ModuleSP module_sp)2413 MemberAttributes::MemberAttributes(const DWARFDIE &die,
2414 const DWARFDIE &parent_die,
2415 ModuleSP module_sp) {
2416 member_byte_offset = (parent_die.Tag() == DW_TAG_union_type) ? 0 : UINT32_MAX;
2417
2418 DWARFAttributes attributes;
2419 const size_t num_attributes = die.GetAttributes(attributes);
2420 for (std::size_t i = 0; i < num_attributes; ++i) {
2421 const dw_attr_t attr = attributes.AttributeAtIndex(i);
2422 DWARFFormValue form_value;
2423 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2424 switch (attr) {
2425 case DW_AT_name:
2426 name = form_value.AsCString();
2427 break;
2428 case DW_AT_type:
2429 encoding_form = form_value;
2430 break;
2431 case DW_AT_bit_offset:
2432 bit_offset = form_value.Signed();
2433 break;
2434 case DW_AT_bit_size:
2435 bit_size = form_value.Unsigned();
2436 break;
2437 case DW_AT_byte_size:
2438 byte_size = form_value.Unsigned();
2439 break;
2440 case DW_AT_const_value:
2441 const_value_form = form_value;
2442 break;
2443 case DW_AT_data_bit_offset:
2444 data_bit_offset = form_value.Unsigned();
2445 break;
2446 case DW_AT_data_member_location:
2447 if (form_value.BlockData()) {
2448 Value initialValue(0);
2449 Value memberOffset(0);
2450 const DWARFDataExtractor &debug_info_data = die.GetData();
2451 uint32_t block_length = form_value.Unsigned();
2452 uint32_t block_offset =
2453 form_value.BlockData() - debug_info_data.GetDataStart();
2454 if (DWARFExpression::Evaluate(
2455 nullptr, // ExecutionContext *
2456 nullptr, // RegisterContext *
2457 module_sp,
2458 DataExtractor(debug_info_data, block_offset, block_length),
2459 die.GetCU(), eRegisterKindDWARF, &initialValue, nullptr,
2460 memberOffset, nullptr)) {
2461 member_byte_offset = memberOffset.ResolveValue(nullptr).UInt();
2462 }
2463 } else {
2464 // With DWARF 3 and later, if the value is an integer constant,
2465 // this form value is the offset in bytes from the beginning of
2466 // the containing entity.
2467 member_byte_offset = form_value.Unsigned();
2468 }
2469 break;
2470
2471 case DW_AT_accessibility:
2472 accessibility = DWARFASTParser::GetAccessTypeFromDWARF(form_value.Unsigned());
2473 break;
2474 case DW_AT_artificial:
2475 is_artificial = form_value.Boolean();
2476 break;
2477 default:
2478 break;
2479 }
2480 }
2481 }
2482
2483 // Clang has a DWARF generation bug where sometimes it represents
2484 // fields that are references with bad byte size and bit size/offset
2485 // information such as:
2486 //
2487 // DW_AT_byte_size( 0x00 )
2488 // DW_AT_bit_size( 0x40 )
2489 // DW_AT_bit_offset( 0xffffffffffffffc0 )
2490 //
2491 // So check the bit offset to make sure it is sane, and if the values
2492 // are not sane, remove them. If we don't do this then we will end up
2493 // with a crash if we try to use this type in an expression when clang
2494 // becomes unhappy with its recycled debug info.
2495 if (byte_size.value_or(0) == 0 && bit_offset < 0) {
2496 bit_size = 0;
2497 bit_offset = 0;
2498 }
2499 }
2500
PropertyAttributes(const DWARFDIE & die)2501 PropertyAttributes::PropertyAttributes(const DWARFDIE &die) {
2502
2503 DWARFAttributes attributes;
2504 const size_t num_attributes = die.GetAttributes(attributes);
2505 for (size_t i = 0; i < num_attributes; ++i) {
2506 const dw_attr_t attr = attributes.AttributeAtIndex(i);
2507 DWARFFormValue form_value;
2508 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2509 switch (attr) {
2510 case DW_AT_APPLE_property_name:
2511 prop_name = form_value.AsCString();
2512 break;
2513 case DW_AT_APPLE_property_getter:
2514 prop_getter_name = form_value.AsCString();
2515 break;
2516 case DW_AT_APPLE_property_setter:
2517 prop_setter_name = form_value.AsCString();
2518 break;
2519 case DW_AT_APPLE_property_attribute:
2520 prop_attributes = form_value.Unsigned();
2521 break;
2522 default:
2523 break;
2524 }
2525 }
2526 }
2527
2528 if (!prop_name)
2529 return;
2530 ConstString fixed_setter;
2531
2532 // Check if the property getter/setter were provided as full names.
2533 // We want basenames, so we extract them.
2534 if (prop_getter_name && prop_getter_name[0] == '-') {
2535 ObjCLanguage::MethodName prop_getter_method(prop_getter_name, true);
2536 prop_getter_name = prop_getter_method.GetSelector().GetCString();
2537 }
2538
2539 if (prop_setter_name && prop_setter_name[0] == '-') {
2540 ObjCLanguage::MethodName prop_setter_method(prop_setter_name, true);
2541 prop_setter_name = prop_setter_method.GetSelector().GetCString();
2542 }
2543
2544 // If the names haven't been provided, they need to be filled in.
2545 if (!prop_getter_name)
2546 prop_getter_name = prop_name;
2547 if (!prop_setter_name && prop_name[0] &&
2548 !(prop_attributes & DW_APPLE_PROPERTY_readonly)) {
2549 StreamString ss;
2550
2551 ss.Printf("set%c%s:", toupper(prop_name[0]), &prop_name[1]);
2552
2553 fixed_setter.SetString(ss.GetString());
2554 prop_setter_name = fixed_setter.GetCString();
2555 }
2556 }
2557
ParseObjCProperty(const DWARFDIE & die,const DWARFDIE & parent_die,const lldb_private::CompilerType & class_clang_type,DelayedPropertyList & delayed_properties)2558 void DWARFASTParserClang::ParseObjCProperty(
2559 const DWARFDIE &die, const DWARFDIE &parent_die,
2560 const lldb_private::CompilerType &class_clang_type,
2561 DelayedPropertyList &delayed_properties) {
2562 // This function can only parse DW_TAG_APPLE_property.
2563 assert(die.Tag() == DW_TAG_APPLE_property);
2564
2565 ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule();
2566
2567 const MemberAttributes attrs(die, parent_die, module_sp);
2568 const PropertyAttributes propAttrs(die);
2569
2570 if (!propAttrs.prop_name) {
2571 module_sp->ReportError(
2572 "0x%8.8" PRIx64 ": DW_TAG_APPLE_property has no name.", die.GetID());
2573 return;
2574 }
2575
2576 Type *member_type = die.ResolveTypeUID(attrs.encoding_form.Reference());
2577 if (!member_type) {
2578 module_sp->ReportError("0x%8.8" PRIx64
2579 ": DW_TAG_APPLE_property '%s' refers to type 0x%8.8x"
2580 " which was unable to be parsed",
2581 die.GetID(), propAttrs.prop_name,
2582 attrs.encoding_form.Reference().GetOffset());
2583 return;
2584 }
2585
2586 ClangASTMetadata metadata;
2587 metadata.SetUserID(die.GetID());
2588 delayed_properties.push_back(DelayedAddObjCClassProperty(
2589 class_clang_type, propAttrs.prop_name,
2590 member_type->GetLayoutCompilerType(), propAttrs.prop_setter_name,
2591 propAttrs.prop_getter_name, propAttrs.prop_attributes, &metadata));
2592 }
2593
ExtractIntFromFormValue(const CompilerType & int_type,const DWARFFormValue & form_value) const2594 llvm::Expected<llvm::APInt> DWARFASTParserClang::ExtractIntFromFormValue(
2595 const CompilerType &int_type, const DWARFFormValue &form_value) const {
2596 clang::QualType qt = ClangUtil::GetQualType(int_type);
2597 assert(qt->isIntegralOrEnumerationType());
2598 TypeSystemClang &ts = *llvm::cast<TypeSystemClang>(int_type.GetTypeSystem());
2599 clang::ASTContext &ast = ts.getASTContext();
2600
2601 const unsigned type_bits = ast.getIntWidth(qt);
2602 const bool is_unsigned = qt->isUnsignedIntegerType();
2603
2604 // The maximum int size supported at the moment by this function. Limited
2605 // by the uint64_t return type of DWARFFormValue::Signed/Unsigned.
2606 constexpr std::size_t max_bit_size = 64;
2607
2608 // For values bigger than 64 bit (e.g. __int128_t values),
2609 // DWARFFormValue's Signed/Unsigned functions will return wrong results so
2610 // emit an error for now.
2611 if (type_bits > max_bit_size) {
2612 auto msg = llvm::formatv("Can only parse integers with up to {0} bits, but "
2613 "given integer has {1} bits.",
2614 max_bit_size, type_bits);
2615 return llvm::createStringError(llvm::inconvertibleErrorCode(), msg.str());
2616 }
2617
2618 // Construct an APInt with the maximum bit size and the given integer.
2619 llvm::APInt result(max_bit_size, form_value.Unsigned(), !is_unsigned);
2620
2621 // Calculate how many bits are required to represent the input value.
2622 // For unsigned types, take the number of active bits in the APInt.
2623 // For signed types, ask APInt how many bits are required to represent the
2624 // signed integer.
2625 const unsigned required_bits =
2626 is_unsigned ? result.getActiveBits() : result.getMinSignedBits();
2627
2628 // If the input value doesn't fit into the integer type, return an error.
2629 if (required_bits > type_bits) {
2630 std::string value_as_str = is_unsigned
2631 ? std::to_string(form_value.Unsigned())
2632 : std::to_string(form_value.Signed());
2633 auto msg = llvm::formatv("Can't store {0} value {1} in integer with {2} "
2634 "bits.",
2635 (is_unsigned ? "unsigned" : "signed"),
2636 value_as_str, type_bits);
2637 return llvm::createStringError(llvm::inconvertibleErrorCode(), msg.str());
2638 }
2639
2640 // Trim the result to the bit width our the int type.
2641 if (result.getBitWidth() > type_bits)
2642 result = result.trunc(type_bits);
2643 return result;
2644 }
2645
ParseSingleMember(const DWARFDIE & die,const DWARFDIE & parent_die,const lldb_private::CompilerType & class_clang_type,lldb::AccessType default_accessibility,lldb_private::ClangASTImporter::LayoutInfo & layout_info,FieldInfo & last_field_info)2646 void DWARFASTParserClang::ParseSingleMember(
2647 const DWARFDIE &die, const DWARFDIE &parent_die,
2648 const lldb_private::CompilerType &class_clang_type,
2649 lldb::AccessType default_accessibility,
2650 lldb_private::ClangASTImporter::LayoutInfo &layout_info,
2651 FieldInfo &last_field_info) {
2652 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups);
2653 // This function can only parse DW_TAG_member.
2654 assert(die.Tag() == DW_TAG_member);
2655
2656 ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule();
2657 const dw_tag_t tag = die.Tag();
2658 // Get the parent byte size so we can verify any members will fit
2659 const uint64_t parent_byte_size =
2660 parent_die.GetAttributeValueAsUnsigned(DW_AT_byte_size, UINT64_MAX);
2661 const uint64_t parent_bit_size =
2662 parent_byte_size == UINT64_MAX ? UINT64_MAX : parent_byte_size * 8;
2663
2664 // FIXME: Remove the workarounds below and make this const.
2665 MemberAttributes attrs(die, parent_die, module_sp);
2666
2667 const bool class_is_objc_object_or_interface =
2668 TypeSystemClang::IsObjCObjectOrInterfaceType(class_clang_type);
2669
2670 // FIXME: Make Clang ignore Objective-C accessibility for expressions
2671 if (class_is_objc_object_or_interface)
2672 attrs.accessibility = eAccessNone;
2673
2674 // Handle static members, which is any member that doesn't have a bit or a
2675 // byte member offset.
2676 if (attrs.member_byte_offset == UINT32_MAX &&
2677 attrs.data_bit_offset == UINT64_MAX) {
2678 Type *var_type = die.ResolveTypeUID(attrs.encoding_form.Reference());
2679
2680 if (var_type) {
2681 if (attrs.accessibility == eAccessNone)
2682 attrs.accessibility = eAccessPublic;
2683 CompilerType ct = var_type->GetForwardCompilerType();
2684 clang::VarDecl *v = TypeSystemClang::AddVariableToRecordType(
2685 class_clang_type, attrs.name, ct, attrs.accessibility);
2686 if (!v) {
2687 LLDB_LOG(log, "Failed to add variable to the record type");
2688 return;
2689 }
2690
2691 bool unused;
2692 // TODO: Support float/double static members as well.
2693 if (!attrs.const_value_form || !ct.IsIntegerOrEnumerationType(unused))
2694 return;
2695 llvm::Expected<llvm::APInt> const_value_or_err =
2696 ExtractIntFromFormValue(ct, *attrs.const_value_form);
2697 if (!const_value_or_err) {
2698 LLDB_LOG_ERROR(log, const_value_or_err.takeError(),
2699 "Failed to add const value to variable {1}: {0}",
2700 v->getQualifiedNameAsString());
2701 return;
2702 }
2703 TypeSystemClang::SetIntegerInitializerForVariable(v, *const_value_or_err);
2704 }
2705 return;
2706 }
2707
2708 Type *member_type = die.ResolveTypeUID(attrs.encoding_form.Reference());
2709 if (!member_type) {
2710 if (attrs.name)
2711 module_sp->ReportError(
2712 "0x%8.8" PRIx64 ": DW_TAG_member '%s' refers to type 0x%8.8x"
2713 " which was unable to be parsed",
2714 die.GetID(), attrs.name, attrs.encoding_form.Reference().GetOffset());
2715 else
2716 module_sp->ReportError(
2717 "0x%8.8" PRIx64 ": DW_TAG_member refers to type 0x%8.8x"
2718 " which was unable to be parsed",
2719 die.GetID(), attrs.encoding_form.Reference().GetOffset());
2720 return;
2721 }
2722
2723 const uint64_t character_width = 8;
2724 const uint64_t word_width = 32;
2725 CompilerType member_clang_type = member_type->GetLayoutCompilerType();
2726
2727 if (attrs.accessibility == eAccessNone)
2728 attrs.accessibility = default_accessibility;
2729
2730 uint64_t field_bit_offset = (attrs.member_byte_offset == UINT32_MAX
2731 ? 0
2732 : (attrs.member_byte_offset * 8));
2733
2734 if (attrs.bit_size > 0) {
2735 FieldInfo this_field_info;
2736 this_field_info.bit_offset = field_bit_offset;
2737 this_field_info.bit_size = attrs.bit_size;
2738
2739 if (attrs.data_bit_offset != UINT64_MAX) {
2740 this_field_info.bit_offset = attrs.data_bit_offset;
2741 } else {
2742 if (!attrs.byte_size)
2743 attrs.byte_size = member_type->GetByteSize(nullptr);
2744
2745 ObjectFile *objfile = die.GetDWARF()->GetObjectFile();
2746 if (objfile->GetByteOrder() == eByteOrderLittle) {
2747 this_field_info.bit_offset += attrs.byte_size.value_or(0) * 8;
2748 this_field_info.bit_offset -= (attrs.bit_offset + attrs.bit_size);
2749 } else {
2750 this_field_info.bit_offset += attrs.bit_offset;
2751 }
2752 }
2753
2754 // The ObjC runtime knows the byte offset but we still need to provide
2755 // the bit-offset in the layout. It just means something different then
2756 // what it does in C and C++. So we skip this check for ObjC types.
2757 //
2758 // We also skip this for fields of a union since they will all have a
2759 // zero offset.
2760 if (!TypeSystemClang::IsObjCObjectOrInterfaceType(class_clang_type) &&
2761 !(parent_die.Tag() == DW_TAG_union_type &&
2762 this_field_info.bit_offset == 0) &&
2763 ((this_field_info.bit_offset >= parent_bit_size) ||
2764 (last_field_info.IsBitfield() &&
2765 !last_field_info.NextBitfieldOffsetIsValid(
2766 this_field_info.bit_offset)))) {
2767 ObjectFile *objfile = die.GetDWARF()->GetObjectFile();
2768 objfile->GetModule()->ReportWarning(
2769 "0x%8.8" PRIx64 ": %s bitfield named \"%s\" has invalid "
2770 "bit offset (0x%8.8" PRIx64
2771 ") member will be ignored. Please file a bug against the "
2772 "compiler and include the preprocessed output for %s\n",
2773 die.GetID(), DW_TAG_value_to_name(tag), attrs.name,
2774 this_field_info.bit_offset, GetUnitName(parent_die).c_str());
2775 return;
2776 }
2777
2778 // Update the field bit offset we will report for layout
2779 field_bit_offset = this_field_info.bit_offset;
2780
2781 // Objective-C has invalid DW_AT_bit_offset values in older
2782 // versions of clang, so we have to be careful and only insert
2783 // unnamed bitfields if we have a new enough clang.
2784 bool detect_unnamed_bitfields = true;
2785
2786 if (class_is_objc_object_or_interface)
2787 detect_unnamed_bitfields =
2788 die.GetCU()->Supports_unnamed_objc_bitfields();
2789
2790 if (detect_unnamed_bitfields) {
2791 llvm::Optional<FieldInfo> unnamed_field_info;
2792 uint64_t last_field_end = 0;
2793
2794 last_field_end = last_field_info.bit_offset + last_field_info.bit_size;
2795
2796 if (!last_field_info.IsBitfield()) {
2797 // The last field was not a bit-field...
2798 // but if it did take up the entire word then we need to extend
2799 // last_field_end so the bit-field does not step into the last
2800 // fields padding.
2801 if (last_field_end != 0 && ((last_field_end % word_width) != 0))
2802 last_field_end += word_width - (last_field_end % word_width);
2803 }
2804
2805 // If we have a gap between the last_field_end and the current
2806 // field we have an unnamed bit-field.
2807 // If we have a base class, we assume there is no unnamed
2808 // bit-field if this is the first field since the gap can be
2809 // attributed to the members from the base class. This assumption
2810 // is not correct if the first field of the derived class is
2811 // indeed an unnamed bit-field. We currently do not have the
2812 // machinary to track the offset of the last field of classes we
2813 // have seen before, so we are not handling this case.
2814 if (this_field_info.bit_offset != last_field_end &&
2815 this_field_info.bit_offset > last_field_end &&
2816 !(last_field_info.bit_offset == 0 &&
2817 last_field_info.bit_size == 0 &&
2818 layout_info.base_offsets.size() != 0)) {
2819 unnamed_field_info = FieldInfo{};
2820 unnamed_field_info->bit_size =
2821 this_field_info.bit_offset - last_field_end;
2822 unnamed_field_info->bit_offset = last_field_end;
2823 }
2824
2825 if (unnamed_field_info) {
2826 clang::FieldDecl *unnamed_bitfield_decl =
2827 TypeSystemClang::AddFieldToRecordType(
2828 class_clang_type, llvm::StringRef(),
2829 m_ast.GetBuiltinTypeForEncodingAndBitSize(eEncodingSint,
2830 word_width),
2831 attrs.accessibility, unnamed_field_info->bit_size);
2832
2833 layout_info.field_offsets.insert(std::make_pair(
2834 unnamed_bitfield_decl, unnamed_field_info->bit_offset));
2835 }
2836 }
2837
2838 last_field_info = this_field_info;
2839 last_field_info.SetIsBitfield(true);
2840 } else {
2841 last_field_info.bit_offset = field_bit_offset;
2842
2843 if (llvm::Optional<uint64_t> clang_type_size =
2844 member_type->GetByteSize(nullptr)) {
2845 last_field_info.bit_size = *clang_type_size * character_width;
2846 }
2847
2848 last_field_info.SetIsBitfield(false);
2849 }
2850
2851 // Don't turn artificial members such as vtable pointers into real FieldDecls
2852 // in our AST. Clang will re-create those articial members and they would
2853 // otherwise just overlap in the layout with the FieldDecls we add here.
2854 // This needs to be done after updating FieldInfo which keeps track of where
2855 // field start/end so we don't later try to fill the the space of this
2856 // artificial member with (unnamed bitfield) padding.
2857 // FIXME: This check should verify that this is indeed an artificial member
2858 // we are supposed to ignore.
2859 if (attrs.is_artificial)
2860 return;
2861
2862 if (!member_clang_type.IsCompleteType())
2863 member_clang_type.GetCompleteType();
2864
2865 {
2866 // Older versions of clang emit array[0] and array[1] in the
2867 // same way (<rdar://problem/12566646>). If the current field
2868 // is at the end of the structure, then there is definitely no
2869 // room for extra elements and we override the type to
2870 // array[0].
2871
2872 CompilerType member_array_element_type;
2873 uint64_t member_array_size;
2874 bool member_array_is_incomplete;
2875
2876 if (member_clang_type.IsArrayType(&member_array_element_type,
2877 &member_array_size,
2878 &member_array_is_incomplete) &&
2879 !member_array_is_incomplete) {
2880 uint64_t parent_byte_size =
2881 parent_die.GetAttributeValueAsUnsigned(DW_AT_byte_size, UINT64_MAX);
2882
2883 if (attrs.member_byte_offset >= parent_byte_size) {
2884 if (member_array_size != 1 &&
2885 (member_array_size != 0 ||
2886 attrs.member_byte_offset > parent_byte_size)) {
2887 module_sp->ReportError(
2888 "0x%8.8" PRIx64 ": DW_TAG_member '%s' refers to type 0x%8.8x"
2889 " which extends beyond the bounds of 0x%8.8" PRIx64,
2890 die.GetID(), attrs.name,
2891 attrs.encoding_form.Reference().GetOffset(),
2892 parent_die.GetID());
2893 }
2894
2895 member_clang_type =
2896 m_ast.CreateArrayType(member_array_element_type, 0, false);
2897 }
2898 }
2899 }
2900
2901 RequireCompleteType(member_clang_type);
2902
2903 clang::FieldDecl *field_decl = TypeSystemClang::AddFieldToRecordType(
2904 class_clang_type, attrs.name, member_clang_type, attrs.accessibility,
2905 attrs.bit_size);
2906
2907 m_ast.SetMetadataAsUserID(field_decl, die.GetID());
2908
2909 layout_info.field_offsets.insert(
2910 std::make_pair(field_decl, field_bit_offset));
2911 }
2912
ParseChildMembers(const DWARFDIE & parent_die,CompilerType & class_clang_type,std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> & base_classes,std::vector<DWARFDIE> & member_function_dies,DelayedPropertyList & delayed_properties,const AccessType default_accessibility,ClangASTImporter::LayoutInfo & layout_info)2913 bool DWARFASTParserClang::ParseChildMembers(
2914 const DWARFDIE &parent_die, CompilerType &class_clang_type,
2915 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> &base_classes,
2916 std::vector<DWARFDIE> &member_function_dies,
2917 DelayedPropertyList &delayed_properties,
2918 const AccessType default_accessibility,
2919 ClangASTImporter::LayoutInfo &layout_info) {
2920 if (!parent_die)
2921 return false;
2922
2923 FieldInfo last_field_info;
2924
2925 ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule();
2926 TypeSystemClang *ast =
2927 llvm::dyn_cast_or_null<TypeSystemClang>(class_clang_type.GetTypeSystem());
2928 if (ast == nullptr)
2929 return false;
2930
2931 for (DWARFDIE die : parent_die.children()) {
2932 dw_tag_t tag = die.Tag();
2933
2934 switch (tag) {
2935 case DW_TAG_APPLE_property:
2936 ParseObjCProperty(die, parent_die, class_clang_type, delayed_properties);
2937 break;
2938
2939 case DW_TAG_member:
2940 ParseSingleMember(die, parent_die, class_clang_type,
2941 default_accessibility, layout_info, last_field_info);
2942 break;
2943
2944 case DW_TAG_subprogram:
2945 // Let the type parsing code handle this one for us.
2946 member_function_dies.push_back(die);
2947 break;
2948
2949 case DW_TAG_inheritance:
2950 ParseInheritance(die, parent_die, class_clang_type, default_accessibility,
2951 module_sp, base_classes, layout_info);
2952 break;
2953
2954 default:
2955 break;
2956 }
2957 }
2958
2959 return true;
2960 }
2961
ParseChildParameters(clang::DeclContext * containing_decl_ctx,const DWARFDIE & parent_die,bool skip_artificial,bool & is_static,bool & is_variadic,bool & has_template_params,std::vector<CompilerType> & function_param_types,std::vector<clang::ParmVarDecl * > & function_param_decls,unsigned & type_quals)2962 size_t DWARFASTParserClang::ParseChildParameters(
2963 clang::DeclContext *containing_decl_ctx, const DWARFDIE &parent_die,
2964 bool skip_artificial, bool &is_static, bool &is_variadic,
2965 bool &has_template_params, std::vector<CompilerType> &function_param_types,
2966 std::vector<clang::ParmVarDecl *> &function_param_decls,
2967 unsigned &type_quals) {
2968 if (!parent_die)
2969 return 0;
2970
2971 size_t arg_idx = 0;
2972 for (DWARFDIE die : parent_die.children()) {
2973 const dw_tag_t tag = die.Tag();
2974 switch (tag) {
2975 case DW_TAG_formal_parameter: {
2976 DWARFAttributes attributes;
2977 const size_t num_attributes = die.GetAttributes(attributes);
2978 if (num_attributes > 0) {
2979 const char *name = nullptr;
2980 DWARFFormValue param_type_die_form;
2981 bool is_artificial = false;
2982 // one of None, Auto, Register, Extern, Static, PrivateExtern
2983
2984 clang::StorageClass storage = clang::SC_None;
2985 uint32_t i;
2986 for (i = 0; i < num_attributes; ++i) {
2987 const dw_attr_t attr = attributes.AttributeAtIndex(i);
2988 DWARFFormValue form_value;
2989 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2990 switch (attr) {
2991 case DW_AT_name:
2992 name = form_value.AsCString();
2993 break;
2994 case DW_AT_type:
2995 param_type_die_form = form_value;
2996 break;
2997 case DW_AT_artificial:
2998 is_artificial = form_value.Boolean();
2999 break;
3000 case DW_AT_location:
3001 case DW_AT_const_value:
3002 case DW_AT_default_value:
3003 case DW_AT_description:
3004 case DW_AT_endianity:
3005 case DW_AT_is_optional:
3006 case DW_AT_segment:
3007 case DW_AT_variable_parameter:
3008 default:
3009 case DW_AT_abstract_origin:
3010 case DW_AT_sibling:
3011 break;
3012 }
3013 }
3014 }
3015
3016 bool skip = false;
3017 if (skip_artificial && is_artificial) {
3018 // In order to determine if a C++ member function is "const" we
3019 // have to look at the const-ness of "this"...
3020 if (arg_idx == 0 &&
3021 DeclKindIsCXXClass(containing_decl_ctx->getDeclKind()) &&
3022 // Often times compilers omit the "this" name for the
3023 // specification DIEs, so we can't rely upon the name being in
3024 // the formal parameter DIE...
3025 (name == nullptr || ::strcmp(name, "this") == 0)) {
3026 Type *this_type =
3027 die.ResolveTypeUID(param_type_die_form.Reference());
3028 if (this_type) {
3029 uint32_t encoding_mask = this_type->GetEncodingMask();
3030 if (encoding_mask & Type::eEncodingIsPointerUID) {
3031 is_static = false;
3032
3033 if (encoding_mask & (1u << Type::eEncodingIsConstUID))
3034 type_quals |= clang::Qualifiers::Const;
3035 if (encoding_mask & (1u << Type::eEncodingIsVolatileUID))
3036 type_quals |= clang::Qualifiers::Volatile;
3037 }
3038 }
3039 }
3040 skip = true;
3041 }
3042
3043 if (!skip) {
3044 Type *type = die.ResolveTypeUID(param_type_die_form.Reference());
3045 if (type) {
3046 function_param_types.push_back(type->GetForwardCompilerType());
3047
3048 clang::ParmVarDecl *param_var_decl =
3049 m_ast.CreateParameterDeclaration(
3050 containing_decl_ctx, GetOwningClangModule(die), name,
3051 type->GetForwardCompilerType(), storage);
3052 assert(param_var_decl);
3053 function_param_decls.push_back(param_var_decl);
3054
3055 m_ast.SetMetadataAsUserID(param_var_decl, die.GetID());
3056 }
3057 }
3058 }
3059 arg_idx++;
3060 } break;
3061
3062 case DW_TAG_unspecified_parameters:
3063 is_variadic = true;
3064 break;
3065
3066 case DW_TAG_template_type_parameter:
3067 case DW_TAG_template_value_parameter:
3068 case DW_TAG_GNU_template_parameter_pack:
3069 // The one caller of this was never using the template_param_infos, and
3070 // the local variable was taking up a large amount of stack space in
3071 // SymbolFileDWARF::ParseType() so this was removed. If we ever need the
3072 // template params back, we can add them back.
3073 // ParseTemplateDIE (dwarf_cu, die, template_param_infos);
3074 has_template_params = true;
3075 break;
3076
3077 default:
3078 break;
3079 }
3080 }
3081 return arg_idx;
3082 }
3083
GetTypeForDIE(const DWARFDIE & die)3084 Type *DWARFASTParserClang::GetTypeForDIE(const DWARFDIE &die) {
3085 if (die) {
3086 SymbolFileDWARF *dwarf = die.GetDWARF();
3087 DWARFAttributes attributes;
3088 const size_t num_attributes = die.GetAttributes(attributes);
3089 if (num_attributes > 0) {
3090 DWARFFormValue type_die_form;
3091 for (size_t i = 0; i < num_attributes; ++i) {
3092 dw_attr_t attr = attributes.AttributeAtIndex(i);
3093 DWARFFormValue form_value;
3094
3095 if (attr == DW_AT_type &&
3096 attributes.ExtractFormValueAtIndex(i, form_value))
3097 return dwarf->ResolveTypeUID(form_value.Reference(), true);
3098 }
3099 }
3100 }
3101
3102 return nullptr;
3103 }
3104
GetClangDeclForDIE(const DWARFDIE & die)3105 clang::Decl *DWARFASTParserClang::GetClangDeclForDIE(const DWARFDIE &die) {
3106 if (!die)
3107 return nullptr;
3108
3109 switch (die.Tag()) {
3110 case DW_TAG_variable:
3111 case DW_TAG_constant:
3112 case DW_TAG_formal_parameter:
3113 case DW_TAG_imported_declaration:
3114 case DW_TAG_imported_module:
3115 break;
3116 default:
3117 return nullptr;
3118 }
3119
3120 DIEToDeclMap::iterator cache_pos = m_die_to_decl.find(die.GetDIE());
3121 if (cache_pos != m_die_to_decl.end())
3122 return cache_pos->second;
3123
3124 if (DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification)) {
3125 clang::Decl *decl = GetClangDeclForDIE(spec_die);
3126 m_die_to_decl[die.GetDIE()] = decl;
3127 return decl;
3128 }
3129
3130 if (DWARFDIE abstract_origin_die =
3131 die.GetReferencedDIE(DW_AT_abstract_origin)) {
3132 clang::Decl *decl = GetClangDeclForDIE(abstract_origin_die);
3133 m_die_to_decl[die.GetDIE()] = decl;
3134 return decl;
3135 }
3136
3137 clang::Decl *decl = nullptr;
3138 switch (die.Tag()) {
3139 case DW_TAG_variable:
3140 case DW_TAG_constant:
3141 case DW_TAG_formal_parameter: {
3142 SymbolFileDWARF *dwarf = die.GetDWARF();
3143 Type *type = GetTypeForDIE(die);
3144 if (dwarf && type) {
3145 const char *name = die.GetName();
3146 clang::DeclContext *decl_context =
3147 TypeSystemClang::DeclContextGetAsDeclContext(
3148 dwarf->GetDeclContextContainingUID(die.GetID()));
3149 decl = m_ast.CreateVariableDeclaration(
3150 decl_context, GetOwningClangModule(die), name,
3151 ClangUtil::GetQualType(type->GetForwardCompilerType()));
3152 }
3153 break;
3154 }
3155 case DW_TAG_imported_declaration: {
3156 SymbolFileDWARF *dwarf = die.GetDWARF();
3157 DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(DW_AT_import);
3158 if (imported_uid) {
3159 CompilerDecl imported_decl = SymbolFileDWARF::GetDecl(imported_uid);
3160 if (imported_decl) {
3161 clang::DeclContext *decl_context =
3162 TypeSystemClang::DeclContextGetAsDeclContext(
3163 dwarf->GetDeclContextContainingUID(die.GetID()));
3164 if (clang::NamedDecl *clang_imported_decl =
3165 llvm::dyn_cast<clang::NamedDecl>(
3166 (clang::Decl *)imported_decl.GetOpaqueDecl()))
3167 decl = m_ast.CreateUsingDeclaration(
3168 decl_context, OptionalClangModuleID(), clang_imported_decl);
3169 }
3170 }
3171 break;
3172 }
3173 case DW_TAG_imported_module: {
3174 SymbolFileDWARF *dwarf = die.GetDWARF();
3175 DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(DW_AT_import);
3176
3177 if (imported_uid) {
3178 CompilerDeclContext imported_decl_ctx =
3179 SymbolFileDWARF::GetDeclContext(imported_uid);
3180 if (imported_decl_ctx) {
3181 clang::DeclContext *decl_context =
3182 TypeSystemClang::DeclContextGetAsDeclContext(
3183 dwarf->GetDeclContextContainingUID(die.GetID()));
3184 if (clang::NamespaceDecl *ns_decl =
3185 TypeSystemClang::DeclContextGetAsNamespaceDecl(
3186 imported_decl_ctx))
3187 decl = m_ast.CreateUsingDirectiveDeclaration(
3188 decl_context, OptionalClangModuleID(), ns_decl);
3189 }
3190 }
3191 break;
3192 }
3193 default:
3194 break;
3195 }
3196
3197 m_die_to_decl[die.GetDIE()] = decl;
3198
3199 return decl;
3200 }
3201
3202 clang::DeclContext *
GetClangDeclContextForDIE(const DWARFDIE & die)3203 DWARFASTParserClang::GetClangDeclContextForDIE(const DWARFDIE &die) {
3204 if (die) {
3205 clang::DeclContext *decl_ctx = GetCachedClangDeclContextForDIE(die);
3206 if (decl_ctx)
3207 return decl_ctx;
3208
3209 bool try_parsing_type = true;
3210 switch (die.Tag()) {
3211 case DW_TAG_compile_unit:
3212 case DW_TAG_partial_unit:
3213 decl_ctx = m_ast.GetTranslationUnitDecl();
3214 try_parsing_type = false;
3215 break;
3216
3217 case DW_TAG_namespace:
3218 decl_ctx = ResolveNamespaceDIE(die);
3219 try_parsing_type = false;
3220 break;
3221
3222 case DW_TAG_lexical_block:
3223 decl_ctx = GetDeclContextForBlock(die);
3224 try_parsing_type = false;
3225 break;
3226
3227 default:
3228 break;
3229 }
3230
3231 if (decl_ctx == nullptr && try_parsing_type) {
3232 Type *type = die.GetDWARF()->ResolveType(die);
3233 if (type)
3234 decl_ctx = GetCachedClangDeclContextForDIE(die);
3235 }
3236
3237 if (decl_ctx) {
3238 LinkDeclContextToDIE(decl_ctx, die);
3239 return decl_ctx;
3240 }
3241 }
3242 return nullptr;
3243 }
3244
3245 OptionalClangModuleID
GetOwningClangModule(const DWARFDIE & die)3246 DWARFASTParserClang::GetOwningClangModule(const DWARFDIE &die) {
3247 if (!die.IsValid())
3248 return {};
3249
3250 for (DWARFDIE parent = die.GetParent(); parent.IsValid();
3251 parent = parent.GetParent()) {
3252 const dw_tag_t tag = parent.Tag();
3253 if (tag == DW_TAG_module) {
3254 DWARFDIE module_die = parent;
3255 auto it = m_die_to_module.find(module_die.GetDIE());
3256 if (it != m_die_to_module.end())
3257 return it->second;
3258 const char *name =
3259 module_die.GetAttributeValueAsString(DW_AT_name, nullptr);
3260 if (!name)
3261 return {};
3262
3263 OptionalClangModuleID id =
3264 m_ast.GetOrCreateClangModule(name, GetOwningClangModule(module_die));
3265 m_die_to_module.insert({module_die.GetDIE(), id});
3266 return id;
3267 }
3268 }
3269 return {};
3270 }
3271
IsSubroutine(const DWARFDIE & die)3272 static bool IsSubroutine(const DWARFDIE &die) {
3273 switch (die.Tag()) {
3274 case DW_TAG_subprogram:
3275 case DW_TAG_inlined_subroutine:
3276 return true;
3277 default:
3278 return false;
3279 }
3280 }
3281
GetContainingFunctionWithAbstractOrigin(const DWARFDIE & die)3282 static DWARFDIE GetContainingFunctionWithAbstractOrigin(const DWARFDIE &die) {
3283 for (DWARFDIE candidate = die; candidate; candidate = candidate.GetParent()) {
3284 if (IsSubroutine(candidate)) {
3285 if (candidate.GetReferencedDIE(DW_AT_abstract_origin)) {
3286 return candidate;
3287 } else {
3288 return DWARFDIE();
3289 }
3290 }
3291 }
3292 assert(0 && "Shouldn't call GetContainingFunctionWithAbstractOrigin on "
3293 "something not in a function");
3294 return DWARFDIE();
3295 }
3296
FindAnyChildWithAbstractOrigin(const DWARFDIE & context)3297 static DWARFDIE FindAnyChildWithAbstractOrigin(const DWARFDIE &context) {
3298 for (DWARFDIE candidate : context.children()) {
3299 if (candidate.GetReferencedDIE(DW_AT_abstract_origin)) {
3300 return candidate;
3301 }
3302 }
3303 return DWARFDIE();
3304 }
3305
FindFirstChildWithAbstractOrigin(const DWARFDIE & block,const DWARFDIE & function)3306 static DWARFDIE FindFirstChildWithAbstractOrigin(const DWARFDIE &block,
3307 const DWARFDIE &function) {
3308 assert(IsSubroutine(function));
3309 for (DWARFDIE context = block; context != function.GetParent();
3310 context = context.GetParent()) {
3311 assert(!IsSubroutine(context) || context == function);
3312 if (DWARFDIE child = FindAnyChildWithAbstractOrigin(context)) {
3313 return child;
3314 }
3315 }
3316 return DWARFDIE();
3317 }
3318
3319 clang::DeclContext *
GetDeclContextForBlock(const DWARFDIE & die)3320 DWARFASTParserClang::GetDeclContextForBlock(const DWARFDIE &die) {
3321 assert(die.Tag() == DW_TAG_lexical_block);
3322 DWARFDIE containing_function_with_abstract_origin =
3323 GetContainingFunctionWithAbstractOrigin(die);
3324 if (!containing_function_with_abstract_origin) {
3325 return (clang::DeclContext *)ResolveBlockDIE(die);
3326 }
3327 DWARFDIE child = FindFirstChildWithAbstractOrigin(
3328 die, containing_function_with_abstract_origin);
3329 CompilerDeclContext decl_context =
3330 GetDeclContextContainingUIDFromDWARF(child);
3331 return (clang::DeclContext *)decl_context.GetOpaqueDeclContext();
3332 }
3333
ResolveBlockDIE(const DWARFDIE & die)3334 clang::BlockDecl *DWARFASTParserClang::ResolveBlockDIE(const DWARFDIE &die) {
3335 if (die && die.Tag() == DW_TAG_lexical_block) {
3336 clang::BlockDecl *decl =
3337 llvm::cast_or_null<clang::BlockDecl>(m_die_to_decl_ctx[die.GetDIE()]);
3338
3339 if (!decl) {
3340 DWARFDIE decl_context_die;
3341 clang::DeclContext *decl_context =
3342 GetClangDeclContextContainingDIE(die, &decl_context_die);
3343 decl =
3344 m_ast.CreateBlockDeclaration(decl_context, GetOwningClangModule(die));
3345
3346 if (decl)
3347 LinkDeclContextToDIE((clang::DeclContext *)decl, die);
3348 }
3349
3350 return decl;
3351 }
3352 return nullptr;
3353 }
3354
3355 clang::NamespaceDecl *
ResolveNamespaceDIE(const DWARFDIE & die)3356 DWARFASTParserClang::ResolveNamespaceDIE(const DWARFDIE &die) {
3357 if (die && die.Tag() == DW_TAG_namespace) {
3358 // See if we already parsed this namespace DIE and associated it with a
3359 // uniqued namespace declaration
3360 clang::NamespaceDecl *namespace_decl =
3361 static_cast<clang::NamespaceDecl *>(m_die_to_decl_ctx[die.GetDIE()]);
3362 if (namespace_decl)
3363 return namespace_decl;
3364 else {
3365 const char *namespace_name = die.GetName();
3366 clang::DeclContext *containing_decl_ctx =
3367 GetClangDeclContextContainingDIE(die, nullptr);
3368 bool is_inline =
3369 die.GetAttributeValueAsUnsigned(DW_AT_export_symbols, 0) != 0;
3370
3371 namespace_decl = m_ast.GetUniqueNamespaceDeclaration(
3372 namespace_name, containing_decl_ctx, GetOwningClangModule(die),
3373 is_inline);
3374
3375 if (namespace_decl)
3376 LinkDeclContextToDIE((clang::DeclContext *)namespace_decl, die);
3377 return namespace_decl;
3378 }
3379 }
3380 return nullptr;
3381 }
3382
GetClangDeclContextContainingDIE(const DWARFDIE & die,DWARFDIE * decl_ctx_die_copy)3383 clang::DeclContext *DWARFASTParserClang::GetClangDeclContextContainingDIE(
3384 const DWARFDIE &die, DWARFDIE *decl_ctx_die_copy) {
3385 SymbolFileDWARF *dwarf = die.GetDWARF();
3386
3387 DWARFDIE decl_ctx_die = dwarf->GetDeclContextDIEContainingDIE(die);
3388
3389 if (decl_ctx_die_copy)
3390 *decl_ctx_die_copy = decl_ctx_die;
3391
3392 if (decl_ctx_die) {
3393 clang::DeclContext *clang_decl_ctx =
3394 GetClangDeclContextForDIE(decl_ctx_die);
3395 if (clang_decl_ctx)
3396 return clang_decl_ctx;
3397 }
3398 return m_ast.GetTranslationUnitDecl();
3399 }
3400
3401 clang::DeclContext *
GetCachedClangDeclContextForDIE(const DWARFDIE & die)3402 DWARFASTParserClang::GetCachedClangDeclContextForDIE(const DWARFDIE &die) {
3403 if (die) {
3404 DIEToDeclContextMap::iterator pos = m_die_to_decl_ctx.find(die.GetDIE());
3405 if (pos != m_die_to_decl_ctx.end())
3406 return pos->second;
3407 }
3408 return nullptr;
3409 }
3410
LinkDeclContextToDIE(clang::DeclContext * decl_ctx,const DWARFDIE & die)3411 void DWARFASTParserClang::LinkDeclContextToDIE(clang::DeclContext *decl_ctx,
3412 const DWARFDIE &die) {
3413 m_die_to_decl_ctx[die.GetDIE()] = decl_ctx;
3414 // There can be many DIEs for a single decl context
3415 // m_decl_ctx_to_die[decl_ctx].insert(die.GetDIE());
3416 m_decl_ctx_to_die.insert(std::make_pair(decl_ctx, die));
3417 }
3418
CopyUniqueClassMethodTypes(const DWARFDIE & src_class_die,const DWARFDIE & dst_class_die,lldb_private::Type * class_type,std::vector<DWARFDIE> & failures)3419 bool DWARFASTParserClang::CopyUniqueClassMethodTypes(
3420 const DWARFDIE &src_class_die, const DWARFDIE &dst_class_die,
3421 lldb_private::Type *class_type, std::vector<DWARFDIE> &failures) {
3422 if (!class_type || !src_class_die || !dst_class_die)
3423 return false;
3424 if (src_class_die.Tag() != dst_class_die.Tag())
3425 return false;
3426
3427 // We need to complete the class type so we can get all of the method types
3428 // parsed so we can then unique those types to their equivalent counterparts
3429 // in "dst_cu" and "dst_class_die"
3430 class_type->GetFullCompilerType();
3431
3432 auto gather = [](DWARFDIE die, UniqueCStringMap<DWARFDIE> &map,
3433 UniqueCStringMap<DWARFDIE> &map_artificial) {
3434 if (die.Tag() != DW_TAG_subprogram)
3435 return;
3436 // Make sure this is a declaration and not a concrete instance by looking
3437 // for DW_AT_declaration set to 1. Sometimes concrete function instances are
3438 // placed inside the class definitions and shouldn't be included in the list
3439 // of things are are tracking here.
3440 if (die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) != 1)
3441 return;
3442
3443 if (const char *name = die.GetMangledName()) {
3444 ConstString const_name(name);
3445 if (die.GetAttributeValueAsUnsigned(DW_AT_artificial, 0))
3446 map_artificial.Append(const_name, die);
3447 else
3448 map.Append(const_name, die);
3449 }
3450 };
3451
3452 UniqueCStringMap<DWARFDIE> src_name_to_die;
3453 UniqueCStringMap<DWARFDIE> dst_name_to_die;
3454 UniqueCStringMap<DWARFDIE> src_name_to_die_artificial;
3455 UniqueCStringMap<DWARFDIE> dst_name_to_die_artificial;
3456 for (DWARFDIE src_die = src_class_die.GetFirstChild(); src_die.IsValid();
3457 src_die = src_die.GetSibling()) {
3458 gather(src_die, src_name_to_die, src_name_to_die_artificial);
3459 }
3460 for (DWARFDIE dst_die = dst_class_die.GetFirstChild(); dst_die.IsValid();
3461 dst_die = dst_die.GetSibling()) {
3462 gather(dst_die, dst_name_to_die, dst_name_to_die_artificial);
3463 }
3464 const uint32_t src_size = src_name_to_die.GetSize();
3465 const uint32_t dst_size = dst_name_to_die.GetSize();
3466
3467 // Is everything kosher so we can go through the members at top speed?
3468 bool fast_path = true;
3469
3470 if (src_size != dst_size)
3471 fast_path = false;
3472
3473 uint32_t idx;
3474
3475 if (fast_path) {
3476 for (idx = 0; idx < src_size; ++idx) {
3477 DWARFDIE src_die = src_name_to_die.GetValueAtIndexUnchecked(idx);
3478 DWARFDIE dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
3479
3480 if (src_die.Tag() != dst_die.Tag())
3481 fast_path = false;
3482
3483 const char *src_name = src_die.GetMangledName();
3484 const char *dst_name = dst_die.GetMangledName();
3485
3486 // Make sure the names match
3487 if (src_name == dst_name || (strcmp(src_name, dst_name) == 0))
3488 continue;
3489
3490 fast_path = false;
3491 }
3492 }
3493
3494 DWARFASTParserClang *src_dwarf_ast_parser =
3495 static_cast<DWARFASTParserClang *>(
3496 SymbolFileDWARF::GetDWARFParser(*src_class_die.GetCU()));
3497 DWARFASTParserClang *dst_dwarf_ast_parser =
3498 static_cast<DWARFASTParserClang *>(
3499 SymbolFileDWARF::GetDWARFParser(*dst_class_die.GetCU()));
3500 auto link = [&](DWARFDIE src, DWARFDIE dst) {
3501 SymbolFileDWARF::DIEToTypePtr &die_to_type =
3502 dst_class_die.GetDWARF()->GetDIEToType();
3503 clang::DeclContext *dst_decl_ctx =
3504 dst_dwarf_ast_parser->m_die_to_decl_ctx[dst.GetDIE()];
3505 if (dst_decl_ctx)
3506 src_dwarf_ast_parser->LinkDeclContextToDIE(dst_decl_ctx, src);
3507
3508 if (Type *src_child_type = die_to_type[src.GetDIE()])
3509 die_to_type[dst.GetDIE()] = src_child_type;
3510 };
3511
3512 // Now do the work of linking the DeclContexts and Types.
3513 if (fast_path) {
3514 // We can do this quickly. Just run across the tables index-for-index
3515 // since we know each node has matching names and tags.
3516 for (idx = 0; idx < src_size; ++idx) {
3517 link(src_name_to_die.GetValueAtIndexUnchecked(idx),
3518 dst_name_to_die.GetValueAtIndexUnchecked(idx));
3519 }
3520 } else {
3521 // We must do this slowly. For each member of the destination, look up a
3522 // member in the source with the same name, check its tag, and unique them
3523 // if everything matches up. Report failures.
3524
3525 if (!src_name_to_die.IsEmpty() && !dst_name_to_die.IsEmpty()) {
3526 src_name_to_die.Sort();
3527
3528 for (idx = 0; idx < dst_size; ++idx) {
3529 ConstString dst_name = dst_name_to_die.GetCStringAtIndex(idx);
3530 DWARFDIE dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
3531 DWARFDIE src_die = src_name_to_die.Find(dst_name, DWARFDIE());
3532
3533 if (src_die && (src_die.Tag() == dst_die.Tag()))
3534 link(src_die, dst_die);
3535 else
3536 failures.push_back(dst_die);
3537 }
3538 }
3539 }
3540
3541 const uint32_t src_size_artificial = src_name_to_die_artificial.GetSize();
3542 const uint32_t dst_size_artificial = dst_name_to_die_artificial.GetSize();
3543
3544 if (src_size_artificial && dst_size_artificial) {
3545 dst_name_to_die_artificial.Sort();
3546
3547 for (idx = 0; idx < src_size_artificial; ++idx) {
3548 ConstString src_name_artificial =
3549 src_name_to_die_artificial.GetCStringAtIndex(idx);
3550 DWARFDIE src_die =
3551 src_name_to_die_artificial.GetValueAtIndexUnchecked(idx);
3552 DWARFDIE dst_die =
3553 dst_name_to_die_artificial.Find(src_name_artificial, DWARFDIE());
3554
3555 // Both classes have the artificial types, link them
3556 if (dst_die)
3557 link(src_die, dst_die);
3558 }
3559 }
3560
3561 if (dst_size_artificial) {
3562 for (idx = 0; idx < dst_size_artificial; ++idx) {
3563 failures.push_back(
3564 dst_name_to_die_artificial.GetValueAtIndexUnchecked(idx));
3565 }
3566 }
3567
3568 return !failures.empty();
3569 }
3570