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