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