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