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>(die.GetID(), dwarf, attrs.name,
1638                                    attrs.byte_size, nullptr, LLDB_INVALID_UID,
1639                                    Type::eEncodingIsUID, &attrs.decl,
1640                                    clang_type, Type::ResolveState::Forward);
1641 
1642   type_sp->SetIsCompleteObjCClass(attrs.is_complete_objc_class);
1643 
1644   // Add our type to the unique type map so we don't end up creating many
1645   // copies of the same type over and over in the ASTContext for our
1646   // module
1647   unique_ast_entry_up->m_type_sp = type_sp;
1648   unique_ast_entry_up->m_die = die;
1649   unique_ast_entry_up->m_declaration = unique_decl;
1650   unique_ast_entry_up->m_byte_size = attrs.byte_size.getValueOr(0);
1651   dwarf->GetUniqueDWARFASTTypeMap().Insert(unique_typename,
1652                                            *unique_ast_entry_up);
1653 
1654   if (attrs.is_forward_declaration && die.HasChildren()) {
1655     // Check to see if the DIE actually has a definition, some version of
1656     // GCC will
1657     // emit DIEs with DW_AT_declaration set to true, but yet still have
1658     // subprogram, members, or inheritance, so we can't trust it
1659     DWARFDIE child_die = die.GetFirstChild();
1660     while (child_die) {
1661       switch (child_die.Tag()) {
1662       case DW_TAG_inheritance:
1663       case DW_TAG_subprogram:
1664       case DW_TAG_member:
1665       case DW_TAG_APPLE_property:
1666       case DW_TAG_class_type:
1667       case DW_TAG_structure_type:
1668       case DW_TAG_enumeration_type:
1669       case DW_TAG_typedef:
1670       case DW_TAG_union_type:
1671         child_die.Clear();
1672         attrs.is_forward_declaration = false;
1673         break;
1674       default:
1675         child_die = child_die.GetSibling();
1676         break;
1677       }
1678     }
1679   }
1680 
1681   if (!attrs.is_forward_declaration) {
1682     // Always start the definition for a class type so that if the class
1683     // has child classes or types that require the class to be created
1684     // for use as their decl contexts the class will be ready to accept
1685     // these child definitions.
1686     if (!die.HasChildren()) {
1687       // No children for this struct/union/class, lets finish it
1688       if (TypeSystemClang::StartTagDeclarationDefinition(clang_type)) {
1689         TypeSystemClang::CompleteTagDeclarationDefinition(clang_type);
1690       } else {
1691         dwarf->GetObjectFile()->GetModule()->ReportError(
1692             "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its "
1693             "definition.\nPlease file a bug and attach the file at the "
1694             "start of this error message",
1695             die.GetOffset(), attrs.name.GetCString());
1696       }
1697 
1698       if (tag == DW_TAG_structure_type) // this only applies in C
1699       {
1700         clang::RecordDecl *record_decl =
1701             TypeSystemClang::GetAsRecordDecl(clang_type);
1702 
1703         if (record_decl) {
1704           GetClangASTImporter().SetRecordLayout(
1705               record_decl, ClangASTImporter::LayoutInfo());
1706         }
1707       }
1708     } else if (clang_type_was_created) {
1709       // Start the definition if the class is not objective C since the
1710       // underlying decls respond to isCompleteDefinition(). Objective
1711       // C decls don't respond to isCompleteDefinition() so we can't
1712       // start the declaration definition right away. For C++
1713       // class/union/structs we want to start the definition in case the
1714       // class is needed as the declaration context for a contained class
1715       // or type without the need to complete that type..
1716 
1717       if (attrs.class_language != eLanguageTypeObjC &&
1718           attrs.class_language != eLanguageTypeObjC_plus_plus)
1719         TypeSystemClang::StartTagDeclarationDefinition(clang_type);
1720 
1721       // Leave this as a forward declaration until we need to know the
1722       // details of the type. lldb_private::Type will automatically call
1723       // the SymbolFile virtual function
1724       // "SymbolFileDWARF::CompleteType(Type *)" When the definition
1725       // needs to be defined.
1726       assert(!dwarf->GetForwardDeclClangTypeToDie().count(
1727                  ClangUtil::RemoveFastQualifiers(clang_type)
1728                      .GetOpaqueQualType()) &&
1729              "Type already in the forward declaration map!");
1730       // Can't assume m_ast.GetSymbolFile() is actually a
1731       // SymbolFileDWARF, it can be a SymbolFileDWARFDebugMap for Apple
1732       // binaries.
1733       dwarf->GetForwardDeclDieToClangType()[die.GetDIE()] =
1734           clang_type.GetOpaqueQualType();
1735       dwarf->GetForwardDeclClangTypeToDie().try_emplace(
1736           ClangUtil::RemoveFastQualifiers(clang_type).GetOpaqueQualType(),
1737           *die.GetDIERef());
1738       m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), true);
1739     }
1740   }
1741 
1742   // If we made a clang type, set the trivial abi if applicable: We only
1743   // do this for pass by value - which implies the Trivial ABI. There
1744   // isn't a way to assert that something that would normally be pass by
1745   // value is pass by reference, so we ignore that attribute if set.
1746   if (attrs.calling_convention == llvm::dwarf::DW_CC_pass_by_value) {
1747     clang::CXXRecordDecl *record_decl =
1748         m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
1749     if (record_decl && record_decl->getDefinition()) {
1750       record_decl->setHasTrivialSpecialMemberForCall();
1751     }
1752   }
1753 
1754   if (attrs.calling_convention == llvm::dwarf::DW_CC_pass_by_reference) {
1755     clang::CXXRecordDecl *record_decl =
1756         m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
1757     if (record_decl)
1758       record_decl->setArgPassingRestrictions(
1759           clang::RecordDecl::APK_CannotPassInRegs);
1760   }
1761   return type_sp;
1762 }
1763 
1764 // DWARF parsing functions
1765 
1766 class DWARFASTParserClang::DelayedAddObjCClassProperty {
1767 public:
1768   DelayedAddObjCClassProperty(
1769       const CompilerType &class_opaque_type, const char *property_name,
1770       const CompilerType &property_opaque_type, // The property type is only
1771                                                 // required if you don't have an
1772                                                 // ivar decl
1773       clang::ObjCIvarDecl *ivar_decl, const char *property_setter_name,
1774       const char *property_getter_name, uint32_t property_attributes,
1775       const ClangASTMetadata *metadata)
1776       : m_class_opaque_type(class_opaque_type), m_property_name(property_name),
1777         m_property_opaque_type(property_opaque_type), m_ivar_decl(ivar_decl),
1778         m_property_setter_name(property_setter_name),
1779         m_property_getter_name(property_getter_name),
1780         m_property_attributes(property_attributes) {
1781     if (metadata != nullptr) {
1782       m_metadata_up.reset(new ClangASTMetadata());
1783       *m_metadata_up = *metadata;
1784     }
1785   }
1786 
1787   DelayedAddObjCClassProperty(const DelayedAddObjCClassProperty &rhs) {
1788     *this = rhs;
1789   }
1790 
1791   DelayedAddObjCClassProperty &
1792   operator=(const DelayedAddObjCClassProperty &rhs) {
1793     m_class_opaque_type = rhs.m_class_opaque_type;
1794     m_property_name = rhs.m_property_name;
1795     m_property_opaque_type = rhs.m_property_opaque_type;
1796     m_ivar_decl = rhs.m_ivar_decl;
1797     m_property_setter_name = rhs.m_property_setter_name;
1798     m_property_getter_name = rhs.m_property_getter_name;
1799     m_property_attributes = rhs.m_property_attributes;
1800 
1801     if (rhs.m_metadata_up) {
1802       m_metadata_up.reset(new ClangASTMetadata());
1803       *m_metadata_up = *rhs.m_metadata_up;
1804     }
1805     return *this;
1806   }
1807 
1808   bool Finalize() {
1809     return TypeSystemClang::AddObjCClassProperty(
1810         m_class_opaque_type, m_property_name, m_property_opaque_type,
1811         m_ivar_decl, m_property_setter_name, m_property_getter_name,
1812         m_property_attributes, m_metadata_up.get());
1813   }
1814 
1815 private:
1816   CompilerType m_class_opaque_type;
1817   const char *m_property_name;
1818   CompilerType m_property_opaque_type;
1819   clang::ObjCIvarDecl *m_ivar_decl;
1820   const char *m_property_setter_name;
1821   const char *m_property_getter_name;
1822   uint32_t m_property_attributes;
1823   std::unique_ptr<ClangASTMetadata> m_metadata_up;
1824 };
1825 
1826 bool DWARFASTParserClang::ParseTemplateDIE(
1827     const DWARFDIE &die,
1828     TypeSystemClang::TemplateParameterInfos &template_param_infos) {
1829   const dw_tag_t tag = die.Tag();
1830   bool is_template_template_argument = false;
1831 
1832   switch (tag) {
1833   case DW_TAG_GNU_template_parameter_pack: {
1834     template_param_infos.packed_args.reset(
1835       new TypeSystemClang::TemplateParameterInfos);
1836     for (DWARFDIE child_die = die.GetFirstChild(); child_die.IsValid();
1837          child_die = child_die.GetSibling()) {
1838       if (!ParseTemplateDIE(child_die, *template_param_infos.packed_args))
1839         return false;
1840     }
1841     if (const char *name = die.GetName()) {
1842       template_param_infos.pack_name = name;
1843     }
1844     return true;
1845   }
1846   case DW_TAG_GNU_template_template_param:
1847     is_template_template_argument = true;
1848     LLVM_FALLTHROUGH;
1849   case DW_TAG_template_type_parameter:
1850   case DW_TAG_template_value_parameter: {
1851     DWARFAttributes attributes;
1852     const size_t num_attributes = die.GetAttributes(attributes);
1853     const char *name = nullptr;
1854     const char *template_name = nullptr;
1855     CompilerType clang_type;
1856     uint64_t uval64 = 0;
1857     bool uval64_valid = false;
1858     if (num_attributes > 0) {
1859       DWARFFormValue form_value;
1860       for (size_t i = 0; i < num_attributes; ++i) {
1861         const dw_attr_t attr = attributes.AttributeAtIndex(i);
1862 
1863         switch (attr) {
1864         case DW_AT_name:
1865           if (attributes.ExtractFormValueAtIndex(i, form_value))
1866             name = form_value.AsCString();
1867           break;
1868 
1869         case DW_AT_GNU_template_name:
1870           if (attributes.ExtractFormValueAtIndex(i, form_value))
1871             template_name = form_value.AsCString();
1872           break;
1873 
1874         case DW_AT_type:
1875           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1876             Type *lldb_type = die.ResolveTypeUID(form_value.Reference());
1877             if (lldb_type)
1878               clang_type = lldb_type->GetForwardCompilerType();
1879           }
1880           break;
1881 
1882         case DW_AT_const_value:
1883           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1884             uval64_valid = true;
1885             uval64 = form_value.Unsigned();
1886           }
1887           break;
1888         default:
1889           break;
1890         }
1891       }
1892 
1893       clang::ASTContext &ast = m_ast.getASTContext();
1894       if (!clang_type)
1895         clang_type = m_ast.GetBasicType(eBasicTypeVoid);
1896 
1897       if (!is_template_template_argument) {
1898         bool is_signed = false;
1899         if (name && name[0])
1900           template_param_infos.names.push_back(name);
1901         else
1902           template_param_infos.names.push_back(NULL);
1903 
1904         // Get the signed value for any integer or enumeration if available
1905         clang_type.IsIntegerOrEnumerationType(is_signed);
1906 
1907         if (tag == DW_TAG_template_value_parameter && uval64_valid) {
1908           llvm::Optional<uint64_t> size = clang_type.GetBitSize(nullptr);
1909           if (!size)
1910             return false;
1911           llvm::APInt apint(*size, uval64, is_signed);
1912           template_param_infos.args.push_back(
1913               clang::TemplateArgument(ast, llvm::APSInt(apint, !is_signed),
1914                                       ClangUtil::GetQualType(clang_type)));
1915         } else {
1916           template_param_infos.args.push_back(
1917               clang::TemplateArgument(ClangUtil::GetQualType(clang_type)));
1918         }
1919       } else {
1920         auto *tplt_type = m_ast.CreateTemplateTemplateParmDecl(template_name);
1921         template_param_infos.names.push_back(name);
1922         template_param_infos.args.push_back(
1923             clang::TemplateArgument(clang::TemplateName(tplt_type)));
1924       }
1925     }
1926   }
1927     return true;
1928 
1929   default:
1930     break;
1931   }
1932   return false;
1933 }
1934 
1935 bool DWARFASTParserClang::ParseTemplateParameterInfos(
1936     const DWARFDIE &parent_die,
1937     TypeSystemClang::TemplateParameterInfos &template_param_infos) {
1938 
1939   if (!parent_die)
1940     return false;
1941 
1942   for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
1943        die = die.GetSibling()) {
1944     const dw_tag_t tag = die.Tag();
1945 
1946     switch (tag) {
1947     case DW_TAG_template_type_parameter:
1948     case DW_TAG_template_value_parameter:
1949     case DW_TAG_GNU_template_parameter_pack:
1950     case DW_TAG_GNU_template_template_param:
1951       ParseTemplateDIE(die, template_param_infos);
1952       break;
1953 
1954     default:
1955       break;
1956     }
1957   }
1958   if (template_param_infos.args.empty())
1959     return false;
1960   return template_param_infos.args.size() == template_param_infos.names.size();
1961 }
1962 
1963 bool DWARFASTParserClang::CompleteRecordType(const DWARFDIE &die,
1964                                              lldb_private::Type *type,
1965                                              CompilerType &clang_type) {
1966   const dw_tag_t tag = die.Tag();
1967   SymbolFileDWARF *dwarf = die.GetDWARF();
1968 
1969   ClangASTImporter::LayoutInfo layout_info;
1970 
1971   if (die.HasChildren()) {
1972     LanguageType class_language = eLanguageTypeUnknown;
1973     if (TypeSystemClang::IsObjCObjectOrInterfaceType(clang_type)) {
1974       class_language = eLanguageTypeObjC;
1975       // For objective C we don't start the definition when the class is
1976       // created.
1977       TypeSystemClang::StartTagDeclarationDefinition(clang_type);
1978     }
1979 
1980     int tag_decl_kind = -1;
1981     AccessType default_accessibility = eAccessNone;
1982     if (tag == DW_TAG_structure_type) {
1983       tag_decl_kind = clang::TTK_Struct;
1984       default_accessibility = eAccessPublic;
1985     } else if (tag == DW_TAG_union_type) {
1986       tag_decl_kind = clang::TTK_Union;
1987       default_accessibility = eAccessPublic;
1988     } else if (tag == DW_TAG_class_type) {
1989       tag_decl_kind = clang::TTK_Class;
1990       default_accessibility = eAccessPrivate;
1991     }
1992 
1993     std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases;
1994     std::vector<int> member_accessibilities;
1995     bool is_a_class = false;
1996     // Parse members and base classes first
1997     std::vector<DWARFDIE> member_function_dies;
1998 
1999     DelayedPropertyList delayed_properties;
2000     ParseChildMembers(die, clang_type, class_language, bases,
2001                       member_accessibilities, member_function_dies,
2002                       delayed_properties, default_accessibility, is_a_class,
2003                       layout_info);
2004 
2005     // Now parse any methods if there were any...
2006     for (const DWARFDIE &die : member_function_dies)
2007       dwarf->ResolveType(die);
2008 
2009     if (class_language == eLanguageTypeObjC) {
2010       ConstString class_name(clang_type.GetTypeName());
2011       if (class_name) {
2012         DIEArray method_die_offsets;
2013         dwarf->GetObjCMethodDIEOffsets(class_name, method_die_offsets);
2014 
2015         if (!method_die_offsets.empty()) {
2016           DWARFDebugInfo &debug_info = dwarf->DebugInfo();
2017 
2018           const size_t num_matches = method_die_offsets.size();
2019           for (size_t i = 0; i < num_matches; ++i) {
2020             const DIERef &die_ref = method_die_offsets[i];
2021             DWARFDIE method_die = debug_info.GetDIE(die_ref);
2022 
2023             if (method_die)
2024               method_die.ResolveType();
2025           }
2026         }
2027 
2028         for (DelayedPropertyList::iterator pi = delayed_properties.begin(),
2029                                            pe = delayed_properties.end();
2030              pi != pe; ++pi)
2031           pi->Finalize();
2032       }
2033     }
2034 
2035     // If we have a DW_TAG_structure_type instead of a DW_TAG_class_type we
2036     // need to tell the clang type it is actually a class.
2037     if (class_language != eLanguageTypeObjC) {
2038       if (is_a_class && tag_decl_kind != clang::TTK_Class)
2039         m_ast.SetTagTypeKind(ClangUtil::GetQualType(clang_type),
2040                              clang::TTK_Class);
2041     }
2042 
2043     // Since DW_TAG_structure_type gets used for both classes and
2044     // structures, we may need to set any DW_TAG_member fields to have a
2045     // "private" access if none was specified. When we parsed the child
2046     // members we tracked that actual accessibility value for each
2047     // DW_TAG_member in the "member_accessibilities" array. If the value
2048     // for the member is zero, then it was set to the
2049     // "default_accessibility" which for structs was "public". Below we
2050     // correct this by setting any fields to "private" that weren't
2051     // correctly set.
2052     if (is_a_class && !member_accessibilities.empty()) {
2053       // This is a class and all members that didn't have their access
2054       // specified are private.
2055       m_ast.SetDefaultAccessForRecordFields(
2056           m_ast.GetAsRecordDecl(clang_type), eAccessPrivate,
2057           &member_accessibilities.front(), member_accessibilities.size());
2058     }
2059 
2060     if (!bases.empty()) {
2061       // Make sure all base classes refer to complete types and not forward
2062       // declarations. If we don't do this, clang will crash with an
2063       // assertion in the call to clang_type.TransferBaseClasses()
2064       for (const auto &base_class : bases) {
2065         clang::TypeSourceInfo *type_source_info =
2066             base_class->getTypeSourceInfo();
2067         if (type_source_info) {
2068           CompilerType base_class_type =
2069               m_ast.GetType(type_source_info->getType());
2070           if (!base_class_type.GetCompleteType()) {
2071             auto module = dwarf->GetObjectFile()->GetModule();
2072             module->ReportError(":: Class '%s' has a base class '%s' which "
2073                                 "does not have a complete definition.",
2074                                 die.GetName(),
2075                                 base_class_type.GetTypeName().GetCString());
2076             if (die.GetCU()->GetProducer() == eProducerClang)
2077               module->ReportError(":: Try compiling the source file with "
2078                                   "-fstandalone-debug.");
2079 
2080             // We have no choice other than to pretend that the base class
2081             // is complete. If we don't do this, clang will crash when we
2082             // call setBases() inside of
2083             // "clang_type.TransferBaseClasses()" below. Since we
2084             // provide layout assistance, all ivars in this class and other
2085             // classes will be fine, this is the best we can do short of
2086             // crashing.
2087             if (TypeSystemClang::StartTagDeclarationDefinition(
2088                     base_class_type)) {
2089               TypeSystemClang::CompleteTagDeclarationDefinition(
2090                   base_class_type);
2091             }
2092           }
2093         }
2094       }
2095 
2096       m_ast.TransferBaseClasses(clang_type.GetOpaqueQualType(),
2097                                 std::move(bases));
2098     }
2099   }
2100 
2101   m_ast.AddMethodOverridesForCXXRecordType(clang_type.GetOpaqueQualType());
2102   TypeSystemClang::BuildIndirectFields(clang_type);
2103   TypeSystemClang::CompleteTagDeclarationDefinition(clang_type);
2104 
2105   if (!layout_info.field_offsets.empty() || !layout_info.base_offsets.empty() ||
2106       !layout_info.vbase_offsets.empty()) {
2107     if (type)
2108       layout_info.bit_size = type->GetByteSize().getValueOr(0) * 8;
2109     if (layout_info.bit_size == 0)
2110       layout_info.bit_size =
2111           die.GetAttributeValueAsUnsigned(DW_AT_byte_size, 0) * 8;
2112 
2113     clang::CXXRecordDecl *record_decl =
2114         m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
2115     if (record_decl)
2116       GetClangASTImporter().SetRecordLayout(record_decl, layout_info);
2117   }
2118 
2119   return (bool)clang_type;
2120 }
2121 
2122 bool DWARFASTParserClang::CompleteEnumType(const DWARFDIE &die,
2123                                            lldb_private::Type *type,
2124                                            CompilerType &clang_type) {
2125   if (TypeSystemClang::StartTagDeclarationDefinition(clang_type)) {
2126     if (die.HasChildren()) {
2127       bool is_signed = false;
2128       clang_type.IsIntegerType(is_signed);
2129       ParseChildEnumerators(clang_type, is_signed,
2130                             type->GetByteSize().getValueOr(0), die);
2131     }
2132     TypeSystemClang::CompleteTagDeclarationDefinition(clang_type);
2133   }
2134   return (bool)clang_type;
2135 }
2136 
2137 bool DWARFASTParserClang::CompleteTypeFromDWARF(const DWARFDIE &die,
2138                                                 lldb_private::Type *type,
2139                                                 CompilerType &clang_type) {
2140   SymbolFileDWARF *dwarf = die.GetDWARF();
2141 
2142   std::lock_guard<std::recursive_mutex> guard(
2143       dwarf->GetObjectFile()->GetModule()->GetMutex());
2144 
2145   // Disable external storage for this type so we don't get anymore
2146   // clang::ExternalASTSource queries for this type.
2147   m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), false);
2148 
2149   if (!die)
2150     return false;
2151 
2152   const dw_tag_t tag = die.Tag();
2153 
2154   Log *log =
2155       nullptr; // (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO|DWARF_LOG_TYPE_COMPLETION));
2156   if (log)
2157     dwarf->GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
2158         log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
2159         die.GetID(), die.GetTagAsCString(), type->GetName().AsCString());
2160   assert(clang_type);
2161   DWARFAttributes attributes;
2162   switch (tag) {
2163   case DW_TAG_structure_type:
2164   case DW_TAG_union_type:
2165   case DW_TAG_class_type:
2166     return CompleteRecordType(die, type, clang_type);
2167   case DW_TAG_enumeration_type:
2168     return CompleteEnumType(die, type, clang_type);
2169   default:
2170     assert(false && "not a forward clang type decl!");
2171     break;
2172   }
2173 
2174   return false;
2175 }
2176 
2177 void DWARFASTParserClang::EnsureAllDIEsInDeclContextHaveBeenParsed(
2178     lldb_private::CompilerDeclContext decl_context) {
2179   auto opaque_decl_ctx =
2180       (clang::DeclContext *)decl_context.GetOpaqueDeclContext();
2181   for (auto it = m_decl_ctx_to_die.find(opaque_decl_ctx);
2182        it != m_decl_ctx_to_die.end() && it->first == opaque_decl_ctx;
2183        it = m_decl_ctx_to_die.erase(it))
2184     for (DWARFDIE decl = it->second.GetFirstChild(); decl;
2185          decl = decl.GetSibling())
2186       GetClangDeclForDIE(decl);
2187 }
2188 
2189 CompilerDecl DWARFASTParserClang::GetDeclForUIDFromDWARF(const DWARFDIE &die) {
2190   clang::Decl *clang_decl = GetClangDeclForDIE(die);
2191   if (clang_decl != nullptr)
2192     return m_ast.GetCompilerDecl(clang_decl);
2193   return CompilerDecl();
2194 }
2195 
2196 CompilerDeclContext
2197 DWARFASTParserClang::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) {
2198   clang::DeclContext *clang_decl_ctx = GetClangDeclContextForDIE(die);
2199   if (clang_decl_ctx)
2200     return m_ast.CreateDeclContext(clang_decl_ctx);
2201   return CompilerDeclContext();
2202 }
2203 
2204 CompilerDeclContext
2205 DWARFASTParserClang::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) {
2206   clang::DeclContext *clang_decl_ctx =
2207       GetClangDeclContextContainingDIE(die, nullptr);
2208   if (clang_decl_ctx)
2209     return m_ast.CreateDeclContext(clang_decl_ctx);
2210   return CompilerDeclContext();
2211 }
2212 
2213 size_t DWARFASTParserClang::ParseChildEnumerators(
2214     lldb_private::CompilerType &clang_type, bool is_signed,
2215     uint32_t enumerator_byte_size, const DWARFDIE &parent_die) {
2216   if (!parent_die)
2217     return 0;
2218 
2219   size_t enumerators_added = 0;
2220 
2221   for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
2222        die = die.GetSibling()) {
2223     const dw_tag_t tag = die.Tag();
2224     if (tag == DW_TAG_enumerator) {
2225       DWARFAttributes attributes;
2226       const size_t num_child_attributes = die.GetAttributes(attributes);
2227       if (num_child_attributes > 0) {
2228         const char *name = nullptr;
2229         bool got_value = false;
2230         int64_t enum_value = 0;
2231         Declaration decl;
2232 
2233         uint32_t i;
2234         for (i = 0; i < num_child_attributes; ++i) {
2235           const dw_attr_t attr = attributes.AttributeAtIndex(i);
2236           DWARFFormValue form_value;
2237           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2238             switch (attr) {
2239             case DW_AT_const_value:
2240               got_value = true;
2241               if (is_signed)
2242                 enum_value = form_value.Signed();
2243               else
2244                 enum_value = form_value.Unsigned();
2245               break;
2246 
2247             case DW_AT_name:
2248               name = form_value.AsCString();
2249               break;
2250 
2251             case DW_AT_description:
2252             default:
2253             case DW_AT_decl_file:
2254               decl.SetFile(die.GetCU()->GetFile(form_value.Unsigned()));
2255               break;
2256             case DW_AT_decl_line:
2257               decl.SetLine(form_value.Unsigned());
2258               break;
2259             case DW_AT_decl_column:
2260               decl.SetColumn(form_value.Unsigned());
2261               break;
2262             case DW_AT_sibling:
2263               break;
2264             }
2265           }
2266         }
2267 
2268         if (name && name[0] && got_value) {
2269           m_ast.AddEnumerationValueToEnumerationType(
2270               clang_type, decl, name, enum_value, enumerator_byte_size * 8);
2271           ++enumerators_added;
2272         }
2273       }
2274     }
2275   }
2276   return enumerators_added;
2277 }
2278 
2279 Function *DWARFASTParserClang::ParseFunctionFromDWARF(CompileUnit &comp_unit,
2280                                                       const DWARFDIE &die) {
2281   DWARFRangeList func_ranges;
2282   const char *name = nullptr;
2283   const char *mangled = nullptr;
2284   int decl_file = 0;
2285   int decl_line = 0;
2286   int decl_column = 0;
2287   int call_file = 0;
2288   int call_line = 0;
2289   int call_column = 0;
2290   DWARFExpression frame_base;
2291 
2292   const dw_tag_t tag = die.Tag();
2293 
2294   if (tag != DW_TAG_subprogram)
2295     return nullptr;
2296 
2297   if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line,
2298                                decl_column, call_file, call_line, call_column,
2299                                &frame_base)) {
2300 
2301     // Union of all ranges in the function DIE (if the function is
2302     // discontiguous)
2303     AddressRange func_range;
2304     lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase(0);
2305     lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd(0);
2306     if (lowest_func_addr != LLDB_INVALID_ADDRESS &&
2307         lowest_func_addr <= highest_func_addr) {
2308       ModuleSP module_sp(die.GetModule());
2309       func_range.GetBaseAddress().ResolveAddressUsingFileSections(
2310           lowest_func_addr, module_sp->GetSectionList());
2311       if (func_range.GetBaseAddress().IsValid())
2312         func_range.SetByteSize(highest_func_addr - lowest_func_addr);
2313     }
2314 
2315     if (func_range.GetBaseAddress().IsValid()) {
2316       Mangled func_name;
2317       if (mangled)
2318         func_name.SetValue(ConstString(mangled), true);
2319       else if ((die.GetParent().Tag() == DW_TAG_compile_unit ||
2320                 die.GetParent().Tag() == DW_TAG_partial_unit) &&
2321                Language::LanguageIsCPlusPlus(
2322                    SymbolFileDWARF::GetLanguage(*die.GetCU())) &&
2323                !Language::LanguageIsObjC(
2324                    SymbolFileDWARF::GetLanguage(*die.GetCU())) &&
2325                name && strcmp(name, "main") != 0) {
2326         // If the mangled name is not present in the DWARF, generate the
2327         // demangled name using the decl context. We skip if the function is
2328         // "main" as its name is never mangled.
2329         bool is_static = false;
2330         bool is_variadic = false;
2331         bool has_template_params = false;
2332         unsigned type_quals = 0;
2333         std::vector<CompilerType> param_types;
2334         std::vector<clang::ParmVarDecl *> param_decls;
2335         StreamString sstr;
2336 
2337         DWARFDeclContext decl_ctx = SymbolFileDWARF::GetDWARFDeclContext(die);
2338         sstr << decl_ctx.GetQualifiedName();
2339 
2340         clang::DeclContext *containing_decl_ctx =
2341             GetClangDeclContextContainingDIE(die, nullptr);
2342         ParseChildParameters(containing_decl_ctx, die, true, is_static,
2343                              is_variadic, has_template_params, param_types,
2344                              param_decls, type_quals);
2345         sstr << "(";
2346         for (size_t i = 0; i < param_types.size(); i++) {
2347           if (i > 0)
2348             sstr << ", ";
2349           sstr << param_types[i].GetTypeName();
2350         }
2351         if (is_variadic)
2352           sstr << ", ...";
2353         sstr << ")";
2354         if (type_quals & clang::Qualifiers::Const)
2355           sstr << " const";
2356 
2357         func_name.SetValue(ConstString(sstr.GetString()), false);
2358       } else
2359         func_name.SetValue(ConstString(name), false);
2360 
2361       FunctionSP func_sp;
2362       std::unique_ptr<Declaration> decl_up;
2363       if (decl_file != 0 || decl_line != 0 || decl_column != 0)
2364         decl_up.reset(new Declaration(die.GetCU()->GetFile(decl_file),
2365                                       decl_line, decl_column));
2366 
2367       SymbolFileDWARF *dwarf = die.GetDWARF();
2368       // Supply the type _only_ if it has already been parsed
2369       Type *func_type = dwarf->GetDIEToType().lookup(die.GetDIE());
2370 
2371       assert(func_type == nullptr || func_type != DIE_IS_BEING_PARSED);
2372 
2373       if (dwarf->FixupAddress(func_range.GetBaseAddress())) {
2374         const user_id_t func_user_id = die.GetID();
2375         func_sp =
2376             std::make_shared<Function>(&comp_unit,
2377                                    func_user_id, // UserID is the DIE offset
2378                                    func_user_id, func_name, func_type,
2379                                        func_range); // first address range
2380 
2381         if (func_sp.get() != nullptr) {
2382           if (frame_base.IsValid())
2383             func_sp->GetFrameBaseExpression() = frame_base;
2384           comp_unit.AddFunction(func_sp);
2385           return func_sp.get();
2386         }
2387       }
2388     }
2389   }
2390   return nullptr;
2391 }
2392 
2393 void DWARFASTParserClang::ParseSingleMember(
2394     const DWARFDIE &die, const DWARFDIE &parent_die,
2395     lldb_private::CompilerType &class_clang_type,
2396     const lldb::LanguageType class_language,
2397     std::vector<int> &member_accessibilities,
2398     lldb::AccessType &default_accessibility,
2399     DelayedPropertyList &delayed_properties,
2400     lldb_private::ClangASTImporter::LayoutInfo &layout_info,
2401     FieldInfo &last_field_info) {
2402   ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule();
2403   const dw_tag_t tag = die.Tag();
2404   // Get the parent byte size so we can verify any members will fit
2405   const uint64_t parent_byte_size =
2406       parent_die.GetAttributeValueAsUnsigned(DW_AT_byte_size, UINT64_MAX);
2407   const uint64_t parent_bit_size =
2408       parent_byte_size == UINT64_MAX ? UINT64_MAX : parent_byte_size * 8;
2409 
2410   DWARFAttributes attributes;
2411   const size_t num_attributes = die.GetAttributes(attributes);
2412   if (num_attributes > 0) {
2413     const char *name = nullptr;
2414     const char *prop_name = nullptr;
2415     const char *prop_getter_name = nullptr;
2416     const char *prop_setter_name = nullptr;
2417     uint32_t prop_attributes = 0;
2418 
2419     bool is_artificial = false;
2420     DWARFFormValue encoding_form;
2421     AccessType accessibility = eAccessNone;
2422     uint32_t member_byte_offset =
2423         (parent_die.Tag() == DW_TAG_union_type) ? 0 : UINT32_MAX;
2424     llvm::Optional<uint64_t> byte_size;
2425     int64_t bit_offset = 0;
2426     uint64_t data_bit_offset = UINT64_MAX;
2427     size_t bit_size = 0;
2428     bool is_external =
2429         false; // On DW_TAG_members, this means the member is static
2430     uint32_t i;
2431     for (i = 0; i < num_attributes && !is_artificial; ++i) {
2432       const dw_attr_t attr = attributes.AttributeAtIndex(i);
2433       DWARFFormValue form_value;
2434       if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2435         // DW_AT_data_member_location indicates the byte offset of the
2436         // word from the base address of the structure.
2437         //
2438         // DW_AT_bit_offset indicates how many bits into the word
2439         // (according to the host endianness) the low-order bit of the
2440         // field starts.  AT_bit_offset can be negative.
2441         //
2442         // DW_AT_bit_size indicates the size of the field in bits.
2443         switch (attr) {
2444         case DW_AT_name:
2445           name = form_value.AsCString();
2446           break;
2447         case DW_AT_type:
2448           encoding_form = form_value;
2449           break;
2450         case DW_AT_bit_offset:
2451           bit_offset = form_value.Signed();
2452           break;
2453         case DW_AT_bit_size:
2454           bit_size = form_value.Unsigned();
2455           break;
2456         case DW_AT_byte_size:
2457           byte_size = form_value.Unsigned();
2458           break;
2459         case DW_AT_data_bit_offset:
2460           data_bit_offset = form_value.Unsigned();
2461           break;
2462         case DW_AT_data_member_location:
2463           if (form_value.BlockData()) {
2464             Value initialValue(0);
2465             Value memberOffset(0);
2466             const DWARFDataExtractor &debug_info_data = die.GetData();
2467             uint32_t block_length = form_value.Unsigned();
2468             uint32_t block_offset =
2469                 form_value.BlockData() - debug_info_data.GetDataStart();
2470             if (DWARFExpression::Evaluate(
2471                     nullptr, // ExecutionContext *
2472                     nullptr, // RegisterContext *
2473                     module_sp,
2474                     DataExtractor(debug_info_data, block_offset, block_length),
2475                     die.GetCU(), eRegisterKindDWARF, &initialValue, nullptr,
2476                     memberOffset, nullptr)) {
2477               member_byte_offset = memberOffset.ResolveValue(nullptr).UInt();
2478             }
2479           } else {
2480             // With DWARF 3 and later, if the value is an integer constant,
2481             // this form value is the offset in bytes from the beginning of
2482             // the containing entity.
2483             member_byte_offset = form_value.Unsigned();
2484           }
2485           break;
2486 
2487         case DW_AT_accessibility:
2488           accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
2489           break;
2490         case DW_AT_artificial:
2491           is_artificial = form_value.Boolean();
2492           break;
2493         case DW_AT_APPLE_property_name:
2494           prop_name = form_value.AsCString();
2495           break;
2496         case DW_AT_APPLE_property_getter:
2497           prop_getter_name = form_value.AsCString();
2498           break;
2499         case DW_AT_APPLE_property_setter:
2500           prop_setter_name = form_value.AsCString();
2501           break;
2502         case DW_AT_APPLE_property_attribute:
2503           prop_attributes = form_value.Unsigned();
2504           break;
2505         case DW_AT_external:
2506           is_external = form_value.Boolean();
2507           break;
2508 
2509         default:
2510         case DW_AT_declaration:
2511         case DW_AT_description:
2512         case DW_AT_mutable:
2513         case DW_AT_visibility:
2514         case DW_AT_sibling:
2515           break;
2516         }
2517       }
2518     }
2519 
2520     if (prop_name) {
2521       ConstString fixed_setter;
2522 
2523       // Check if the property getter/setter were provided as full names.
2524       // We want basenames, so we extract them.
2525 
2526       if (prop_getter_name && prop_getter_name[0] == '-') {
2527         ObjCLanguage::MethodName prop_getter_method(prop_getter_name, true);
2528         prop_getter_name = prop_getter_method.GetSelector().GetCString();
2529       }
2530 
2531       if (prop_setter_name && prop_setter_name[0] == '-') {
2532         ObjCLanguage::MethodName prop_setter_method(prop_setter_name, true);
2533         prop_setter_name = prop_setter_method.GetSelector().GetCString();
2534       }
2535 
2536       // If the names haven't been provided, they need to be filled in.
2537 
2538       if (!prop_getter_name) {
2539         prop_getter_name = prop_name;
2540       }
2541       if (!prop_setter_name && prop_name[0] &&
2542           !(prop_attributes & DW_APPLE_PROPERTY_readonly)) {
2543         StreamString ss;
2544 
2545         ss.Printf("set%c%s:", toupper(prop_name[0]), &prop_name[1]);
2546 
2547         fixed_setter.SetString(ss.GetString());
2548         prop_setter_name = fixed_setter.GetCString();
2549       }
2550     }
2551 
2552     // Clang has a DWARF generation bug where sometimes it represents
2553     // fields that are references with bad byte size and bit size/offset
2554     // information such as:
2555     //
2556     //  DW_AT_byte_size( 0x00 )
2557     //  DW_AT_bit_size( 0x40 )
2558     //  DW_AT_bit_offset( 0xffffffffffffffc0 )
2559     //
2560     // So check the bit offset to make sure it is sane, and if the values
2561     // are not sane, remove them. If we don't do this then we will end up
2562     // with a crash if we try to use this type in an expression when clang
2563     // becomes unhappy with its recycled debug info.
2564 
2565     if (byte_size.getValueOr(0) == 0 && bit_offset < 0) {
2566       bit_size = 0;
2567       bit_offset = 0;
2568     }
2569 
2570     // FIXME: Make Clang ignore Objective-C accessibility for expressions
2571     if (class_language == eLanguageTypeObjC ||
2572         class_language == eLanguageTypeObjC_plus_plus)
2573       accessibility = eAccessNone;
2574 
2575     // Handle static members
2576     if (is_external && member_byte_offset == UINT32_MAX) {
2577       Type *var_type = die.ResolveTypeUID(encoding_form.Reference());
2578 
2579       if (var_type) {
2580         if (accessibility == eAccessNone)
2581           accessibility = eAccessPublic;
2582         TypeSystemClang::AddVariableToRecordType(
2583             class_clang_type, name, var_type->GetLayoutCompilerType(),
2584             accessibility);
2585       }
2586       return;
2587     }
2588 
2589     if (!is_artificial) {
2590       Type *member_type = die.ResolveTypeUID(encoding_form.Reference());
2591 
2592       clang::FieldDecl *field_decl = nullptr;
2593       const uint64_t character_width = 8;
2594       const uint64_t word_width = 32;
2595       if (tag == DW_TAG_member) {
2596         if (member_type) {
2597           CompilerType member_clang_type = member_type->GetLayoutCompilerType();
2598 
2599           if (accessibility == eAccessNone)
2600             accessibility = default_accessibility;
2601           member_accessibilities.push_back(accessibility);
2602 
2603           uint64_t field_bit_offset =
2604               (member_byte_offset == UINT32_MAX ? 0 : (member_byte_offset * 8));
2605 
2606           if (bit_size > 0) {
2607             FieldInfo this_field_info;
2608             this_field_info.bit_offset = field_bit_offset;
2609             this_field_info.bit_size = bit_size;
2610 
2611             if (data_bit_offset != UINT64_MAX) {
2612               this_field_info.bit_offset = data_bit_offset;
2613             } else {
2614               if (!byte_size)
2615                 byte_size = member_type->GetByteSize();
2616 
2617               ObjectFile *objfile = die.GetDWARF()->GetObjectFile();
2618               if (objfile->GetByteOrder() == eByteOrderLittle) {
2619                 this_field_info.bit_offset += byte_size.getValueOr(0) * 8;
2620                 this_field_info.bit_offset -= (bit_offset + bit_size);
2621               } else {
2622                 this_field_info.bit_offset += bit_offset;
2623               }
2624             }
2625 
2626             if ((this_field_info.bit_offset >= parent_bit_size) ||
2627                 (last_field_info.IsBitfield() &&
2628                  !last_field_info.NextBitfieldOffsetIsValid(
2629                      this_field_info.bit_offset))) {
2630               ObjectFile *objfile = die.GetDWARF()->GetObjectFile();
2631               objfile->GetModule()->ReportWarning(
2632                   "0x%8.8" PRIx64 ": %s bitfield named \"%s\" has invalid "
2633                   "bit offset (0x%8.8" PRIx64
2634                   ") member will be ignored. Please file a bug against the "
2635                   "compiler and include the preprocessed output for %s\n",
2636                   die.GetID(), DW_TAG_value_to_name(tag), name,
2637                   this_field_info.bit_offset, GetUnitName(parent_die).c_str());
2638               return;
2639             }
2640 
2641             // Update the field bit offset we will report for layout
2642             field_bit_offset = this_field_info.bit_offset;
2643 
2644             // Objective-C has invalid DW_AT_bit_offset values in older
2645             // versions of clang, so we have to be careful and only insert
2646             // unnamed bitfields if we have a new enough clang.
2647             bool detect_unnamed_bitfields = true;
2648 
2649             if (class_language == eLanguageTypeObjC ||
2650                 class_language == eLanguageTypeObjC_plus_plus)
2651               detect_unnamed_bitfields =
2652                   die.GetCU()->Supports_unnamed_objc_bitfields();
2653 
2654             if (detect_unnamed_bitfields) {
2655               clang::Optional<FieldInfo> unnamed_field_info;
2656               uint64_t last_field_end = 0;
2657 
2658               last_field_end =
2659                   last_field_info.bit_offset + last_field_info.bit_size;
2660 
2661               if (!last_field_info.IsBitfield()) {
2662                 // The last field was not a bit-field...
2663                 // but if it did take up the entire word then we need to extend
2664                 // last_field_end so the bit-field does not step into the last
2665                 // fields padding.
2666                 if (last_field_end != 0 && ((last_field_end % word_width) != 0))
2667                   last_field_end += word_width - (last_field_end % word_width);
2668               }
2669 
2670               // If we have a gap between the last_field_end and the current
2671               // field we have an unnamed bit-field
2672               if (this_field_info.bit_offset != last_field_end &&
2673                   !(this_field_info.bit_offset < last_field_end)) {
2674                 unnamed_field_info = FieldInfo{};
2675                 unnamed_field_info->bit_size =
2676                     this_field_info.bit_offset - last_field_end;
2677                 unnamed_field_info->bit_offset = last_field_end;
2678               }
2679 
2680               if (unnamed_field_info) {
2681                 clang::FieldDecl *unnamed_bitfield_decl =
2682                     TypeSystemClang::AddFieldToRecordType(
2683                         class_clang_type, llvm::StringRef(),
2684                         m_ast.GetBuiltinTypeForEncodingAndBitSize(eEncodingSint,
2685                                                                   word_width),
2686                         accessibility, unnamed_field_info->bit_size);
2687 
2688                 layout_info.field_offsets.insert(std::make_pair(
2689                     unnamed_bitfield_decl, unnamed_field_info->bit_offset));
2690               }
2691             }
2692 
2693             last_field_info = this_field_info;
2694             last_field_info.SetIsBitfield(true);
2695           } else {
2696             last_field_info.bit_offset = field_bit_offset;
2697 
2698             if (llvm::Optional<uint64_t> clang_type_size =
2699                     member_clang_type.GetByteSize(nullptr)) {
2700               last_field_info.bit_size = *clang_type_size * character_width;
2701             }
2702 
2703             last_field_info.SetIsBitfield(false);
2704           }
2705 
2706           if (!member_clang_type.IsCompleteType())
2707             member_clang_type.GetCompleteType();
2708 
2709           {
2710             // Older versions of clang emit array[0] and array[1] in the
2711             // same way (<rdar://problem/12566646>). If the current field
2712             // is at the end of the structure, then there is definitely no
2713             // room for extra elements and we override the type to
2714             // array[0].
2715 
2716             CompilerType member_array_element_type;
2717             uint64_t member_array_size;
2718             bool member_array_is_incomplete;
2719 
2720             if (member_clang_type.IsArrayType(&member_array_element_type,
2721                                               &member_array_size,
2722                                               &member_array_is_incomplete) &&
2723                 !member_array_is_incomplete) {
2724               uint64_t parent_byte_size =
2725                   parent_die.GetAttributeValueAsUnsigned(DW_AT_byte_size,
2726                                                          UINT64_MAX);
2727 
2728               if (member_byte_offset >= parent_byte_size) {
2729                 if (member_array_size != 1 &&
2730                     (member_array_size != 0 ||
2731                      member_byte_offset > parent_byte_size)) {
2732                   module_sp->ReportError(
2733                       "0x%8.8" PRIx64
2734                       ": DW_TAG_member '%s' refers to type 0x%8.8x"
2735                       " which extends beyond the bounds of 0x%8.8" PRIx64,
2736                       die.GetID(), name, encoding_form.Reference().GetOffset(),
2737                       parent_die.GetID());
2738                 }
2739 
2740                 member_clang_type =
2741                     m_ast.CreateArrayType(member_array_element_type, 0, false);
2742               }
2743             }
2744           }
2745 
2746           if (TypeSystemClang::IsCXXClassType(member_clang_type) &&
2747               !member_clang_type.GetCompleteType()) {
2748             if (die.GetCU()->GetProducer() == eProducerClang)
2749               module_sp->ReportError(
2750                   "DWARF DIE at 0x%8.8x (class %s) has a member variable "
2751                   "0x%8.8x (%s) whose type is a forward declaration, not a "
2752                   "complete definition.\nTry compiling the source file "
2753                   "with -fstandalone-debug",
2754                   parent_die.GetOffset(), parent_die.GetName(), die.GetOffset(),
2755                   name);
2756             else
2757               module_sp->ReportError(
2758                   "DWARF DIE at 0x%8.8x (class %s) has a member variable "
2759                   "0x%8.8x (%s) whose type is a forward declaration, not a "
2760                   "complete definition.\nPlease file a bug against the "
2761                   "compiler and include the preprocessed output for %s",
2762                   parent_die.GetOffset(), parent_die.GetName(), die.GetOffset(),
2763                   name, GetUnitName(parent_die).c_str());
2764             // We have no choice other than to pretend that the member
2765             // class is complete. If we don't do this, clang will crash
2766             // when trying to layout the class. Since we provide layout
2767             // assistance, all ivars in this class and other classes will
2768             // be fine, this is the best we can do short of crashing.
2769             if (TypeSystemClang::StartTagDeclarationDefinition(
2770                     member_clang_type)) {
2771               TypeSystemClang::CompleteTagDeclarationDefinition(
2772                   member_clang_type);
2773             } else {
2774               module_sp->ReportError(
2775                   "DWARF DIE at 0x%8.8x (class %s) has a member variable "
2776                   "0x%8.8x (%s) whose type claims to be a C++ class but we "
2777                   "were not able to start its definition.\nPlease file a "
2778                   "bug and attach the file at the start of this error "
2779                   "message",
2780                   parent_die.GetOffset(), parent_die.GetName(), die.GetOffset(),
2781                   name);
2782             }
2783           }
2784 
2785           field_decl = TypeSystemClang::AddFieldToRecordType(
2786               class_clang_type, name, member_clang_type, accessibility,
2787               bit_size);
2788 
2789           m_ast.SetMetadataAsUserID(field_decl, die.GetID());
2790 
2791           layout_info.field_offsets.insert(
2792               std::make_pair(field_decl, field_bit_offset));
2793         } else {
2794           if (name)
2795             module_sp->ReportError(
2796                 "0x%8.8" PRIx64 ": DW_TAG_member '%s' refers to type 0x%8.8x"
2797                 " which was unable to be parsed",
2798                 die.GetID(), name, encoding_form.Reference().GetOffset());
2799           else
2800             module_sp->ReportError(
2801                 "0x%8.8" PRIx64 ": DW_TAG_member refers to type 0x%8.8x"
2802                 " which was unable to be parsed",
2803                 die.GetID(), encoding_form.Reference().GetOffset());
2804         }
2805       }
2806 
2807       if (prop_name != nullptr && member_type) {
2808         clang::ObjCIvarDecl *ivar_decl = nullptr;
2809 
2810         if (field_decl) {
2811           ivar_decl = clang::dyn_cast<clang::ObjCIvarDecl>(field_decl);
2812           assert(ivar_decl != nullptr);
2813         }
2814 
2815         ClangASTMetadata metadata;
2816         metadata.SetUserID(die.GetID());
2817         delayed_properties.push_back(DelayedAddObjCClassProperty(
2818             class_clang_type, prop_name, member_type->GetLayoutCompilerType(),
2819             ivar_decl, prop_setter_name, prop_getter_name, prop_attributes,
2820             &metadata));
2821 
2822         if (ivar_decl)
2823           m_ast.SetMetadataAsUserID(ivar_decl, die.GetID());
2824       }
2825     }
2826   }
2827 }
2828 
2829 bool DWARFASTParserClang::ParseChildMembers(
2830     const DWARFDIE &parent_die, CompilerType &class_clang_type,
2831     const LanguageType class_language,
2832     std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> &base_classes,
2833     std::vector<int> &member_accessibilities,
2834     std::vector<DWARFDIE> &member_function_dies,
2835     DelayedPropertyList &delayed_properties, AccessType &default_accessibility,
2836     bool &is_a_class, ClangASTImporter::LayoutInfo &layout_info) {
2837   if (!parent_die)
2838     return false;
2839 
2840   FieldInfo last_field_info;
2841 
2842   ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule();
2843   TypeSystemClang *ast =
2844       llvm::dyn_cast_or_null<TypeSystemClang>(class_clang_type.GetTypeSystem());
2845   if (ast == nullptr)
2846     return false;
2847 
2848   for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
2849        die = die.GetSibling()) {
2850     dw_tag_t tag = die.Tag();
2851 
2852     switch (tag) {
2853     case DW_TAG_member:
2854     case DW_TAG_APPLE_property:
2855       ParseSingleMember(die, parent_die, class_clang_type, class_language,
2856                         member_accessibilities, default_accessibility,
2857                         delayed_properties, layout_info, last_field_info);
2858       break;
2859 
2860     case DW_TAG_subprogram:
2861       // Let the type parsing code handle this one for us.
2862       member_function_dies.push_back(die);
2863       break;
2864 
2865     case DW_TAG_inheritance: {
2866       is_a_class = true;
2867       if (default_accessibility == eAccessNone)
2868         default_accessibility = eAccessPrivate;
2869       // TODO: implement DW_TAG_inheritance type parsing
2870       DWARFAttributes attributes;
2871       const size_t num_attributes = die.GetAttributes(attributes);
2872       if (num_attributes > 0) {
2873         DWARFFormValue encoding_form;
2874         AccessType accessibility = default_accessibility;
2875         bool is_virtual = false;
2876         bool is_base_of_class = true;
2877         off_t member_byte_offset = 0;
2878         uint32_t i;
2879         for (i = 0; i < num_attributes; ++i) {
2880           const dw_attr_t attr = attributes.AttributeAtIndex(i);
2881           DWARFFormValue form_value;
2882           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2883             switch (attr) {
2884             case DW_AT_type:
2885               encoding_form = form_value;
2886               break;
2887             case DW_AT_data_member_location:
2888               if (form_value.BlockData()) {
2889                 Value initialValue(0);
2890                 Value memberOffset(0);
2891                 const DWARFDataExtractor &debug_info_data = die.GetData();
2892                 uint32_t block_length = form_value.Unsigned();
2893                 uint32_t block_offset =
2894                     form_value.BlockData() - debug_info_data.GetDataStart();
2895                 if (DWARFExpression::Evaluate(
2896                         nullptr, nullptr, module_sp,
2897                         DataExtractor(debug_info_data, block_offset,
2898                                       block_length),
2899                         die.GetCU(), eRegisterKindDWARF, &initialValue, nullptr,
2900                         memberOffset, nullptr)) {
2901                   member_byte_offset =
2902                       memberOffset.ResolveValue(nullptr).UInt();
2903                 }
2904               } else {
2905                 // With DWARF 3 and later, if the value is an integer constant,
2906                 // this form value is the offset in bytes from the beginning of
2907                 // the containing entity.
2908                 member_byte_offset = form_value.Unsigned();
2909               }
2910               break;
2911 
2912             case DW_AT_accessibility:
2913               accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
2914               break;
2915 
2916             case DW_AT_virtuality:
2917               is_virtual = form_value.Boolean();
2918               break;
2919 
2920             case DW_AT_sibling:
2921               break;
2922 
2923             default:
2924               break;
2925             }
2926           }
2927         }
2928 
2929         Type *base_class_type = die.ResolveTypeUID(encoding_form.Reference());
2930         if (base_class_type == nullptr) {
2931           module_sp->ReportError("0x%8.8x: DW_TAG_inheritance failed to "
2932                                  "resolve the base class at 0x%8.8x"
2933                                  " from enclosing type 0x%8.8x. \nPlease file "
2934                                  "a bug and attach the file at the start of "
2935                                  "this error message",
2936                                  die.GetOffset(),
2937                                  encoding_form.Reference().GetOffset(),
2938                                  parent_die.GetOffset());
2939           break;
2940         }
2941 
2942         CompilerType base_class_clang_type =
2943             base_class_type->GetFullCompilerType();
2944         assert(base_class_clang_type);
2945         if (class_language == eLanguageTypeObjC) {
2946           ast->SetObjCSuperClass(class_clang_type, base_class_clang_type);
2947         } else {
2948           std::unique_ptr<clang::CXXBaseSpecifier> result =
2949               ast->CreateBaseClassSpecifier(
2950                   base_class_clang_type.GetOpaqueQualType(), accessibility,
2951                   is_virtual, is_base_of_class);
2952           if (!result)
2953             break;
2954 
2955           base_classes.push_back(std::move(result));
2956 
2957           if (is_virtual) {
2958             // Do not specify any offset for virtual inheritance. The DWARF
2959             // produced by clang doesn't give us a constant offset, but gives
2960             // us a DWARF expressions that requires an actual object in memory.
2961             // the DW_AT_data_member_location for a virtual base class looks
2962             // like:
2963             //      DW_AT_data_member_location( DW_OP_dup, DW_OP_deref,
2964             //      DW_OP_constu(0x00000018), DW_OP_minus, DW_OP_deref,
2965             //      DW_OP_plus )
2966             // Given this, there is really no valid response we can give to
2967             // clang for virtual base class offsets, and this should eventually
2968             // be removed from LayoutRecordType() in the external
2969             // AST source in clang.
2970           } else {
2971             layout_info.base_offsets.insert(std::make_pair(
2972                 ast->GetAsCXXRecordDecl(
2973                     base_class_clang_type.GetOpaqueQualType()),
2974                 clang::CharUnits::fromQuantity(member_byte_offset)));
2975           }
2976         }
2977       }
2978     } break;
2979 
2980     default:
2981       break;
2982     }
2983   }
2984 
2985   return true;
2986 }
2987 
2988 size_t DWARFASTParserClang::ParseChildParameters(
2989     clang::DeclContext *containing_decl_ctx, const DWARFDIE &parent_die,
2990     bool skip_artificial, bool &is_static, bool &is_variadic,
2991     bool &has_template_params, std::vector<CompilerType> &function_param_types,
2992     std::vector<clang::ParmVarDecl *> &function_param_decls,
2993     unsigned &type_quals) {
2994   if (!parent_die)
2995     return 0;
2996 
2997   size_t arg_idx = 0;
2998   for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
2999        die = die.GetSibling()) {
3000     const dw_tag_t tag = die.Tag();
3001     switch (tag) {
3002     case DW_TAG_formal_parameter: {
3003       DWARFAttributes attributes;
3004       const size_t num_attributes = die.GetAttributes(attributes);
3005       if (num_attributes > 0) {
3006         const char *name = nullptr;
3007         DWARFFormValue param_type_die_form;
3008         bool is_artificial = false;
3009         // one of None, Auto, Register, Extern, Static, PrivateExtern
3010 
3011         clang::StorageClass storage = clang::SC_None;
3012         uint32_t i;
3013         for (i = 0; i < num_attributes; ++i) {
3014           const dw_attr_t attr = attributes.AttributeAtIndex(i);
3015           DWARFFormValue form_value;
3016           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3017             switch (attr) {
3018             case DW_AT_name:
3019               name = form_value.AsCString();
3020               break;
3021             case DW_AT_type:
3022               param_type_die_form = form_value;
3023               break;
3024             case DW_AT_artificial:
3025               is_artificial = form_value.Boolean();
3026               break;
3027             case DW_AT_location:
3028             case DW_AT_const_value:
3029             case DW_AT_default_value:
3030             case DW_AT_description:
3031             case DW_AT_endianity:
3032             case DW_AT_is_optional:
3033             case DW_AT_segment:
3034             case DW_AT_variable_parameter:
3035             default:
3036             case DW_AT_abstract_origin:
3037             case DW_AT_sibling:
3038               break;
3039             }
3040           }
3041         }
3042 
3043         bool skip = false;
3044         if (skip_artificial && is_artificial) {
3045           // In order to determine if a C++ member function is "const" we
3046           // have to look at the const-ness of "this"...
3047           if (arg_idx == 0 &&
3048               DeclKindIsCXXClass(containing_decl_ctx->getDeclKind()) &&
3049               // Often times compilers omit the "this" name for the
3050               // specification DIEs, so we can't rely upon the name being in
3051               // the formal parameter DIE...
3052               (name == nullptr || ::strcmp(name, "this") == 0)) {
3053             Type *this_type =
3054                 die.ResolveTypeUID(param_type_die_form.Reference());
3055             if (this_type) {
3056               uint32_t encoding_mask = this_type->GetEncodingMask();
3057               if (encoding_mask & Type::eEncodingIsPointerUID) {
3058                 is_static = false;
3059 
3060                 if (encoding_mask & (1u << Type::eEncodingIsConstUID))
3061                   type_quals |= clang::Qualifiers::Const;
3062                 if (encoding_mask & (1u << Type::eEncodingIsVolatileUID))
3063                   type_quals |= clang::Qualifiers::Volatile;
3064               }
3065             }
3066           }
3067           skip = true;
3068         }
3069 
3070         if (!skip) {
3071           Type *type = die.ResolveTypeUID(param_type_die_form.Reference());
3072           if (type) {
3073             function_param_types.push_back(type->GetForwardCompilerType());
3074 
3075             clang::ParmVarDecl *param_var_decl =
3076                 m_ast.CreateParameterDeclaration(containing_decl_ctx, name,
3077                                                  type->GetForwardCompilerType(),
3078                                                  storage);
3079             assert(param_var_decl);
3080             function_param_decls.push_back(param_var_decl);
3081 
3082             m_ast.SetMetadataAsUserID(param_var_decl, die.GetID());
3083           }
3084         }
3085       }
3086       arg_idx++;
3087     } break;
3088 
3089     case DW_TAG_unspecified_parameters:
3090       is_variadic = true;
3091       break;
3092 
3093     case DW_TAG_template_type_parameter:
3094     case DW_TAG_template_value_parameter:
3095     case DW_TAG_GNU_template_parameter_pack:
3096       // The one caller of this was never using the template_param_infos, and
3097       // the local variable was taking up a large amount of stack space in
3098       // SymbolFileDWARF::ParseType() so this was removed. If we ever need the
3099       // template params back, we can add them back.
3100       // ParseTemplateDIE (dwarf_cu, die, template_param_infos);
3101       has_template_params = true;
3102       break;
3103 
3104     default:
3105       break;
3106     }
3107   }
3108   return arg_idx;
3109 }
3110 
3111 llvm::Optional<SymbolFile::ArrayInfo>
3112 DWARFASTParser::ParseChildArrayInfo(const DWARFDIE &parent_die,
3113                                     const ExecutionContext *exe_ctx) {
3114   SymbolFile::ArrayInfo array_info;
3115   if (!parent_die)
3116     return llvm::None;
3117 
3118   for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
3119        die = die.GetSibling()) {
3120     const dw_tag_t tag = die.Tag();
3121     switch (tag) {
3122     case DW_TAG_subrange_type: {
3123       DWARFAttributes attributes;
3124       const size_t num_child_attributes = die.GetAttributes(attributes);
3125       if (num_child_attributes > 0) {
3126         uint64_t num_elements = 0;
3127         uint64_t lower_bound = 0;
3128         uint64_t upper_bound = 0;
3129         bool upper_bound_valid = false;
3130         uint32_t i;
3131         for (i = 0; i < num_child_attributes; ++i) {
3132           const dw_attr_t attr = attributes.AttributeAtIndex(i);
3133           DWARFFormValue form_value;
3134           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3135             switch (attr) {
3136             case DW_AT_name:
3137               break;
3138 
3139             case DW_AT_count:
3140               if (DWARFDIE var_die = die.GetReferencedDIE(DW_AT_count)) {
3141                 if (var_die.Tag() == DW_TAG_variable)
3142                   if (exe_ctx) {
3143                     if (auto frame = exe_ctx->GetFrameSP()) {
3144                       Status error;
3145                       lldb::VariableSP var_sp;
3146                       auto valobj_sp = frame->GetValueForVariableExpressionPath(
3147                           var_die.GetName(), eNoDynamicValues, 0, var_sp,
3148                           error);
3149                       if (valobj_sp) {
3150                         num_elements = valobj_sp->GetValueAsUnsigned(0);
3151                         break;
3152                       }
3153                     }
3154                   }
3155               } else
3156                 num_elements = form_value.Unsigned();
3157               break;
3158 
3159             case DW_AT_bit_stride:
3160               array_info.bit_stride = form_value.Unsigned();
3161               break;
3162 
3163             case DW_AT_byte_stride:
3164               array_info.byte_stride = form_value.Unsigned();
3165               break;
3166 
3167             case DW_AT_lower_bound:
3168               lower_bound = form_value.Unsigned();
3169               break;
3170 
3171             case DW_AT_upper_bound:
3172               upper_bound_valid = true;
3173               upper_bound = form_value.Unsigned();
3174               break;
3175 
3176             default:
3177             case DW_AT_abstract_origin:
3178             case DW_AT_accessibility:
3179             case DW_AT_allocated:
3180             case DW_AT_associated:
3181             case DW_AT_data_location:
3182             case DW_AT_declaration:
3183             case DW_AT_description:
3184             case DW_AT_sibling:
3185             case DW_AT_threads_scaled:
3186             case DW_AT_type:
3187             case DW_AT_visibility:
3188               break;
3189             }
3190           }
3191         }
3192 
3193         if (num_elements == 0) {
3194           if (upper_bound_valid && upper_bound >= lower_bound)
3195             num_elements = upper_bound - lower_bound + 1;
3196         }
3197 
3198         array_info.element_orders.push_back(num_elements);
3199       }
3200     } break;
3201     default:
3202       break;
3203     }
3204   }
3205   return array_info;
3206 }
3207 
3208 Type *DWARFASTParserClang::GetTypeForDIE(const DWARFDIE &die) {
3209   if (die) {
3210     SymbolFileDWARF *dwarf = die.GetDWARF();
3211     DWARFAttributes attributes;
3212     const size_t num_attributes = die.GetAttributes(attributes);
3213     if (num_attributes > 0) {
3214       DWARFFormValue type_die_form;
3215       for (size_t i = 0; i < num_attributes; ++i) {
3216         dw_attr_t attr = attributes.AttributeAtIndex(i);
3217         DWARFFormValue form_value;
3218 
3219         if (attr == DW_AT_type &&
3220             attributes.ExtractFormValueAtIndex(i, form_value))
3221           return dwarf->ResolveTypeUID(form_value.Reference(), true);
3222       }
3223     }
3224   }
3225 
3226   return nullptr;
3227 }
3228 
3229 clang::Decl *DWARFASTParserClang::GetClangDeclForDIE(const DWARFDIE &die) {
3230   if (!die)
3231     return nullptr;
3232 
3233   switch (die.Tag()) {
3234   case DW_TAG_variable:
3235   case DW_TAG_constant:
3236   case DW_TAG_formal_parameter:
3237   case DW_TAG_imported_declaration:
3238   case DW_TAG_imported_module:
3239     break;
3240   default:
3241     return nullptr;
3242   }
3243 
3244   DIEToDeclMap::iterator cache_pos = m_die_to_decl.find(die.GetDIE());
3245   if (cache_pos != m_die_to_decl.end())
3246     return cache_pos->second;
3247 
3248   if (DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification)) {
3249     clang::Decl *decl = GetClangDeclForDIE(spec_die);
3250     m_die_to_decl[die.GetDIE()] = decl;
3251     m_decl_to_die[decl].insert(die.GetDIE());
3252     return decl;
3253   }
3254 
3255   if (DWARFDIE abstract_origin_die =
3256           die.GetReferencedDIE(DW_AT_abstract_origin)) {
3257     clang::Decl *decl = GetClangDeclForDIE(abstract_origin_die);
3258     m_die_to_decl[die.GetDIE()] = decl;
3259     m_decl_to_die[decl].insert(die.GetDIE());
3260     return decl;
3261   }
3262 
3263   clang::Decl *decl = nullptr;
3264   switch (die.Tag()) {
3265   case DW_TAG_variable:
3266   case DW_TAG_constant:
3267   case DW_TAG_formal_parameter: {
3268     SymbolFileDWARF *dwarf = die.GetDWARF();
3269     Type *type = GetTypeForDIE(die);
3270     if (dwarf && type) {
3271       const char *name = die.GetName();
3272       clang::DeclContext *decl_context =
3273           TypeSystemClang::DeclContextGetAsDeclContext(
3274               dwarf->GetDeclContextContainingUID(die.GetID()));
3275       decl = m_ast.CreateVariableDeclaration(
3276           decl_context, name,
3277           ClangUtil::GetQualType(type->GetForwardCompilerType()));
3278     }
3279     break;
3280   }
3281   case DW_TAG_imported_declaration: {
3282     SymbolFileDWARF *dwarf = die.GetDWARF();
3283     DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(DW_AT_import);
3284     if (imported_uid) {
3285       CompilerDecl imported_decl = SymbolFileDWARF::GetDecl(imported_uid);
3286       if (imported_decl) {
3287         clang::DeclContext *decl_context =
3288             TypeSystemClang::DeclContextGetAsDeclContext(
3289                 dwarf->GetDeclContextContainingUID(die.GetID()));
3290         if (clang::NamedDecl *clang_imported_decl =
3291                 llvm::dyn_cast<clang::NamedDecl>(
3292                     (clang::Decl *)imported_decl.GetOpaqueDecl()))
3293           decl =
3294               m_ast.CreateUsingDeclaration(decl_context, clang_imported_decl);
3295       }
3296     }
3297     break;
3298   }
3299   case DW_TAG_imported_module: {
3300     SymbolFileDWARF *dwarf = die.GetDWARF();
3301     DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(DW_AT_import);
3302 
3303     if (imported_uid) {
3304       CompilerDeclContext imported_decl_ctx =
3305           SymbolFileDWARF::GetDeclContext(imported_uid);
3306       if (imported_decl_ctx) {
3307         clang::DeclContext *decl_context =
3308             TypeSystemClang::DeclContextGetAsDeclContext(
3309                 dwarf->GetDeclContextContainingUID(die.GetID()));
3310         if (clang::NamespaceDecl *ns_decl =
3311                 TypeSystemClang::DeclContextGetAsNamespaceDecl(
3312                     imported_decl_ctx))
3313           decl = m_ast.CreateUsingDirectiveDeclaration(decl_context, ns_decl);
3314       }
3315     }
3316     break;
3317   }
3318   default:
3319     break;
3320   }
3321 
3322   m_die_to_decl[die.GetDIE()] = decl;
3323   m_decl_to_die[decl].insert(die.GetDIE());
3324 
3325   return decl;
3326 }
3327 
3328 clang::DeclContext *
3329 DWARFASTParserClang::GetClangDeclContextForDIE(const DWARFDIE &die) {
3330   if (die) {
3331     clang::DeclContext *decl_ctx = GetCachedClangDeclContextForDIE(die);
3332     if (decl_ctx)
3333       return decl_ctx;
3334 
3335     bool try_parsing_type = true;
3336     switch (die.Tag()) {
3337     case DW_TAG_compile_unit:
3338     case DW_TAG_partial_unit:
3339       decl_ctx = m_ast.GetTranslationUnitDecl();
3340       try_parsing_type = false;
3341       break;
3342 
3343     case DW_TAG_namespace:
3344       decl_ctx = ResolveNamespaceDIE(die);
3345       try_parsing_type = false;
3346       break;
3347 
3348     case DW_TAG_lexical_block:
3349       decl_ctx = GetDeclContextForBlock(die);
3350       try_parsing_type = false;
3351       break;
3352 
3353     default:
3354       break;
3355     }
3356 
3357     if (decl_ctx == nullptr && try_parsing_type) {
3358       Type *type = die.GetDWARF()->ResolveType(die);
3359       if (type)
3360         decl_ctx = GetCachedClangDeclContextForDIE(die);
3361     }
3362 
3363     if (decl_ctx) {
3364       LinkDeclContextToDIE(decl_ctx, die);
3365       return decl_ctx;
3366     }
3367   }
3368   return nullptr;
3369 }
3370 
3371 static bool IsSubroutine(const DWARFDIE &die) {
3372   switch (die.Tag()) {
3373   case DW_TAG_subprogram:
3374   case DW_TAG_inlined_subroutine:
3375     return true;
3376   default:
3377     return false;
3378   }
3379 }
3380 
3381 static DWARFDIE GetContainingFunctionWithAbstractOrigin(const DWARFDIE &die) {
3382   for (DWARFDIE candidate = die; candidate; candidate = candidate.GetParent()) {
3383     if (IsSubroutine(candidate)) {
3384       if (candidate.GetReferencedDIE(DW_AT_abstract_origin)) {
3385         return candidate;
3386       } else {
3387         return DWARFDIE();
3388       }
3389     }
3390   }
3391   assert(0 && "Shouldn't call GetContainingFunctionWithAbstractOrigin on "
3392               "something not in a function");
3393   return DWARFDIE();
3394 }
3395 
3396 static DWARFDIE FindAnyChildWithAbstractOrigin(const DWARFDIE &context) {
3397   for (DWARFDIE candidate = context.GetFirstChild(); candidate.IsValid();
3398        candidate = candidate.GetSibling()) {
3399     if (candidate.GetReferencedDIE(DW_AT_abstract_origin)) {
3400       return candidate;
3401     }
3402   }
3403   return DWARFDIE();
3404 }
3405 
3406 static DWARFDIE FindFirstChildWithAbstractOrigin(const DWARFDIE &block,
3407                                                  const DWARFDIE &function) {
3408   assert(IsSubroutine(function));
3409   for (DWARFDIE context = block; context != function.GetParent();
3410        context = context.GetParent()) {
3411     assert(!IsSubroutine(context) || context == function);
3412     if (DWARFDIE child = FindAnyChildWithAbstractOrigin(context)) {
3413       return child;
3414     }
3415   }
3416   return DWARFDIE();
3417 }
3418 
3419 clang::DeclContext *
3420 DWARFASTParserClang::GetDeclContextForBlock(const DWARFDIE &die) {
3421   assert(die.Tag() == DW_TAG_lexical_block);
3422   DWARFDIE containing_function_with_abstract_origin =
3423       GetContainingFunctionWithAbstractOrigin(die);
3424   if (!containing_function_with_abstract_origin) {
3425     return (clang::DeclContext *)ResolveBlockDIE(die);
3426   }
3427   DWARFDIE child = FindFirstChildWithAbstractOrigin(
3428       die, containing_function_with_abstract_origin);
3429   CompilerDeclContext decl_context =
3430       GetDeclContextContainingUIDFromDWARF(child);
3431   return (clang::DeclContext *)decl_context.GetOpaqueDeclContext();
3432 }
3433 
3434 clang::BlockDecl *DWARFASTParserClang::ResolveBlockDIE(const DWARFDIE &die) {
3435   if (die && die.Tag() == DW_TAG_lexical_block) {
3436     clang::BlockDecl *decl =
3437         llvm::cast_or_null<clang::BlockDecl>(m_die_to_decl_ctx[die.GetDIE()]);
3438 
3439     if (!decl) {
3440       DWARFDIE decl_context_die;
3441       clang::DeclContext *decl_context =
3442           GetClangDeclContextContainingDIE(die, &decl_context_die);
3443       decl = m_ast.CreateBlockDeclaration(decl_context);
3444 
3445       if (decl)
3446         LinkDeclContextToDIE((clang::DeclContext *)decl, die);
3447     }
3448 
3449     return decl;
3450   }
3451   return nullptr;
3452 }
3453 
3454 clang::NamespaceDecl *
3455 DWARFASTParserClang::ResolveNamespaceDIE(const DWARFDIE &die) {
3456   if (die && die.Tag() == DW_TAG_namespace) {
3457     // See if we already parsed this namespace DIE and associated it with a
3458     // uniqued namespace declaration
3459     clang::NamespaceDecl *namespace_decl =
3460         static_cast<clang::NamespaceDecl *>(m_die_to_decl_ctx[die.GetDIE()]);
3461     if (namespace_decl)
3462       return namespace_decl;
3463     else {
3464       const char *namespace_name = die.GetName();
3465       clang::DeclContext *containing_decl_ctx =
3466           GetClangDeclContextContainingDIE(die, nullptr);
3467       bool is_inline =
3468           die.GetAttributeValueAsUnsigned(DW_AT_export_symbols, 0) != 0;
3469 
3470       namespace_decl = m_ast.GetUniqueNamespaceDeclaration(
3471           namespace_name, containing_decl_ctx, is_inline);
3472       Log *log =
3473           nullptr; // (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
3474       if (log) {
3475         SymbolFileDWARF *dwarf = die.GetDWARF();
3476         if (namespace_name) {
3477           dwarf->GetObjectFile()->GetModule()->LogMessage(
3478               log,
3479               "ASTContext => %p: 0x%8.8" PRIx64
3480               ": DW_TAG_namespace with DW_AT_name(\"%s\") => "
3481               "clang::NamespaceDecl *%p (original = %p)",
3482               static_cast<void *>(&m_ast.getASTContext()), die.GetID(),
3483               namespace_name, static_cast<void *>(namespace_decl),
3484               static_cast<void *>(namespace_decl->getOriginalNamespace()));
3485         } else {
3486           dwarf->GetObjectFile()->GetModule()->LogMessage(
3487               log,
3488               "ASTContext => %p: 0x%8.8" PRIx64
3489               ": DW_TAG_namespace (anonymous) => clang::NamespaceDecl *%p "
3490               "(original = %p)",
3491               static_cast<void *>(&m_ast.getASTContext()), die.GetID(),
3492               static_cast<void *>(namespace_decl),
3493               static_cast<void *>(namespace_decl->getOriginalNamespace()));
3494         }
3495       }
3496 
3497       if (namespace_decl)
3498         LinkDeclContextToDIE((clang::DeclContext *)namespace_decl, die);
3499       return namespace_decl;
3500     }
3501   }
3502   return nullptr;
3503 }
3504 
3505 clang::DeclContext *DWARFASTParserClang::GetClangDeclContextContainingDIE(
3506     const DWARFDIE &die, DWARFDIE *decl_ctx_die_copy) {
3507   SymbolFileDWARF *dwarf = die.GetDWARF();
3508 
3509   DWARFDIE decl_ctx_die = dwarf->GetDeclContextDIEContainingDIE(die);
3510 
3511   if (decl_ctx_die_copy)
3512     *decl_ctx_die_copy = decl_ctx_die;
3513 
3514   if (decl_ctx_die) {
3515     clang::DeclContext *clang_decl_ctx =
3516         GetClangDeclContextForDIE(decl_ctx_die);
3517     if (clang_decl_ctx)
3518       return clang_decl_ctx;
3519   }
3520   return m_ast.GetTranslationUnitDecl();
3521 }
3522 
3523 clang::DeclContext *
3524 DWARFASTParserClang::GetCachedClangDeclContextForDIE(const DWARFDIE &die) {
3525   if (die) {
3526     DIEToDeclContextMap::iterator pos = m_die_to_decl_ctx.find(die.GetDIE());
3527     if (pos != m_die_to_decl_ctx.end())
3528       return pos->second;
3529   }
3530   return nullptr;
3531 }
3532 
3533 void DWARFASTParserClang::LinkDeclContextToDIE(clang::DeclContext *decl_ctx,
3534                                                const DWARFDIE &die) {
3535   m_die_to_decl_ctx[die.GetDIE()] = decl_ctx;
3536   // There can be many DIEs for a single decl context
3537   // m_decl_ctx_to_die[decl_ctx].insert(die.GetDIE());
3538   m_decl_ctx_to_die.insert(std::make_pair(decl_ctx, die));
3539 }
3540 
3541 bool DWARFASTParserClang::CopyUniqueClassMethodTypes(
3542     const DWARFDIE &src_class_die, const DWARFDIE &dst_class_die,
3543     lldb_private::Type *class_type, std::vector<DWARFDIE> &failures) {
3544   if (!class_type || !src_class_die || !dst_class_die)
3545     return false;
3546   if (src_class_die.Tag() != dst_class_die.Tag())
3547     return false;
3548 
3549   // We need to complete the class type so we can get all of the method types
3550   // parsed so we can then unique those types to their equivalent counterparts
3551   // in "dst_cu" and "dst_class_die"
3552   class_type->GetFullCompilerType();
3553 
3554   DWARFDIE src_die;
3555   DWARFDIE dst_die;
3556   UniqueCStringMap<DWARFDIE> src_name_to_die;
3557   UniqueCStringMap<DWARFDIE> dst_name_to_die;
3558   UniqueCStringMap<DWARFDIE> src_name_to_die_artificial;
3559   UniqueCStringMap<DWARFDIE> dst_name_to_die_artificial;
3560   for (src_die = src_class_die.GetFirstChild(); src_die.IsValid();
3561        src_die = src_die.GetSibling()) {
3562     if (src_die.Tag() == DW_TAG_subprogram) {
3563       // Make sure this is a declaration and not a concrete instance by looking
3564       // for DW_AT_declaration set to 1. Sometimes concrete function instances
3565       // are placed inside the class definitions and shouldn't be included in
3566       // the list of things are are tracking here.
3567       if (src_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) == 1) {
3568         const char *src_name = src_die.GetMangledName();
3569         if (src_name) {
3570           ConstString src_const_name(src_name);
3571           if (src_die.GetAttributeValueAsUnsigned(DW_AT_artificial, 0))
3572             src_name_to_die_artificial.Append(src_const_name, src_die);
3573           else
3574             src_name_to_die.Append(src_const_name, src_die);
3575         }
3576       }
3577     }
3578   }
3579   for (dst_die = dst_class_die.GetFirstChild(); dst_die.IsValid();
3580        dst_die = dst_die.GetSibling()) {
3581     if (dst_die.Tag() == DW_TAG_subprogram) {
3582       // Make sure this is a declaration and not a concrete instance by looking
3583       // for DW_AT_declaration set to 1. Sometimes concrete function instances
3584       // are placed inside the class definitions and shouldn't be included in
3585       // the list of things are are tracking here.
3586       if (dst_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) == 1) {
3587         const char *dst_name = dst_die.GetMangledName();
3588         if (dst_name) {
3589           ConstString dst_const_name(dst_name);
3590           if (dst_die.GetAttributeValueAsUnsigned(DW_AT_artificial, 0))
3591             dst_name_to_die_artificial.Append(dst_const_name, dst_die);
3592           else
3593             dst_name_to_die.Append(dst_const_name, dst_die);
3594         }
3595       }
3596     }
3597   }
3598   const uint32_t src_size = src_name_to_die.GetSize();
3599   const uint32_t dst_size = dst_name_to_die.GetSize();
3600   Log *log = nullptr; // (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO |
3601                       // DWARF_LOG_TYPE_COMPLETION));
3602 
3603   // Is everything kosher so we can go through the members at top speed?
3604   bool fast_path = true;
3605 
3606   if (src_size != dst_size) {
3607     if (src_size != 0 && dst_size != 0) {
3608       LLDB_LOGF(log,
3609                 "warning: trying to unique class DIE 0x%8.8x to 0x%8.8x, "
3610                 "but they didn't have the same size (src=%d, dst=%d)",
3611                 src_class_die.GetOffset(), dst_class_die.GetOffset(), src_size,
3612                 dst_size);
3613     }
3614 
3615     fast_path = false;
3616   }
3617 
3618   uint32_t idx;
3619 
3620   if (fast_path) {
3621     for (idx = 0; idx < src_size; ++idx) {
3622       src_die = src_name_to_die.GetValueAtIndexUnchecked(idx);
3623       dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
3624 
3625       if (src_die.Tag() != dst_die.Tag()) {
3626         LLDB_LOGF(log,
3627                   "warning: tried to unique class DIE 0x%8.8x to 0x%8.8x, "
3628                   "but 0x%8.8x (%s) tags didn't match 0x%8.8x (%s)",
3629                   src_class_die.GetOffset(), dst_class_die.GetOffset(),
3630                   src_die.GetOffset(), src_die.GetTagAsCString(),
3631                   dst_die.GetOffset(), dst_die.GetTagAsCString());
3632         fast_path = false;
3633       }
3634 
3635       const char *src_name = src_die.GetMangledName();
3636       const char *dst_name = dst_die.GetMangledName();
3637 
3638       // Make sure the names match
3639       if (src_name == dst_name || (strcmp(src_name, dst_name) == 0))
3640         continue;
3641 
3642       LLDB_LOGF(log,
3643                 "warning: tried to unique class DIE 0x%8.8x to 0x%8.8x, "
3644                 "but 0x%8.8x (%s) names didn't match 0x%8.8x (%s)",
3645                 src_class_die.GetOffset(), dst_class_die.GetOffset(),
3646                 src_die.GetOffset(), src_name, dst_die.GetOffset(), dst_name);
3647 
3648       fast_path = false;
3649     }
3650   }
3651 
3652   DWARFASTParserClang *src_dwarf_ast_parser =
3653       static_cast<DWARFASTParserClang *>(
3654           SymbolFileDWARF::GetDWARFParser(*src_die.GetCU()));
3655   DWARFASTParserClang *dst_dwarf_ast_parser =
3656       static_cast<DWARFASTParserClang *>(
3657           SymbolFileDWARF::GetDWARFParser(*dst_die.GetCU()));
3658 
3659   // Now do the work of linking the DeclContexts and Types.
3660   if (fast_path) {
3661     // We can do this quickly.  Just run across the tables index-for-index
3662     // since we know each node has matching names and tags.
3663     for (idx = 0; idx < src_size; ++idx) {
3664       src_die = src_name_to_die.GetValueAtIndexUnchecked(idx);
3665       dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
3666 
3667       clang::DeclContext *src_decl_ctx =
3668           src_dwarf_ast_parser->m_die_to_decl_ctx[src_die.GetDIE()];
3669       if (src_decl_ctx) {
3670         LLDB_LOGF(log, "uniquing decl context %p from 0x%8.8x for 0x%8.8x",
3671                   static_cast<void *>(src_decl_ctx), src_die.GetOffset(),
3672                   dst_die.GetOffset());
3673         dst_dwarf_ast_parser->LinkDeclContextToDIE(src_decl_ctx, dst_die);
3674       } else {
3675         LLDB_LOGF(log,
3676                   "warning: tried to unique decl context from 0x%8.8x for "
3677                   "0x%8.8x, but none was found",
3678                   src_die.GetOffset(), dst_die.GetOffset());
3679       }
3680 
3681       Type *src_child_type =
3682           dst_die.GetDWARF()->GetDIEToType()[src_die.GetDIE()];
3683       if (src_child_type) {
3684         LLDB_LOGF(log,
3685                   "uniquing type %p (uid=0x%" PRIx64
3686                   ") from 0x%8.8x for 0x%8.8x",
3687                   static_cast<void *>(src_child_type), src_child_type->GetID(),
3688                   src_die.GetOffset(), dst_die.GetOffset());
3689         dst_die.GetDWARF()->GetDIEToType()[dst_die.GetDIE()] = src_child_type;
3690       } else {
3691         LLDB_LOGF(log,
3692                   "warning: tried to unique lldb_private::Type from "
3693                   "0x%8.8x for 0x%8.8x, but none was found",
3694                   src_die.GetOffset(), dst_die.GetOffset());
3695       }
3696     }
3697   } else {
3698     // We must do this slowly.  For each member of the destination, look up a
3699     // member in the source with the same name, check its tag, and unique them
3700     // if everything matches up.  Report failures.
3701 
3702     if (!src_name_to_die.IsEmpty() && !dst_name_to_die.IsEmpty()) {
3703       src_name_to_die.Sort();
3704 
3705       for (idx = 0; idx < dst_size; ++idx) {
3706         ConstString dst_name = dst_name_to_die.GetCStringAtIndex(idx);
3707         dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
3708         src_die = src_name_to_die.Find(dst_name, DWARFDIE());
3709 
3710         if (src_die && (src_die.Tag() == dst_die.Tag())) {
3711           clang::DeclContext *src_decl_ctx =
3712               src_dwarf_ast_parser->m_die_to_decl_ctx[src_die.GetDIE()];
3713           if (src_decl_ctx) {
3714             LLDB_LOGF(log, "uniquing decl context %p from 0x%8.8x for 0x%8.8x",
3715                       static_cast<void *>(src_decl_ctx), src_die.GetOffset(),
3716                       dst_die.GetOffset());
3717             dst_dwarf_ast_parser->LinkDeclContextToDIE(src_decl_ctx, dst_die);
3718           } else {
3719             LLDB_LOGF(log,
3720                       "warning: tried to unique decl context from 0x%8.8x "
3721                       "for 0x%8.8x, but none was found",
3722                       src_die.GetOffset(), dst_die.GetOffset());
3723           }
3724 
3725           Type *src_child_type =
3726               dst_die.GetDWARF()->GetDIEToType()[src_die.GetDIE()];
3727           if (src_child_type) {
3728             LLDB_LOGF(
3729                 log,
3730                 "uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
3731                 static_cast<void *>(src_child_type), src_child_type->GetID(),
3732                 src_die.GetOffset(), dst_die.GetOffset());
3733             dst_die.GetDWARF()->GetDIEToType()[dst_die.GetDIE()] =
3734                 src_child_type;
3735           } else {
3736             LLDB_LOGF(log,
3737                       "warning: tried to unique lldb_private::Type from "
3738                       "0x%8.8x for 0x%8.8x, but none was found",
3739                       src_die.GetOffset(), dst_die.GetOffset());
3740           }
3741         } else {
3742           LLDB_LOGF(log, "warning: couldn't find a match for 0x%8.8x",
3743                     dst_die.GetOffset());
3744 
3745           failures.push_back(dst_die);
3746         }
3747       }
3748     }
3749   }
3750 
3751   const uint32_t src_size_artificial = src_name_to_die_artificial.GetSize();
3752   const uint32_t dst_size_artificial = dst_name_to_die_artificial.GetSize();
3753 
3754   if (src_size_artificial && dst_size_artificial) {
3755     dst_name_to_die_artificial.Sort();
3756 
3757     for (idx = 0; idx < src_size_artificial; ++idx) {
3758       ConstString src_name_artificial =
3759           src_name_to_die_artificial.GetCStringAtIndex(idx);
3760       src_die = src_name_to_die_artificial.GetValueAtIndexUnchecked(idx);
3761       dst_die =
3762           dst_name_to_die_artificial.Find(src_name_artificial, DWARFDIE());
3763 
3764       if (dst_die) {
3765         // Both classes have the artificial types, link them
3766         clang::DeclContext *src_decl_ctx =
3767             src_dwarf_ast_parser->m_die_to_decl_ctx[src_die.GetDIE()];
3768         if (src_decl_ctx) {
3769           LLDB_LOGF(log, "uniquing decl context %p from 0x%8.8x for 0x%8.8x",
3770                     static_cast<void *>(src_decl_ctx), src_die.GetOffset(),
3771                     dst_die.GetOffset());
3772           dst_dwarf_ast_parser->LinkDeclContextToDIE(src_decl_ctx, dst_die);
3773         } else {
3774           LLDB_LOGF(log,
3775                     "warning: tried to unique decl context from 0x%8.8x "
3776                     "for 0x%8.8x, but none was found",
3777                     src_die.GetOffset(), dst_die.GetOffset());
3778         }
3779 
3780         Type *src_child_type =
3781             dst_die.GetDWARF()->GetDIEToType()[src_die.GetDIE()];
3782         if (src_child_type) {
3783           LLDB_LOGF(
3784               log,
3785               "uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
3786               static_cast<void *>(src_child_type), src_child_type->GetID(),
3787               src_die.GetOffset(), dst_die.GetOffset());
3788           dst_die.GetDWARF()->GetDIEToType()[dst_die.GetDIE()] = src_child_type;
3789         } else {
3790           LLDB_LOGF(log,
3791                     "warning: tried to unique lldb_private::Type from "
3792                     "0x%8.8x for 0x%8.8x, but none was found",
3793                     src_die.GetOffset(), dst_die.GetOffset());
3794         }
3795       }
3796     }
3797   }
3798 
3799   if (dst_size_artificial) {
3800     for (idx = 0; idx < dst_size_artificial; ++idx) {
3801       ConstString dst_name_artificial =
3802           dst_name_to_die_artificial.GetCStringAtIndex(idx);
3803       dst_die = dst_name_to_die_artificial.GetValueAtIndexUnchecked(idx);
3804       LLDB_LOGF(log,
3805                 "warning: need to create artificial method for 0x%8.8x for "
3806                 "method '%s'",
3807                 dst_die.GetOffset(), dst_name_artificial.GetCString());
3808 
3809       failures.push_back(dst_die);
3810     }
3811   }
3812 
3813   return !failures.empty();
3814 }
3815