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