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