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