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