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