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