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