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