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