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