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