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