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