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