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