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