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