SymbolFileDWARF.cpp revision 764bca576e78c9bbfb01894cc4d96e96830c77f1
1//===-- SymbolFileDWARF.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 "SymbolFileDWARF.h"
11
12// Other libraries and framework includes
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclGroup.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/Basic/Builtins.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/Basic/Specifiers.h"
25#include "clang/Sema/DeclSpec.h"
26
27#include "llvm/Support/Casting.h"
28
29#include "lldb/Core/Module.h"
30#include "lldb/Core/PluginManager.h"
31#include "lldb/Core/RegularExpression.h"
32#include "lldb/Core/Scalar.h"
33#include "lldb/Core/Section.h"
34#include "lldb/Core/StreamFile.h"
35#include "lldb/Core/StreamString.h"
36#include "lldb/Core/Timer.h"
37#include "lldb/Core/Value.h"
38
39#include "lldb/Host/Host.h"
40
41#include "lldb/Symbol/Block.h"
42#include "lldb/Symbol/ClangExternalASTSourceCallbacks.h"
43#include "lldb/Symbol/CompileUnit.h"
44#include "lldb/Symbol/LineTable.h"
45#include "lldb/Symbol/ObjectFile.h"
46#include "lldb/Symbol/SymbolVendor.h"
47#include "lldb/Symbol/VariableList.h"
48
49#include "lldb/Target/ObjCLanguageRuntime.h"
50#include "lldb/Target/CPPLanguageRuntime.h"
51
52#include "DWARFCompileUnit.h"
53#include "DWARFDebugAbbrev.h"
54#include "DWARFDebugAranges.h"
55#include "DWARFDebugInfo.h"
56#include "DWARFDebugInfoEntry.h"
57#include "DWARFDebugLine.h"
58#include "DWARFDebugPubnames.h"
59#include "DWARFDebugRanges.h"
60#include "DWARFDeclContext.h"
61#include "DWARFDIECollection.h"
62#include "DWARFFormValue.h"
63#include "DWARFLocationList.h"
64#include "LogChannelDWARF.h"
65#include "SymbolFileDWARFDebugMap.h"
66
67#include <map>
68
69//#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
70
71#ifdef ENABLE_DEBUG_PRINTF
72#include <stdio.h>
73#define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__)
74#else
75#define DEBUG_PRINTF(fmt, ...)
76#endif
77
78#define DIE_IS_BEING_PARSED ((lldb_private::Type*)1)
79
80using namespace lldb;
81using namespace lldb_private;
82
83//static inline bool
84//child_requires_parent_class_union_or_struct_to_be_completed (dw_tag_t tag)
85//{
86//    switch (tag)
87//    {
88//    default:
89//        break;
90//    case DW_TAG_subprogram:
91//    case DW_TAG_inlined_subroutine:
92//    case DW_TAG_class_type:
93//    case DW_TAG_structure_type:
94//    case DW_TAG_union_type:
95//        return true;
96//    }
97//    return false;
98//}
99//
100static AccessType
101DW_ACCESS_to_AccessType (uint32_t dwarf_accessibility)
102{
103    switch (dwarf_accessibility)
104    {
105        case DW_ACCESS_public:      return eAccessPublic;
106        case DW_ACCESS_private:     return eAccessPrivate;
107        case DW_ACCESS_protected:   return eAccessProtected;
108        default:                    break;
109    }
110    return eAccessNone;
111}
112
113#if defined(LLDB_CONFIGURATION_DEBUG) or defined(LLDB_CONFIGURATION_RELEASE)
114
115class DIEStack
116{
117public:
118
119    void Push (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
120    {
121        m_dies.push_back (DIEInfo(cu, die));
122    }
123
124
125    void LogDIEs (Log *log, SymbolFileDWARF *dwarf)
126    {
127        StreamString log_strm;
128        const size_t n = m_dies.size();
129        log_strm.Printf("DIEStack[%" PRIu64 "]:\n", (uint64_t)n);
130        for (size_t i=0; i<n; i++)
131        {
132            DWARFCompileUnit *cu = m_dies[i].cu;
133            const DWARFDebugInfoEntry *die = m_dies[i].die;
134            std::string qualified_name;
135            die->GetQualifiedName(dwarf, cu, qualified_name);
136            log_strm.Printf ("[%" PRIu64 "] 0x%8.8x: %s name='%s'\n",
137                             (uint64_t)i,
138                             die->GetOffset(),
139                             DW_TAG_value_to_name(die->Tag()),
140                             qualified_name.c_str());
141        }
142        log->PutCString(log_strm.GetData());
143    }
144    void Pop ()
145    {
146        m_dies.pop_back();
147    }
148
149    class ScopedPopper
150    {
151    public:
152        ScopedPopper (DIEStack &die_stack) :
153            m_die_stack (die_stack),
154            m_valid (false)
155        {
156        }
157
158        void
159        Push (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
160        {
161            m_valid = true;
162            m_die_stack.Push (cu, die);
163        }
164
165        ~ScopedPopper ()
166        {
167            if (m_valid)
168                m_die_stack.Pop();
169        }
170
171
172
173    protected:
174        DIEStack &m_die_stack;
175        bool m_valid;
176    };
177
178protected:
179    struct DIEInfo {
180        DIEInfo (DWARFCompileUnit *c, const DWARFDebugInfoEntry *d) :
181            cu(c),
182            die(d)
183        {
184        }
185        DWARFCompileUnit *cu;
186        const DWARFDebugInfoEntry *die;
187    };
188    typedef std::vector<DIEInfo> Stack;
189    Stack m_dies;
190};
191#endif
192
193void
194SymbolFileDWARF::Initialize()
195{
196    LogChannelDWARF::Initialize();
197    PluginManager::RegisterPlugin (GetPluginNameStatic(),
198                                   GetPluginDescriptionStatic(),
199                                   CreateInstance);
200}
201
202void
203SymbolFileDWARF::Terminate()
204{
205    PluginManager::UnregisterPlugin (CreateInstance);
206    LogChannelDWARF::Initialize();
207}
208
209
210const char *
211SymbolFileDWARF::GetPluginNameStatic()
212{
213    return "dwarf";
214}
215
216const char *
217SymbolFileDWARF::GetPluginDescriptionStatic()
218{
219    return "DWARF and DWARF3 debug symbol file reader.";
220}
221
222
223SymbolFile*
224SymbolFileDWARF::CreateInstance (ObjectFile* obj_file)
225{
226    return new SymbolFileDWARF(obj_file);
227}
228
229TypeList *
230SymbolFileDWARF::GetTypeList ()
231{
232    if (GetDebugMapSymfile ())
233        return m_debug_map_symfile->GetTypeList();
234    return m_obj_file->GetModule()->GetTypeList();
235
236}
237
238//----------------------------------------------------------------------
239// Gets the first parent that is a lexical block, function or inlined
240// subroutine, or compile unit.
241//----------------------------------------------------------------------
242static const DWARFDebugInfoEntry *
243GetParentSymbolContextDIE(const DWARFDebugInfoEntry *child_die)
244{
245    const DWARFDebugInfoEntry *die;
246    for (die = child_die->GetParent(); die != NULL; die = die->GetParent())
247    {
248        dw_tag_t tag = die->Tag();
249
250        switch (tag)
251        {
252        case DW_TAG_compile_unit:
253        case DW_TAG_subprogram:
254        case DW_TAG_inlined_subroutine:
255        case DW_TAG_lexical_block:
256            return die;
257        }
258    }
259    return NULL;
260}
261
262
263SymbolFileDWARF::SymbolFileDWARF(ObjectFile* objfile) :
264    SymbolFile (objfile),
265    UserID (0),  // Used by SymbolFileDWARFDebugMap to when this class parses .o files to contain the .o file index/ID
266    m_debug_map_module_wp (),
267    m_debug_map_symfile (NULL),
268    m_clang_tu_decl (NULL),
269    m_flags(),
270    m_data_debug_abbrev (),
271    m_data_debug_aranges (),
272    m_data_debug_frame (),
273    m_data_debug_info (),
274    m_data_debug_line (),
275    m_data_debug_loc (),
276    m_data_debug_ranges (),
277    m_data_debug_str (),
278    m_data_apple_names (),
279    m_data_apple_types (),
280    m_data_apple_namespaces (),
281    m_abbr(),
282    m_info(),
283    m_line(),
284    m_apple_names_ap (),
285    m_apple_types_ap (),
286    m_apple_namespaces_ap (),
287    m_apple_objc_ap (),
288    m_function_basename_index(),
289    m_function_fullname_index(),
290    m_function_method_index(),
291    m_function_selector_index(),
292    m_objc_class_selectors_index(),
293    m_global_index(),
294    m_type_index(),
295    m_namespace_index(),
296    m_indexed (false),
297    m_is_external_ast_source (false),
298    m_using_apple_tables (false),
299    m_supports_DW_AT_APPLE_objc_complete_type (eLazyBoolCalculate),
300    m_ranges(),
301    m_unique_ast_type_map ()
302{
303}
304
305SymbolFileDWARF::~SymbolFileDWARF()
306{
307    if (m_is_external_ast_source)
308    {
309        ModuleSP module_sp (m_obj_file->GetModule());
310        if (module_sp)
311            module_sp->GetClangASTContext().RemoveExternalSource ();
312    }
313}
314
315static const ConstString &
316GetDWARFMachOSegmentName ()
317{
318    static ConstString g_dwarf_section_name ("__DWARF");
319    return g_dwarf_section_name;
320}
321
322UniqueDWARFASTTypeMap &
323SymbolFileDWARF::GetUniqueDWARFASTTypeMap ()
324{
325    if (GetDebugMapSymfile ())
326        return m_debug_map_symfile->GetUniqueDWARFASTTypeMap ();
327    return m_unique_ast_type_map;
328}
329
330ClangASTContext &
331SymbolFileDWARF::GetClangASTContext ()
332{
333    if (GetDebugMapSymfile ())
334        return m_debug_map_symfile->GetClangASTContext ();
335
336    ClangASTContext &ast = m_obj_file->GetModule()->GetClangASTContext();
337    if (!m_is_external_ast_source)
338    {
339        m_is_external_ast_source = true;
340        llvm::OwningPtr<clang::ExternalASTSource> ast_source_ap (
341            new ClangExternalASTSourceCallbacks (SymbolFileDWARF::CompleteTagDecl,
342                                                 SymbolFileDWARF::CompleteObjCInterfaceDecl,
343                                                 SymbolFileDWARF::FindExternalVisibleDeclsByName,
344                                                 SymbolFileDWARF::LayoutRecordType,
345                                                 this));
346        ast.SetExternalSource (ast_source_ap);
347    }
348    return ast;
349}
350
351void
352SymbolFileDWARF::InitializeObject()
353{
354    // Install our external AST source callbacks so we can complete Clang types.
355    ModuleSP module_sp (m_obj_file->GetModule());
356    if (module_sp)
357    {
358        const SectionList *section_list = m_obj_file->GetSectionList();
359
360        const Section* section = section_list->FindSectionByName(GetDWARFMachOSegmentName ()).get();
361
362        // Memory map the DWARF mach-o segment so we have everything mmap'ed
363        // to keep our heap memory usage down.
364        if (section)
365            m_obj_file->MemoryMapSectionData(section, m_dwarf_data);
366    }
367    get_apple_names_data();
368    if (m_data_apple_names.GetByteSize() > 0)
369    {
370        m_apple_names_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_names, get_debug_str_data(), ".apple_names"));
371        if (m_apple_names_ap->IsValid())
372            m_using_apple_tables = true;
373        else
374            m_apple_names_ap.reset();
375    }
376    get_apple_types_data();
377    if (m_data_apple_types.GetByteSize() > 0)
378    {
379        m_apple_types_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_types, get_debug_str_data(), ".apple_types"));
380        if (m_apple_types_ap->IsValid())
381            m_using_apple_tables = true;
382        else
383            m_apple_types_ap.reset();
384    }
385
386    get_apple_namespaces_data();
387    if (m_data_apple_namespaces.GetByteSize() > 0)
388    {
389        m_apple_namespaces_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_namespaces, get_debug_str_data(), ".apple_namespaces"));
390        if (m_apple_namespaces_ap->IsValid())
391            m_using_apple_tables = true;
392        else
393            m_apple_namespaces_ap.reset();
394    }
395
396    get_apple_objc_data();
397    if (m_data_apple_objc.GetByteSize() > 0)
398    {
399        m_apple_objc_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_objc, get_debug_str_data(), ".apple_objc"));
400        if (m_apple_objc_ap->IsValid())
401            m_using_apple_tables = true;
402        else
403            m_apple_objc_ap.reset();
404    }
405}
406
407bool
408SymbolFileDWARF::SupportedVersion(uint16_t version)
409{
410    return version == 2 || version == 3 || version == 4;
411}
412
413uint32_t
414SymbolFileDWARF::CalculateAbilities ()
415{
416    uint32_t abilities = 0;
417    if (m_obj_file != NULL)
418    {
419        const Section* section = NULL;
420        const SectionList *section_list = m_obj_file->GetSectionList();
421        if (section_list == NULL)
422            return 0;
423
424        uint64_t debug_abbrev_file_size = 0;
425        uint64_t debug_info_file_size = 0;
426        uint64_t debug_line_file_size = 0;
427
428        section = section_list->FindSectionByName(GetDWARFMachOSegmentName ()).get();
429
430        if (section)
431            section_list = &section->GetChildren ();
432
433        section = section_list->FindSectionByType (eSectionTypeDWARFDebugInfo, true).get();
434        if (section != NULL)
435        {
436            debug_info_file_size = section->GetFileSize();
437
438            section = section_list->FindSectionByType (eSectionTypeDWARFDebugAbbrev, true).get();
439            if (section)
440                debug_abbrev_file_size = section->GetFileSize();
441            else
442                m_flags.Set (flagsGotDebugAbbrevData);
443
444            section = section_list->FindSectionByType (eSectionTypeDWARFDebugAranges, true).get();
445            if (!section)
446                m_flags.Set (flagsGotDebugArangesData);
447
448            section = section_list->FindSectionByType (eSectionTypeDWARFDebugFrame, true).get();
449            if (!section)
450                m_flags.Set (flagsGotDebugFrameData);
451
452            section = section_list->FindSectionByType (eSectionTypeDWARFDebugLine, true).get();
453            if (section)
454                debug_line_file_size = section->GetFileSize();
455            else
456                m_flags.Set (flagsGotDebugLineData);
457
458            section = section_list->FindSectionByType (eSectionTypeDWARFDebugLoc, true).get();
459            if (!section)
460                m_flags.Set (flagsGotDebugLocData);
461
462            section = section_list->FindSectionByType (eSectionTypeDWARFDebugMacInfo, true).get();
463            if (!section)
464                m_flags.Set (flagsGotDebugMacInfoData);
465
466            section = section_list->FindSectionByType (eSectionTypeDWARFDebugPubNames, true).get();
467            if (!section)
468                m_flags.Set (flagsGotDebugPubNamesData);
469
470            section = section_list->FindSectionByType (eSectionTypeDWARFDebugPubTypes, true).get();
471            if (!section)
472                m_flags.Set (flagsGotDebugPubTypesData);
473
474            section = section_list->FindSectionByType (eSectionTypeDWARFDebugRanges, true).get();
475            if (!section)
476                m_flags.Set (flagsGotDebugRangesData);
477
478            section = section_list->FindSectionByType (eSectionTypeDWARFDebugStr, true).get();
479            if (!section)
480                m_flags.Set (flagsGotDebugStrData);
481        }
482        else
483        {
484            const char *symfile_dir_cstr = m_obj_file->GetFileSpec().GetDirectory().GetCString();
485            if (symfile_dir_cstr)
486            {
487                if (strcasestr(symfile_dir_cstr, ".dsym"))
488                {
489                    if (m_obj_file->GetType() == ObjectFile::eTypeDebugInfo)
490                    {
491                        // We have a dSYM file that didn't have a any debug info.
492                        // If the string table has a size of 1, then it was made from
493                        // an executable with no debug info, or from an executable that
494                        // was stripped.
495                        section = section_list->FindSectionByType (eSectionTypeDWARFDebugStr, true).get();
496                        if (section && section->GetFileSize() == 1)
497                        {
498                            m_obj_file->GetModule()->ReportWarning ("empty dSYM file detected, dSYM was created with an executable with no debug info.");
499                        }
500                    }
501                }
502            }
503        }
504
505        if (debug_abbrev_file_size > 0 && debug_info_file_size > 0)
506            abilities |= CompileUnits | Functions | Blocks | GlobalVariables | LocalVariables | VariableTypes;
507
508        if (debug_line_file_size > 0)
509            abilities |= LineTables;
510    }
511    return abilities;
512}
513
514const DataExtractor&
515SymbolFileDWARF::GetCachedSectionData (uint32_t got_flag, SectionType sect_type, DataExtractor &data)
516{
517    if (m_flags.IsClear (got_flag))
518    {
519        m_flags.Set (got_flag);
520        const SectionList *section_list = m_obj_file->GetSectionList();
521        if (section_list)
522        {
523            SectionSP section_sp (section_list->FindSectionByType(sect_type, true));
524            if (section_sp)
525            {
526                // See if we memory mapped the DWARF segment?
527                if (m_dwarf_data.GetByteSize())
528                {
529                    data.SetData(m_dwarf_data, section_sp->GetOffset (), section_sp->GetFileSize());
530                }
531                else
532                {
533                    if (m_obj_file->ReadSectionData (section_sp.get(), data) == 0)
534                        data.Clear();
535                }
536            }
537        }
538    }
539    return data;
540}
541
542const DataExtractor&
543SymbolFileDWARF::get_debug_abbrev_data()
544{
545    return GetCachedSectionData (flagsGotDebugAbbrevData, eSectionTypeDWARFDebugAbbrev, m_data_debug_abbrev);
546}
547
548const DataExtractor&
549SymbolFileDWARF::get_debug_aranges_data()
550{
551    return GetCachedSectionData (flagsGotDebugArangesData, eSectionTypeDWARFDebugAranges, m_data_debug_aranges);
552}
553
554const DataExtractor&
555SymbolFileDWARF::get_debug_frame_data()
556{
557    return GetCachedSectionData (flagsGotDebugFrameData, eSectionTypeDWARFDebugFrame, m_data_debug_frame);
558}
559
560const DataExtractor&
561SymbolFileDWARF::get_debug_info_data()
562{
563    return GetCachedSectionData (flagsGotDebugInfoData, eSectionTypeDWARFDebugInfo, m_data_debug_info);
564}
565
566const DataExtractor&
567SymbolFileDWARF::get_debug_line_data()
568{
569    return GetCachedSectionData (flagsGotDebugLineData, eSectionTypeDWARFDebugLine, m_data_debug_line);
570}
571
572const DataExtractor&
573SymbolFileDWARF::get_debug_loc_data()
574{
575    return GetCachedSectionData (flagsGotDebugLocData, eSectionTypeDWARFDebugLoc, m_data_debug_loc);
576}
577
578const DataExtractor&
579SymbolFileDWARF::get_debug_ranges_data()
580{
581    return GetCachedSectionData (flagsGotDebugRangesData, eSectionTypeDWARFDebugRanges, m_data_debug_ranges);
582}
583
584const DataExtractor&
585SymbolFileDWARF::get_debug_str_data()
586{
587    return GetCachedSectionData (flagsGotDebugStrData, eSectionTypeDWARFDebugStr, m_data_debug_str);
588}
589
590const DataExtractor&
591SymbolFileDWARF::get_apple_names_data()
592{
593    return GetCachedSectionData (flagsGotAppleNamesData, eSectionTypeDWARFAppleNames, m_data_apple_names);
594}
595
596const DataExtractor&
597SymbolFileDWARF::get_apple_types_data()
598{
599    return GetCachedSectionData (flagsGotAppleTypesData, eSectionTypeDWARFAppleTypes, m_data_apple_types);
600}
601
602const DataExtractor&
603SymbolFileDWARF::get_apple_namespaces_data()
604{
605    return GetCachedSectionData (flagsGotAppleNamespacesData, eSectionTypeDWARFAppleNamespaces, m_data_apple_namespaces);
606}
607
608const DataExtractor&
609SymbolFileDWARF::get_apple_objc_data()
610{
611    return GetCachedSectionData (flagsGotAppleObjCData, eSectionTypeDWARFAppleObjC, m_data_apple_objc);
612}
613
614
615DWARFDebugAbbrev*
616SymbolFileDWARF::DebugAbbrev()
617{
618    if (m_abbr.get() == NULL)
619    {
620        const DataExtractor &debug_abbrev_data = get_debug_abbrev_data();
621        if (debug_abbrev_data.GetByteSize() > 0)
622        {
623            m_abbr.reset(new DWARFDebugAbbrev());
624            if (m_abbr.get())
625                m_abbr->Parse(debug_abbrev_data);
626        }
627    }
628    return m_abbr.get();
629}
630
631const DWARFDebugAbbrev*
632SymbolFileDWARF::DebugAbbrev() const
633{
634    return m_abbr.get();
635}
636
637
638DWARFDebugInfo*
639SymbolFileDWARF::DebugInfo()
640{
641    if (m_info.get() == NULL)
642    {
643        Timer scoped_timer(__PRETTY_FUNCTION__, "%s this = %p", __PRETTY_FUNCTION__, this);
644        if (get_debug_info_data().GetByteSize() > 0)
645        {
646            m_info.reset(new DWARFDebugInfo());
647            if (m_info.get())
648            {
649                m_info->SetDwarfData(this);
650            }
651        }
652    }
653    return m_info.get();
654}
655
656const DWARFDebugInfo*
657SymbolFileDWARF::DebugInfo() const
658{
659    return m_info.get();
660}
661
662DWARFCompileUnit*
663SymbolFileDWARF::GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit)
664{
665    DWARFDebugInfo* info = DebugInfo();
666    if (info)
667    {
668        if (GetDebugMapSymfile ())
669        {
670            // The debug map symbol file made the compile units for this DWARF
671            // file which is .o file with DWARF in it, and we should have
672            // only 1 compile unit which is at offset zero in the DWARF.
673            // TODO: modify to support LTO .o files where each .o file might
674            // have multiple DW_TAG_compile_unit tags.
675            return info->GetCompileUnit(0).get();
676        }
677        else
678        {
679            // Just a normal DWARF file whose user ID for the compile unit is
680            // the DWARF offset itself
681            return info->GetCompileUnit((dw_offset_t)comp_unit->GetID()).get();
682        }
683    }
684    return NULL;
685}
686
687
688DWARFDebugRanges*
689SymbolFileDWARF::DebugRanges()
690{
691    if (m_ranges.get() == NULL)
692    {
693        Timer scoped_timer(__PRETTY_FUNCTION__, "%s this = %p", __PRETTY_FUNCTION__, this);
694        if (get_debug_ranges_data().GetByteSize() > 0)
695        {
696            m_ranges.reset(new DWARFDebugRanges());
697            if (m_ranges.get())
698                m_ranges->Extract(this);
699        }
700    }
701    return m_ranges.get();
702}
703
704const DWARFDebugRanges*
705SymbolFileDWARF::DebugRanges() const
706{
707    return m_ranges.get();
708}
709
710lldb::CompUnitSP
711SymbolFileDWARF::ParseCompileUnit (DWARFCompileUnit* dwarf_cu, uint32_t cu_idx)
712{
713    CompUnitSP cu_sp;
714    if (dwarf_cu)
715    {
716        CompileUnit *comp_unit = (CompileUnit*)dwarf_cu->GetUserData();
717        if (comp_unit)
718        {
719            // We already parsed this compile unit, had out a shared pointer to it
720            cu_sp = comp_unit->shared_from_this();
721        }
722        else
723        {
724            if (GetDebugMapSymfile ())
725            {
726                // Let the debug map create the compile unit
727                cu_sp = m_debug_map_symfile->GetCompileUnit(this);
728                dwarf_cu->SetUserData(cu_sp.get());
729            }
730            else
731            {
732                ModuleSP module_sp (m_obj_file->GetModule());
733                if (module_sp)
734                {
735                    const DWARFDebugInfoEntry * cu_die = dwarf_cu->GetCompileUnitDIEOnly ();
736                    if (cu_die)
737                    {
738                        const char * cu_die_name = cu_die->GetName(this, dwarf_cu);
739                        const char * cu_comp_dir = cu_die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_comp_dir, NULL);
740                        LanguageType cu_language = (LanguageType)cu_die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_language, 0);
741                        if (cu_die_name)
742                        {
743                            std::string ramapped_file;
744                            FileSpec cu_file_spec;
745
746                            if (cu_die_name[0] == '/' || cu_comp_dir == NULL || cu_comp_dir[0] == '\0')
747                            {
748                                // If we have a full path to the compile unit, we don't need to resolve
749                                // the file.  This can be expensive e.g. when the source files are NFS mounted.
750                                if (module_sp->RemapSourceFile(cu_die_name, ramapped_file))
751                                    cu_file_spec.SetFile (ramapped_file.c_str(), false);
752                                else
753                                    cu_file_spec.SetFile (cu_die_name, false);
754                            }
755                            else
756                            {
757                                std::string fullpath(cu_comp_dir);
758                                if (*fullpath.rbegin() != '/')
759                                    fullpath += '/';
760                                fullpath += cu_die_name;
761                                if (module_sp->RemapSourceFile (fullpath.c_str(), ramapped_file))
762                                    cu_file_spec.SetFile (ramapped_file.c_str(), false);
763                                else
764                                    cu_file_spec.SetFile (fullpath.c_str(), false);
765                            }
766
767                            cu_sp.reset(new CompileUnit (module_sp,
768                                                         dwarf_cu,
769                                                         cu_file_spec,
770                                                         MakeUserID(dwarf_cu->GetOffset()),
771                                                         cu_language));
772                            if (cu_sp)
773                            {
774                                dwarf_cu->SetUserData(cu_sp.get());
775
776                                // Figure out the compile unit index if we weren't given one
777                                if (cu_idx == UINT32_MAX)
778                                    DebugInfo()->GetCompileUnit(dwarf_cu->GetOffset(), &cu_idx);
779
780                                m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(cu_idx, cu_sp);
781                            }
782                        }
783                    }
784                }
785            }
786        }
787    }
788    return cu_sp;
789}
790
791uint32_t
792SymbolFileDWARF::GetNumCompileUnits()
793{
794    DWARFDebugInfo* info = DebugInfo();
795    if (info)
796        return info->GetNumCompileUnits();
797    return 0;
798}
799
800CompUnitSP
801SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx)
802{
803    CompUnitSP cu_sp;
804    DWARFDebugInfo* info = DebugInfo();
805    if (info)
806    {
807        DWARFCompileUnit* dwarf_cu = info->GetCompileUnitAtIndex(cu_idx);
808        if (dwarf_cu)
809            cu_sp = ParseCompileUnit(dwarf_cu, cu_idx);
810    }
811    return cu_sp;
812}
813
814static void
815AddRangesToBlock (Block& block,
816                  DWARFDebugRanges::RangeList& ranges,
817                  addr_t block_base_addr)
818{
819    const size_t num_ranges = ranges.GetSize();
820    for (size_t i = 0; i<num_ranges; ++i)
821    {
822        const DWARFDebugRanges::Range &range = ranges.GetEntryRef (i);
823        const addr_t range_base = range.GetRangeBase();
824        assert (range_base >= block_base_addr);
825        block.AddRange(Block::Range (range_base - block_base_addr, range.GetByteSize()));;
826    }
827    block.FinalizeRanges ();
828}
829
830
831Function *
832SymbolFileDWARF::ParseCompileUnitFunction (const SymbolContext& sc, DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry *die)
833{
834    DWARFDebugRanges::RangeList func_ranges;
835    const char *name = NULL;
836    const char *mangled = NULL;
837    int decl_file = 0;
838    int decl_line = 0;
839    int decl_column = 0;
840    int call_file = 0;
841    int call_line = 0;
842    int call_column = 0;
843    DWARFExpression frame_base;
844
845    assert (die->Tag() == DW_TAG_subprogram);
846
847    if (die->Tag() != DW_TAG_subprogram)
848        return NULL;
849
850    if (die->GetDIENamesAndRanges (this,
851                                   dwarf_cu,
852                                   name,
853                                   mangled,
854                                   func_ranges,
855                                   decl_file,
856                                   decl_line,
857                                   decl_column,
858                                   call_file,
859                                   call_line,
860                                   call_column,
861                                   &frame_base))
862    {
863        // Union of all ranges in the function DIE (if the function is discontiguous)
864        AddressRange func_range;
865        lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase (0);
866        lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd (0);
867        if (lowest_func_addr != LLDB_INVALID_ADDRESS && lowest_func_addr <= highest_func_addr)
868        {
869            func_range.GetBaseAddress().ResolveAddressUsingFileSections (lowest_func_addr, m_obj_file->GetSectionList());
870            if (func_range.GetBaseAddress().IsValid())
871                func_range.SetByteSize(highest_func_addr - lowest_func_addr);
872        }
873
874        if (func_range.GetBaseAddress().IsValid())
875        {
876            Mangled func_name;
877            if (mangled)
878                func_name.SetValue(ConstString(mangled), true);
879            else if (name)
880                func_name.SetValue(ConstString(name), false);
881
882            FunctionSP func_sp;
883            std::unique_ptr<Declaration> decl_ap;
884            if (decl_file != 0 || decl_line != 0 || decl_column != 0)
885                decl_ap.reset(new Declaration (sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),
886                                               decl_line,
887                                               decl_column));
888
889            // Supply the type _only_ if it has already been parsed
890            Type *func_type = m_die_to_type.lookup (die);
891
892            assert(func_type == NULL || func_type != DIE_IS_BEING_PARSED);
893
894            if (FixupAddress (func_range.GetBaseAddress()))
895            {
896                const user_id_t func_user_id = MakeUserID(die->GetOffset());
897                func_sp.reset(new Function (sc.comp_unit,
898                                            MakeUserID(func_user_id),       // UserID is the DIE offset
899                                            MakeUserID(func_user_id),
900                                            func_name,
901                                            func_type,
902                                            func_range));           // first address range
903
904                if (func_sp.get() != NULL)
905                {
906                    if (frame_base.IsValid())
907                        func_sp->GetFrameBaseExpression() = frame_base;
908                    sc.comp_unit->AddFunction(func_sp);
909                    return func_sp.get();
910                }
911            }
912        }
913    }
914    return NULL;
915}
916
917bool
918SymbolFileDWARF::FixupAddress (Address &addr)
919{
920    SymbolFileDWARFDebugMap * debug_map_symfile = GetDebugMapSymfile ();
921    if (debug_map_symfile)
922    {
923        return debug_map_symfile->LinkOSOAddress(addr);
924    }
925    // This is a normal DWARF file, no address fixups need to happen
926    return true;
927}
928lldb::LanguageType
929SymbolFileDWARF::ParseCompileUnitLanguage (const SymbolContext& sc)
930{
931    assert (sc.comp_unit);
932    DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
933    if (dwarf_cu)
934    {
935        const DWARFDebugInfoEntry *die = dwarf_cu->GetCompileUnitDIEOnly();
936        if (die)
937        {
938            const uint32_t language = die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_language, 0);
939            if (language)
940                return (lldb::LanguageType)language;
941        }
942    }
943    return eLanguageTypeUnknown;
944}
945
946size_t
947SymbolFileDWARF::ParseCompileUnitFunctions(const SymbolContext &sc)
948{
949    assert (sc.comp_unit);
950    size_t functions_added = 0;
951    DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
952    if (dwarf_cu)
953    {
954        DWARFDIECollection function_dies;
955        const size_t num_functions = dwarf_cu->AppendDIEsWithTag (DW_TAG_subprogram, function_dies);
956        size_t func_idx;
957        for (func_idx = 0; func_idx < num_functions; ++func_idx)
958        {
959            const DWARFDebugInfoEntry *die = function_dies.GetDIEPtrAtIndex(func_idx);
960            if (sc.comp_unit->FindFunctionByUID (MakeUserID(die->GetOffset())).get() == NULL)
961            {
962                if (ParseCompileUnitFunction(sc, dwarf_cu, die))
963                    ++functions_added;
964            }
965        }
966        //FixupTypes();
967    }
968    return functions_added;
969}
970
971bool
972SymbolFileDWARF::ParseCompileUnitSupportFiles (const SymbolContext& sc, FileSpecList& support_files)
973{
974    assert (sc.comp_unit);
975    DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
976    if (dwarf_cu)
977    {
978        const DWARFDebugInfoEntry * cu_die = dwarf_cu->GetCompileUnitDIEOnly();
979
980        if (cu_die)
981        {
982            const char * cu_comp_dir = cu_die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_comp_dir, NULL);
983            dw_offset_t stmt_list = cu_die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_stmt_list, DW_INVALID_OFFSET);
984
985            // All file indexes in DWARF are one based and a file of index zero is
986            // supposed to be the compile unit itself.
987            support_files.Append (*sc.comp_unit);
988
989            return DWARFDebugLine::ParseSupportFiles(sc.comp_unit->GetModule(), get_debug_line_data(), cu_comp_dir, stmt_list, support_files);
990        }
991    }
992    return false;
993}
994
995struct ParseDWARFLineTableCallbackInfo
996{
997    LineTable* line_table;
998    std::unique_ptr<LineSequence> sequence_ap;
999};
1000
1001//----------------------------------------------------------------------
1002// ParseStatementTableCallback
1003//----------------------------------------------------------------------
1004static void
1005ParseDWARFLineTableCallback(dw_offset_t offset, const DWARFDebugLine::State& state, void* userData)
1006{
1007    if (state.row == DWARFDebugLine::State::StartParsingLineTable)
1008    {
1009        // Just started parsing the line table
1010    }
1011    else if (state.row == DWARFDebugLine::State::DoneParsingLineTable)
1012    {
1013        // Done parsing line table, nothing to do for the cleanup
1014    }
1015    else
1016    {
1017        ParseDWARFLineTableCallbackInfo* info = (ParseDWARFLineTableCallbackInfo*)userData;
1018        LineTable* line_table = info->line_table;
1019
1020        // If this is our first time here, we need to create a
1021        // sequence container.
1022        if (!info->sequence_ap.get())
1023        {
1024            info->sequence_ap.reset(line_table->CreateLineSequenceContainer());
1025            assert(info->sequence_ap.get());
1026        }
1027        line_table->AppendLineEntryToSequence (info->sequence_ap.get(),
1028                                               state.address,
1029                                               state.line,
1030                                               state.column,
1031                                               state.file,
1032                                               state.is_stmt,
1033                                               state.basic_block,
1034                                               state.prologue_end,
1035                                               state.epilogue_begin,
1036                                               state.end_sequence);
1037        if (state.end_sequence)
1038        {
1039            // First, put the current sequence into the line table.
1040            line_table->InsertSequence(info->sequence_ap.get());
1041            // Then, empty it to prepare for the next sequence.
1042            info->sequence_ap->Clear();
1043        }
1044    }
1045}
1046
1047bool
1048SymbolFileDWARF::ParseCompileUnitLineTable (const SymbolContext &sc)
1049{
1050    assert (sc.comp_unit);
1051    if (sc.comp_unit->GetLineTable() != NULL)
1052        return true;
1053
1054    DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1055    if (dwarf_cu)
1056    {
1057        const DWARFDebugInfoEntry *dwarf_cu_die = dwarf_cu->GetCompileUnitDIEOnly();
1058        if (dwarf_cu_die)
1059        {
1060            const dw_offset_t cu_line_offset = dwarf_cu_die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_stmt_list, DW_INVALID_OFFSET);
1061            if (cu_line_offset != DW_INVALID_OFFSET)
1062            {
1063                std::unique_ptr<LineTable> line_table_ap(new LineTable(sc.comp_unit));
1064                if (line_table_ap.get())
1065                {
1066                    ParseDWARFLineTableCallbackInfo info;
1067                    info.line_table = line_table_ap.get();
1068                    lldb::offset_t offset = cu_line_offset;
1069                    DWARFDebugLine::ParseStatementTable(get_debug_line_data(), &offset, ParseDWARFLineTableCallback, &info);
1070                    if (m_debug_map_symfile)
1071                    {
1072                        // We have an object file that has a line table with addresses
1073                        // that are not linked. We need to link the line table and convert
1074                        // the addresses that are relative to the .o file into addresses
1075                        // for the main executable.
1076                        sc.comp_unit->SetLineTable (m_debug_map_symfile->LinkOSOLineTable (this, line_table_ap.get()));
1077                    }
1078                    else
1079                    {
1080                        sc.comp_unit->SetLineTable(line_table_ap.release());
1081                        return true;
1082                    }
1083                }
1084            }
1085        }
1086    }
1087    return false;
1088}
1089
1090size_t
1091SymbolFileDWARF::ParseFunctionBlocks
1092(
1093    const SymbolContext& sc,
1094    Block *parent_block,
1095    DWARFCompileUnit* dwarf_cu,
1096    const DWARFDebugInfoEntry *die,
1097    addr_t subprogram_low_pc,
1098    uint32_t depth
1099)
1100{
1101    size_t blocks_added = 0;
1102    while (die != NULL)
1103    {
1104        dw_tag_t tag = die->Tag();
1105
1106        switch (tag)
1107        {
1108        case DW_TAG_inlined_subroutine:
1109        case DW_TAG_subprogram:
1110        case DW_TAG_lexical_block:
1111            {
1112                Block *block = NULL;
1113                if (tag == DW_TAG_subprogram)
1114                {
1115                    // Skip any DW_TAG_subprogram DIEs that are inside
1116                    // of a normal or inlined functions. These will be
1117                    // parsed on their own as separate entities.
1118
1119                    if (depth > 0)
1120                        break;
1121
1122                    block = parent_block;
1123                }
1124                else
1125                {
1126                    BlockSP block_sp(new Block (MakeUserID(die->GetOffset())));
1127                    parent_block->AddChild(block_sp);
1128                    block = block_sp.get();
1129                }
1130                DWARFDebugRanges::RangeList ranges;
1131                const char *name = NULL;
1132                const char *mangled_name = NULL;
1133
1134                int decl_file = 0;
1135                int decl_line = 0;
1136                int decl_column = 0;
1137                int call_file = 0;
1138                int call_line = 0;
1139                int call_column = 0;
1140                if (die->GetDIENamesAndRanges (this,
1141                                               dwarf_cu,
1142                                               name,
1143                                               mangled_name,
1144                                               ranges,
1145                                               decl_file, decl_line, decl_column,
1146                                               call_file, call_line, call_column))
1147                {
1148                    if (tag == DW_TAG_subprogram)
1149                    {
1150                        assert (subprogram_low_pc == LLDB_INVALID_ADDRESS);
1151                        subprogram_low_pc = ranges.GetMinRangeBase(0);
1152                    }
1153                    else if (tag == DW_TAG_inlined_subroutine)
1154                    {
1155                        // We get called here for inlined subroutines in two ways.
1156                        // The first time is when we are making the Function object
1157                        // for this inlined concrete instance.  Since we're creating a top level block at
1158                        // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS.  So we need to
1159                        // adjust the containing address.
1160                        // The second time is when we are parsing the blocks inside the function that contains
1161                        // the inlined concrete instance.  Since these will be blocks inside the containing "real"
1162                        // function the offset will be for that function.
1163                        if (subprogram_low_pc == LLDB_INVALID_ADDRESS)
1164                        {
1165                            subprogram_low_pc = ranges.GetMinRangeBase(0);
1166                        }
1167                    }
1168
1169                    AddRangesToBlock (*block, ranges, subprogram_low_pc);
1170
1171                    if (tag != DW_TAG_subprogram && (name != NULL || mangled_name != NULL))
1172                    {
1173                        std::unique_ptr<Declaration> decl_ap;
1174                        if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1175                            decl_ap.reset(new Declaration(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),
1176                                                          decl_line, decl_column));
1177
1178                        std::unique_ptr<Declaration> call_ap;
1179                        if (call_file != 0 || call_line != 0 || call_column != 0)
1180                            call_ap.reset(new Declaration(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(call_file),
1181                                                          call_line, call_column));
1182
1183                        block->SetInlinedFunctionInfo (name, mangled_name, decl_ap.get(), call_ap.get());
1184                    }
1185
1186                    ++blocks_added;
1187
1188                    if (die->HasChildren())
1189                    {
1190                        blocks_added += ParseFunctionBlocks (sc,
1191                                                             block,
1192                                                             dwarf_cu,
1193                                                             die->GetFirstChild(),
1194                                                             subprogram_low_pc,
1195                                                             depth + 1);
1196                    }
1197                }
1198            }
1199            break;
1200        default:
1201            break;
1202        }
1203
1204        // Only parse siblings of the block if we are not at depth zero. A depth
1205        // of zero indicates we are currently parsing the top level
1206        // DW_TAG_subprogram DIE
1207
1208        if (depth == 0)
1209            die = NULL;
1210        else
1211            die = die->GetSibling();
1212    }
1213    return blocks_added;
1214}
1215
1216bool
1217SymbolFileDWARF::ParseTemplateDIE (DWARFCompileUnit* dwarf_cu,
1218                                   const DWARFDebugInfoEntry *die,
1219                                   ClangASTContext::TemplateParameterInfos &template_param_infos)
1220{
1221    const dw_tag_t tag = die->Tag();
1222
1223    switch (tag)
1224    {
1225    case DW_TAG_template_type_parameter:
1226    case DW_TAG_template_value_parameter:
1227        {
1228            const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
1229
1230            DWARFDebugInfoEntry::Attributes attributes;
1231            const size_t num_attributes = die->GetAttributes (this,
1232                                                              dwarf_cu,
1233                                                              fixed_form_sizes,
1234                                                              attributes);
1235            const char *name = NULL;
1236            Type *lldb_type = NULL;
1237            clang_type_t clang_type = NULL;
1238            uint64_t uval64 = 0;
1239            bool uval64_valid = false;
1240            if (num_attributes > 0)
1241            {
1242                DWARFFormValue form_value;
1243                for (size_t i=0; i<num_attributes; ++i)
1244                {
1245                    const dw_attr_t attr = attributes.AttributeAtIndex(i);
1246
1247                    switch (attr)
1248                    {
1249                        case DW_AT_name:
1250                            if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1251                                name = form_value.AsCString(&get_debug_str_data());
1252                            break;
1253
1254                        case DW_AT_type:
1255                            if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1256                            {
1257                                const dw_offset_t type_die_offset = form_value.Reference(dwarf_cu);
1258                                lldb_type = ResolveTypeUID(type_die_offset);
1259                                if (lldb_type)
1260                                    clang_type = lldb_type->GetClangForwardType();
1261                            }
1262                            break;
1263
1264                        case DW_AT_const_value:
1265                            if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1266                            {
1267                                uval64_valid = true;
1268                                uval64 = form_value.Unsigned();
1269                            }
1270                            break;
1271                        default:
1272                            break;
1273                    }
1274                }
1275
1276                clang::ASTContext *ast = GetClangASTContext().getASTContext();
1277                if (!clang_type)
1278                    clang_type = ast->VoidTy.getAsOpaquePtr();
1279
1280                if (clang_type)
1281                {
1282                    bool is_signed = false;
1283                    if (name && name[0])
1284                        template_param_infos.names.push_back(name);
1285                    else
1286                        template_param_infos.names.push_back(NULL);
1287
1288                    clang::QualType clang_qual_type (clang::QualType::getFromOpaquePtr (clang_type));
1289                    if (tag == DW_TAG_template_value_parameter &&
1290                        lldb_type != NULL &&
1291                        ClangASTContext::IsIntegerType (clang_type, is_signed) &&
1292                        uval64_valid)
1293                    {
1294                        llvm::APInt apint (lldb_type->GetByteSize() * 8, uval64, is_signed);
1295                        template_param_infos.args.push_back (clang::TemplateArgument (*ast,
1296                                                                                      llvm::APSInt(apint),
1297                                                                                      clang_qual_type));
1298                    }
1299                    else
1300                    {
1301                        template_param_infos.args.push_back (clang::TemplateArgument (clang_qual_type));
1302                    }
1303                }
1304                else
1305                {
1306                    return false;
1307                }
1308
1309            }
1310        }
1311        return true;
1312
1313    default:
1314        break;
1315    }
1316    return false;
1317}
1318
1319bool
1320SymbolFileDWARF::ParseTemplateParameterInfos (DWARFCompileUnit* dwarf_cu,
1321                                              const DWARFDebugInfoEntry *parent_die,
1322                                              ClangASTContext::TemplateParameterInfos &template_param_infos)
1323{
1324
1325    if (parent_die == NULL)
1326        return false;
1327
1328    Args template_parameter_names;
1329    for (const DWARFDebugInfoEntry *die = parent_die->GetFirstChild();
1330         die != NULL;
1331         die = die->GetSibling())
1332    {
1333        const dw_tag_t tag = die->Tag();
1334
1335        switch (tag)
1336        {
1337            case DW_TAG_template_type_parameter:
1338            case DW_TAG_template_value_parameter:
1339                ParseTemplateDIE (dwarf_cu, die, template_param_infos);
1340            break;
1341
1342        default:
1343            break;
1344        }
1345    }
1346    if (template_param_infos.args.empty())
1347        return false;
1348    return template_param_infos.args.size() == template_param_infos.names.size();
1349}
1350
1351clang::ClassTemplateDecl *
1352SymbolFileDWARF::ParseClassTemplateDecl (clang::DeclContext *decl_ctx,
1353                                         lldb::AccessType access_type,
1354                                         const char *parent_name,
1355                                         int tag_decl_kind,
1356                                         const ClangASTContext::TemplateParameterInfos &template_param_infos)
1357{
1358    if (template_param_infos.IsValid())
1359    {
1360        std::string template_basename(parent_name);
1361        template_basename.erase (template_basename.find('<'));
1362        ClangASTContext &ast = GetClangASTContext();
1363
1364        return ast.CreateClassTemplateDecl (decl_ctx,
1365                                            access_type,
1366                                            template_basename.c_str(),
1367                                            tag_decl_kind,
1368                                            template_param_infos);
1369    }
1370    return NULL;
1371}
1372
1373class SymbolFileDWARF::DelayedAddObjCClassProperty
1374{
1375public:
1376    DelayedAddObjCClassProperty
1377    (
1378        clang::ASTContext      *ast,
1379        lldb::clang_type_t      class_opaque_type,
1380        const char             *property_name,
1381        lldb::clang_type_t      property_opaque_type,  // The property type is only required if you don't have an ivar decl
1382        clang::ObjCIvarDecl    *ivar_decl,
1383        const char             *property_setter_name,
1384        const char             *property_getter_name,
1385        uint32_t                property_attributes,
1386        const ClangASTMetadata *metadata
1387    ) :
1388        m_ast                   (ast),
1389        m_class_opaque_type     (class_opaque_type),
1390        m_property_name         (property_name),
1391        m_property_opaque_type  (property_opaque_type),
1392        m_ivar_decl             (ivar_decl),
1393        m_property_setter_name  (property_setter_name),
1394        m_property_getter_name  (property_getter_name),
1395        m_property_attributes   (property_attributes)
1396    {
1397        if (metadata != NULL)
1398        {
1399            m_metadata_ap.reset(new ClangASTMetadata());
1400            *m_metadata_ap = *metadata;
1401        }
1402    }
1403
1404    DelayedAddObjCClassProperty (const DelayedAddObjCClassProperty &rhs)
1405    {
1406      *this = rhs;
1407    }
1408
1409    DelayedAddObjCClassProperty& operator= (const DelayedAddObjCClassProperty &rhs)
1410    {
1411        m_ast                  = rhs.m_ast;
1412        m_class_opaque_type    = rhs.m_class_opaque_type;
1413        m_property_name        = rhs.m_property_name;
1414        m_property_opaque_type = rhs.m_property_opaque_type;
1415        m_ivar_decl            = rhs.m_ivar_decl;
1416        m_property_setter_name = rhs.m_property_setter_name;
1417        m_property_getter_name = rhs.m_property_getter_name;
1418        m_property_attributes  = rhs.m_property_attributes;
1419
1420        if (rhs.m_metadata_ap.get())
1421        {
1422            m_metadata_ap.reset (new ClangASTMetadata());
1423            *m_metadata_ap = *rhs.m_metadata_ap;
1424        }
1425        return *this;
1426    }
1427
1428    bool Finalize() const
1429    {
1430        return ClangASTContext::AddObjCClassProperty (m_ast,
1431                                                      m_class_opaque_type,
1432                                                      m_property_name,
1433                                                      m_property_opaque_type,
1434                                                      m_ivar_decl,
1435                                                      m_property_setter_name,
1436                                                      m_property_getter_name,
1437                                                      m_property_attributes,
1438                                                      m_metadata_ap.get());
1439    }
1440private:
1441    clang::ASTContext      *m_ast;
1442    lldb::clang_type_t      m_class_opaque_type;
1443    const char             *m_property_name;
1444    lldb::clang_type_t      m_property_opaque_type;
1445    clang::ObjCIvarDecl    *m_ivar_decl;
1446    const char             *m_property_setter_name;
1447    const char             *m_property_getter_name;
1448    uint32_t                m_property_attributes;
1449    std::unique_ptr<ClangASTMetadata> m_metadata_ap;
1450};
1451
1452struct BitfieldInfo
1453{
1454    uint64_t bit_size;
1455    uint64_t bit_offset;
1456
1457    BitfieldInfo () :
1458        bit_size (LLDB_INVALID_ADDRESS),
1459        bit_offset (LLDB_INVALID_ADDRESS)
1460    {
1461    }
1462
1463    bool IsValid ()
1464    {
1465        return (bit_size != LLDB_INVALID_ADDRESS) &&
1466               (bit_offset != LLDB_INVALID_ADDRESS);
1467    }
1468};
1469
1470
1471bool
1472SymbolFileDWARF::ClassOrStructIsVirtual (DWARFCompileUnit* dwarf_cu,
1473                                         const DWARFDebugInfoEntry *parent_die)
1474{
1475    if (parent_die)
1476    {
1477        for (const DWARFDebugInfoEntry *die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
1478        {
1479            dw_tag_t tag = die->Tag();
1480            bool check_virtuality = false;
1481            switch (tag)
1482            {
1483                case DW_TAG_inheritance:
1484                case DW_TAG_subprogram:
1485                    check_virtuality = true;
1486                    break;
1487                default:
1488                    break;
1489            }
1490            if (check_virtuality)
1491            {
1492                if (die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_virtuality, 0) != 0)
1493                    return true;
1494            }
1495        }
1496    }
1497    return false;
1498}
1499
1500size_t
1501SymbolFileDWARF::ParseChildMembers
1502(
1503    const SymbolContext& sc,
1504    DWARFCompileUnit* dwarf_cu,
1505    const DWARFDebugInfoEntry *parent_die,
1506    clang_type_t class_clang_type,
1507    const LanguageType class_language,
1508    std::vector<clang::CXXBaseSpecifier *>& base_classes,
1509    std::vector<int>& member_accessibilities,
1510    DWARFDIECollection& member_function_dies,
1511    DelayedPropertyList& delayed_properties,
1512    AccessType& default_accessibility,
1513    bool &is_a_class,
1514    LayoutInfo &layout_info
1515)
1516{
1517    if (parent_die == NULL)
1518        return 0;
1519
1520    size_t count = 0;
1521    const DWARFDebugInfoEntry *die;
1522    const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
1523    uint32_t member_idx = 0;
1524    BitfieldInfo last_field_info;
1525
1526    for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
1527    {
1528        dw_tag_t tag = die->Tag();
1529
1530        switch (tag)
1531        {
1532        case DW_TAG_member:
1533        case DW_TAG_APPLE_property:
1534            {
1535                DWARFDebugInfoEntry::Attributes attributes;
1536                const size_t num_attributes = die->GetAttributes (this,
1537                                                                  dwarf_cu,
1538                                                                  fixed_form_sizes,
1539                                                                  attributes);
1540                if (num_attributes > 0)
1541                {
1542                    Declaration decl;
1543                    //DWARFExpression location;
1544                    const char *name = NULL;
1545                    const char *prop_name = NULL;
1546                    const char *prop_getter_name = NULL;
1547                    const char *prop_setter_name = NULL;
1548                    uint32_t prop_attributes = 0;
1549
1550
1551                    bool is_artificial = false;
1552                    lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
1553                    AccessType accessibility = eAccessNone;
1554                    uint32_t member_byte_offset = UINT32_MAX;
1555                    size_t byte_size = 0;
1556                    size_t bit_offset = 0;
1557                    size_t bit_size = 0;
1558                    bool is_external = false; // On DW_TAG_members, this means the member is static
1559                    uint32_t i;
1560                    for (i=0; i<num_attributes && !is_artificial; ++i)
1561                    {
1562                        const dw_attr_t attr = attributes.AttributeAtIndex(i);
1563                        DWARFFormValue form_value;
1564                        if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1565                        {
1566                            switch (attr)
1567                            {
1568                            case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
1569                            case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
1570                            case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
1571                            case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
1572                            case DW_AT_type:        encoding_uid = form_value.Reference(dwarf_cu); break;
1573                            case DW_AT_bit_offset:  bit_offset = form_value.Unsigned(); break;
1574                            case DW_AT_bit_size:    bit_size = form_value.Unsigned(); break;
1575                            case DW_AT_byte_size:   byte_size = form_value.Unsigned(); break;
1576                            case DW_AT_data_member_location:
1577                                if (form_value.BlockData())
1578                                {
1579                                    Value initialValue(0);
1580                                    Value memberOffset(0);
1581                                    const DataExtractor& debug_info_data = get_debug_info_data();
1582                                    uint32_t block_length = form_value.Unsigned();
1583                                    uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
1584                                    if (DWARFExpression::Evaluate(NULL, // ExecutionContext *
1585                                                                  NULL, // clang::ASTContext *
1586                                                                  NULL, // ClangExpressionVariableList *
1587                                                                  NULL, // ClangExpressionDeclMap *
1588                                                                  NULL, // RegisterContext *
1589                                                                  debug_info_data,
1590                                                                  block_offset,
1591                                                                  block_length,
1592                                                                  eRegisterKindDWARF,
1593                                                                  &initialValue,
1594                                                                  memberOffset,
1595                                                                  NULL))
1596                                    {
1597                                        member_byte_offset = memberOffset.ResolveValue(NULL, NULL).UInt();
1598                                    }
1599                                }
1600                                break;
1601
1602                            case DW_AT_accessibility: accessibility = DW_ACCESS_to_AccessType (form_value.Unsigned()); break;
1603                            case DW_AT_artificial: is_artificial = form_value.Boolean(); break;
1604                            case DW_AT_APPLE_property_name:      prop_name = form_value.AsCString(&get_debug_str_data()); break;
1605                            case DW_AT_APPLE_property_getter:    prop_getter_name = form_value.AsCString(&get_debug_str_data()); break;
1606                            case DW_AT_APPLE_property_setter:    prop_setter_name = form_value.AsCString(&get_debug_str_data()); break;
1607                            case DW_AT_APPLE_property_attribute: prop_attributes = form_value.Unsigned(); break;
1608                            case DW_AT_external:                 is_external = form_value.Boolean(); break;
1609
1610                            default:
1611                            case DW_AT_declaration:
1612                            case DW_AT_description:
1613                            case DW_AT_mutable:
1614                            case DW_AT_visibility:
1615                            case DW_AT_sibling:
1616                                break;
1617                            }
1618                        }
1619                    }
1620
1621                    if (prop_name)
1622                    {
1623                        ConstString fixed_getter;
1624                        ConstString fixed_setter;
1625
1626                        // Check if the property getter/setter were provided as full
1627                        // names.  We want basenames, so we extract them.
1628
1629                        if (prop_getter_name && prop_getter_name[0] == '-')
1630                        {
1631                            ObjCLanguageRuntime::MethodName prop_getter_method(prop_getter_name, true);
1632                            prop_getter_name = prop_getter_method.GetSelector().GetCString();
1633                        }
1634
1635                        if (prop_setter_name && prop_setter_name[0] == '-')
1636                        {
1637                            ObjCLanguageRuntime::MethodName prop_setter_method(prop_setter_name, true);
1638                            prop_setter_name = prop_setter_method.GetSelector().GetCString();
1639                        }
1640
1641                        // If the names haven't been provided, they need to be
1642                        // filled in.
1643
1644                        if (!prop_getter_name)
1645                        {
1646                            prop_getter_name = prop_name;
1647                        }
1648                        if (!prop_setter_name && prop_name[0] && !(prop_attributes & DW_APPLE_PROPERTY_readonly))
1649                        {
1650                            StreamString ss;
1651
1652                            ss.Printf("set%c%s:",
1653                                      toupper(prop_name[0]),
1654                                      &prop_name[1]);
1655
1656                            fixed_setter.SetCString(ss.GetData());
1657                            prop_setter_name = fixed_setter.GetCString();
1658                        }
1659                    }
1660
1661                    // Clang has a DWARF generation bug where sometimes it
1662                    // represents fields that are references with bad byte size
1663                    // and bit size/offset information such as:
1664                    //
1665                    //  DW_AT_byte_size( 0x00 )
1666                    //  DW_AT_bit_size( 0x40 )
1667                    //  DW_AT_bit_offset( 0xffffffffffffffc0 )
1668                    //
1669                    // So check the bit offset to make sure it is sane, and if
1670                    // the values are not sane, remove them. If we don't do this
1671                    // then we will end up with a crash if we try to use this
1672                    // type in an expression when clang becomes unhappy with its
1673                    // recycled debug info.
1674
1675                    if (bit_offset > 128)
1676                    {
1677                        bit_size = 0;
1678                        bit_offset = 0;
1679                    }
1680
1681                    // FIXME: Make Clang ignore Objective-C accessibility for expressions
1682                    if (class_language == eLanguageTypeObjC ||
1683                        class_language == eLanguageTypeObjC_plus_plus)
1684                        accessibility = eAccessNone;
1685
1686                    if (member_idx == 0 && !is_artificial && name && (strstr (name, "_vptr$") == name))
1687                    {
1688                        // Not all compilers will mark the vtable pointer
1689                        // member as artificial (llvm-gcc). We can't have
1690                        // the virtual members in our classes otherwise it
1691                        // throws off all child offsets since we end up
1692                        // having and extra pointer sized member in our
1693                        // class layouts.
1694                        is_artificial = true;
1695                    }
1696
1697                    // Skip static members
1698                    if (is_external && member_byte_offset == UINT32_MAX)
1699                    {
1700                        Type *var_type = ResolveTypeUID(encoding_uid);
1701
1702                        if (var_type)
1703                        {
1704                            GetClangASTContext().AddVariableToRecordType (class_clang_type,
1705                                                                          name,
1706                                                                          var_type->GetClangLayoutType(),
1707                                                                          accessibility);
1708                        }
1709                        break;
1710                    }
1711
1712                    if (is_artificial == false)
1713                    {
1714                        Type *member_type = ResolveTypeUID(encoding_uid);
1715
1716                        clang::FieldDecl *field_decl = NULL;
1717                        if (tag == DW_TAG_member)
1718                        {
1719                            if (member_type)
1720                            {
1721                                if (accessibility == eAccessNone)
1722                                    accessibility = default_accessibility;
1723                                member_accessibilities.push_back(accessibility);
1724
1725                                BitfieldInfo this_field_info;
1726
1727                                this_field_info.bit_size = bit_size;
1728
1729                                if (member_byte_offset != UINT32_MAX || bit_size != 0)
1730                                {
1731                                    /////////////////////////////////////////////////////////////
1732                                    // How to locate a field given the DWARF debug information
1733                                    //
1734                                    // AT_byte_size indicates the size of the word in which the
1735                                    // bit offset must be interpreted.
1736                                    //
1737                                    // AT_data_member_location indicates the byte offset of the
1738                                    // word from the base address of the structure.
1739                                    //
1740                                    // AT_bit_offset indicates how many bits into the word
1741                                    // (according to the host endianness) the low-order bit of
1742                                    // the field starts.  AT_bit_offset can be negative.
1743                                    //
1744                                    // AT_bit_size indicates the size of the field in bits.
1745                                    /////////////////////////////////////////////////////////////
1746
1747                                    this_field_info.bit_offset = 0;
1748
1749                                    this_field_info.bit_offset += (member_byte_offset == UINT32_MAX ? 0 : (member_byte_offset * 8));
1750
1751                                    if (GetObjectFile()->GetByteOrder() == eByteOrderLittle)
1752                                    {
1753                                        this_field_info.bit_offset += byte_size * 8;
1754                                        this_field_info.bit_offset -= (bit_offset + bit_size);
1755                                    }
1756                                    else
1757                                    {
1758                                        this_field_info.bit_offset += bit_offset;
1759                                    }
1760                                }
1761
1762                                // If the member to be emitted did not start on a character boundary and there is
1763                                // empty space between the last field and this one, then we need to emit an
1764                                // anonymous member filling up the space up to its start.  There are three cases
1765                                // here:
1766                                //
1767                                // 1 If the previous member ended on a character boundary, then we can emit an
1768                                //   anonymous member starting at the most recent character boundary.
1769                                //
1770                                // 2 If the previous member did not end on a character boundary and the distance
1771                                //   from the end of the previous member to the current member is less than a
1772                                //   word width, then we can emit an anonymous member starting right after the
1773                                //   previous member and right before this member.
1774                                //
1775                                // 3 If the previous member did not end on a character boundary and the distance
1776                                //   from the end of the previous member to the current member is greater than
1777                                //   or equal a word width, then we act as in Case 1.
1778
1779                                const uint64_t character_width = 8;
1780                                const uint64_t word_width = 32;
1781
1782                                if (this_field_info.IsValid())
1783                                {
1784                                    // Objective-C has invalid DW_AT_bit_offset values in older versions
1785                                    // of clang, so we have to be careful and only insert unnammed bitfields
1786                                    // if we have a new enough clang.
1787                                    bool detect_unnamed_bitfields = true;
1788
1789                                    if (class_language == eLanguageTypeObjC || class_language == eLanguageTypeObjC_plus_plus)
1790                                        detect_unnamed_bitfields = dwarf_cu->Supports_unnamed_objc_bitfields ();
1791
1792                                    if (detect_unnamed_bitfields)
1793                                    {
1794                                        BitfieldInfo anon_field_info;
1795
1796                                        if ((this_field_info.bit_offset % character_width) != 0) // not char aligned
1797                                        {
1798                                            uint64_t last_field_end = 0;
1799
1800                                            if (last_field_info.IsValid())
1801                                                last_field_end = last_field_info.bit_offset + last_field_info.bit_size;
1802
1803                                            if (this_field_info.bit_offset != last_field_end)
1804                                            {
1805                                                if (((last_field_end % character_width) == 0) ||                    // case 1
1806                                                    (this_field_info.bit_offset - last_field_end >= word_width))    // case 3
1807                                                {
1808                                                    anon_field_info.bit_size = this_field_info.bit_offset % character_width;
1809                                                    anon_field_info.bit_offset = this_field_info.bit_offset - anon_field_info.bit_size;
1810                                                }
1811                                                else                                                                // case 2
1812                                                {
1813                                                    anon_field_info.bit_size = this_field_info.bit_offset - last_field_end;
1814                                                    anon_field_info.bit_offset = last_field_end;
1815                                                }
1816                                            }
1817                                        }
1818
1819                                        if (anon_field_info.IsValid())
1820                                        {
1821                                            clang::FieldDecl *unnamed_bitfield_decl = GetClangASTContext().AddFieldToRecordType (class_clang_type,
1822                                                                                                                                 NULL,
1823                                                                                                                                 GetClangASTContext().GetBuiltinTypeForEncodingAndBitSize(eEncodingSint, word_width),
1824                                                                                                                                 accessibility,
1825                                                                                                                                 anon_field_info.bit_size);
1826
1827                                            layout_info.field_offsets.insert(std::make_pair(unnamed_bitfield_decl, anon_field_info.bit_offset));
1828                                        }
1829                                    }
1830                                }
1831
1832                                clang_type_t member_clang_type = member_type->GetClangLayoutType();
1833
1834                                {
1835                                    // Older versions of clang emit array[0] and array[1] in the same way (<rdar://problem/12566646>).
1836                                    // If the current field is at the end of the structure, then there is definitely no room for extra
1837                                    // elements and we override the type to array[0].
1838
1839                                    clang_type_t member_array_element_type;
1840                                    uint64_t member_array_size;
1841                                    bool member_array_is_incomplete;
1842
1843                                    if (GetClangASTContext().IsArrayType(member_clang_type,
1844                                                                         &member_array_element_type,
1845                                                                         &member_array_size,
1846                                                                         &member_array_is_incomplete) &&
1847                                        !member_array_is_incomplete)
1848                                    {
1849                                        uint64_t parent_byte_size = parent_die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_byte_size, UINT64_MAX);
1850
1851                                        if (member_byte_offset >= parent_byte_size)
1852                                        {
1853                                            if (member_array_size != 1)
1854                                            {
1855                                                GetObjectFile()->GetModule()->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,
1856                                                                                           MakeUserID(die->GetOffset()),
1857                                                                                           name,
1858                                                                                           encoding_uid,
1859                                                                                           MakeUserID(parent_die->GetOffset()));
1860                                            }
1861
1862                                            member_clang_type = GetClangASTContext().CreateArrayType(member_array_element_type, 0, false);
1863                                        }
1864                                    }
1865                                }
1866
1867                                field_decl = GetClangASTContext().AddFieldToRecordType (class_clang_type,
1868                                                                                        name,
1869                                                                                        member_clang_type,
1870                                                                                        accessibility,
1871                                                                                        bit_size);
1872
1873                                GetClangASTContext().SetMetadataAsUserID (field_decl, MakeUserID(die->GetOffset()));
1874
1875                                if (this_field_info.IsValid())
1876                                {
1877                                    layout_info.field_offsets.insert(std::make_pair(field_decl, this_field_info.bit_offset));
1878                                    last_field_info = this_field_info;
1879                                }
1880                            }
1881                            else
1882                            {
1883                                if (name)
1884                                    GetObjectFile()->GetModule()->ReportError ("0x%8.8" PRIx64 ": DW_TAG_member '%s' refers to type 0x%8.8" PRIx64 " which was unable to be parsed",
1885                                                                               MakeUserID(die->GetOffset()),
1886                                                                               name,
1887                                                                               encoding_uid);
1888                                else
1889                                    GetObjectFile()->GetModule()->ReportError ("0x%8.8" PRIx64 ": DW_TAG_member refers to type 0x%8.8" PRIx64 " which was unable to be parsed",
1890                                                                               MakeUserID(die->GetOffset()),
1891                                                                               encoding_uid);
1892                            }
1893                        }
1894
1895                        if (prop_name != NULL)
1896                        {
1897                            clang::ObjCIvarDecl *ivar_decl = NULL;
1898
1899                            if (field_decl)
1900                            {
1901                                ivar_decl = clang::dyn_cast<clang::ObjCIvarDecl>(field_decl);
1902                                assert (ivar_decl != NULL);
1903                            }
1904
1905                            ClangASTMetadata metadata;
1906                            metadata.SetUserID (MakeUserID(die->GetOffset()));
1907                            delayed_properties.push_back(DelayedAddObjCClassProperty(GetClangASTContext().getASTContext(),
1908                                                                                     class_clang_type,
1909                                                                                     prop_name,
1910                                                                                     member_type->GetClangLayoutType(),
1911                                                                                     ivar_decl,
1912                                                                                     prop_setter_name,
1913                                                                                     prop_getter_name,
1914                                                                                     prop_attributes,
1915                                                                                     &metadata));
1916
1917                            if (ivar_decl)
1918                                GetClangASTContext().SetMetadataAsUserID (ivar_decl, MakeUserID(die->GetOffset()));
1919                        }
1920                    }
1921                }
1922                ++member_idx;
1923            }
1924            break;
1925
1926        case DW_TAG_subprogram:
1927            // Let the type parsing code handle this one for us.
1928            member_function_dies.Append (die);
1929            break;
1930
1931        case DW_TAG_inheritance:
1932            {
1933                is_a_class = true;
1934                if (default_accessibility == eAccessNone)
1935                    default_accessibility = eAccessPrivate;
1936                // TODO: implement DW_TAG_inheritance type parsing
1937                DWARFDebugInfoEntry::Attributes attributes;
1938                const size_t num_attributes = die->GetAttributes (this,
1939                                                                  dwarf_cu,
1940                                                                  fixed_form_sizes,
1941                                                                  attributes);
1942                if (num_attributes > 0)
1943                {
1944                    Declaration decl;
1945                    DWARFExpression location;
1946                    lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
1947                    AccessType accessibility = default_accessibility;
1948                    bool is_virtual = false;
1949                    bool is_base_of_class = true;
1950                    off_t member_byte_offset = 0;
1951                    uint32_t i;
1952                    for (i=0; i<num_attributes; ++i)
1953                    {
1954                        const dw_attr_t attr = attributes.AttributeAtIndex(i);
1955                        DWARFFormValue form_value;
1956                        if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1957                        {
1958                            switch (attr)
1959                            {
1960                            case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
1961                            case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
1962                            case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
1963                            case DW_AT_type:        encoding_uid = form_value.Reference(dwarf_cu); break;
1964                            case DW_AT_data_member_location:
1965                                if (form_value.BlockData())
1966                                {
1967                                    Value initialValue(0);
1968                                    Value memberOffset(0);
1969                                    const DataExtractor& debug_info_data = get_debug_info_data();
1970                                    uint32_t block_length = form_value.Unsigned();
1971                                    uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
1972                                    if (DWARFExpression::Evaluate (NULL,
1973                                                                   NULL,
1974                                                                   NULL,
1975                                                                   NULL,
1976                                                                   NULL,
1977                                                                   debug_info_data,
1978                                                                   block_offset,
1979                                                                   block_length,
1980                                                                   eRegisterKindDWARF,
1981                                                                   &initialValue,
1982                                                                   memberOffset,
1983                                                                   NULL))
1984                                    {
1985                                        member_byte_offset = memberOffset.ResolveValue(NULL, NULL).UInt();
1986                                    }
1987                                }
1988                                break;
1989
1990                            case DW_AT_accessibility:
1991                                accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
1992                                break;
1993
1994                            case DW_AT_virtuality: is_virtual = form_value.Boolean(); break;
1995                            default:
1996                            case DW_AT_sibling:
1997                                break;
1998                            }
1999                        }
2000                    }
2001
2002                    Type *base_class_type = ResolveTypeUID(encoding_uid);
2003                    assert(base_class_type);
2004
2005                    clang_type_t base_class_clang_type = base_class_type->GetClangFullType();
2006                    assert (base_class_clang_type);
2007                    if (class_language == eLanguageTypeObjC)
2008                    {
2009                        GetClangASTContext().SetObjCSuperClass(class_clang_type, base_class_clang_type);
2010                    }
2011                    else
2012                    {
2013                        base_classes.push_back (GetClangASTContext().CreateBaseClassSpecifier (base_class_clang_type,
2014                                                                                               accessibility,
2015                                                                                               is_virtual,
2016                                                                                               is_base_of_class));
2017
2018                        if (is_virtual)
2019                        {
2020                            layout_info.vbase_offsets.insert(std::make_pair(ClangASTType::GetAsCXXRecordDecl(class_clang_type),
2021                                                                            clang::CharUnits::fromQuantity(member_byte_offset)));
2022                        }
2023                        else
2024                        {
2025                            layout_info.base_offsets.insert(std::make_pair(ClangASTType::GetAsCXXRecordDecl(class_clang_type),
2026                                                                           clang::CharUnits::fromQuantity(member_byte_offset)));
2027                        }
2028                    }
2029                }
2030            }
2031            break;
2032
2033        default:
2034            break;
2035        }
2036    }
2037
2038    return count;
2039}
2040
2041
2042clang::DeclContext*
2043SymbolFileDWARF::GetClangDeclContextContainingTypeUID (lldb::user_id_t type_uid)
2044{
2045    DWARFDebugInfo* debug_info = DebugInfo();
2046    if (debug_info && UserIDMatches(type_uid))
2047    {
2048        DWARFCompileUnitSP cu_sp;
2049        const DWARFDebugInfoEntry* die = debug_info->GetDIEPtr(type_uid, &cu_sp);
2050        if (die)
2051            return GetClangDeclContextContainingDIE (cu_sp.get(), die, NULL);
2052    }
2053    return NULL;
2054}
2055
2056clang::DeclContext*
2057SymbolFileDWARF::GetClangDeclContextForTypeUID (const lldb_private::SymbolContext &sc, lldb::user_id_t type_uid)
2058{
2059    if (UserIDMatches(type_uid))
2060        return GetClangDeclContextForDIEOffset (sc, type_uid);
2061    return NULL;
2062}
2063
2064Type*
2065SymbolFileDWARF::ResolveTypeUID (lldb::user_id_t type_uid)
2066{
2067    if (UserIDMatches(type_uid))
2068    {
2069        DWARFDebugInfo* debug_info = DebugInfo();
2070        if (debug_info)
2071        {
2072            DWARFCompileUnitSP cu_sp;
2073            const DWARFDebugInfoEntry* type_die = debug_info->GetDIEPtr(type_uid, &cu_sp);
2074            const bool assert_not_being_parsed = true;
2075            return ResolveTypeUID (cu_sp.get(), type_die, assert_not_being_parsed);
2076        }
2077    }
2078    return NULL;
2079}
2080
2081Type*
2082SymbolFileDWARF::ResolveTypeUID (DWARFCompileUnit* cu, const DWARFDebugInfoEntry* die, bool assert_not_being_parsed)
2083{
2084    if (die != NULL)
2085    {
2086        Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
2087        if (log)
2088            GetObjectFile()->GetModule()->LogMessage (log,
2089                                                      "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
2090                                                      die->GetOffset(),
2091                                                      DW_TAG_value_to_name(die->Tag()),
2092                                                      die->GetName(this, cu));
2093
2094        // We might be coming in in the middle of a type tree (a class
2095        // withing a class, an enum within a class), so parse any needed
2096        // parent DIEs before we get to this one...
2097        const DWARFDebugInfoEntry *decl_ctx_die = GetDeclContextDIEContainingDIE (cu, die);
2098        switch (decl_ctx_die->Tag())
2099        {
2100            case DW_TAG_structure_type:
2101            case DW_TAG_union_type:
2102            case DW_TAG_class_type:
2103            {
2104                // Get the type, which could be a forward declaration
2105                if (log)
2106                    GetObjectFile()->GetModule()->LogMessage (log,
2107                                                              "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' resolve parent forward type for 0x%8.8x",
2108                                                              die->GetOffset(),
2109                                                              DW_TAG_value_to_name(die->Tag()),
2110                                                              die->GetName(this, cu),
2111                                                              decl_ctx_die->GetOffset());
2112//
2113//                Type *parent_type = ResolveTypeUID (cu, decl_ctx_die, assert_not_being_parsed);
2114//                if (child_requires_parent_class_union_or_struct_to_be_completed(die->Tag()))
2115//                {
2116//                    if (log)
2117//                        GetObjectFile()->GetModule()->LogMessage (log,
2118//                                                                  "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' resolve parent full type for 0x%8.8x since die is a function",
2119//                                                                  die->GetOffset(),
2120//                                                                  DW_TAG_value_to_name(die->Tag()),
2121//                                                                  die->GetName(this, cu),
2122//                                                                  decl_ctx_die->GetOffset());
2123//                    // Ask the type to complete itself if it already hasn't since if we
2124//                    // want a function (method or static) from a class, the class must
2125//                    // create itself and add it's own methods and class functions.
2126//                    if (parent_type)
2127//                        parent_type->GetClangFullType();
2128//                }
2129            }
2130            break;
2131
2132            default:
2133                break;
2134        }
2135        return ResolveType (cu, die);
2136    }
2137    return NULL;
2138}
2139
2140// This function is used when SymbolFileDWARFDebugMap owns a bunch of
2141// SymbolFileDWARF objects to detect if this DWARF file is the one that
2142// can resolve a clang_type.
2143bool
2144SymbolFileDWARF::HasForwardDeclForClangType (lldb::clang_type_t clang_type)
2145{
2146    clang_type_t clang_type_no_qualifiers = ClangASTType::RemoveFastQualifiers(clang_type);
2147    const DWARFDebugInfoEntry* die = m_forward_decl_clang_type_to_die.lookup (clang_type_no_qualifiers);
2148    return die != NULL;
2149}
2150
2151
2152lldb::clang_type_t
2153SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (lldb::clang_type_t clang_type)
2154{
2155    // We have a struct/union/class/enum that needs to be fully resolved.
2156    clang_type_t clang_type_no_qualifiers = ClangASTType::RemoveFastQualifiers(clang_type);
2157    const DWARFDebugInfoEntry* die = m_forward_decl_clang_type_to_die.lookup (clang_type_no_qualifiers);
2158    if (die == NULL)
2159    {
2160        // We have already resolved this type...
2161        return clang_type;
2162    }
2163    // Once we start resolving this type, remove it from the forward declaration
2164    // map in case anyone child members or other types require this type to get resolved.
2165    // The type will get resolved when all of the calls to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition
2166    // are done.
2167    m_forward_decl_clang_type_to_die.erase (clang_type_no_qualifiers);
2168
2169
2170    // Disable external storage for this type so we don't get anymore
2171    // clang::ExternalASTSource queries for this type.
2172    ClangASTContext::SetHasExternalStorage (clang_type, false);
2173
2174    DWARFDebugInfo* debug_info = DebugInfo();
2175
2176    DWARFCompileUnit *dwarf_cu = debug_info->GetCompileUnitContainingDIE (die->GetOffset()).get();
2177    Type *type = m_die_to_type.lookup (die);
2178
2179    const dw_tag_t tag = die->Tag();
2180
2181    Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO|DWARF_LOG_TYPE_COMPLETION));
2182    if (log)
2183    {
2184        GetObjectFile()->GetModule()->LogMessageVerboseBacktrace (log,
2185                                                                  "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
2186                                                                  MakeUserID(die->GetOffset()),
2187                                                                  DW_TAG_value_to_name(tag),
2188                                                                  type->GetName().AsCString());
2189
2190    }
2191    assert (clang_type);
2192    DWARFDebugInfoEntry::Attributes attributes;
2193
2194    ClangASTContext &ast = GetClangASTContext();
2195
2196    switch (tag)
2197    {
2198    case DW_TAG_structure_type:
2199    case DW_TAG_union_type:
2200    case DW_TAG_class_type:
2201        {
2202            LayoutInfo layout_info;
2203
2204            {
2205                if (die->HasChildren())
2206                {
2207
2208                    LanguageType class_language = eLanguageTypeUnknown;
2209                    bool is_objc_class = ClangASTContext::IsObjCClassType (clang_type);
2210                    if (is_objc_class)
2211                    {
2212                        class_language = eLanguageTypeObjC;
2213                        // For objective C we don't start the definition when
2214                        // the class is created.
2215                        ast.StartTagDeclarationDefinition (clang_type);
2216                    }
2217
2218                    int tag_decl_kind = -1;
2219                    AccessType default_accessibility = eAccessNone;
2220                    if (tag == DW_TAG_structure_type)
2221                    {
2222                        tag_decl_kind = clang::TTK_Struct;
2223                        default_accessibility = eAccessPublic;
2224                    }
2225                    else if (tag == DW_TAG_union_type)
2226                    {
2227                        tag_decl_kind = clang::TTK_Union;
2228                        default_accessibility = eAccessPublic;
2229                    }
2230                    else if (tag == DW_TAG_class_type)
2231                    {
2232                        tag_decl_kind = clang::TTK_Class;
2233                        default_accessibility = eAccessPrivate;
2234                    }
2235
2236                    SymbolContext sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
2237                    std::vector<clang::CXXBaseSpecifier *> base_classes;
2238                    std::vector<int> member_accessibilities;
2239                    bool is_a_class = false;
2240                    // Parse members and base classes first
2241                    DWARFDIECollection member_function_dies;
2242
2243                    DelayedPropertyList delayed_properties;
2244                    ParseChildMembers (sc,
2245                                       dwarf_cu,
2246                                       die,
2247                                       clang_type,
2248                                       class_language,
2249                                       base_classes,
2250                                       member_accessibilities,
2251                                       member_function_dies,
2252                                       delayed_properties,
2253                                       default_accessibility,
2254                                       is_a_class,
2255                                       layout_info);
2256
2257                    // Now parse any methods if there were any...
2258                    size_t num_functions = member_function_dies.Size();
2259                    if (num_functions > 0)
2260                    {
2261                        for (size_t i=0; i<num_functions; ++i)
2262                        {
2263                            ResolveType(dwarf_cu, member_function_dies.GetDIEPtrAtIndex(i));
2264                        }
2265                    }
2266
2267                    if (class_language == eLanguageTypeObjC)
2268                    {
2269                        std::string class_str (ClangASTType::GetTypeNameForOpaqueQualType(ast.getASTContext(), clang_type));
2270                        if (!class_str.empty())
2271                        {
2272
2273                            DIEArray method_die_offsets;
2274                            if (m_using_apple_tables)
2275                            {
2276                                if (m_apple_objc_ap.get())
2277                                    m_apple_objc_ap->FindByName(class_str.c_str(), method_die_offsets);
2278                            }
2279                            else
2280                            {
2281                                if (!m_indexed)
2282                                    Index ();
2283
2284                                ConstString class_name (class_str.c_str());
2285                                m_objc_class_selectors_index.Find (class_name, method_die_offsets);
2286                            }
2287
2288                            if (!method_die_offsets.empty())
2289                            {
2290                                DWARFDebugInfo* debug_info = DebugInfo();
2291
2292                                DWARFCompileUnit* method_cu = NULL;
2293                                const size_t num_matches = method_die_offsets.size();
2294                                for (size_t i=0; i<num_matches; ++i)
2295                                {
2296                                    const dw_offset_t die_offset = method_die_offsets[i];
2297                                    DWARFDebugInfoEntry *method_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &method_cu);
2298
2299                                    if (method_die)
2300                                        ResolveType (method_cu, method_die);
2301                                    else
2302                                    {
2303                                        if (m_using_apple_tables)
2304                                        {
2305                                            GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_objc accelerator table had bad die 0x%8.8x for '%s')\n",
2306                                                                                                       die_offset, class_str.c_str());
2307                                        }
2308                                    }
2309                                }
2310                            }
2311
2312                            for (DelayedPropertyList::const_iterator pi = delayed_properties.begin(), pe = delayed_properties.end();
2313                                 pi != pe;
2314                                 ++pi)
2315                                pi->Finalize();
2316                        }
2317                    }
2318
2319                    // If we have a DW_TAG_structure_type instead of a DW_TAG_class_type we
2320                    // need to tell the clang type it is actually a class.
2321                    if (class_language != eLanguageTypeObjC)
2322                    {
2323                        if (is_a_class && tag_decl_kind != clang::TTK_Class)
2324                            ast.SetTagTypeKind (clang_type, clang::TTK_Class);
2325                    }
2326
2327                    // Since DW_TAG_structure_type gets used for both classes
2328                    // and structures, we may need to set any DW_TAG_member
2329                    // fields to have a "private" access if none was specified.
2330                    // When we parsed the child members we tracked that actual
2331                    // accessibility value for each DW_TAG_member in the
2332                    // "member_accessibilities" array. If the value for the
2333                    // member is zero, then it was set to the "default_accessibility"
2334                    // which for structs was "public". Below we correct this
2335                    // by setting any fields to "private" that weren't correctly
2336                    // set.
2337                    if (is_a_class && !member_accessibilities.empty())
2338                    {
2339                        // This is a class and all members that didn't have
2340                        // their access specified are private.
2341                        ast.SetDefaultAccessForRecordFields (clang_type,
2342                                                             eAccessPrivate,
2343                                                             &member_accessibilities.front(),
2344                                                             member_accessibilities.size());
2345                    }
2346
2347                    if (!base_classes.empty())
2348                    {
2349                        ast.SetBaseClassesForClassType (clang_type,
2350                                                        &base_classes.front(),
2351                                                        base_classes.size());
2352
2353                        // Clang will copy each CXXBaseSpecifier in "base_classes"
2354                        // so we have to free them all.
2355                        ClangASTContext::DeleteBaseClassSpecifiers (&base_classes.front(),
2356                                                                    base_classes.size());
2357                    }
2358                }
2359            }
2360
2361            ast.BuildIndirectFields (clang_type);
2362
2363            ast.CompleteTagDeclarationDefinition (clang_type);
2364
2365            if (!layout_info.field_offsets.empty() ||
2366                !layout_info.base_offsets.empty()  ||
2367                !layout_info.vbase_offsets.empty() )
2368            {
2369                if (type)
2370                    layout_info.bit_size = type->GetByteSize() * 8;
2371                if (layout_info.bit_size == 0)
2372                    layout_info.bit_size = die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_byte_size, 0) * 8;
2373
2374                clang::CXXRecordDecl *record_decl = ClangASTType::GetAsCXXRecordDecl(clang_type);
2375                if (record_decl)
2376                {
2377                    if (log)
2378                    {
2379                        GetObjectFile()->GetModule()->LogMessage (log,
2380                                                                  "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) caching layout info for record_decl = %p, bit_size = %" PRIu64 ", alignment = %" PRIu64 ", field_offsets[%u], base_offsets[%u], vbase_offsets[%u])",
2381                                                                  clang_type,
2382                                                                  record_decl,
2383                                                                  layout_info.bit_size,
2384                                                                  layout_info.alignment,
2385                                                                  (uint32_t)layout_info.field_offsets.size(),
2386                                                                  (uint32_t)layout_info.base_offsets.size(),
2387                                                                  (uint32_t)layout_info.vbase_offsets.size());
2388
2389                        uint32_t idx;
2390                        {
2391                        llvm::DenseMap <const clang::FieldDecl *, uint64_t>::const_iterator pos, end = layout_info.field_offsets.end();
2392                        for (idx = 0, pos = layout_info.field_offsets.begin(); pos != end; ++pos, ++idx)
2393                        {
2394                            GetObjectFile()->GetModule()->LogMessage (log,
2395                                                                      "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) field[%u] = { bit_offset=%u, name='%s' }",
2396                                                                      clang_type,
2397                                                                      idx,
2398                                                                      (uint32_t)pos->second,
2399                                                                      pos->first->getNameAsString().c_str());
2400                        }
2401                        }
2402
2403                        {
2404                        llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits>::const_iterator base_pos, base_end = layout_info.base_offsets.end();
2405                        for (idx = 0, base_pos = layout_info.base_offsets.begin(); base_pos != base_end; ++base_pos, ++idx)
2406                        {
2407                            GetObjectFile()->GetModule()->LogMessage (log,
2408                                                                      "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) base[%u] = { byte_offset=%u, name='%s' }",
2409                                                                      clang_type,
2410                                                                      idx,
2411                                                                      (uint32_t)base_pos->second.getQuantity(),
2412                                                                      base_pos->first->getNameAsString().c_str());
2413                        }
2414                        }
2415                        {
2416                        llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits>::const_iterator vbase_pos, vbase_end = layout_info.vbase_offsets.end();
2417                        for (idx = 0, vbase_pos = layout_info.vbase_offsets.begin(); vbase_pos != vbase_end; ++vbase_pos, ++idx)
2418                        {
2419                            GetObjectFile()->GetModule()->LogMessage (log,
2420                                                                      "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) vbase[%u] = { byte_offset=%u, name='%s' }",
2421                                                                      clang_type,
2422                                                                      idx,
2423                                                                      (uint32_t)vbase_pos->second.getQuantity(),
2424                                                                      vbase_pos->first->getNameAsString().c_str());
2425                        }
2426                        }
2427                    }
2428                    m_record_decl_to_layout_map.insert(std::make_pair(record_decl, layout_info));
2429                }
2430            }
2431        }
2432
2433        return clang_type;
2434
2435    case DW_TAG_enumeration_type:
2436        ast.StartTagDeclarationDefinition (clang_type);
2437        if (die->HasChildren())
2438        {
2439            SymbolContext sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
2440            bool is_signed = false;
2441            ast.IsIntegerType(clang_type, is_signed);
2442            ParseChildEnumerators(sc, clang_type, is_signed, type->GetByteSize(), dwarf_cu, die);
2443        }
2444        ast.CompleteTagDeclarationDefinition (clang_type);
2445        return clang_type;
2446
2447    default:
2448        assert(false && "not a forward clang type decl!");
2449        break;
2450    }
2451    return NULL;
2452}
2453
2454Type*
2455SymbolFileDWARF::ResolveType (DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry* type_die, bool assert_not_being_parsed)
2456{
2457    if (type_die != NULL)
2458    {
2459        Type *type = m_die_to_type.lookup (type_die);
2460
2461        if (type == NULL)
2462            type = GetTypeForDIE (dwarf_cu, type_die).get();
2463
2464        if (assert_not_being_parsed)
2465        {
2466            if (type != DIE_IS_BEING_PARSED)
2467                return type;
2468
2469            GetObjectFile()->GetModule()->ReportError ("Parsing a die that is being parsed die: 0x%8.8x: %s %s",
2470                                                       type_die->GetOffset(),
2471                                                       DW_TAG_value_to_name(type_die->Tag()),
2472                                                       type_die->GetName(this, dwarf_cu));
2473
2474        }
2475        else
2476            return type;
2477    }
2478    return NULL;
2479}
2480
2481CompileUnit*
2482SymbolFileDWARF::GetCompUnitForDWARFCompUnit (DWARFCompileUnit* dwarf_cu, uint32_t cu_idx)
2483{
2484    // Check if the symbol vendor already knows about this compile unit?
2485    if (dwarf_cu->GetUserData() == NULL)
2486    {
2487        // The symbol vendor doesn't know about this compile unit, we
2488        // need to parse and add it to the symbol vendor object.
2489        return ParseCompileUnit(dwarf_cu, cu_idx).get();
2490    }
2491    return (CompileUnit*)dwarf_cu->GetUserData();
2492}
2493
2494bool
2495SymbolFileDWARF::GetFunction (DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry* func_die, SymbolContext& sc)
2496{
2497    sc.Clear(false);
2498    // Check if the symbol vendor already knows about this compile unit?
2499    sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
2500
2501    sc.function = sc.comp_unit->FindFunctionByUID (MakeUserID(func_die->GetOffset())).get();
2502    if (sc.function == NULL)
2503        sc.function = ParseCompileUnitFunction(sc, dwarf_cu, func_die);
2504
2505    if (sc.function)
2506    {
2507        sc.module_sp = sc.function->CalculateSymbolContextModule();
2508        return true;
2509    }
2510
2511    return false;
2512}
2513
2514uint32_t
2515SymbolFileDWARF::ResolveSymbolContext (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc)
2516{
2517    Timer scoped_timer(__PRETTY_FUNCTION__,
2518                       "SymbolFileDWARF::ResolveSymbolContext (so_addr = { section = %p, offset = 0x%" PRIx64 " }, resolve_scope = 0x%8.8x)",
2519                       so_addr.GetSection().get(),
2520                       so_addr.GetOffset(),
2521                       resolve_scope);
2522    uint32_t resolved = 0;
2523    if (resolve_scope & (   eSymbolContextCompUnit |
2524                            eSymbolContextFunction |
2525                            eSymbolContextBlock |
2526                            eSymbolContextLineEntry))
2527    {
2528        lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
2529
2530        DWARFDebugInfo* debug_info = DebugInfo();
2531        if (debug_info)
2532        {
2533            const dw_offset_t cu_offset = debug_info->GetCompileUnitAranges().FindAddress(file_vm_addr);
2534            if (cu_offset != DW_INVALID_OFFSET)
2535            {
2536                uint32_t cu_idx = DW_INVALID_INDEX;
2537                DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnit(cu_offset, &cu_idx).get();
2538                if (dwarf_cu)
2539                {
2540                    sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2541                    if (sc.comp_unit)
2542                    {
2543                        resolved |= eSymbolContextCompUnit;
2544
2545                        bool force_check_line_table = false;
2546                        if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock))
2547                        {
2548                            DWARFDebugInfoEntry *function_die = NULL;
2549                            DWARFDebugInfoEntry *block_die = NULL;
2550                            if (resolve_scope & eSymbolContextBlock)
2551                            {
2552                                dwarf_cu->LookupAddress(file_vm_addr, &function_die, &block_die);
2553                            }
2554                            else
2555                            {
2556                                dwarf_cu->LookupAddress(file_vm_addr, &function_die, NULL);
2557                            }
2558
2559                            if (function_die != NULL)
2560                            {
2561                                sc.function = sc.comp_unit->FindFunctionByUID (MakeUserID(function_die->GetOffset())).get();
2562                                if (sc.function == NULL)
2563                                    sc.function = ParseCompileUnitFunction(sc, dwarf_cu, function_die);
2564                            }
2565                            else
2566                            {
2567                                // We might have had a compile unit that had discontiguous
2568                                // address ranges where the gaps are symbols that don't have
2569                                // any debug info. Discontiguous compile unit address ranges
2570                                // should only happen when there aren't other functions from
2571                                // other compile units in these gaps. This helps keep the size
2572                                // of the aranges down.
2573                                force_check_line_table = true;
2574                            }
2575
2576                            if (sc.function != NULL)
2577                            {
2578                                resolved |= eSymbolContextFunction;
2579
2580                                if (resolve_scope & eSymbolContextBlock)
2581                                {
2582                                    Block& block = sc.function->GetBlock (true);
2583
2584                                    if (block_die != NULL)
2585                                        sc.block = block.FindBlockByID (MakeUserID(block_die->GetOffset()));
2586                                    else
2587                                        sc.block = block.FindBlockByID (MakeUserID(function_die->GetOffset()));
2588                                    if (sc.block)
2589                                        resolved |= eSymbolContextBlock;
2590                                }
2591                            }
2592                        }
2593
2594                        if ((resolve_scope & eSymbolContextLineEntry) || force_check_line_table)
2595                        {
2596                            LineTable *line_table = sc.comp_unit->GetLineTable();
2597                            if (line_table != NULL)
2598                            {
2599                                // And address that makes it into this function should be in terms
2600                                // of this debug file if there is no debug map, or it will be an
2601                                // address in the .o file which needs to be fixed up to be in terms
2602                                // of the debug map executable. Either way, calling FixupAddress()
2603                                // will work for us.
2604                                Address exe_so_addr (so_addr);
2605                                if (FixupAddress(exe_so_addr))
2606                                {
2607                                    if (line_table->FindLineEntryByAddress (exe_so_addr, sc.line_entry))
2608                                    {
2609                                        resolved |= eSymbolContextLineEntry;
2610                                    }
2611                                }
2612                            }
2613                        }
2614
2615                        if (force_check_line_table && !(resolved & eSymbolContextLineEntry))
2616                        {
2617                            // We might have had a compile unit that had discontiguous
2618                            // address ranges where the gaps are symbols that don't have
2619                            // any debug info. Discontiguous compile unit address ranges
2620                            // should only happen when there aren't other functions from
2621                            // other compile units in these gaps. This helps keep the size
2622                            // of the aranges down.
2623                            sc.comp_unit = NULL;
2624                            resolved &= ~eSymbolContextCompUnit;
2625                        }
2626                    }
2627                    else
2628                    {
2629                        GetObjectFile()->GetModule()->ReportWarning ("0x%8.8x: compile unit %u failed to create a valid lldb_private::CompileUnit class.",
2630                                                                     cu_offset,
2631                                                                     cu_idx);
2632                    }
2633                }
2634            }
2635        }
2636    }
2637    return resolved;
2638}
2639
2640
2641
2642uint32_t
2643SymbolFileDWARF::ResolveSymbolContext(const FileSpec& file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
2644{
2645    const uint32_t prev_size = sc_list.GetSize();
2646    if (resolve_scope & eSymbolContextCompUnit)
2647    {
2648        DWARFDebugInfo* debug_info = DebugInfo();
2649        if (debug_info)
2650        {
2651            uint32_t cu_idx;
2652            DWARFCompileUnit* dwarf_cu = NULL;
2653
2654            for (cu_idx = 0; (dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx)) != NULL; ++cu_idx)
2655            {
2656                CompileUnit *dc_cu = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2657                const bool full_match = file_spec.GetDirectory();
2658                bool file_spec_matches_cu_file_spec = dc_cu != NULL && FileSpec::Equal(file_spec, *dc_cu, full_match);
2659                if (check_inlines || file_spec_matches_cu_file_spec)
2660                {
2661                    SymbolContext sc (m_obj_file->GetModule());
2662                    sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2663                    if (sc.comp_unit)
2664                    {
2665                        uint32_t file_idx = UINT32_MAX;
2666
2667                        // If we are looking for inline functions only and we don't
2668                        // find it in the support files, we are done.
2669                        if (check_inlines)
2670                        {
2671                            file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex (1, file_spec, true);
2672                            if (file_idx == UINT32_MAX)
2673                                continue;
2674                        }
2675
2676                        if (line != 0)
2677                        {
2678                            LineTable *line_table = sc.comp_unit->GetLineTable();
2679
2680                            if (line_table != NULL && line != 0)
2681                            {
2682                                // We will have already looked up the file index if
2683                                // we are searching for inline entries.
2684                                if (!check_inlines)
2685                                    file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex (1, file_spec, true);
2686
2687                                if (file_idx != UINT32_MAX)
2688                                {
2689                                    uint32_t found_line;
2690                                    uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex (0, file_idx, line, false, &sc.line_entry);
2691                                    found_line = sc.line_entry.line;
2692
2693                                    while (line_idx != UINT32_MAX)
2694                                    {
2695                                        sc.function = NULL;
2696                                        sc.block = NULL;
2697                                        if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock))
2698                                        {
2699                                            const lldb::addr_t file_vm_addr = sc.line_entry.range.GetBaseAddress().GetFileAddress();
2700                                            if (file_vm_addr != LLDB_INVALID_ADDRESS)
2701                                            {
2702                                                DWARFDebugInfoEntry *function_die = NULL;
2703                                                DWARFDebugInfoEntry *block_die = NULL;
2704                                                dwarf_cu->LookupAddress(file_vm_addr, &function_die, resolve_scope & eSymbolContextBlock ? &block_die : NULL);
2705
2706                                                if (function_die != NULL)
2707                                                {
2708                                                    sc.function = sc.comp_unit->FindFunctionByUID (MakeUserID(function_die->GetOffset())).get();
2709                                                    if (sc.function == NULL)
2710                                                        sc.function = ParseCompileUnitFunction(sc, dwarf_cu, function_die);
2711                                                }
2712
2713                                                if (sc.function != NULL)
2714                                                {
2715                                                    Block& block = sc.function->GetBlock (true);
2716
2717                                                    if (block_die != NULL)
2718                                                        sc.block = block.FindBlockByID (MakeUserID(block_die->GetOffset()));
2719                                                    else
2720                                                        sc.block = block.FindBlockByID (MakeUserID(function_die->GetOffset()));
2721                                                }
2722                                            }
2723                                        }
2724
2725                                        sc_list.Append(sc);
2726                                        line_idx = line_table->FindLineEntryIndexByFileIndex (line_idx + 1, file_idx, found_line, true, &sc.line_entry);
2727                                    }
2728                                }
2729                            }
2730                            else if (file_spec_matches_cu_file_spec && !check_inlines)
2731                            {
2732                                // only append the context if we aren't looking for inline call sites
2733                                // by file and line and if the file spec matches that of the compile unit
2734                                sc_list.Append(sc);
2735                            }
2736                        }
2737                        else if (file_spec_matches_cu_file_spec && !check_inlines)
2738                        {
2739                            // only append the context if we aren't looking for inline call sites
2740                            // by file and line and if the file spec matches that of the compile unit
2741                            sc_list.Append(sc);
2742                        }
2743
2744                        if (!check_inlines)
2745                            break;
2746                    }
2747                }
2748            }
2749        }
2750    }
2751    return sc_list.GetSize() - prev_size;
2752}
2753
2754void
2755SymbolFileDWARF::Index ()
2756{
2757    if (m_indexed)
2758        return;
2759    m_indexed = true;
2760    Timer scoped_timer (__PRETTY_FUNCTION__,
2761                        "SymbolFileDWARF::Index (%s)",
2762                        GetObjectFile()->GetFileSpec().GetFilename().AsCString());
2763
2764    DWARFDebugInfo* debug_info = DebugInfo();
2765    if (debug_info)
2766    {
2767        uint32_t cu_idx = 0;
2768        const uint32_t num_compile_units = GetNumCompileUnits();
2769        for (cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
2770        {
2771            DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
2772
2773            bool clear_dies = dwarf_cu->ExtractDIEsIfNeeded (false) > 1;
2774
2775            dwarf_cu->Index (cu_idx,
2776                             m_function_basename_index,
2777                             m_function_fullname_index,
2778                             m_function_method_index,
2779                             m_function_selector_index,
2780                             m_objc_class_selectors_index,
2781                             m_global_index,
2782                             m_type_index,
2783                             m_namespace_index);
2784
2785            // Keep memory down by clearing DIEs if this generate function
2786            // caused them to be parsed
2787            if (clear_dies)
2788                dwarf_cu->ClearDIEs (true);
2789        }
2790
2791        m_function_basename_index.Finalize();
2792        m_function_fullname_index.Finalize();
2793        m_function_method_index.Finalize();
2794        m_function_selector_index.Finalize();
2795        m_objc_class_selectors_index.Finalize();
2796        m_global_index.Finalize();
2797        m_type_index.Finalize();
2798        m_namespace_index.Finalize();
2799
2800#if defined (ENABLE_DEBUG_PRINTF)
2801        StreamFile s(stdout, false);
2802        s.Printf ("DWARF index for '%s/%s':",
2803                  GetObjectFile()->GetFileSpec().GetDirectory().AsCString(),
2804                  GetObjectFile()->GetFileSpec().GetFilename().AsCString());
2805        s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
2806        s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
2807        s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
2808        s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
2809        s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
2810        s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
2811        s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
2812        s.Printf("\nNamepaces:\n");             m_namespace_index.Dump (&s);
2813#endif
2814    }
2815}
2816
2817bool
2818SymbolFileDWARF::NamespaceDeclMatchesThisSymbolFile (const ClangNamespaceDecl *namespace_decl)
2819{
2820    if (namespace_decl == NULL)
2821    {
2822        // Invalid namespace decl which means we aren't matching only things
2823        // in this symbol file, so return true to indicate it matches this
2824        // symbol file.
2825        return true;
2826    }
2827
2828    clang::ASTContext *namespace_ast = namespace_decl->GetASTContext();
2829
2830    if (namespace_ast == NULL)
2831        return true;    // No AST in the "namespace_decl", return true since it
2832                        // could then match any symbol file, including this one
2833
2834    if (namespace_ast == GetClangASTContext().getASTContext())
2835        return true;    // The ASTs match, return true
2836
2837    // The namespace AST was valid, and it does not match...
2838    Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2839
2840    if (log)
2841        GetObjectFile()->GetModule()->LogMessage(log, "Valid namespace does not match symbol file");
2842
2843    return false;
2844}
2845
2846bool
2847SymbolFileDWARF::DIEIsInNamespace (const ClangNamespaceDecl *namespace_decl,
2848                                   DWARFCompileUnit* cu,
2849                                   const DWARFDebugInfoEntry* die)
2850{
2851    // No namespace specified, so the answesr i
2852    if (namespace_decl == NULL)
2853        return true;
2854
2855    Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2856
2857    const DWARFDebugInfoEntry *decl_ctx_die = NULL;
2858    clang::DeclContext *die_clang_decl_ctx = GetClangDeclContextContainingDIE (cu, die, &decl_ctx_die);
2859    if (decl_ctx_die)
2860    {
2861        clang::NamespaceDecl *clang_namespace_decl = namespace_decl->GetNamespaceDecl();
2862
2863        if (clang_namespace_decl)
2864        {
2865            if (decl_ctx_die->Tag() != DW_TAG_namespace)
2866            {
2867                if (log)
2868                    GetObjectFile()->GetModule()->LogMessage(log, "Found a match, but its parent is not a namespace");
2869                return false;
2870            }
2871
2872            if (clang_namespace_decl == die_clang_decl_ctx)
2873                return true;
2874            else
2875                return false;
2876        }
2877        else
2878        {
2879            // We have a namespace_decl that was not NULL but it contained
2880            // a NULL "clang::NamespaceDecl", so this means the global namespace
2881            // So as long the the contained decl context DIE isn't a namespace
2882            // we should be ok.
2883            if (decl_ctx_die->Tag() != DW_TAG_namespace)
2884                return true;
2885        }
2886    }
2887
2888    if (log)
2889        GetObjectFile()->GetModule()->LogMessage(log, "Found a match, but its parent doesn't exist");
2890
2891    return false;
2892}
2893uint32_t
2894SymbolFileDWARF::FindGlobalVariables (const ConstString &name, const lldb_private::ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, VariableList& variables)
2895{
2896    Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2897
2898    if (log)
2899    {
2900        GetObjectFile()->GetModule()->LogMessage (log,
2901                                                  "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", namespace_decl=%p, append=%u, max_matches=%u, variables)",
2902                                                  name.GetCString(),
2903                                                  namespace_decl,
2904                                                  append,
2905                                                  max_matches);
2906    }
2907
2908    if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
2909		return 0;
2910
2911    DWARFDebugInfo* info = DebugInfo();
2912    if (info == NULL)
2913        return 0;
2914
2915    // If we aren't appending the results to this list, then clear the list
2916    if (!append)
2917        variables.Clear();
2918
2919    // Remember how many variables are in the list before we search in case
2920    // we are appending the results to a variable list.
2921    const uint32_t original_size = variables.GetSize();
2922
2923    DIEArray die_offsets;
2924
2925    if (m_using_apple_tables)
2926    {
2927        if (m_apple_names_ap.get())
2928        {
2929            const char *name_cstr = name.GetCString();
2930            const char *base_name_start;
2931            const char *base_name_end = NULL;
2932
2933            if (!CPPLanguageRuntime::StripNamespacesFromVariableName(name_cstr, base_name_start, base_name_end))
2934                base_name_start = name_cstr;
2935
2936            m_apple_names_ap->FindByName (base_name_start, die_offsets);
2937        }
2938    }
2939    else
2940    {
2941        // Index the DWARF if we haven't already
2942        if (!m_indexed)
2943            Index ();
2944
2945        m_global_index.Find (name, die_offsets);
2946    }
2947
2948    const size_t num_die_matches = die_offsets.size();
2949    if (num_die_matches)
2950    {
2951        SymbolContext sc;
2952        sc.module_sp = m_obj_file->GetModule();
2953        assert (sc.module_sp);
2954
2955        DWARFDebugInfo* debug_info = DebugInfo();
2956        DWARFCompileUnit* dwarf_cu = NULL;
2957        const DWARFDebugInfoEntry* die = NULL;
2958        bool done = false;
2959        for (size_t i=0; i<num_die_matches && !done; ++i)
2960        {
2961            const dw_offset_t die_offset = die_offsets[i];
2962            die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
2963
2964            if (die)
2965            {
2966                switch (die->Tag())
2967                {
2968                    default:
2969                    case DW_TAG_subprogram:
2970                    case DW_TAG_inlined_subroutine:
2971                    case DW_TAG_try_block:
2972                    case DW_TAG_catch_block:
2973                        break;
2974
2975                    case DW_TAG_variable:
2976                        {
2977                            sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
2978
2979                            if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
2980                                continue;
2981
2982                            ParseVariables(sc, dwarf_cu, LLDB_INVALID_ADDRESS, die, false, false, &variables);
2983
2984                            if (variables.GetSize() - original_size >= max_matches)
2985                                done = true;
2986                        }
2987                        break;
2988                }
2989            }
2990            else
2991            {
2992                if (m_using_apple_tables)
2993                {
2994                    GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')\n",
2995                                                                               die_offset, name.GetCString());
2996                }
2997            }
2998        }
2999    }
3000
3001    // Return the number of variable that were appended to the list
3002    const uint32_t num_matches = variables.GetSize() - original_size;
3003    if (log && num_matches > 0)
3004    {
3005        GetObjectFile()->GetModule()->LogMessage (log,
3006                                                  "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", namespace_decl=%p, append=%u, max_matches=%u, variables) => %u",
3007                                                  name.GetCString(),
3008                                                  namespace_decl,
3009                                                  append,
3010                                                  max_matches,
3011                                                  num_matches);
3012    }
3013    return num_matches;
3014}
3015
3016uint32_t
3017SymbolFileDWARF::FindGlobalVariables(const RegularExpression& regex, bool append, uint32_t max_matches, VariableList& variables)
3018{
3019    Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3020
3021    if (log)
3022    {
3023        GetObjectFile()->GetModule()->LogMessage (log,
3024                                                  "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", append=%u, max_matches=%u, variables)",
3025                                                  regex.GetText(),
3026                                                  append,
3027                                                  max_matches);
3028    }
3029
3030    DWARFDebugInfo* info = DebugInfo();
3031    if (info == NULL)
3032        return 0;
3033
3034    // If we aren't appending the results to this list, then clear the list
3035    if (!append)
3036        variables.Clear();
3037
3038    // Remember how many variables are in the list before we search in case
3039    // we are appending the results to a variable list.
3040    const uint32_t original_size = variables.GetSize();
3041
3042    DIEArray die_offsets;
3043
3044    if (m_using_apple_tables)
3045    {
3046        if (m_apple_names_ap.get())
3047        {
3048            DWARFMappedHash::DIEInfoArray hash_data_array;
3049            if (m_apple_names_ap->AppendAllDIEsThatMatchingRegex (regex, hash_data_array))
3050                DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
3051        }
3052    }
3053    else
3054    {
3055        // Index the DWARF if we haven't already
3056        if (!m_indexed)
3057            Index ();
3058
3059        m_global_index.Find (regex, die_offsets);
3060    }
3061
3062    SymbolContext sc;
3063    sc.module_sp = m_obj_file->GetModule();
3064    assert (sc.module_sp);
3065
3066    DWARFCompileUnit* dwarf_cu = NULL;
3067    const DWARFDebugInfoEntry* die = NULL;
3068    const size_t num_matches = die_offsets.size();
3069    if (num_matches)
3070    {
3071        DWARFDebugInfo* debug_info = DebugInfo();
3072        for (size_t i=0; i<num_matches; ++i)
3073        {
3074            const dw_offset_t die_offset = die_offsets[i];
3075            die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3076
3077            if (die)
3078            {
3079                sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
3080
3081                ParseVariables(sc, dwarf_cu, LLDB_INVALID_ADDRESS, die, false, false, &variables);
3082
3083                if (variables.GetSize() - original_size >= max_matches)
3084                    break;
3085            }
3086            else
3087            {
3088                if (m_using_apple_tables)
3089                {
3090                    GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for regex '%s')\n",
3091                                                                               die_offset, regex.GetText());
3092                }
3093            }
3094        }
3095    }
3096
3097    // Return the number of variable that were appended to the list
3098    return variables.GetSize() - original_size;
3099}
3100
3101
3102bool
3103SymbolFileDWARF::ResolveFunction (dw_offset_t die_offset,
3104                                  DWARFCompileUnit *&dwarf_cu,
3105                                  SymbolContextList& sc_list)
3106{
3107    const DWARFDebugInfoEntry *die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3108    return ResolveFunction (dwarf_cu, die, sc_list);
3109}
3110
3111
3112bool
3113SymbolFileDWARF::ResolveFunction (DWARFCompileUnit *cu,
3114                                  const DWARFDebugInfoEntry *die,
3115                                  SymbolContextList& sc_list)
3116{
3117    SymbolContext sc;
3118
3119    if (die == NULL)
3120        return false;
3121
3122    // If we were passed a die that is not a function, just return false...
3123    if (die->Tag() != DW_TAG_subprogram && die->Tag() != DW_TAG_inlined_subroutine)
3124        return false;
3125
3126    const DWARFDebugInfoEntry* inlined_die = NULL;
3127    if (die->Tag() == DW_TAG_inlined_subroutine)
3128    {
3129        inlined_die = die;
3130
3131        while ((die = die->GetParent()) != NULL)
3132        {
3133            if (die->Tag() == DW_TAG_subprogram)
3134                break;
3135        }
3136    }
3137    assert (die->Tag() == DW_TAG_subprogram);
3138    if (GetFunction (cu, die, sc))
3139    {
3140        Address addr;
3141        // Parse all blocks if needed
3142        if (inlined_die)
3143        {
3144            sc.block = sc.function->GetBlock (true).FindBlockByID (MakeUserID(inlined_die->GetOffset()));
3145            assert (sc.block != NULL);
3146            if (sc.block->GetStartAddress (addr) == false)
3147                addr.Clear();
3148        }
3149        else
3150        {
3151            sc.block = NULL;
3152            addr = sc.function->GetAddressRange().GetBaseAddress();
3153        }
3154
3155        if (addr.IsValid())
3156        {
3157            sc_list.Append(sc);
3158            return true;
3159        }
3160    }
3161
3162    return false;
3163}
3164
3165void
3166SymbolFileDWARF::FindFunctions (const ConstString &name,
3167                                const NameToDIE &name_to_die,
3168                                SymbolContextList& sc_list)
3169{
3170    DIEArray die_offsets;
3171    if (name_to_die.Find (name, die_offsets))
3172    {
3173        ParseFunctions (die_offsets, sc_list);
3174    }
3175}
3176
3177
3178void
3179SymbolFileDWARF::FindFunctions (const RegularExpression &regex,
3180                                const NameToDIE &name_to_die,
3181                                SymbolContextList& sc_list)
3182{
3183    DIEArray die_offsets;
3184    if (name_to_die.Find (regex, die_offsets))
3185    {
3186        ParseFunctions (die_offsets, sc_list);
3187    }
3188}
3189
3190
3191void
3192SymbolFileDWARF::FindFunctions (const RegularExpression &regex,
3193                                const DWARFMappedHash::MemoryTable &memory_table,
3194                                SymbolContextList& sc_list)
3195{
3196    DIEArray die_offsets;
3197    DWARFMappedHash::DIEInfoArray hash_data_array;
3198    if (memory_table.AppendAllDIEsThatMatchingRegex (regex, hash_data_array))
3199    {
3200        DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
3201        ParseFunctions (die_offsets, sc_list);
3202    }
3203}
3204
3205void
3206SymbolFileDWARF::ParseFunctions (const DIEArray &die_offsets,
3207                                 SymbolContextList& sc_list)
3208{
3209    const size_t num_matches = die_offsets.size();
3210    if (num_matches)
3211    {
3212        SymbolContext sc;
3213
3214        DWARFCompileUnit* dwarf_cu = NULL;
3215        for (size_t i=0; i<num_matches; ++i)
3216        {
3217            const dw_offset_t die_offset = die_offsets[i];
3218            ResolveFunction (die_offset, dwarf_cu, sc_list);
3219        }
3220    }
3221}
3222
3223bool
3224SymbolFileDWARF::FunctionDieMatchesPartialName (const DWARFDebugInfoEntry* die,
3225                                                const DWARFCompileUnit *dwarf_cu,
3226                                                uint32_t name_type_mask,
3227                                                const char *partial_name,
3228                                                const char *base_name_start,
3229                                                const char *base_name_end)
3230{
3231    // If we are looking only for methods, throw away all the ones that are or aren't in C++ classes:
3232    if (name_type_mask == eFunctionNameTypeMethod || name_type_mask == eFunctionNameTypeBase)
3233    {
3234        clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIEOffset(die->GetOffset());
3235        if (!containing_decl_ctx)
3236            return false;
3237
3238        bool is_cxx_method = DeclKindIsCXXClass(containing_decl_ctx->getDeclKind());
3239
3240        if (name_type_mask == eFunctionNameTypeMethod)
3241        {
3242            if (is_cxx_method == false)
3243                return false;
3244        }
3245
3246        if (name_type_mask == eFunctionNameTypeBase)
3247        {
3248            if (is_cxx_method == true)
3249                return false;
3250        }
3251    }
3252
3253    // Now we need to check whether the name we got back for this type matches the extra specifications
3254    // that were in the name we're looking up:
3255    if (base_name_start != partial_name || *base_name_end != '\0')
3256    {
3257        // First see if the stuff to the left matches the full name.  To do that let's see if
3258        // we can pull out the mips linkage name attribute:
3259
3260        Mangled best_name;
3261        DWARFDebugInfoEntry::Attributes attributes;
3262        DWARFFormValue form_value;
3263        die->GetAttributes(this, dwarf_cu, NULL, attributes);
3264        uint32_t idx = attributes.FindAttributeIndex(DW_AT_MIPS_linkage_name);
3265        if (idx == UINT32_MAX)
3266            idx = attributes.FindAttributeIndex(DW_AT_linkage_name);
3267        if (idx != UINT32_MAX)
3268        {
3269            if (attributes.ExtractFormValueAtIndex(this, idx, form_value))
3270            {
3271                const char *mangled_name = form_value.AsCString(&get_debug_str_data());
3272                if (mangled_name)
3273                    best_name.SetValue (ConstString(mangled_name), true);
3274            }
3275        }
3276
3277        if (!best_name)
3278        {
3279            idx = attributes.FindAttributeIndex(DW_AT_name);
3280            if (idx != UINT32_MAX && attributes.ExtractFormValueAtIndex(this, idx, form_value))
3281            {
3282                const char *name = form_value.AsCString(&get_debug_str_data());
3283                best_name.SetValue (ConstString(name), false);
3284            }
3285        }
3286
3287        if (best_name.GetDemangledName())
3288        {
3289            const char *demangled = best_name.GetDemangledName().GetCString();
3290            if (demangled)
3291            {
3292                std::string name_no_parens(partial_name, base_name_end - partial_name);
3293                const char *partial_in_demangled = strstr (demangled, name_no_parens.c_str());
3294                if (partial_in_demangled == NULL)
3295                    return false;
3296                else
3297                {
3298                    // Sort out the case where our name is something like "Process::Destroy" and the match is
3299                    // "SBProcess::Destroy" - that shouldn't be a match.  We should really always match on
3300                    // namespace boundaries...
3301
3302                    if (partial_name[0] == ':'  && partial_name[1] == ':')
3303                    {
3304                        // The partial name was already on a namespace boundary so all matches are good.
3305                        return true;
3306                    }
3307                    else if (partial_in_demangled == demangled)
3308                    {
3309                        // They both start the same, so this is an good match.
3310                        return true;
3311                    }
3312                    else
3313                    {
3314                        if (partial_in_demangled - demangled == 1)
3315                        {
3316                            // Only one character difference, can't be a namespace boundary...
3317                            return false;
3318                        }
3319                        else if (*(partial_in_demangled - 1) == ':' && *(partial_in_demangled - 2) == ':')
3320                        {
3321                            // We are on a namespace boundary, so this is also good.
3322                            return true;
3323                        }
3324                        else
3325                            return false;
3326                    }
3327                }
3328            }
3329        }
3330    }
3331
3332    return true;
3333}
3334
3335uint32_t
3336SymbolFileDWARF::FindFunctions (const ConstString &name,
3337                                const lldb_private::ClangNamespaceDecl *namespace_decl,
3338                                uint32_t name_type_mask,
3339                                bool include_inlines,
3340                                bool append,
3341                                SymbolContextList& sc_list)
3342{
3343    Timer scoped_timer (__PRETTY_FUNCTION__,
3344                        "SymbolFileDWARF::FindFunctions (name = '%s')",
3345                        name.AsCString());
3346
3347    // eFunctionNameTypeAuto should be pre-resolved by a call to Module::PrepareForFunctionNameLookup()
3348    assert ((name_type_mask & eFunctionNameTypeAuto) == 0);
3349
3350    Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3351
3352    if (log)
3353    {
3354        GetObjectFile()->GetModule()->LogMessage (log,
3355                                                  "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, append=%u, sc_list)",
3356                                                  name.GetCString(),
3357                                                  name_type_mask,
3358                                                  append);
3359    }
3360
3361    // If we aren't appending the results to this list, then clear the list
3362    if (!append)
3363        sc_list.Clear();
3364
3365    if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
3366		return 0;
3367
3368    // If name is empty then we won't find anything.
3369    if (name.IsEmpty())
3370        return 0;
3371
3372    // Remember how many sc_list are in the list before we search in case
3373    // we are appending the results to a variable list.
3374
3375    const char *name_cstr = name.GetCString();
3376
3377    const uint32_t original_size = sc_list.GetSize();
3378
3379    DWARFDebugInfo* info = DebugInfo();
3380    if (info == NULL)
3381        return 0;
3382
3383    DWARFCompileUnit *dwarf_cu = NULL;
3384    std::set<const DWARFDebugInfoEntry *> resolved_dies;
3385    if (m_using_apple_tables)
3386    {
3387        if (m_apple_names_ap.get())
3388        {
3389
3390            DIEArray die_offsets;
3391
3392            uint32_t num_matches = 0;
3393
3394            if (name_type_mask & eFunctionNameTypeFull)
3395            {
3396                // If they asked for the full name, match what they typed.  At some point we may
3397                // want to canonicalize this (strip double spaces, etc.  For now, we just add all the
3398                // dies that we find by exact match.
3399                num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3400                for (uint32_t i = 0; i < num_matches; i++)
3401                {
3402                    const dw_offset_t die_offset = die_offsets[i];
3403                    const DWARFDebugInfoEntry *die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3404                    if (die)
3405                    {
3406                        if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3407                            continue;
3408
3409                        if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3410                            continue;
3411
3412                        if (resolved_dies.find(die) == resolved_dies.end())
3413                        {
3414                            if (ResolveFunction (dwarf_cu, die, sc_list))
3415                                resolved_dies.insert(die);
3416                        }
3417                    }
3418                    else
3419                    {
3420                        GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3421                                                                                   die_offset, name_cstr);
3422                    }
3423                }
3424            }
3425
3426            if (name_type_mask & eFunctionNameTypeSelector)
3427            {
3428                if (namespace_decl && *namespace_decl)
3429                    return 0; // no selectors in namespaces
3430
3431                num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3432                // Now make sure these are actually ObjC methods.  In this case we can simply look up the name,
3433                // and if it is an ObjC method name, we're good.
3434
3435                for (uint32_t i = 0; i < num_matches; i++)
3436                {
3437                    const dw_offset_t die_offset = die_offsets[i];
3438                    const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3439                    if (die)
3440                    {
3441                        const char *die_name = die->GetName(this, dwarf_cu);
3442                        if (ObjCLanguageRuntime::IsPossibleObjCMethodName(die_name))
3443                        {
3444                            if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3445                                continue;
3446
3447                            if (resolved_dies.find(die) == resolved_dies.end())
3448                            {
3449                                if (ResolveFunction (dwarf_cu, die, sc_list))
3450                                    resolved_dies.insert(die);
3451                            }
3452                        }
3453                    }
3454                    else
3455                    {
3456                        GetObjectFile()->GetModule()->ReportError ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3457                                                                   die_offset, name_cstr);
3458                    }
3459                }
3460                die_offsets.clear();
3461            }
3462
3463            if (((name_type_mask & eFunctionNameTypeMethod) && !namespace_decl) || name_type_mask & eFunctionNameTypeBase)
3464            {
3465                // The apple_names table stores just the "base name" of C++ methods in the table.  So we have to
3466                // extract the base name, look that up, and if there is any other information in the name we were
3467                // passed in we have to post-filter based on that.
3468
3469                // FIXME: Arrange the logic above so that we don't calculate the base name twice:
3470                num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3471
3472                for (uint32_t i = 0; i < num_matches; i++)
3473                {
3474                    const dw_offset_t die_offset = die_offsets[i];
3475                    const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3476                    if (die)
3477                    {
3478                        if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3479                            continue;
3480
3481                        if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3482                            continue;
3483
3484                        // If we get to here, the die is good, and we should add it:
3485                        if (resolved_dies.find(die) == resolved_dies.end())
3486                        if (ResolveFunction (dwarf_cu, die, sc_list))
3487                        {
3488                            bool keep_die = true;
3489                            if ((name_type_mask & (eFunctionNameTypeBase|eFunctionNameTypeMethod)) != (eFunctionNameTypeBase|eFunctionNameTypeMethod))
3490                            {
3491                                // We are looking for either basenames or methods, so we need to
3492                                // trim out the ones we won't want by looking at the type
3493                                SymbolContext sc;
3494                                if (sc_list.GetLastContext(sc))
3495                                {
3496                                    if (sc.block)
3497                                    {
3498                                        // We have an inlined function
3499                                    }
3500                                    else if (sc.function)
3501                                    {
3502                                        Type *type = sc.function->GetType();
3503
3504                                        clang::DeclContext* decl_ctx = GetClangDeclContextContainingTypeUID (type->GetID());
3505                                        if (decl_ctx->isRecord())
3506                                        {
3507                                            if (name_type_mask & eFunctionNameTypeBase)
3508                                            {
3509                                                sc_list.RemoveContextAtIndex(sc_list.GetSize()-1);
3510                                                keep_die = false;
3511                                            }
3512                                        }
3513                                        else
3514                                        {
3515                                            if (name_type_mask & eFunctionNameTypeMethod)
3516                                            {
3517                                                sc_list.RemoveContextAtIndex(sc_list.GetSize()-1);
3518                                                keep_die = false;
3519                                            }
3520                                        }
3521                                    }
3522                                }
3523                            }
3524                            if (keep_die)
3525                                resolved_dies.insert(die);
3526                        }
3527                    }
3528                    else
3529                    {
3530                        GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3531                                                                                   die_offset, name_cstr);
3532                    }
3533                }
3534                die_offsets.clear();
3535            }
3536        }
3537    }
3538    else
3539    {
3540
3541        // Index the DWARF if we haven't already
3542        if (!m_indexed)
3543            Index ();
3544
3545        if (name_type_mask & eFunctionNameTypeFull)
3546            FindFunctions (name, m_function_fullname_index, sc_list);
3547
3548        DIEArray die_offsets;
3549        DWARFCompileUnit *dwarf_cu = NULL;
3550
3551        if (name_type_mask & eFunctionNameTypeBase)
3552        {
3553            uint32_t num_base = m_function_basename_index.Find(name, die_offsets);
3554            for (uint32_t i = 0; i < num_base; i++)
3555            {
3556                const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offsets[i], &dwarf_cu);
3557                if (die)
3558                {
3559                    if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3560                        continue;
3561
3562                    if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3563                        continue;
3564
3565                    // If we get to here, the die is good, and we should add it:
3566                    if (resolved_dies.find(die) == resolved_dies.end())
3567                    {
3568                        if (ResolveFunction (dwarf_cu, die, sc_list))
3569                            resolved_dies.insert(die);
3570                    }
3571                }
3572            }
3573            die_offsets.clear();
3574        }
3575
3576        if (name_type_mask & eFunctionNameTypeMethod)
3577        {
3578            if (namespace_decl && *namespace_decl)
3579                return 0; // no methods in namespaces
3580
3581            uint32_t num_base = m_function_method_index.Find(name, die_offsets);
3582            {
3583                for (uint32_t i = 0; i < num_base; i++)
3584                {
3585                    const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offsets[i], &dwarf_cu);
3586                    if (die)
3587                    {
3588                        if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3589                            continue;
3590
3591                        // If we get to here, the die is good, and we should add it:
3592                        if (resolved_dies.find(die) == resolved_dies.end())
3593                        {
3594                            if (ResolveFunction (dwarf_cu, die, sc_list))
3595                                resolved_dies.insert(die);
3596                        }
3597                    }
3598                }
3599            }
3600            die_offsets.clear();
3601        }
3602
3603        if ((name_type_mask & eFunctionNameTypeSelector) && (!namespace_decl || !*namespace_decl))
3604        {
3605            FindFunctions (name, m_function_selector_index, sc_list);
3606        }
3607
3608    }
3609
3610    // Return the number of variable that were appended to the list
3611    const uint32_t num_matches = sc_list.GetSize() - original_size;
3612
3613    if (log && num_matches > 0)
3614    {
3615        GetObjectFile()->GetModule()->LogMessage (log,
3616                                                  "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, append=%u, sc_list) => %u",
3617                                                  name.GetCString(),
3618                                                  name_type_mask,
3619                                                  append,
3620                                                  num_matches);
3621    }
3622    return num_matches;
3623}
3624
3625uint32_t
3626SymbolFileDWARF::FindFunctions(const RegularExpression& regex, bool include_inlines, bool append, SymbolContextList& sc_list)
3627{
3628    Timer scoped_timer (__PRETTY_FUNCTION__,
3629                        "SymbolFileDWARF::FindFunctions (regex = '%s')",
3630                        regex.GetText());
3631
3632    Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3633
3634    if (log)
3635    {
3636        GetObjectFile()->GetModule()->LogMessage (log,
3637                                                  "SymbolFileDWARF::FindFunctions (regex=\"%s\", append=%u, sc_list)",
3638                                                  regex.GetText(),
3639                                                  append);
3640    }
3641
3642
3643    // If we aren't appending the results to this list, then clear the list
3644    if (!append)
3645        sc_list.Clear();
3646
3647    // Remember how many sc_list are in the list before we search in case
3648    // we are appending the results to a variable list.
3649    uint32_t original_size = sc_list.GetSize();
3650
3651    if (m_using_apple_tables)
3652    {
3653        if (m_apple_names_ap.get())
3654            FindFunctions (regex, *m_apple_names_ap, sc_list);
3655    }
3656    else
3657    {
3658        // Index the DWARF if we haven't already
3659        if (!m_indexed)
3660            Index ();
3661
3662        FindFunctions (regex, m_function_basename_index, sc_list);
3663
3664        FindFunctions (regex, m_function_fullname_index, sc_list);
3665    }
3666
3667    // Return the number of variable that were appended to the list
3668    return sc_list.GetSize() - original_size;
3669}
3670
3671uint32_t
3672SymbolFileDWARF::FindTypes (const SymbolContext& sc,
3673                            const ConstString &name,
3674                            const lldb_private::ClangNamespaceDecl *namespace_decl,
3675                            bool append,
3676                            uint32_t max_matches,
3677                            TypeList& types)
3678{
3679    DWARFDebugInfo* info = DebugInfo();
3680    if (info == NULL)
3681        return 0;
3682
3683    Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3684
3685    if (log)
3686    {
3687        if (namespace_decl)
3688        {
3689            GetObjectFile()->GetModule()->LogMessage (log,
3690                                                      "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(%p) \"%s\", append=%u, max_matches=%u, type_list)",
3691                                                      name.GetCString(),
3692                                                      namespace_decl->GetNamespaceDecl(),
3693                                                      namespace_decl->GetQualifiedName().c_str(),
3694                                                      append,
3695                                                      max_matches);
3696        }
3697        else
3698        {
3699            GetObjectFile()->GetModule()->LogMessage (log,
3700                                                      "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(NULL), append=%u, max_matches=%u, type_list)",
3701                                                      name.GetCString(),
3702                                                      append,
3703                                                      max_matches);
3704        }
3705    }
3706
3707    // If we aren't appending the results to this list, then clear the list
3708    if (!append)
3709        types.Clear();
3710
3711    if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
3712		return 0;
3713
3714    DIEArray die_offsets;
3715
3716    if (m_using_apple_tables)
3717    {
3718        if (m_apple_types_ap.get())
3719        {
3720            const char *name_cstr = name.GetCString();
3721            m_apple_types_ap->FindByName (name_cstr, die_offsets);
3722        }
3723    }
3724    else
3725    {
3726        if (!m_indexed)
3727            Index ();
3728
3729        m_type_index.Find (name, die_offsets);
3730    }
3731
3732    const size_t num_die_matches = die_offsets.size();
3733
3734    if (num_die_matches)
3735    {
3736        const uint32_t initial_types_size = types.GetSize();
3737        DWARFCompileUnit* dwarf_cu = NULL;
3738        const DWARFDebugInfoEntry* die = NULL;
3739        DWARFDebugInfo* debug_info = DebugInfo();
3740        for (size_t i=0; i<num_die_matches; ++i)
3741        {
3742            const dw_offset_t die_offset = die_offsets[i];
3743            die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3744
3745            if (die)
3746            {
3747                if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3748                    continue;
3749
3750                Type *matching_type = ResolveType (dwarf_cu, die);
3751                if (matching_type)
3752                {
3753                    // We found a type pointer, now find the shared pointer form our type list
3754                    types.InsertUnique (matching_type->shared_from_this());
3755                    if (types.GetSize() >= max_matches)
3756                        break;
3757                }
3758            }
3759            else
3760            {
3761                if (m_using_apple_tables)
3762                {
3763                    GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
3764                                                                               die_offset, name.GetCString());
3765                }
3766            }
3767
3768        }
3769        const uint32_t num_matches = types.GetSize() - initial_types_size;
3770        if (log && num_matches)
3771        {
3772            if (namespace_decl)
3773            {
3774                GetObjectFile()->GetModule()->LogMessage (log,
3775                                                          "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(%p) \"%s\", append=%u, max_matches=%u, type_list) => %u",
3776                                                          name.GetCString(),
3777                                                          namespace_decl->GetNamespaceDecl(),
3778                                                          namespace_decl->GetQualifiedName().c_str(),
3779                                                          append,
3780                                                          max_matches,
3781                                                          num_matches);
3782            }
3783            else
3784            {
3785                GetObjectFile()->GetModule()->LogMessage (log,
3786                                                          "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(NULL), append=%u, max_matches=%u, type_list) => %u",
3787                                                          name.GetCString(),
3788                                                          append,
3789                                                          max_matches,
3790                                                          num_matches);
3791            }
3792        }
3793        return num_matches;
3794    }
3795    return 0;
3796}
3797
3798
3799ClangNamespaceDecl
3800SymbolFileDWARF::FindNamespace (const SymbolContext& sc,
3801                                const ConstString &name,
3802                                const lldb_private::ClangNamespaceDecl *parent_namespace_decl)
3803{
3804    Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3805
3806    if (log)
3807    {
3808        GetObjectFile()->GetModule()->LogMessage (log,
3809                                                  "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
3810                                                  name.GetCString());
3811    }
3812
3813    if (!NamespaceDeclMatchesThisSymbolFile(parent_namespace_decl))
3814		return ClangNamespaceDecl();
3815
3816    ClangNamespaceDecl namespace_decl;
3817    DWARFDebugInfo* info = DebugInfo();
3818    if (info)
3819    {
3820        DIEArray die_offsets;
3821
3822        // Index if we already haven't to make sure the compile units
3823        // get indexed and make their global DIE index list
3824        if (m_using_apple_tables)
3825        {
3826            if (m_apple_namespaces_ap.get())
3827            {
3828                const char *name_cstr = name.GetCString();
3829                m_apple_namespaces_ap->FindByName (name_cstr, die_offsets);
3830            }
3831        }
3832        else
3833        {
3834            if (!m_indexed)
3835                Index ();
3836
3837            m_namespace_index.Find (name, die_offsets);
3838        }
3839
3840        DWARFCompileUnit* dwarf_cu = NULL;
3841        const DWARFDebugInfoEntry* die = NULL;
3842        const size_t num_matches = die_offsets.size();
3843        if (num_matches)
3844        {
3845            DWARFDebugInfo* debug_info = DebugInfo();
3846            for (size_t i=0; i<num_matches; ++i)
3847            {
3848                const dw_offset_t die_offset = die_offsets[i];
3849                die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3850
3851                if (die)
3852                {
3853                    if (parent_namespace_decl && !DIEIsInNamespace (parent_namespace_decl, dwarf_cu, die))
3854                        continue;
3855
3856                    clang::NamespaceDecl *clang_namespace_decl = ResolveNamespaceDIE (dwarf_cu, die);
3857                    if (clang_namespace_decl)
3858                    {
3859                        namespace_decl.SetASTContext (GetClangASTContext().getASTContext());
3860                        namespace_decl.SetNamespaceDecl (clang_namespace_decl);
3861                        break;
3862                    }
3863                }
3864                else
3865                {
3866                    if (m_using_apple_tables)
3867                    {
3868                        GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_namespaces accelerator table had bad die 0x%8.8x for '%s')\n",
3869                                                                   die_offset, name.GetCString());
3870                    }
3871                }
3872
3873            }
3874        }
3875    }
3876    if (log && namespace_decl.GetNamespaceDecl())
3877    {
3878        GetObjectFile()->GetModule()->LogMessage (log,
3879                                                  "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => clang::NamespaceDecl(%p) \"%s\"",
3880                                                  name.GetCString(),
3881                                                  namespace_decl.GetNamespaceDecl(),
3882                                                  namespace_decl.GetQualifiedName().c_str());
3883    }
3884
3885    return namespace_decl;
3886}
3887
3888uint32_t
3889SymbolFileDWARF::FindTypes(std::vector<dw_offset_t> die_offsets, uint32_t max_matches, TypeList& types)
3890{
3891    // Remember how many sc_list are in the list before we search in case
3892    // we are appending the results to a variable list.
3893    uint32_t original_size = types.GetSize();
3894
3895    const uint32_t num_die_offsets = die_offsets.size();
3896    // Parse all of the types we found from the pubtypes matches
3897    uint32_t i;
3898    uint32_t num_matches = 0;
3899    for (i = 0; i < num_die_offsets; ++i)
3900    {
3901        Type *matching_type = ResolveTypeUID (die_offsets[i]);
3902        if (matching_type)
3903        {
3904            // We found a type pointer, now find the shared pointer form our type list
3905            types.InsertUnique (matching_type->shared_from_this());
3906            ++num_matches;
3907            if (num_matches >= max_matches)
3908                break;
3909        }
3910    }
3911
3912    // Return the number of variable that were appended to the list
3913    return types.GetSize() - original_size;
3914}
3915
3916
3917size_t
3918SymbolFileDWARF::ParseChildParameters (const SymbolContext& sc,
3919                                       clang::DeclContext *containing_decl_ctx,
3920                                       DWARFCompileUnit* dwarf_cu,
3921                                       const DWARFDebugInfoEntry *parent_die,
3922                                       bool skip_artificial,
3923                                       bool &is_static,
3924                                       TypeList* type_list,
3925                                       std::vector<clang_type_t>& function_param_types,
3926                                       std::vector<clang::ParmVarDecl*>& function_param_decls,
3927                                       unsigned &type_quals,
3928                                       ClangASTContext::TemplateParameterInfos &template_param_infos)
3929{
3930    if (parent_die == NULL)
3931        return 0;
3932
3933    const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
3934
3935    size_t arg_idx = 0;
3936    const DWARFDebugInfoEntry *die;
3937    for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
3938    {
3939        dw_tag_t tag = die->Tag();
3940        switch (tag)
3941        {
3942        case DW_TAG_formal_parameter:
3943            {
3944                DWARFDebugInfoEntry::Attributes attributes;
3945                const size_t num_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
3946                if (num_attributes > 0)
3947                {
3948                    const char *name = NULL;
3949                    Declaration decl;
3950                    dw_offset_t param_type_die_offset = DW_INVALID_OFFSET;
3951                    bool is_artificial = false;
3952                    // one of None, Auto, Register, Extern, Static, PrivateExtern
3953
3954                    clang::StorageClass storage = clang::SC_None;
3955                    uint32_t i;
3956                    for (i=0; i<num_attributes; ++i)
3957                    {
3958                        const dw_attr_t attr = attributes.AttributeAtIndex(i);
3959                        DWARFFormValue form_value;
3960                        if (attributes.ExtractFormValueAtIndex(this, i, form_value))
3961                        {
3962                            switch (attr)
3963                            {
3964                            case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
3965                            case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
3966                            case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
3967                            case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
3968                            case DW_AT_type:        param_type_die_offset = form_value.Reference(dwarf_cu); break;
3969                            case DW_AT_artificial:  is_artificial = form_value.Boolean(); break;
3970                            case DW_AT_location:
3971    //                          if (form_value.BlockData())
3972    //                          {
3973    //                              const DataExtractor& debug_info_data = debug_info();
3974    //                              uint32_t block_length = form_value.Unsigned();
3975    //                              DataExtractor location(debug_info_data, form_value.BlockData() - debug_info_data.GetDataStart(), block_length);
3976    //                          }
3977    //                          else
3978    //                          {
3979    //                          }
3980    //                          break;
3981                            case DW_AT_const_value:
3982                            case DW_AT_default_value:
3983                            case DW_AT_description:
3984                            case DW_AT_endianity:
3985                            case DW_AT_is_optional:
3986                            case DW_AT_segment:
3987                            case DW_AT_variable_parameter:
3988                            default:
3989                            case DW_AT_abstract_origin:
3990                            case DW_AT_sibling:
3991                                break;
3992                            }
3993                        }
3994                    }
3995
3996                    bool skip = false;
3997                    if (skip_artificial)
3998                    {
3999                        if (is_artificial)
4000                        {
4001                            // In order to determine if a C++ member function is
4002                            // "const" we have to look at the const-ness of "this"...
4003                            // Ugly, but that
4004                            if (arg_idx == 0)
4005                            {
4006                                if (DeclKindIsCXXClass(containing_decl_ctx->getDeclKind()))
4007                                {
4008                                    // Often times compilers omit the "this" name for the
4009                                    // specification DIEs, so we can't rely upon the name
4010                                    // being in the formal parameter DIE...
4011                                    if (name == NULL || ::strcmp(name, "this")==0)
4012                                    {
4013                                        Type *this_type = ResolveTypeUID (param_type_die_offset);
4014                                        if (this_type)
4015                                        {
4016                                            uint32_t encoding_mask = this_type->GetEncodingMask();
4017                                            if (encoding_mask & Type::eEncodingIsPointerUID)
4018                                            {
4019                                                is_static = false;
4020
4021                                                if (encoding_mask & (1u << Type::eEncodingIsConstUID))
4022                                                    type_quals |= clang::Qualifiers::Const;
4023                                                if (encoding_mask & (1u << Type::eEncodingIsVolatileUID))
4024                                                    type_quals |= clang::Qualifiers::Volatile;
4025                                            }
4026                                        }
4027                                    }
4028                                }
4029                            }
4030                            skip = true;
4031                        }
4032                        else
4033                        {
4034
4035                            // HACK: Objective C formal parameters "self" and "_cmd"
4036                            // are not marked as artificial in the DWARF...
4037                            CompileUnit *comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
4038                            if (comp_unit)
4039                            {
4040                                switch (comp_unit->GetLanguage())
4041                                {
4042                                    case eLanguageTypeObjC:
4043                                    case eLanguageTypeObjC_plus_plus:
4044                                        if (name && name[0] && (strcmp (name, "self") == 0 || strcmp (name, "_cmd") == 0))
4045                                            skip = true;
4046                                        break;
4047                                    default:
4048                                        break;
4049                                }
4050                            }
4051                        }
4052                    }
4053
4054                    if (!skip)
4055                    {
4056                        Type *type = ResolveTypeUID(param_type_die_offset);
4057                        if (type)
4058                        {
4059                            function_param_types.push_back (type->GetClangForwardType());
4060
4061                            clang::ParmVarDecl *param_var_decl = GetClangASTContext().CreateParameterDeclaration (name,
4062                                                                                                                  type->GetClangForwardType(),
4063                                                                                                                  storage);
4064                            assert(param_var_decl);
4065                            function_param_decls.push_back(param_var_decl);
4066
4067                            GetClangASTContext().SetMetadataAsUserID (param_var_decl, MakeUserID(die->GetOffset()));
4068                        }
4069                    }
4070                }
4071                arg_idx++;
4072            }
4073            break;
4074
4075        case DW_TAG_template_type_parameter:
4076        case DW_TAG_template_value_parameter:
4077            ParseTemplateDIE (dwarf_cu, die,template_param_infos);
4078            break;
4079
4080        default:
4081            break;
4082        }
4083    }
4084    return arg_idx;
4085}
4086
4087size_t
4088SymbolFileDWARF::ParseChildEnumerators
4089(
4090    const SymbolContext& sc,
4091    clang_type_t enumerator_clang_type,
4092    bool is_signed,
4093    uint32_t enumerator_byte_size,
4094    DWARFCompileUnit* dwarf_cu,
4095    const DWARFDebugInfoEntry *parent_die
4096)
4097{
4098    if (parent_die == NULL)
4099        return 0;
4100
4101    size_t enumerators_added = 0;
4102    const DWARFDebugInfoEntry *die;
4103    const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
4104
4105    for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
4106    {
4107        const dw_tag_t tag = die->Tag();
4108        if (tag == DW_TAG_enumerator)
4109        {
4110            DWARFDebugInfoEntry::Attributes attributes;
4111            const size_t num_child_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
4112            if (num_child_attributes > 0)
4113            {
4114                const char *name = NULL;
4115                bool got_value = false;
4116                int64_t enum_value = 0;
4117                Declaration decl;
4118
4119                uint32_t i;
4120                for (i=0; i<num_child_attributes; ++i)
4121                {
4122                    const dw_attr_t attr = attributes.AttributeAtIndex(i);
4123                    DWARFFormValue form_value;
4124                    if (attributes.ExtractFormValueAtIndex(this, i, form_value))
4125                    {
4126                        switch (attr)
4127                        {
4128                        case DW_AT_const_value:
4129                            got_value = true;
4130                            if (is_signed)
4131                                enum_value = form_value.Signed();
4132                            else
4133                                enum_value = form_value.Unsigned();
4134                            break;
4135
4136                        case DW_AT_name:
4137                            name = form_value.AsCString(&get_debug_str_data());
4138                            break;
4139
4140                        case DW_AT_description:
4141                        default:
4142                        case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
4143                        case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
4144                        case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
4145                        case DW_AT_sibling:
4146                            break;
4147                        }
4148                    }
4149                }
4150
4151                if (name && name[0] && got_value)
4152                {
4153                    GetClangASTContext().AddEnumerationValueToEnumerationType (enumerator_clang_type,
4154                                                                               enumerator_clang_type,
4155                                                                               decl,
4156                                                                               name,
4157                                                                               enum_value,
4158                                                                               enumerator_byte_size * 8);
4159                    ++enumerators_added;
4160                }
4161            }
4162        }
4163    }
4164    return enumerators_added;
4165}
4166
4167void
4168SymbolFileDWARF::ParseChildArrayInfo
4169(
4170    const SymbolContext& sc,
4171    DWARFCompileUnit* dwarf_cu,
4172    const DWARFDebugInfoEntry *parent_die,
4173    int64_t& first_index,
4174    std::vector<uint64_t>& element_orders,
4175    uint32_t& byte_stride,
4176    uint32_t& bit_stride
4177)
4178{
4179    if (parent_die == NULL)
4180        return;
4181
4182    const DWARFDebugInfoEntry *die;
4183    const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
4184    for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
4185    {
4186        const dw_tag_t tag = die->Tag();
4187        switch (tag)
4188        {
4189        case DW_TAG_subrange_type:
4190            {
4191                DWARFDebugInfoEntry::Attributes attributes;
4192                const size_t num_child_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
4193                if (num_child_attributes > 0)
4194                {
4195                    uint64_t num_elements = 0;
4196                    uint64_t lower_bound = 0;
4197                    uint64_t upper_bound = 0;
4198                    bool upper_bound_valid = false;
4199                    uint32_t i;
4200                    for (i=0; i<num_child_attributes; ++i)
4201                    {
4202                        const dw_attr_t attr = attributes.AttributeAtIndex(i);
4203                        DWARFFormValue form_value;
4204                        if (attributes.ExtractFormValueAtIndex(this, i, form_value))
4205                        {
4206                            switch (attr)
4207                            {
4208                            case DW_AT_name:
4209                                break;
4210
4211                            case DW_AT_count:
4212                                num_elements = form_value.Unsigned();
4213                                break;
4214
4215                            case DW_AT_bit_stride:
4216                                bit_stride = form_value.Unsigned();
4217                                break;
4218
4219                            case DW_AT_byte_stride:
4220                                byte_stride = form_value.Unsigned();
4221                                break;
4222
4223                            case DW_AT_lower_bound:
4224                                lower_bound = form_value.Unsigned();
4225                                break;
4226
4227                            case DW_AT_upper_bound:
4228                                upper_bound_valid = true;
4229                                upper_bound = form_value.Unsigned();
4230                                break;
4231
4232                            default:
4233                            case DW_AT_abstract_origin:
4234                            case DW_AT_accessibility:
4235                            case DW_AT_allocated:
4236                            case DW_AT_associated:
4237                            case DW_AT_data_location:
4238                            case DW_AT_declaration:
4239                            case DW_AT_description:
4240                            case DW_AT_sibling:
4241                            case DW_AT_threads_scaled:
4242                            case DW_AT_type:
4243                            case DW_AT_visibility:
4244                                break;
4245                            }
4246                        }
4247                    }
4248
4249                    if (num_elements == 0)
4250                    {
4251                        if (upper_bound_valid && upper_bound >= lower_bound)
4252                            num_elements = upper_bound - lower_bound + 1;
4253                    }
4254
4255                    element_orders.push_back (num_elements);
4256                }
4257            }
4258            break;
4259        }
4260    }
4261}
4262
4263TypeSP
4264SymbolFileDWARF::GetTypeForDIE (DWARFCompileUnit *dwarf_cu, const DWARFDebugInfoEntry* die)
4265{
4266    TypeSP type_sp;
4267    if (die != NULL)
4268    {
4269        assert(dwarf_cu != NULL);
4270        Type *type_ptr = m_die_to_type.lookup (die);
4271        if (type_ptr == NULL)
4272        {
4273            CompileUnit* lldb_cu = GetCompUnitForDWARFCompUnit(dwarf_cu);
4274            assert (lldb_cu);
4275            SymbolContext sc(lldb_cu);
4276            type_sp = ParseType(sc, dwarf_cu, die, NULL);
4277        }
4278        else if (type_ptr != DIE_IS_BEING_PARSED)
4279        {
4280            // Grab the existing type from the master types lists
4281            type_sp = type_ptr->shared_from_this();
4282        }
4283
4284    }
4285    return type_sp;
4286}
4287
4288clang::DeclContext *
4289SymbolFileDWARF::GetClangDeclContextContainingDIEOffset (dw_offset_t die_offset)
4290{
4291    if (die_offset != DW_INVALID_OFFSET)
4292    {
4293        DWARFCompileUnitSP cu_sp;
4294        const DWARFDebugInfoEntry* die = DebugInfo()->GetDIEPtr(die_offset, &cu_sp);
4295        return GetClangDeclContextContainingDIE (cu_sp.get(), die, NULL);
4296    }
4297    return NULL;
4298}
4299
4300clang::DeclContext *
4301SymbolFileDWARF::GetClangDeclContextForDIEOffset (const SymbolContext &sc, dw_offset_t die_offset)
4302{
4303    if (die_offset != DW_INVALID_OFFSET)
4304    {
4305        DWARFDebugInfo* debug_info = DebugInfo();
4306        if (debug_info)
4307        {
4308            DWARFCompileUnitSP cu_sp;
4309            const DWARFDebugInfoEntry* die = debug_info->GetDIEPtr(die_offset, &cu_sp);
4310            if (die)
4311                return GetClangDeclContextForDIE (sc, cu_sp.get(), die);
4312        }
4313    }
4314    return NULL;
4315}
4316
4317clang::NamespaceDecl *
4318SymbolFileDWARF::ResolveNamespaceDIE (DWARFCompileUnit *dwarf_cu, const DWARFDebugInfoEntry *die)
4319{
4320    if (die && die->Tag() == DW_TAG_namespace)
4321    {
4322        // See if we already parsed this namespace DIE and associated it with a
4323        // uniqued namespace declaration
4324        clang::NamespaceDecl *namespace_decl = static_cast<clang::NamespaceDecl *>(m_die_to_decl_ctx[die]);
4325        if (namespace_decl)
4326            return namespace_decl;
4327        else
4328        {
4329            const char *namespace_name = die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_name, NULL);
4330            clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, NULL);
4331            namespace_decl = GetClangASTContext().GetUniqueNamespaceDeclaration (namespace_name, containing_decl_ctx);
4332            Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
4333            if (log)
4334            {
4335                if (namespace_name)
4336                {
4337                    GetObjectFile()->GetModule()->LogMessage (log,
4338                                                              "ASTContext => %p: 0x%8.8" PRIx64 ": DW_TAG_namespace with DW_AT_name(\"%s\") => clang::NamespaceDecl *%p (original = %p)",
4339                                                              GetClangASTContext().getASTContext(),
4340                                                              MakeUserID(die->GetOffset()),
4341                                                              namespace_name,
4342                                                              namespace_decl,
4343                                                              namespace_decl->getOriginalNamespace());
4344                }
4345                else
4346                {
4347                    GetObjectFile()->GetModule()->LogMessage (log,
4348                                                              "ASTContext => %p: 0x%8.8" PRIx64 ": DW_TAG_namespace (anonymous) => clang::NamespaceDecl *%p (original = %p)",
4349                                                              GetClangASTContext().getASTContext(),
4350                                                              MakeUserID(die->GetOffset()),
4351                                                              namespace_decl,
4352                                                              namespace_decl->getOriginalNamespace());
4353                }
4354            }
4355
4356            if (namespace_decl)
4357                LinkDeclContextToDIE((clang::DeclContext*)namespace_decl, die);
4358            return namespace_decl;
4359        }
4360    }
4361    return NULL;
4362}
4363
4364clang::DeclContext *
4365SymbolFileDWARF::GetClangDeclContextForDIE (const SymbolContext &sc, DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
4366{
4367    clang::DeclContext *clang_decl_ctx = GetCachedClangDeclContextForDIE (die);
4368    if (clang_decl_ctx)
4369        return clang_decl_ctx;
4370    // If this DIE has a specification, or an abstract origin, then trace to those.
4371
4372    dw_offset_t die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_specification, DW_INVALID_OFFSET);
4373    if (die_offset != DW_INVALID_OFFSET)
4374        return GetClangDeclContextForDIEOffset (sc, die_offset);
4375
4376    die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_abstract_origin, DW_INVALID_OFFSET);
4377    if (die_offset != DW_INVALID_OFFSET)
4378        return GetClangDeclContextForDIEOffset (sc, die_offset);
4379
4380    Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
4381    if (log)
4382        GetObjectFile()->GetModule()->LogMessage(log, "SymbolFileDWARF::GetClangDeclContextForDIE (die = 0x%8.8x) %s '%s'", die->GetOffset(), DW_TAG_value_to_name(die->Tag()), die->GetName(this, cu));
4383    // This is the DIE we want.  Parse it, then query our map.
4384    bool assert_not_being_parsed = true;
4385    ResolveTypeUID (cu, die, assert_not_being_parsed);
4386
4387    clang_decl_ctx = GetCachedClangDeclContextForDIE (die);
4388
4389    return clang_decl_ctx;
4390}
4391
4392clang::DeclContext *
4393SymbolFileDWARF::GetClangDeclContextContainingDIE (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die, const DWARFDebugInfoEntry **decl_ctx_die_copy)
4394{
4395    if (m_clang_tu_decl == NULL)
4396        m_clang_tu_decl = GetClangASTContext().getASTContext()->getTranslationUnitDecl();
4397
4398    const DWARFDebugInfoEntry *decl_ctx_die = GetDeclContextDIEContainingDIE (cu, die);
4399
4400    if (decl_ctx_die_copy)
4401        *decl_ctx_die_copy = decl_ctx_die;
4402
4403    if (decl_ctx_die)
4404    {
4405
4406        DIEToDeclContextMap::iterator pos = m_die_to_decl_ctx.find (decl_ctx_die);
4407        if (pos != m_die_to_decl_ctx.end())
4408            return pos->second;
4409
4410        switch (decl_ctx_die->Tag())
4411        {
4412        case DW_TAG_compile_unit:
4413            return m_clang_tu_decl;
4414
4415        case DW_TAG_namespace:
4416            return ResolveNamespaceDIE (cu, decl_ctx_die);
4417            break;
4418
4419        case DW_TAG_structure_type:
4420        case DW_TAG_union_type:
4421        case DW_TAG_class_type:
4422            {
4423                Type* type = ResolveType (cu, decl_ctx_die);
4424                if (type)
4425                {
4426                    clang::DeclContext *decl_ctx = ClangASTContext::GetDeclContextForType (type->GetClangForwardType ());
4427                    if (decl_ctx)
4428                    {
4429                        LinkDeclContextToDIE (decl_ctx, decl_ctx_die);
4430                        if (decl_ctx)
4431                            return decl_ctx;
4432                    }
4433                }
4434            }
4435            break;
4436
4437        default:
4438            break;
4439        }
4440    }
4441    return m_clang_tu_decl;
4442}
4443
4444
4445const DWARFDebugInfoEntry *
4446SymbolFileDWARF::GetDeclContextDIEContainingDIE (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
4447{
4448    if (cu && die)
4449    {
4450        const DWARFDebugInfoEntry * const decl_die = die;
4451
4452        while (die != NULL)
4453        {
4454            // If this is the original DIE that we are searching for a declaration
4455            // for, then don't look in the cache as we don't want our own decl
4456            // context to be our decl context...
4457            if (decl_die != die)
4458            {
4459                switch (die->Tag())
4460                {
4461                    case DW_TAG_compile_unit:
4462                    case DW_TAG_namespace:
4463                    case DW_TAG_structure_type:
4464                    case DW_TAG_union_type:
4465                    case DW_TAG_class_type:
4466                        return die;
4467
4468                    default:
4469                        break;
4470                }
4471            }
4472
4473            dw_offset_t die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_specification, DW_INVALID_OFFSET);
4474            if (die_offset != DW_INVALID_OFFSET)
4475            {
4476                DWARFCompileUnit *spec_cu = cu;
4477                const DWARFDebugInfoEntry *spec_die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &spec_cu);
4478                const DWARFDebugInfoEntry *spec_die_decl_ctx_die = GetDeclContextDIEContainingDIE (spec_cu, spec_die);
4479                if (spec_die_decl_ctx_die)
4480                    return spec_die_decl_ctx_die;
4481            }
4482
4483            die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_abstract_origin, DW_INVALID_OFFSET);
4484            if (die_offset != DW_INVALID_OFFSET)
4485            {
4486                DWARFCompileUnit *abs_cu = cu;
4487                const DWARFDebugInfoEntry *abs_die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &abs_cu);
4488                const DWARFDebugInfoEntry *abs_die_decl_ctx_die = GetDeclContextDIEContainingDIE (abs_cu, abs_die);
4489                if (abs_die_decl_ctx_die)
4490                    return abs_die_decl_ctx_die;
4491            }
4492
4493            die = die->GetParent();
4494        }
4495    }
4496    return NULL;
4497}
4498
4499
4500Symbol *
4501SymbolFileDWARF::GetObjCClassSymbol (const ConstString &objc_class_name)
4502{
4503    Symbol *objc_class_symbol = NULL;
4504    if (m_obj_file)
4505    {
4506        Symtab *symtab = m_obj_file->GetSymtab();
4507        if (symtab)
4508        {
4509            objc_class_symbol = symtab->FindFirstSymbolWithNameAndType (objc_class_name,
4510                                                                        eSymbolTypeObjCClass,
4511                                                                        Symtab::eDebugNo,
4512                                                                        Symtab::eVisibilityAny);
4513        }
4514    }
4515    return objc_class_symbol;
4516}
4517
4518// Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If they don't
4519// then we can end up looking through all class types for a complete type and never find
4520// the full definition. We need to know if this attribute is supported, so we determine
4521// this here and cache th result. We also need to worry about the debug map DWARF file
4522// if we are doing darwin DWARF in .o file debugging.
4523bool
4524SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type (DWARFCompileUnit *cu)
4525{
4526    if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate)
4527    {
4528        m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
4529        if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
4530            m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
4531        else
4532        {
4533            DWARFDebugInfo* debug_info = DebugInfo();
4534            const uint32_t num_compile_units = GetNumCompileUnits();
4535            for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
4536            {
4537                DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
4538                if (dwarf_cu != cu && dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type())
4539                {
4540                    m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
4541                    break;
4542                }
4543            }
4544        }
4545        if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo && GetDebugMapSymfile ())
4546            return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type (this);
4547    }
4548    return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
4549}
4550
4551// This function can be used when a DIE is found that is a forward declaration
4552// DIE and we want to try and find a type that has the complete definition.
4553TypeSP
4554SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE (const DWARFDebugInfoEntry *die,
4555                                                       const ConstString &type_name,
4556                                                       bool must_be_implementation)
4557{
4558
4559    TypeSP type_sp;
4560
4561    if (!type_name || (must_be_implementation && !GetObjCClassSymbol (type_name)))
4562        return type_sp;
4563
4564    DIEArray die_offsets;
4565
4566    if (m_using_apple_tables)
4567    {
4568        if (m_apple_types_ap.get())
4569        {
4570            const char *name_cstr = type_name.GetCString();
4571            m_apple_types_ap->FindCompleteObjCClassByName (name_cstr, die_offsets, must_be_implementation);
4572        }
4573    }
4574    else
4575    {
4576        if (!m_indexed)
4577            Index ();
4578
4579        m_type_index.Find (type_name, die_offsets);
4580    }
4581
4582    const size_t num_matches = die_offsets.size();
4583
4584    DWARFCompileUnit* type_cu = NULL;
4585    const DWARFDebugInfoEntry* type_die = NULL;
4586    if (num_matches)
4587    {
4588        DWARFDebugInfo* debug_info = DebugInfo();
4589        for (size_t i=0; i<num_matches; ++i)
4590        {
4591            const dw_offset_t die_offset = die_offsets[i];
4592            type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
4593
4594            if (type_die)
4595            {
4596                bool try_resolving_type = false;
4597
4598                // Don't try and resolve the DIE we are looking for with the DIE itself!
4599                if (type_die != die)
4600                {
4601                    switch (type_die->Tag())
4602                    {
4603                        case DW_TAG_class_type:
4604                        case DW_TAG_structure_type:
4605                            try_resolving_type = true;
4606                            break;
4607                        default:
4608                            break;
4609                    }
4610                }
4611
4612                if (try_resolving_type)
4613                {
4614					if (must_be_implementation && type_cu->Supports_DW_AT_APPLE_objc_complete_type())
4615	                    try_resolving_type = type_die->GetAttributeValueAsUnsigned (this, type_cu, DW_AT_APPLE_objc_complete_type, 0);
4616
4617                    if (try_resolving_type)
4618                    {
4619                        Type *resolved_type = ResolveType (type_cu, type_die, false);
4620                        if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
4621                        {
4622                            DEBUG_PRINTF ("resolved 0x%8.8" PRIx64 " (cu 0x%8.8" PRIx64 ") from %s to 0x%8.8" PRIx64 " (cu 0x%8.8" PRIx64 ")\n",
4623                                          MakeUserID(die->GetOffset()),
4624                                          MakeUserID(dwarf_cu->GetOffset()),
4625                                          m_obj_file->GetFileSpec().GetFilename().AsCString(),
4626                                          MakeUserID(type_die->GetOffset()),
4627                                          MakeUserID(type_cu->GetOffset()));
4628
4629                            if (die)
4630                                m_die_to_type[die] = resolved_type;
4631                            type_sp = resolved_type->shared_from_this();
4632                            break;
4633                        }
4634                    }
4635                }
4636            }
4637            else
4638            {
4639                if (m_using_apple_tables)
4640                {
4641                    GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
4642                                                               die_offset, type_name.GetCString());
4643                }
4644            }
4645
4646        }
4647    }
4648    return type_sp;
4649}
4650
4651
4652//----------------------------------------------------------------------
4653// This function helps to ensure that the declaration contexts match for
4654// two different DIEs. Often times debug information will refer to a
4655// forward declaration of a type (the equivalent of "struct my_struct;".
4656// There will often be a declaration of that type elsewhere that has the
4657// full definition. When we go looking for the full type "my_struct", we
4658// will find one or more matches in the accelerator tables and we will
4659// then need to make sure the type was in the same declaration context
4660// as the original DIE. This function can efficiently compare two DIEs
4661// and will return true when the declaration context matches, and false
4662// when they don't.
4663//----------------------------------------------------------------------
4664bool
4665SymbolFileDWARF::DIEDeclContextsMatch (DWARFCompileUnit* cu1, const DWARFDebugInfoEntry *die1,
4666                                       DWARFCompileUnit* cu2, const DWARFDebugInfoEntry *die2)
4667{
4668    if (die1 == die2)
4669        return true;
4670
4671#if defined (LLDB_CONFIGURATION_DEBUG)
4672    // You can't and shouldn't call this function with a compile unit from
4673    // two different SymbolFileDWARF instances.
4674    assert (DebugInfo()->ContainsCompileUnit (cu1));
4675    assert (DebugInfo()->ContainsCompileUnit (cu2));
4676#endif
4677
4678    DWARFDIECollection decl_ctx_1;
4679    DWARFDIECollection decl_ctx_2;
4680    //The declaration DIE stack is a stack of the declaration context
4681    // DIEs all the way back to the compile unit. If a type "T" is
4682    // declared inside a class "B", and class "B" is declared inside
4683    // a class "A" and class "A" is in a namespace "lldb", and the
4684    // namespace is in a compile unit, there will be a stack of DIEs:
4685    //
4686    //   [0] DW_TAG_class_type for "B"
4687    //   [1] DW_TAG_class_type for "A"
4688    //   [2] DW_TAG_namespace  for "lldb"
4689    //   [3] DW_TAG_compile_unit for the source file.
4690    //
4691    // We grab both contexts and make sure that everything matches
4692    // all the way back to the compiler unit.
4693
4694    // First lets grab the decl contexts for both DIEs
4695    die1->GetDeclContextDIEs (this, cu1, decl_ctx_1);
4696    die2->GetDeclContextDIEs (this, cu2, decl_ctx_2);
4697    // Make sure the context arrays have the same size, otherwise
4698    // we are done
4699    const size_t count1 = decl_ctx_1.Size();
4700    const size_t count2 = decl_ctx_2.Size();
4701    if (count1 != count2)
4702        return false;
4703
4704    // Make sure the DW_TAG values match all the way back up the the
4705    // compile unit. If they don't, then we are done.
4706    const DWARFDebugInfoEntry *decl_ctx_die1;
4707    const DWARFDebugInfoEntry *decl_ctx_die2;
4708    size_t i;
4709    for (i=0; i<count1; i++)
4710    {
4711        decl_ctx_die1 = decl_ctx_1.GetDIEPtrAtIndex (i);
4712        decl_ctx_die2 = decl_ctx_2.GetDIEPtrAtIndex (i);
4713        if (decl_ctx_die1->Tag() != decl_ctx_die2->Tag())
4714            return false;
4715    }
4716#if defined LLDB_CONFIGURATION_DEBUG
4717
4718    // Make sure the top item in the decl context die array is always
4719    // DW_TAG_compile_unit. If it isn't then something went wrong in
4720    // the DWARFDebugInfoEntry::GetDeclContextDIEs() function...
4721    assert (decl_ctx_1.GetDIEPtrAtIndex (count1 - 1)->Tag() == DW_TAG_compile_unit);
4722
4723#endif
4724    // Always skip the compile unit when comparing by only iterating up to
4725    // "count - 1". Here we compare the names as we go.
4726    for (i=0; i<count1 - 1; i++)
4727    {
4728        decl_ctx_die1 = decl_ctx_1.GetDIEPtrAtIndex (i);
4729        decl_ctx_die2 = decl_ctx_2.GetDIEPtrAtIndex (i);
4730        const char *name1 = decl_ctx_die1->GetName(this, cu1);
4731        const char *name2 = decl_ctx_die2->GetName(this, cu2);
4732        // If the string was from a DW_FORM_strp, then the pointer will often
4733        // be the same!
4734        if (name1 == name2)
4735            continue;
4736
4737        // Name pointers are not equal, so only compare the strings
4738        // if both are not NULL.
4739        if (name1 && name2)
4740        {
4741            // If the strings don't compare, we are done...
4742            if (strcmp(name1, name2) != 0)
4743                return false;
4744        }
4745        else
4746        {
4747            // One name was NULL while the other wasn't
4748            return false;
4749        }
4750    }
4751    // We made it through all of the checks and the declaration contexts
4752    // are equal.
4753    return true;
4754}
4755
4756// This function can be used when a DIE is found that is a forward declaration
4757// DIE and we want to try and find a type that has the complete definition.
4758// "cu" and "die" must be from this SymbolFileDWARF
4759TypeSP
4760SymbolFileDWARF::FindDefinitionTypeForDIE (DWARFCompileUnit* cu,
4761                                           const DWARFDebugInfoEntry *die,
4762                                           const ConstString &type_name)
4763{
4764    TypeSP type_sp;
4765
4766#if defined (LLDB_CONFIGURATION_DEBUG)
4767    // You can't and shouldn't call this function with a compile unit from
4768    // another SymbolFileDWARF instance.
4769    assert (DebugInfo()->ContainsCompileUnit (cu));
4770#endif
4771
4772    if (cu == NULL || die == NULL || !type_name)
4773        return type_sp;
4774
4775    std::string qualified_name;
4776
4777    Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION|DWARF_LOG_LOOKUPS));
4778    if (log)
4779    {
4780        die->GetQualifiedName(this, cu, qualified_name);
4781        GetObjectFile()->GetModule()->LogMessage (log,
4782                                                  "SymbolFileDWARF::FindDefinitionTypeForDIE(die=0x%8.8x (%s), name='%s')",
4783                                                  die->GetOffset(),
4784                                                  qualified_name.c_str(),
4785                                                  type_name.GetCString());
4786    }
4787
4788    DIEArray die_offsets;
4789
4790    if (m_using_apple_tables)
4791    {
4792        if (m_apple_types_ap.get())
4793        {
4794            const bool has_tag = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeTag);
4795            const bool has_qualified_name_hash = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeQualNameHash);
4796            if (has_tag && has_qualified_name_hash)
4797            {
4798                if (qualified_name.empty())
4799                    die->GetQualifiedName(this, cu, qualified_name);
4800
4801                const uint32_t qualified_name_hash = MappedHash::HashStringUsingDJB (qualified_name.c_str());
4802                if (log)
4803                    GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTagAndQualifiedNameHash()");
4804                m_apple_types_ap->FindByNameAndTagAndQualifiedNameHash (type_name.GetCString(), die->Tag(), qualified_name_hash, die_offsets);
4805            }
4806            else if (has_tag > 1)
4807            {
4808                if (log)
4809                    GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTag()");
4810                m_apple_types_ap->FindByNameAndTag (type_name.GetCString(), die->Tag(), die_offsets);
4811            }
4812            else
4813            {
4814                m_apple_types_ap->FindByName (type_name.GetCString(), die_offsets);
4815            }
4816        }
4817    }
4818    else
4819    {
4820        if (!m_indexed)
4821            Index ();
4822
4823        m_type_index.Find (type_name, die_offsets);
4824    }
4825
4826    const size_t num_matches = die_offsets.size();
4827
4828    const dw_tag_t die_tag = die->Tag();
4829
4830    DWARFCompileUnit* type_cu = NULL;
4831    const DWARFDebugInfoEntry* type_die = NULL;
4832    if (num_matches)
4833    {
4834        DWARFDebugInfo* debug_info = DebugInfo();
4835        for (size_t i=0; i<num_matches; ++i)
4836        {
4837            const dw_offset_t die_offset = die_offsets[i];
4838            type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
4839
4840            if (type_die)
4841            {
4842                bool try_resolving_type = false;
4843
4844                // Don't try and resolve the DIE we are looking for with the DIE itself!
4845                if (type_die != die)
4846                {
4847                    const dw_tag_t type_die_tag = type_die->Tag();
4848                    // Make sure the tags match
4849                    if (type_die_tag == die_tag)
4850                    {
4851                        // The tags match, lets try resolving this type
4852                        try_resolving_type = true;
4853                    }
4854                    else
4855                    {
4856                        // The tags don't match, but we need to watch our for a
4857                        // forward declaration for a struct and ("struct foo")
4858                        // ends up being a class ("class foo { ... };") or
4859                        // vice versa.
4860                        switch (type_die_tag)
4861                        {
4862                        case DW_TAG_class_type:
4863                            // We had a "class foo", see if we ended up with a "struct foo { ... };"
4864                            try_resolving_type = (die_tag == DW_TAG_structure_type);
4865                            break;
4866                        case DW_TAG_structure_type:
4867                            // We had a "struct foo", see if we ended up with a "class foo { ... };"
4868                            try_resolving_type = (die_tag == DW_TAG_class_type);
4869                            break;
4870                        default:
4871                            // Tags don't match, don't event try to resolve
4872                            // using this type whose name matches....
4873                            break;
4874                        }
4875                    }
4876                }
4877
4878                if (try_resolving_type)
4879                {
4880                    if (log)
4881                    {
4882                        std::string qualified_name;
4883                        type_die->GetQualifiedName(this, cu, qualified_name);
4884                        GetObjectFile()->GetModule()->LogMessage (log,
4885                                                                  "SymbolFileDWARF::FindDefinitionTypeForDIE(die=0x%8.8x, name='%s') trying die=0x%8.8x (%s)",
4886                                                                  die->GetOffset(),
4887                                                                  type_name.GetCString(),
4888                                                                  type_die->GetOffset(),
4889                                                                  qualified_name.c_str());
4890                    }
4891
4892                    // Make sure the decl contexts match all the way up
4893                    if (DIEDeclContextsMatch(cu, die, type_cu, type_die))
4894                    {
4895                        Type *resolved_type = ResolveType (type_cu, type_die, false);
4896                        if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
4897                        {
4898                            DEBUG_PRINTF ("resolved 0x%8.8" PRIx64 " (cu 0x%8.8" PRIx64 ") from %s to 0x%8.8" PRIx64 " (cu 0x%8.8" PRIx64 ")\n",
4899                                          MakeUserID(die->GetOffset()),
4900                                          MakeUserID(dwarf_cu->GetOffset()),
4901                                          m_obj_file->GetFileSpec().GetFilename().AsCString(),
4902                                          MakeUserID(type_die->GetOffset()),
4903                                          MakeUserID(type_cu->GetOffset()));
4904
4905                            m_die_to_type[die] = resolved_type;
4906                            type_sp = resolved_type->shared_from_this();
4907                            break;
4908                        }
4909                    }
4910                }
4911                else
4912                {
4913                    if (log)
4914                    {
4915                        std::string qualified_name;
4916                        type_die->GetQualifiedName(this, cu, qualified_name);
4917                        GetObjectFile()->GetModule()->LogMessage (log,
4918                                                                  "SymbolFileDWARF::FindDefinitionTypeForDIE(die=0x%8.8x, name='%s') ignoring die=0x%8.8x (%s)",
4919                                                                  die->GetOffset(),
4920                                                                  type_name.GetCString(),
4921                                                                  type_die->GetOffset(),
4922                                                                  qualified_name.c_str());
4923                    }
4924                }
4925            }
4926            else
4927            {
4928                if (m_using_apple_tables)
4929                {
4930                    GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
4931                                                                               die_offset, type_name.GetCString());
4932                }
4933            }
4934
4935        }
4936    }
4937    return type_sp;
4938}
4939
4940TypeSP
4941SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext (const DWARFDeclContext &dwarf_decl_ctx)
4942{
4943    TypeSP type_sp;
4944
4945    const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
4946    if (dwarf_decl_ctx_count > 0)
4947    {
4948        const ConstString type_name(dwarf_decl_ctx[0].name);
4949        const dw_tag_t tag = dwarf_decl_ctx[0].tag;
4950
4951        if (type_name)
4952        {
4953            Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION|DWARF_LOG_LOOKUPS));
4954            if (log)
4955            {
4956                GetObjectFile()->GetModule()->LogMessage (log,
4957                                                          "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s')",
4958                                                          DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
4959                                                          dwarf_decl_ctx.GetQualifiedName());
4960            }
4961
4962            DIEArray die_offsets;
4963
4964            if (m_using_apple_tables)
4965            {
4966                if (m_apple_types_ap.get())
4967                {
4968                    const bool has_tag = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeTag);
4969                    const bool has_qualified_name_hash = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeQualNameHash);
4970                    if (has_tag && has_qualified_name_hash)
4971                    {
4972                        const char *qualified_name = dwarf_decl_ctx.GetQualifiedName();
4973                        const uint32_t qualified_name_hash = MappedHash::HashStringUsingDJB (qualified_name);
4974                        if (log)
4975                            GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTagAndQualifiedNameHash()");
4976                        m_apple_types_ap->FindByNameAndTagAndQualifiedNameHash (type_name.GetCString(), tag, qualified_name_hash, die_offsets);
4977                    }
4978                    else if (has_tag)
4979                    {
4980                        if (log)
4981                            GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTag()");
4982                        m_apple_types_ap->FindByNameAndTag (type_name.GetCString(), tag, die_offsets);
4983                    }
4984                    else
4985                    {
4986                        m_apple_types_ap->FindByName (type_name.GetCString(), die_offsets);
4987                    }
4988                }
4989            }
4990            else
4991            {
4992                if (!m_indexed)
4993                    Index ();
4994
4995                m_type_index.Find (type_name, die_offsets);
4996            }
4997
4998            const size_t num_matches = die_offsets.size();
4999
5000
5001            DWARFCompileUnit* type_cu = NULL;
5002            const DWARFDebugInfoEntry* type_die = NULL;
5003            if (num_matches)
5004            {
5005                DWARFDebugInfo* debug_info = DebugInfo();
5006                for (size_t i=0; i<num_matches; ++i)
5007                {
5008                    const dw_offset_t die_offset = die_offsets[i];
5009                    type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
5010
5011                    if (type_die)
5012                    {
5013                        bool try_resolving_type = false;
5014
5015                        // Don't try and resolve the DIE we are looking for with the DIE itself!
5016                        const dw_tag_t type_tag = type_die->Tag();
5017                        // Make sure the tags match
5018                        if (type_tag == tag)
5019                        {
5020                            // The tags match, lets try resolving this type
5021                            try_resolving_type = true;
5022                        }
5023                        else
5024                        {
5025                            // The tags don't match, but we need to watch our for a
5026                            // forward declaration for a struct and ("struct foo")
5027                            // ends up being a class ("class foo { ... };") or
5028                            // vice versa.
5029                            switch (type_tag)
5030                            {
5031                                case DW_TAG_class_type:
5032                                    // We had a "class foo", see if we ended up with a "struct foo { ... };"
5033                                    try_resolving_type = (tag == DW_TAG_structure_type);
5034                                    break;
5035                                case DW_TAG_structure_type:
5036                                    // We had a "struct foo", see if we ended up with a "class foo { ... };"
5037                                    try_resolving_type = (tag == DW_TAG_class_type);
5038                                    break;
5039                                default:
5040                                    // Tags don't match, don't event try to resolve
5041                                    // using this type whose name matches....
5042                                    break;
5043                            }
5044                        }
5045
5046                        if (try_resolving_type)
5047                        {
5048                            DWARFDeclContext type_dwarf_decl_ctx;
5049                            type_die->GetDWARFDeclContext (this, type_cu, type_dwarf_decl_ctx);
5050
5051                            if (log)
5052                            {
5053                                GetObjectFile()->GetModule()->LogMessage (log,
5054                                                                          "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') trying die=0x%8.8x (%s)",
5055                                                                          DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
5056                                                                          dwarf_decl_ctx.GetQualifiedName(),
5057                                                                          type_die->GetOffset(),
5058                                                                          type_dwarf_decl_ctx.GetQualifiedName());
5059                            }
5060
5061                            // Make sure the decl contexts match all the way up
5062                            if (dwarf_decl_ctx == type_dwarf_decl_ctx)
5063                            {
5064                                Type *resolved_type = ResolveType (type_cu, type_die, false);
5065                                if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
5066                                {
5067                                    type_sp = resolved_type->shared_from_this();
5068                                    break;
5069                                }
5070                            }
5071                        }
5072                        else
5073                        {
5074                            if (log)
5075                            {
5076                                std::string qualified_name;
5077                                type_die->GetQualifiedName(this, type_cu, qualified_name);
5078                                GetObjectFile()->GetModule()->LogMessage (log,
5079                                                                          "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') ignoring die=0x%8.8x (%s)",
5080                                                                          DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
5081                                                                          dwarf_decl_ctx.GetQualifiedName(),
5082                                                                          type_die->GetOffset(),
5083                                                                          qualified_name.c_str());
5084                            }
5085                        }
5086                    }
5087                    else
5088                    {
5089                        if (m_using_apple_tables)
5090                        {
5091                            GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
5092                                                                                       die_offset, type_name.GetCString());
5093                        }
5094                    }
5095
5096                }
5097            }
5098        }
5099    }
5100    return type_sp;
5101}
5102
5103bool
5104SymbolFileDWARF::CopyUniqueClassMethodTypes (SymbolFileDWARF *src_symfile,
5105                                             Type *class_type,
5106                                             DWARFCompileUnit* src_cu,
5107                                             const DWARFDebugInfoEntry *src_class_die,
5108                                             DWARFCompileUnit* dst_cu,
5109                                             const DWARFDebugInfoEntry *dst_class_die,
5110                                             llvm::SmallVectorImpl <const DWARFDebugInfoEntry *> &failures)
5111{
5112    if (!class_type || !src_cu || !src_class_die || !dst_cu || !dst_class_die)
5113        return false;
5114    if (src_class_die->Tag() != dst_class_die->Tag())
5115        return false;
5116
5117    // We need to complete the class type so we can get all of the method types
5118    // parsed so we can then unique those types to their equivalent counterparts
5119    // in "dst_cu" and "dst_class_die"
5120    class_type->GetClangFullType();
5121
5122    const DWARFDebugInfoEntry *src_die;
5123    const DWARFDebugInfoEntry *dst_die;
5124    UniqueCStringMap<const DWARFDebugInfoEntry *> src_name_to_die;
5125    UniqueCStringMap<const DWARFDebugInfoEntry *> dst_name_to_die;
5126    UniqueCStringMap<const DWARFDebugInfoEntry *> src_name_to_die_artificial;
5127    UniqueCStringMap<const DWARFDebugInfoEntry *> dst_name_to_die_artificial;
5128    for (src_die = src_class_die->GetFirstChild(); src_die != NULL; src_die = src_die->GetSibling())
5129    {
5130        if (src_die->Tag() == DW_TAG_subprogram)
5131        {
5132            // Make sure this is a declaration and not a concrete instance by looking
5133            // for DW_AT_declaration set to 1. Sometimes concrete function instances
5134            // are placed inside the class definitions and shouldn't be included in
5135            // the list of things are are tracking here.
5136            if (src_die->GetAttributeValueAsUnsigned(src_symfile, src_cu, DW_AT_declaration, 0) == 1)
5137            {
5138                const char *src_name = src_die->GetMangledName (src_symfile, src_cu);
5139                if (src_name)
5140                {
5141                    ConstString src_const_name(src_name);
5142                    if (src_die->GetAttributeValueAsUnsigned(src_symfile, src_cu, DW_AT_artificial, 0))
5143                        src_name_to_die_artificial.Append(src_const_name.GetCString(), src_die);
5144                    else
5145                        src_name_to_die.Append(src_const_name.GetCString(), src_die);
5146                }
5147            }
5148        }
5149    }
5150    for (dst_die = dst_class_die->GetFirstChild(); dst_die != NULL; dst_die = dst_die->GetSibling())
5151    {
5152        if (dst_die->Tag() == DW_TAG_subprogram)
5153        {
5154            // Make sure this is a declaration and not a concrete instance by looking
5155            // for DW_AT_declaration set to 1. Sometimes concrete function instances
5156            // are placed inside the class definitions and shouldn't be included in
5157            // the list of things are are tracking here.
5158            if (dst_die->GetAttributeValueAsUnsigned(this, dst_cu, DW_AT_declaration, 0) == 1)
5159            {
5160                const char *dst_name = dst_die->GetMangledName (this, dst_cu);
5161                if (dst_name)
5162                {
5163                    ConstString dst_const_name(dst_name);
5164                    if (dst_die->GetAttributeValueAsUnsigned(this, dst_cu, DW_AT_artificial, 0))
5165                        dst_name_to_die_artificial.Append(dst_const_name.GetCString(), dst_die);
5166                    else
5167                        dst_name_to_die.Append(dst_const_name.GetCString(), dst_die);
5168                }
5169            }
5170        }
5171    }
5172    const uint32_t src_size = src_name_to_die.GetSize ();
5173    const uint32_t dst_size = dst_name_to_die.GetSize ();
5174    Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO | DWARF_LOG_TYPE_COMPLETION));
5175
5176    // Is everything kosher so we can go through the members at top speed?
5177    bool fast_path = true;
5178
5179    if (src_size != dst_size)
5180    {
5181        if (src_size != 0 && dst_size != 0)
5182        {
5183            if (log)
5184                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)",
5185                            src_class_die->GetOffset(),
5186                            dst_class_die->GetOffset(),
5187                            src_size,
5188                            dst_size);
5189        }
5190
5191        fast_path = false;
5192    }
5193
5194    uint32_t idx;
5195
5196    if (fast_path)
5197    {
5198        for (idx = 0; idx < src_size; ++idx)
5199        {
5200            src_die = src_name_to_die.GetValueAtIndexUnchecked (idx);
5201            dst_die = dst_name_to_die.GetValueAtIndexUnchecked (idx);
5202
5203            if (src_die->Tag() != dst_die->Tag())
5204            {
5205                if (log)
5206                    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)",
5207                                src_class_die->GetOffset(),
5208                                dst_class_die->GetOffset(),
5209                                src_die->GetOffset(),
5210                                DW_TAG_value_to_name(src_die->Tag()),
5211                                dst_die->GetOffset(),
5212                                DW_TAG_value_to_name(src_die->Tag()));
5213                fast_path = false;
5214            }
5215
5216            const char *src_name = src_die->GetMangledName (src_symfile, src_cu);
5217            const char *dst_name = dst_die->GetMangledName (this, dst_cu);
5218
5219            // Make sure the names match
5220            if (src_name == dst_name || (strcmp (src_name, dst_name) == 0))
5221                continue;
5222
5223            if (log)
5224                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)",
5225                            src_class_die->GetOffset(),
5226                            dst_class_die->GetOffset(),
5227                            src_die->GetOffset(),
5228                            src_name,
5229                            dst_die->GetOffset(),
5230                            dst_name);
5231
5232            fast_path = false;
5233        }
5234    }
5235
5236    // Now do the work of linking the DeclContexts and Types.
5237    if (fast_path)
5238    {
5239        // We can do this quickly.  Just run across the tables index-for-index since
5240        // we know each node has matching names and tags.
5241        for (idx = 0; idx < src_size; ++idx)
5242        {
5243            src_die = src_name_to_die.GetValueAtIndexUnchecked (idx);
5244            dst_die = dst_name_to_die.GetValueAtIndexUnchecked (idx);
5245
5246            clang::DeclContext *src_decl_ctx = src_symfile->m_die_to_decl_ctx[src_die];
5247            if (src_decl_ctx)
5248            {
5249                if (log)
5250                    log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x", src_decl_ctx, src_die->GetOffset(), dst_die->GetOffset());
5251                LinkDeclContextToDIE (src_decl_ctx, dst_die);
5252            }
5253            else
5254            {
5255                if (log)
5256                    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());
5257            }
5258
5259            Type *src_child_type = m_die_to_type[src_die];
5260            if (src_child_type)
5261            {
5262                if (log)
5263                    log->Printf ("uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x", src_child_type, src_child_type->GetID(), src_die->GetOffset(), dst_die->GetOffset());
5264                m_die_to_type[dst_die] = src_child_type;
5265            }
5266            else
5267            {
5268                if (log)
5269                    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());
5270            }
5271        }
5272    }
5273    else
5274    {
5275        // We must do this slowly.  For each member of the destination, look
5276        // up a member in the source with the same name, check its tag, and
5277        // unique them if everything matches up.  Report failures.
5278
5279        if (!src_name_to_die.IsEmpty() && !dst_name_to_die.IsEmpty())
5280        {
5281            src_name_to_die.Sort();
5282
5283            for (idx = 0; idx < dst_size; ++idx)
5284            {
5285                const char *dst_name = dst_name_to_die.GetCStringAtIndex(idx);
5286                dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
5287                src_die = src_name_to_die.Find(dst_name, NULL);
5288
5289                if (src_die && (src_die->Tag() == dst_die->Tag()))
5290                {
5291                    clang::DeclContext *src_decl_ctx = src_symfile->m_die_to_decl_ctx[src_die];
5292                    if (src_decl_ctx)
5293                    {
5294                        if (log)
5295                            log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x", src_decl_ctx, src_die->GetOffset(), dst_die->GetOffset());
5296                        LinkDeclContextToDIE (src_decl_ctx, dst_die);
5297                    }
5298                    else
5299                    {
5300                        if (log)
5301                            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());
5302                    }
5303
5304                    Type *src_child_type = m_die_to_type[src_die];
5305                    if (src_child_type)
5306                    {
5307                        if (log)
5308                            log->Printf ("uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x", src_child_type, src_child_type->GetID(), src_die->GetOffset(), dst_die->GetOffset());
5309                        m_die_to_type[dst_die] = src_child_type;
5310                    }
5311                    else
5312                    {
5313                        if (log)
5314                            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());
5315                    }
5316                }
5317                else
5318                {
5319                    if (log)
5320                        log->Printf ("warning: couldn't find a match for 0x%8.8x", dst_die->GetOffset());
5321
5322                    failures.push_back(dst_die);
5323                }
5324            }
5325        }
5326    }
5327
5328    const uint32_t src_size_artificial = src_name_to_die_artificial.GetSize ();
5329    const uint32_t dst_size_artificial = dst_name_to_die_artificial.GetSize ();
5330
5331    UniqueCStringMap<const DWARFDebugInfoEntry *> name_to_die_artificial_not_in_src;
5332
5333    if (src_size_artificial && dst_size_artificial)
5334    {
5335        dst_name_to_die_artificial.Sort();
5336
5337        for (idx = 0; idx < src_size_artificial; ++idx)
5338        {
5339            const char *src_name_artificial = src_name_to_die_artificial.GetCStringAtIndex(idx);
5340            src_die = src_name_to_die_artificial.GetValueAtIndexUnchecked (idx);
5341            dst_die = dst_name_to_die_artificial.Find(src_name_artificial, NULL);
5342
5343            if (dst_die)
5344            {
5345                // Both classes have the artificial types, link them
5346                clang::DeclContext *src_decl_ctx = m_die_to_decl_ctx[src_die];
5347                if (src_decl_ctx)
5348                {
5349                    if (log)
5350                        log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x", src_decl_ctx, src_die->GetOffset(), dst_die->GetOffset());
5351                    LinkDeclContextToDIE (src_decl_ctx, dst_die);
5352                }
5353                else
5354                {
5355                    if (log)
5356                        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());
5357                }
5358
5359                Type *src_child_type = m_die_to_type[src_die];
5360                if (src_child_type)
5361                {
5362                    if (log)
5363                        log->Printf ("uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x", src_child_type, src_child_type->GetID(), src_die->GetOffset(), dst_die->GetOffset());
5364                    m_die_to_type[dst_die] = src_child_type;
5365                }
5366                else
5367                {
5368                    if (log)
5369                        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());
5370                }
5371            }
5372        }
5373    }
5374
5375    if (dst_size_artificial)
5376    {
5377        for (idx = 0; idx < dst_size_artificial; ++idx)
5378        {
5379            const char *dst_name_artificial = dst_name_to_die_artificial.GetCStringAtIndex(idx);
5380            dst_die = dst_name_to_die_artificial.GetValueAtIndexUnchecked (idx);
5381            if (log)
5382                log->Printf ("warning: need to create artificial method for 0x%8.8x for method '%s'", dst_die->GetOffset(), dst_name_artificial);
5383
5384            failures.push_back(dst_die);
5385        }
5386    }
5387
5388    return (failures.size() != 0);
5389}
5390
5391TypeSP
5392SymbolFileDWARF::ParseType (const SymbolContext& sc, DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry *die, bool *type_is_new_ptr)
5393{
5394    TypeSP type_sp;
5395
5396    if (type_is_new_ptr)
5397        *type_is_new_ptr = false;
5398
5399#if defined(LLDB_CONFIGURATION_DEBUG) or defined(LLDB_CONFIGURATION_RELEASE)
5400    static DIEStack g_die_stack;
5401    DIEStack::ScopedPopper scoped_die_logger(g_die_stack);
5402#endif
5403
5404    AccessType accessibility = eAccessNone;
5405    if (die != NULL)
5406    {
5407        Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
5408        if (log)
5409        {
5410            const DWARFDebugInfoEntry *context_die;
5411            clang::DeclContext *context = GetClangDeclContextContainingDIE (dwarf_cu, die, &context_die);
5412
5413            GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x, decl_ctx = %p (die 0x%8.8x)) %s name = '%s')",
5414                        die->GetOffset(),
5415                        context,
5416                        context_die->GetOffset(),
5417                        DW_TAG_value_to_name(die->Tag()),
5418                        die->GetName(this, dwarf_cu));
5419
5420#if defined(LLDB_CONFIGURATION_DEBUG) or defined(LLDB_CONFIGURATION_RELEASE)
5421            scoped_die_logger.Push (dwarf_cu, die);
5422            g_die_stack.LogDIEs(log, this);
5423#endif
5424        }
5425//
5426//        Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
5427//        if (log && dwarf_cu)
5428//        {
5429//            StreamString s;
5430//            die->DumpLocation (this, dwarf_cu, s);
5431//            GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDwarf::%s %s", __FUNCTION__, s.GetData());
5432//
5433//        }
5434
5435        Type *type_ptr = m_die_to_type.lookup (die);
5436        TypeList* type_list = GetTypeList();
5437        if (type_ptr == NULL)
5438        {
5439            ClangASTContext &ast = GetClangASTContext();
5440            if (type_is_new_ptr)
5441                *type_is_new_ptr = true;
5442
5443            const dw_tag_t tag = die->Tag();
5444
5445            bool is_forward_declaration = false;
5446            DWARFDebugInfoEntry::Attributes attributes;
5447            const char *type_name_cstr = NULL;
5448            ConstString type_name_const_str;
5449            Type::ResolveState resolve_state = Type::eResolveStateUnresolved;
5450            uint64_t byte_size = 0;
5451            Declaration decl;
5452
5453            Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID;
5454            clang_type_t clang_type = NULL;
5455
5456            dw_attr_t attr;
5457
5458            switch (tag)
5459            {
5460            case DW_TAG_base_type:
5461            case DW_TAG_pointer_type:
5462            case DW_TAG_reference_type:
5463            case DW_TAG_rvalue_reference_type:
5464            case DW_TAG_typedef:
5465            case DW_TAG_const_type:
5466            case DW_TAG_restrict_type:
5467            case DW_TAG_volatile_type:
5468            case DW_TAG_unspecified_type:
5469                {
5470                    // Set a bit that lets us know that we are currently parsing this
5471                    m_die_to_type[die] = DIE_IS_BEING_PARSED;
5472
5473                    const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
5474                    uint32_t encoding = 0;
5475                    lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
5476
5477                    if (num_attributes > 0)
5478                    {
5479                        uint32_t i;
5480                        for (i=0; i<num_attributes; ++i)
5481                        {
5482                            attr = attributes.AttributeAtIndex(i);
5483                            DWARFFormValue form_value;
5484                            if (attributes.ExtractFormValueAtIndex(this, i, form_value))
5485                            {
5486                                switch (attr)
5487                                {
5488                                case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
5489                                case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
5490                                case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
5491                                case DW_AT_name:
5492
5493                                    type_name_cstr = form_value.AsCString(&get_debug_str_data());
5494                                    // Work around a bug in llvm-gcc where they give a name to a reference type which doesn't
5495                                    // include the "&"...
5496                                    if (tag == DW_TAG_reference_type)
5497                                    {
5498                                        if (strchr (type_name_cstr, '&') == NULL)
5499                                            type_name_cstr = NULL;
5500                                    }
5501                                    if (type_name_cstr)
5502                                        type_name_const_str.SetCString(type_name_cstr);
5503                                    break;
5504                                case DW_AT_byte_size:   byte_size = form_value.Unsigned(); break;
5505                                case DW_AT_encoding:    encoding = form_value.Unsigned(); break;
5506                                case DW_AT_type:        encoding_uid = form_value.Reference(dwarf_cu); break;
5507                                default:
5508                                case DW_AT_sibling:
5509                                    break;
5510                                }
5511                            }
5512                        }
5513                    }
5514
5515                    DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\") type => 0x%8.8x\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr, encoding_uid);
5516
5517                    switch (tag)
5518                    {
5519                    default:
5520                        break;
5521
5522                    case DW_TAG_unspecified_type:
5523                        if (strcmp(type_name_cstr, "nullptr_t") == 0)
5524                        {
5525                            resolve_state = Type::eResolveStateFull;
5526                            clang_type = ast.getASTContext()->NullPtrTy.getAsOpaquePtr();
5527                            break;
5528                        }
5529                        // Fall through to base type below in case we can handle the type there...
5530
5531                    case DW_TAG_base_type:
5532                        resolve_state = Type::eResolveStateFull;
5533                        clang_type = ast.GetBuiltinTypeForDWARFEncodingAndBitSize (type_name_cstr,
5534                                                                                   encoding,
5535                                                                                   byte_size * 8);
5536                        break;
5537
5538                    case DW_TAG_pointer_type:           encoding_data_type = Type::eEncodingIsPointerUID;           break;
5539                    case DW_TAG_reference_type:         encoding_data_type = Type::eEncodingIsLValueReferenceUID;   break;
5540                    case DW_TAG_rvalue_reference_type:  encoding_data_type = Type::eEncodingIsRValueReferenceUID;   break;
5541                    case DW_TAG_typedef:                encoding_data_type = Type::eEncodingIsTypedefUID;           break;
5542                    case DW_TAG_const_type:             encoding_data_type = Type::eEncodingIsConstUID;             break;
5543                    case DW_TAG_restrict_type:          encoding_data_type = Type::eEncodingIsRestrictUID;          break;
5544                    case DW_TAG_volatile_type:          encoding_data_type = Type::eEncodingIsVolatileUID;          break;
5545                    }
5546
5547                    if (clang_type == NULL && (encoding_data_type == Type::eEncodingIsPointerUID || encoding_data_type == Type::eEncodingIsTypedefUID) && sc.comp_unit != NULL)
5548                    {
5549                        bool translation_unit_is_objc = (sc.comp_unit->GetLanguage() == eLanguageTypeObjC || sc.comp_unit->GetLanguage() == eLanguageTypeObjC_plus_plus);
5550
5551                        if (translation_unit_is_objc)
5552                        {
5553                            if (type_name_cstr != NULL)
5554                            {
5555                                static ConstString g_objc_type_name_id("id");
5556                                static ConstString g_objc_type_name_Class("Class");
5557                                static ConstString g_objc_type_name_selector("SEL");
5558
5559                                if (type_name_const_str == g_objc_type_name_id)
5560                                {
5561                                    if (log)
5562                                        GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'id' built-in type.",
5563                                                                                  die->GetOffset(),
5564                                                                                  DW_TAG_value_to_name(die->Tag()),
5565                                                                                  die->GetName(this, dwarf_cu));
5566                                    clang_type = ast.GetBuiltInType_objc_id();
5567                                    encoding_data_type = Type::eEncodingIsUID;
5568                                    encoding_uid = LLDB_INVALID_UID;
5569                                    resolve_state = Type::eResolveStateFull;
5570
5571                                }
5572                                else if (type_name_const_str == g_objc_type_name_Class)
5573                                {
5574                                    if (log)
5575                                        GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'Class' built-in type.",
5576                                                                                  die->GetOffset(),
5577                                                                                  DW_TAG_value_to_name(die->Tag()),
5578                                                                                  die->GetName(this, dwarf_cu));
5579                                    clang_type = ast.GetBuiltInType_objc_Class();
5580                                    encoding_data_type = Type::eEncodingIsUID;
5581                                    encoding_uid = LLDB_INVALID_UID;
5582                                    resolve_state = Type::eResolveStateFull;
5583                                }
5584                                else if (type_name_const_str == g_objc_type_name_selector)
5585                                {
5586                                    if (log)
5587                                        GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'selector' built-in type.",
5588                                                                                  die->GetOffset(),
5589                                                                                  DW_TAG_value_to_name(die->Tag()),
5590                                                                                  die->GetName(this, dwarf_cu));
5591                                    clang_type = ast.GetBuiltInType_objc_selector();
5592                                    encoding_data_type = Type::eEncodingIsUID;
5593                                    encoding_uid = LLDB_INVALID_UID;
5594                                    resolve_state = Type::eResolveStateFull;
5595                                }
5596                            }
5597                            else if (encoding_data_type == Type::eEncodingIsPointerUID && encoding_uid != LLDB_INVALID_UID)
5598                            {
5599                                // Clang sometimes erroneously emits id as objc_object*.  In that case we fix up the type to "id".
5600
5601                                DWARFDebugInfoEntry* encoding_die = dwarf_cu->GetDIEPtr(encoding_uid);
5602
5603                                if (encoding_die && encoding_die->Tag() == DW_TAG_structure_type)
5604                                {
5605                                    if (const char *struct_name = encoding_die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_name, NULL))
5606                                    {
5607                                        if (!strcmp(struct_name, "objc_object"))
5608                                        {
5609                                            if (log)
5610                                                GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is 'objc_object*', which we overrode to 'id'.",
5611                                                                                          die->GetOffset(),
5612                                                                                          DW_TAG_value_to_name(die->Tag()),
5613                                                                                          die->GetName(this, dwarf_cu));
5614                                            clang_type = ast.GetBuiltInType_objc_id();
5615                                            encoding_data_type = Type::eEncodingIsUID;
5616                                            encoding_uid = LLDB_INVALID_UID;
5617                                            resolve_state = Type::eResolveStateFull;
5618                                        }
5619                                    }
5620                                }
5621                            }
5622                        }
5623                    }
5624
5625                    type_sp.reset( new Type (MakeUserID(die->GetOffset()),
5626                                             this,
5627                                             type_name_const_str,
5628                                             byte_size,
5629                                             NULL,
5630                                             encoding_uid,
5631                                             encoding_data_type,
5632                                             &decl,
5633                                             clang_type,
5634                                             resolve_state));
5635
5636                    m_die_to_type[die] = type_sp.get();
5637
5638//                  Type* encoding_type = GetUniquedTypeForDIEOffset(encoding_uid, type_sp, NULL, 0, 0, false);
5639//                  if (encoding_type != NULL)
5640//                  {
5641//                      if (encoding_type != DIE_IS_BEING_PARSED)
5642//                          type_sp->SetEncodingType(encoding_type);
5643//                      else
5644//                          m_indirect_fixups.push_back(type_sp.get());
5645//                  }
5646                }
5647                break;
5648
5649            case DW_TAG_structure_type:
5650            case DW_TAG_union_type:
5651            case DW_TAG_class_type:
5652                {
5653                    // Set a bit that lets us know that we are currently parsing this
5654                    m_die_to_type[die] = DIE_IS_BEING_PARSED;
5655                    bool byte_size_valid = false;
5656
5657                    LanguageType class_language = eLanguageTypeUnknown;
5658                    bool is_complete_objc_class = false;
5659                    //bool struct_is_class = false;
5660                    const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
5661                    if (num_attributes > 0)
5662                    {
5663                        uint32_t i;
5664                        for (i=0; i<num_attributes; ++i)
5665                        {
5666                            attr = attributes.AttributeAtIndex(i);
5667                            DWARFFormValue form_value;
5668                            if (attributes.ExtractFormValueAtIndex(this, i, form_value))
5669                            {
5670                                switch (attr)
5671                                {
5672                                case DW_AT_decl_file:
5673                                    if (dwarf_cu->DW_AT_decl_file_attributes_are_invalid())
5674									{
5675										// llvm-gcc outputs invalid DW_AT_decl_file attributes that always
5676										// point to the compile unit file, so we clear this invalid value
5677										// so that we can still unique types efficiently.
5678                                        decl.SetFile(FileSpec ("<invalid>", false));
5679									}
5680                                    else
5681                                        decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned()));
5682                                    break;
5683
5684                                case DW_AT_decl_line:
5685                                    decl.SetLine(form_value.Unsigned());
5686                                    break;
5687
5688                                case DW_AT_decl_column:
5689                                    decl.SetColumn(form_value.Unsigned());
5690                                    break;
5691
5692                                case DW_AT_name:
5693                                    type_name_cstr = form_value.AsCString(&get_debug_str_data());
5694                                    type_name_const_str.SetCString(type_name_cstr);
5695                                    break;
5696
5697                                case DW_AT_byte_size:
5698                                    byte_size = form_value.Unsigned();
5699                                    byte_size_valid = true;
5700                                    break;
5701
5702                                case DW_AT_accessibility:
5703                                    accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
5704                                    break;
5705
5706                                case DW_AT_declaration:
5707                                    is_forward_declaration = form_value.Boolean();
5708                                    break;
5709
5710                                case DW_AT_APPLE_runtime_class:
5711                                    class_language = (LanguageType)form_value.Signed();
5712                                    break;
5713
5714                                case DW_AT_APPLE_objc_complete_type:
5715                                    is_complete_objc_class = form_value.Signed();
5716                                    break;
5717
5718                                case DW_AT_allocated:
5719                                case DW_AT_associated:
5720                                case DW_AT_data_location:
5721                                case DW_AT_description:
5722                                case DW_AT_start_scope:
5723                                case DW_AT_visibility:
5724                                default:
5725                                case DW_AT_sibling:
5726                                    break;
5727                                }
5728                            }
5729                        }
5730                    }
5731
5732                    UniqueDWARFASTType unique_ast_entry;
5733
5734                    // Only try and unique the type if it has a name.
5735                    if (type_name_const_str &&
5736                        GetUniqueDWARFASTTypeMap().Find (type_name_const_str,
5737                                                         this,
5738                                                         dwarf_cu,
5739                                                         die,
5740                                                         decl,
5741                                                         byte_size_valid ? byte_size : -1,
5742                                                         unique_ast_entry))
5743                    {
5744                        // We have already parsed this type or from another
5745                        // compile unit. GCC loves to use the "one definition
5746                        // rule" which can result in multiple definitions
5747                        // of the same class over and over in each compile
5748                        // unit.
5749                        type_sp = unique_ast_entry.m_type_sp;
5750                        if (type_sp)
5751                        {
5752                            m_die_to_type[die] = type_sp.get();
5753                            return type_sp;
5754                        }
5755                    }
5756
5757                    DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
5758
5759                    int tag_decl_kind = -1;
5760                    AccessType default_accessibility = eAccessNone;
5761                    if (tag == DW_TAG_structure_type)
5762                    {
5763                        tag_decl_kind = clang::TTK_Struct;
5764                        default_accessibility = eAccessPublic;
5765                    }
5766                    else if (tag == DW_TAG_union_type)
5767                    {
5768                        tag_decl_kind = clang::TTK_Union;
5769                        default_accessibility = eAccessPublic;
5770                    }
5771                    else if (tag == DW_TAG_class_type)
5772                    {
5773                        tag_decl_kind = clang::TTK_Class;
5774                        default_accessibility = eAccessPrivate;
5775                    }
5776
5777                    if (byte_size_valid && byte_size == 0 && type_name_cstr &&
5778                        die->HasChildren() == false &&
5779                        sc.comp_unit->GetLanguage() == eLanguageTypeObjC)
5780                    {
5781                        // Work around an issue with clang at the moment where
5782                        // forward declarations for objective C classes are emitted
5783                        // as:
5784                        //  DW_TAG_structure_type [2]
5785                        //  DW_AT_name( "ForwardObjcClass" )
5786                        //  DW_AT_byte_size( 0x00 )
5787                        //  DW_AT_decl_file( "..." )
5788                        //  DW_AT_decl_line( 1 )
5789                        //
5790                        // Note that there is no DW_AT_declaration and there are
5791                        // no children, and the byte size is zero.
5792                        is_forward_declaration = true;
5793                    }
5794
5795                    if (class_language == eLanguageTypeObjC ||
5796                        class_language == eLanguageTypeObjC_plus_plus)
5797                    {
5798                        if (!is_complete_objc_class && Supports_DW_AT_APPLE_objc_complete_type(dwarf_cu))
5799                        {
5800                            // We have a valid eSymbolTypeObjCClass class symbol whose
5801                            // name matches the current objective C class that we
5802                            // are trying to find and this DIE isn't the complete
5803                            // definition (we checked is_complete_objc_class above and
5804                            // know it is false), so the real definition is in here somewhere
5805                            type_sp = FindCompleteObjCDefinitionTypeForDIE (die, type_name_const_str, true);
5806
5807                            if (!type_sp && GetDebugMapSymfile ())
5808                            {
5809                                // We weren't able to find a full declaration in
5810                                // this DWARF, see if we have a declaration anywhere
5811                                // else...
5812                                type_sp = m_debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE (die, type_name_const_str, true);
5813                            }
5814
5815                            if (type_sp)
5816                            {
5817                                if (log)
5818                                {
5819                                    GetObjectFile()->GetModule()->LogMessage (log,
5820                                                                              "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is an incomplete objc type, complete type is 0x%8.8" PRIx64,
5821                                                                              this,
5822                                                                              die->GetOffset(),
5823                                                                              DW_TAG_value_to_name(tag),
5824                                                                              type_name_cstr,
5825                                                                              type_sp->GetID());
5826                                }
5827
5828                                // We found a real definition for this type elsewhere
5829                                // so lets use it and cache the fact that we found
5830                                // a complete type for this die
5831                                m_die_to_type[die] = type_sp.get();
5832                                return type_sp;
5833                            }
5834                        }
5835                    }
5836
5837
5838                    if (is_forward_declaration)
5839                    {
5840                        // We have a forward declaration to a type and we need
5841                        // to try and find a full declaration. We look in the
5842                        // current type index just in case we have a forward
5843                        // declaration followed by an actual declarations in the
5844                        // DWARF. If this fails, we need to look elsewhere...
5845                        if (log)
5846                        {
5847                            GetObjectFile()->GetModule()->LogMessage (log,
5848                                                                      "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a forward declaration, trying to find complete type",
5849                                                                      this,
5850                                                                      die->GetOffset(),
5851                                                                      DW_TAG_value_to_name(tag),
5852                                                                      type_name_cstr);
5853                        }
5854
5855                        DWARFDeclContext die_decl_ctx;
5856                        die->GetDWARFDeclContext(this, dwarf_cu, die_decl_ctx);
5857
5858                        //type_sp = FindDefinitionTypeForDIE (dwarf_cu, die, type_name_const_str);
5859                        type_sp = FindDefinitionTypeForDWARFDeclContext (die_decl_ctx);
5860
5861                        if (!type_sp && GetDebugMapSymfile ())
5862                        {
5863                            // We weren't able to find a full declaration in
5864                            // this DWARF, see if we have a declaration anywhere
5865                            // else...
5866                            type_sp = m_debug_map_symfile->FindDefinitionTypeForDWARFDeclContext (die_decl_ctx);
5867                        }
5868
5869                        if (type_sp)
5870                        {
5871                            if (log)
5872                            {
5873                                GetObjectFile()->GetModule()->LogMessage (log,
5874                                                                          "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a forward declaration, complete type is 0x%8.8" PRIx64,
5875                                                                          this,
5876                                                                          die->GetOffset(),
5877                                                                          DW_TAG_value_to_name(tag),
5878                                                                          type_name_cstr,
5879                                                                          type_sp->GetID());
5880                            }
5881
5882                            // We found a real definition for this type elsewhere
5883                            // so lets use it and cache the fact that we found
5884                            // a complete type for this die
5885                            m_die_to_type[die] = type_sp.get();
5886                            return type_sp;
5887                        }
5888                    }
5889                    assert (tag_decl_kind != -1);
5890                    bool clang_type_was_created = false;
5891                    clang_type = m_forward_decl_die_to_clang_type.lookup (die);
5892                    if (clang_type == NULL)
5893                    {
5894                        const DWARFDebugInfoEntry *decl_ctx_die;
5895
5896                        clang::DeclContext *decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, &decl_ctx_die);
5897                        if (accessibility == eAccessNone && decl_ctx)
5898                        {
5899                            // Check the decl context that contains this class/struct/union.
5900                            // If it is a class we must give it an accessability.
5901                            const clang::Decl::Kind containing_decl_kind = decl_ctx->getDeclKind();
5902                            if (DeclKindIsCXXClass (containing_decl_kind))
5903                                accessibility = default_accessibility;
5904                        }
5905
5906                        ClangASTMetadata metadata;
5907                        metadata.SetUserID(MakeUserID(die->GetOffset()));
5908                        metadata.SetIsDynamicCXXType(ClassOrStructIsVirtual (dwarf_cu, die));
5909
5910                        if (type_name_cstr && strchr (type_name_cstr, '<'))
5911                        {
5912                            ClangASTContext::TemplateParameterInfos template_param_infos;
5913                            if (ParseTemplateParameterInfos (dwarf_cu, die, template_param_infos))
5914                            {
5915                                clang::ClassTemplateDecl *class_template_decl = ParseClassTemplateDecl (decl_ctx,
5916                                                                                                        accessibility,
5917                                                                                                        type_name_cstr,
5918                                                                                                        tag_decl_kind,
5919                                                                                                        template_param_infos);
5920
5921                                clang::ClassTemplateSpecializationDecl *class_specialization_decl = ast.CreateClassTemplateSpecializationDecl (decl_ctx,
5922                                                                                                                                               class_template_decl,
5923                                                                                                                                               tag_decl_kind,
5924                                                                                                                                               template_param_infos);
5925                                clang_type = ast.CreateClassTemplateSpecializationType (class_specialization_decl);
5926                                clang_type_was_created = true;
5927
5928                                GetClangASTContext().SetMetadata (class_template_decl, metadata);
5929                                GetClangASTContext().SetMetadata (class_specialization_decl, metadata);
5930                            }
5931                        }
5932
5933                        if (!clang_type_was_created)
5934                        {
5935                            clang_type_was_created = true;
5936                            clang_type = ast.CreateRecordType (decl_ctx,
5937                                                               accessibility,
5938                                                               type_name_cstr,
5939                                                               tag_decl_kind,
5940                                                               class_language,
5941                                                               &metadata);
5942                        }
5943                    }
5944
5945                    // Store a forward declaration to this class type in case any
5946                    // parameters in any class methods need it for the clang
5947                    // types for function prototypes.
5948                    LinkDeclContextToDIE(ClangASTContext::GetDeclContextForType(clang_type), die);
5949                    type_sp.reset (new Type (MakeUserID(die->GetOffset()),
5950                                             this,
5951                                             type_name_const_str,
5952                                             byte_size,
5953                                             NULL,
5954                                             LLDB_INVALID_UID,
5955                                             Type::eEncodingIsUID,
5956                                             &decl,
5957                                             clang_type,
5958                                             Type::eResolveStateForward));
5959
5960                    type_sp->SetIsCompleteObjCClass(is_complete_objc_class);
5961
5962
5963                    // Add our type to the unique type map so we don't
5964                    // end up creating many copies of the same type over
5965                    // and over in the ASTContext for our module
5966                    unique_ast_entry.m_type_sp = type_sp;
5967                    unique_ast_entry.m_symfile = this;
5968                    unique_ast_entry.m_cu = dwarf_cu;
5969                    unique_ast_entry.m_die = die;
5970                    unique_ast_entry.m_declaration = decl;
5971                    unique_ast_entry.m_byte_size = byte_size;
5972                    GetUniqueDWARFASTTypeMap().Insert (type_name_const_str,
5973                                                       unique_ast_entry);
5974
5975                    if (!is_forward_declaration)
5976                    {
5977                        // Always start the definition for a class type so that
5978                        // if the class has child classes or types that require
5979                        // the class to be created for use as their decl contexts
5980                        // the class will be ready to accept these child definitions.
5981                        if (die->HasChildren() == false)
5982                        {
5983                            // No children for this struct/union/class, lets finish it
5984                            ast.StartTagDeclarationDefinition (clang_type);
5985                            ast.CompleteTagDeclarationDefinition (clang_type);
5986
5987                            if (tag == DW_TAG_structure_type) // this only applies in C
5988                            {
5989                                clang::QualType qual_type = clang::QualType::getFromOpaquePtr (clang_type);
5990                                const clang::RecordType *record_type = qual_type->getAs<clang::RecordType> ();
5991
5992                                if (record_type)
5993                                {
5994                                    clang::RecordDecl *record_decl = record_type->getDecl();
5995
5996                                    if (record_decl)
5997                                    {
5998                                        LayoutInfo layout_info;
5999
6000                                        layout_info.alignment = 0;
6001                                        layout_info.bit_size = 0;
6002
6003                                        m_record_decl_to_layout_map.insert(std::make_pair(record_decl, layout_info));
6004                                    }
6005                                }
6006                            }
6007                        }
6008                        else if (clang_type_was_created)
6009                        {
6010                            // Start the definition if the class is not objective C since
6011                            // the underlying decls respond to isCompleteDefinition(). Objective
6012                            // C decls dont' respond to isCompleteDefinition() so we can't
6013                            // start the declaration definition right away. For C++ classs/union/structs
6014                            // we want to start the definition in case the class is needed as the
6015                            // declaration context for a contained class or type without the need
6016                            // to complete that type..
6017
6018                            if (class_language != eLanguageTypeObjC &&
6019                                class_language != eLanguageTypeObjC_plus_plus)
6020                                ast.StartTagDeclarationDefinition (clang_type);
6021
6022                            // Leave this as a forward declaration until we need
6023                            // to know the details of the type. lldb_private::Type
6024                            // will automatically call the SymbolFile virtual function
6025                            // "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition(Type *)"
6026                            // When the definition needs to be defined.
6027                            m_forward_decl_die_to_clang_type[die] = clang_type;
6028                            m_forward_decl_clang_type_to_die[ClangASTType::RemoveFastQualifiers (clang_type)] = die;
6029                            ClangASTContext::SetHasExternalStorage (clang_type, true);
6030                        }
6031                    }
6032
6033                }
6034                break;
6035
6036            case DW_TAG_enumeration_type:
6037                {
6038                    // Set a bit that lets us know that we are currently parsing this
6039                    m_die_to_type[die] = DIE_IS_BEING_PARSED;
6040
6041                    lldb::user_id_t encoding_uid = DW_INVALID_OFFSET;
6042
6043                    const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6044                    if (num_attributes > 0)
6045                    {
6046                        uint32_t i;
6047
6048                        for (i=0; i<num_attributes; ++i)
6049                        {
6050                            attr = attributes.AttributeAtIndex(i);
6051                            DWARFFormValue form_value;
6052                            if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6053                            {
6054                                switch (attr)
6055                                {
6056                                case DW_AT_decl_file:       decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6057                                case DW_AT_decl_line:       decl.SetLine(form_value.Unsigned()); break;
6058                                case DW_AT_decl_column:     decl.SetColumn(form_value.Unsigned()); break;
6059                                case DW_AT_name:
6060                                    type_name_cstr = form_value.AsCString(&get_debug_str_data());
6061                                    type_name_const_str.SetCString(type_name_cstr);
6062                                    break;
6063                                case DW_AT_type:            encoding_uid = form_value.Reference(dwarf_cu); break;
6064                                case DW_AT_byte_size:       byte_size = form_value.Unsigned(); break;
6065                                case DW_AT_accessibility:   break; //accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6066                                case DW_AT_declaration:     break; //is_forward_declaration = form_value.Boolean(); break;
6067                                case DW_AT_allocated:
6068                                case DW_AT_associated:
6069                                case DW_AT_bit_stride:
6070                                case DW_AT_byte_stride:
6071                                case DW_AT_data_location:
6072                                case DW_AT_description:
6073                                case DW_AT_start_scope:
6074                                case DW_AT_visibility:
6075                                case DW_AT_specification:
6076                                case DW_AT_abstract_origin:
6077                                case DW_AT_sibling:
6078                                    break;
6079                                }
6080                            }
6081                        }
6082
6083                        DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6084
6085                        clang_type_t enumerator_clang_type = NULL;
6086                        clang_type = m_forward_decl_die_to_clang_type.lookup (die);
6087                        if (clang_type == NULL)
6088                        {
6089                            if (encoding_uid != DW_INVALID_OFFSET)
6090                            {
6091                                Type *enumerator_type = ResolveTypeUID(encoding_uid);
6092                                if (enumerator_type)
6093                                    enumerator_clang_type = enumerator_type->GetClangFullType();
6094                            }
6095
6096                            if (enumerator_clang_type == NULL)
6097                                enumerator_clang_type = ast.GetBuiltinTypeForDWARFEncodingAndBitSize (NULL,
6098                                                                                                      DW_ATE_signed,
6099                                                                                                      byte_size * 8);
6100
6101                            clang_type = ast.CreateEnumerationType (type_name_cstr,
6102                                                                    GetClangDeclContextContainingDIE (dwarf_cu, die, NULL),
6103                                                                    decl,
6104                                                                    enumerator_clang_type);
6105                        }
6106                        else
6107                        {
6108                            enumerator_clang_type = ClangASTContext::GetEnumerationIntegerType (clang_type);
6109                        }
6110
6111                        LinkDeclContextToDIE(ClangASTContext::GetDeclContextForType(clang_type), die);
6112
6113                        type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6114                                                 this,
6115                                                 type_name_const_str,
6116                                                 byte_size,
6117                                                 NULL,
6118                                                 encoding_uid,
6119                                                 Type::eEncodingIsUID,
6120                                                 &decl,
6121                                                 clang_type,
6122                                                 Type::eResolveStateForward));
6123
6124                        ast.StartTagDeclarationDefinition (clang_type);
6125                        if (die->HasChildren())
6126                        {
6127                            SymbolContext cu_sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
6128                            bool is_signed = false;
6129                            ast.IsIntegerType(enumerator_clang_type, is_signed);
6130                            ParseChildEnumerators(cu_sc, clang_type, is_signed, type_sp->GetByteSize(), dwarf_cu, die);
6131                        }
6132                        ast.CompleteTagDeclarationDefinition (clang_type);
6133                    }
6134                }
6135                break;
6136
6137            case DW_TAG_inlined_subroutine:
6138            case DW_TAG_subprogram:
6139            case DW_TAG_subroutine_type:
6140                {
6141                    // Set a bit that lets us know that we are currently parsing this
6142                    m_die_to_type[die] = DIE_IS_BEING_PARSED;
6143
6144                    //const char *mangled = NULL;
6145                    dw_offset_t type_die_offset = DW_INVALID_OFFSET;
6146                    bool is_variadic = false;
6147                    bool is_inline = false;
6148                    bool is_static = false;
6149                    bool is_virtual = false;
6150                    bool is_explicit = false;
6151                    bool is_artificial = false;
6152                    dw_offset_t specification_die_offset = DW_INVALID_OFFSET;
6153                    dw_offset_t abstract_origin_die_offset = DW_INVALID_OFFSET;
6154                    dw_offset_t object_pointer_die_offset = DW_INVALID_OFFSET;
6155
6156                    unsigned type_quals = 0;
6157                    clang::StorageClass storage = clang::SC_None;//, Extern, Static, PrivateExtern
6158
6159
6160                    const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6161                    if (num_attributes > 0)
6162                    {
6163                        uint32_t i;
6164                        for (i=0; i<num_attributes; ++i)
6165                        {
6166                            attr = attributes.AttributeAtIndex(i);
6167                            DWARFFormValue form_value;
6168                            if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6169                            {
6170                                switch (attr)
6171                                {
6172                                case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6173                                case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
6174                                case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
6175                                case DW_AT_name:
6176                                    type_name_cstr = form_value.AsCString(&get_debug_str_data());
6177                                    type_name_const_str.SetCString(type_name_cstr);
6178                                    break;
6179
6180                                case DW_AT_linkage_name:
6181                                case DW_AT_MIPS_linkage_name:   break; // mangled = form_value.AsCString(&get_debug_str_data()); break;
6182                                case DW_AT_type:                type_die_offset = form_value.Reference(dwarf_cu); break;
6183                                case DW_AT_accessibility:       accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6184                                case DW_AT_declaration:         break; // is_forward_declaration = form_value.Boolean(); break;
6185                                case DW_AT_inline:              is_inline = form_value.Boolean(); break;
6186                                case DW_AT_virtuality:          is_virtual = form_value.Boolean();  break;
6187                                case DW_AT_explicit:            is_explicit = form_value.Boolean();  break;
6188                                case DW_AT_artificial:          is_artificial = form_value.Boolean();  break;
6189
6190
6191                                case DW_AT_external:
6192                                    if (form_value.Unsigned())
6193                                    {
6194                                        if (storage == clang::SC_None)
6195                                            storage = clang::SC_Extern;
6196                                        else
6197                                            storage = clang::SC_PrivateExtern;
6198                                    }
6199                                    break;
6200
6201                                case DW_AT_specification:
6202                                    specification_die_offset = form_value.Reference(dwarf_cu);
6203                                    break;
6204
6205                                case DW_AT_abstract_origin:
6206                                    abstract_origin_die_offset = form_value.Reference(dwarf_cu);
6207                                    break;
6208
6209                                case DW_AT_object_pointer:
6210                                    object_pointer_die_offset = form_value.Reference(dwarf_cu);
6211                                    break;
6212
6213                                case DW_AT_allocated:
6214                                case DW_AT_associated:
6215                                case DW_AT_address_class:
6216                                case DW_AT_calling_convention:
6217                                case DW_AT_data_location:
6218                                case DW_AT_elemental:
6219                                case DW_AT_entry_pc:
6220                                case DW_AT_frame_base:
6221                                case DW_AT_high_pc:
6222                                case DW_AT_low_pc:
6223                                case DW_AT_prototyped:
6224                                case DW_AT_pure:
6225                                case DW_AT_ranges:
6226                                case DW_AT_recursive:
6227                                case DW_AT_return_addr:
6228                                case DW_AT_segment:
6229                                case DW_AT_start_scope:
6230                                case DW_AT_static_link:
6231                                case DW_AT_trampoline:
6232                                case DW_AT_visibility:
6233                                case DW_AT_vtable_elem_location:
6234                                case DW_AT_description:
6235                                case DW_AT_sibling:
6236                                    break;
6237                                }
6238                            }
6239                        }
6240                    }
6241
6242                    std::string object_pointer_name;
6243                    if (object_pointer_die_offset != DW_INVALID_OFFSET)
6244                    {
6245                        // Get the name from the object pointer die
6246                        StreamString s;
6247                        if (DWARFDebugInfoEntry::GetName (this, dwarf_cu, object_pointer_die_offset, s))
6248                        {
6249                            object_pointer_name.assign(s.GetData());
6250                        }
6251                    }
6252
6253                    DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6254
6255                    clang_type_t return_clang_type = NULL;
6256                    Type *func_type = NULL;
6257
6258                    if (type_die_offset != DW_INVALID_OFFSET)
6259                        func_type = ResolveTypeUID(type_die_offset);
6260
6261                    if (func_type)
6262                        return_clang_type = func_type->GetClangForwardType();
6263                    else
6264                        return_clang_type = ast.GetBuiltInType_void();
6265
6266
6267                    std::vector<clang_type_t> function_param_types;
6268                    std::vector<clang::ParmVarDecl*> function_param_decls;
6269
6270                    // Parse the function children for the parameters
6271
6272                    const DWARFDebugInfoEntry *decl_ctx_die = NULL;
6273                    clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, &decl_ctx_die);
6274                    const clang::Decl::Kind containing_decl_kind = containing_decl_ctx->getDeclKind();
6275
6276                    const bool is_cxx_method = DeclKindIsCXXClass (containing_decl_kind);
6277                    // Start off static. This will be set to false in ParseChildParameters(...)
6278                    // if we find a "this" paramters as the first parameter
6279                    if (is_cxx_method)
6280                        is_static = true;
6281                    ClangASTContext::TemplateParameterInfos template_param_infos;
6282
6283                    if (die->HasChildren())
6284                    {
6285                        bool skip_artificial = true;
6286                        ParseChildParameters (sc,
6287                                              containing_decl_ctx,
6288                                              dwarf_cu,
6289                                              die,
6290                                              skip_artificial,
6291                                              is_static,
6292                                              type_list,
6293                                              function_param_types,
6294                                              function_param_decls,
6295                                              type_quals,
6296                                              template_param_infos);
6297                    }
6298
6299                    // clang_type will get the function prototype clang type after this call
6300                    clang_type = ast.CreateFunctionType (return_clang_type,
6301                                                         function_param_types.data(),
6302                                                         function_param_types.size(),
6303                                                         is_variadic,
6304                                                         type_quals);
6305
6306                    if (type_name_cstr)
6307                    {
6308                        bool type_handled = false;
6309                        if (tag == DW_TAG_subprogram)
6310                        {
6311                            ObjCLanguageRuntime::MethodName objc_method (type_name_cstr, true);
6312                            if (objc_method.IsValid(true))
6313                            {
6314                                SymbolContext empty_sc;
6315                                clang_type_t class_opaque_type = NULL;
6316                                ConstString class_name(objc_method.GetClassName());
6317                                if (class_name)
6318                                {
6319                                    TypeList types;
6320                                    TypeSP complete_objc_class_type_sp (FindCompleteObjCDefinitionTypeForDIE (NULL, class_name, false));
6321
6322                                    if (complete_objc_class_type_sp)
6323                                    {
6324                                        clang_type_t type_clang_forward_type = complete_objc_class_type_sp->GetClangForwardType();
6325                                        if (ClangASTContext::IsObjCClassType (type_clang_forward_type))
6326                                            class_opaque_type = type_clang_forward_type;
6327                                    }
6328                                }
6329
6330                                if (class_opaque_type)
6331                                {
6332                                    // If accessibility isn't set to anything valid, assume public for
6333                                    // now...
6334                                    if (accessibility == eAccessNone)
6335                                        accessibility = eAccessPublic;
6336
6337                                    clang::ObjCMethodDecl *objc_method_decl = ast.AddMethodToObjCObjectType (class_opaque_type,
6338                                                                                                             type_name_cstr,
6339                                                                                                             clang_type,
6340                                                                                                             accessibility,
6341                                                                                                             is_artificial);
6342                                    type_handled = objc_method_decl != NULL;
6343                                    if (type_handled)
6344                                    {
6345                                        LinkDeclContextToDIE(ClangASTContext::GetAsDeclContext(objc_method_decl), die);
6346                                        GetClangASTContext().SetMetadataAsUserID (objc_method_decl, MakeUserID(die->GetOffset()));
6347                                    }
6348                                    else
6349                                    {
6350                                        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",
6351                                                                                   die->GetOffset(),
6352                                                                                   tag,
6353                                                                                   DW_TAG_value_to_name(tag));
6354                                    }
6355                                }
6356                            }
6357                            else if (is_cxx_method)
6358                            {
6359                                // Look at the parent of this DIE and see if is is
6360                                // a class or struct and see if this is actually a
6361                                // C++ method
6362                                Type *class_type = ResolveType (dwarf_cu, decl_ctx_die);
6363                                if (class_type)
6364                                {
6365                                    if (class_type->GetID() != MakeUserID(decl_ctx_die->GetOffset()))
6366                                    {
6367                                        // We uniqued the parent class of this function to another class
6368                                        // so we now need to associate all dies under "decl_ctx_die" to
6369                                        // DIEs in the DIE for "class_type"...
6370                                        SymbolFileDWARF *class_symfile = NULL;
6371                                        DWARFCompileUnitSP class_type_cu_sp;
6372                                        const DWARFDebugInfoEntry *class_type_die = NULL;
6373
6374                                        SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
6375                                        if (debug_map_symfile)
6376                                        {
6377                                            class_symfile = debug_map_symfile->GetSymbolFileByOSOIndex(SymbolFileDWARFDebugMap::GetOSOIndexFromUserID(class_type->GetID()));
6378                                            class_type_die = class_symfile->DebugInfo()->GetDIEPtr(class_type->GetID(), &class_type_cu_sp);
6379                                        }
6380                                        else
6381                                        {
6382                                            class_symfile = this;
6383                                            class_type_die = DebugInfo()->GetDIEPtr(class_type->GetID(), &class_type_cu_sp);
6384                                        }
6385                                        if (class_type_die)
6386                                        {
6387                                            llvm::SmallVector<const DWARFDebugInfoEntry *, 0> failures;
6388
6389                                            CopyUniqueClassMethodTypes (class_symfile,
6390                                                                        class_type,
6391                                                                        class_type_cu_sp.get(),
6392                                                                        class_type_die,
6393                                                                        dwarf_cu,
6394                                                                        decl_ctx_die,
6395                                                                        failures);
6396
6397                                            // FIXME do something with these failures that's smarter than
6398                                            // just dropping them on the ground.  Unfortunately classes don't
6399                                            // like having stuff added to them after their definitions are
6400                                            // complete...
6401
6402                                            type_ptr = m_die_to_type[die];
6403                                            if (type_ptr && type_ptr != DIE_IS_BEING_PARSED)
6404                                            {
6405                                                type_sp = type_ptr->shared_from_this();
6406                                                break;
6407                                            }
6408                                        }
6409                                    }
6410
6411                                    if (specification_die_offset != DW_INVALID_OFFSET)
6412                                    {
6413                                        // We have a specification which we are going to base our function
6414                                        // prototype off of, so we need this type to be completed so that the
6415                                        // m_die_to_decl_ctx for the method in the specification has a valid
6416                                        // clang decl context.
6417                                        class_type->GetClangForwardType();
6418                                        // If we have a specification, then the function type should have been
6419                                        // made with the specification and not with this die.
6420                                        DWARFCompileUnitSP spec_cu_sp;
6421                                        const DWARFDebugInfoEntry* spec_die = DebugInfo()->GetDIEPtr(specification_die_offset, &spec_cu_sp);
6422                                        clang::DeclContext *spec_clang_decl_ctx = GetClangDeclContextForDIE (sc, dwarf_cu, spec_die);
6423                                        if (spec_clang_decl_ctx)
6424                                        {
6425                                            LinkDeclContextToDIE(spec_clang_decl_ctx, die);
6426                                        }
6427                                        else
6428                                        {
6429                                            GetObjectFile()->GetModule()->ReportWarning ("0x%8.8" PRIx64 ": DW_AT_specification(0x%8.8x) has no decl\n",
6430                                                                                         MakeUserID(die->GetOffset()),
6431                                                                                         specification_die_offset);
6432                                        }
6433                                        type_handled = true;
6434                                    }
6435                                    else if (abstract_origin_die_offset != DW_INVALID_OFFSET)
6436                                    {
6437                                        // We have a specification which we are going to base our function
6438                                        // prototype off of, so we need this type to be completed so that the
6439                                        // m_die_to_decl_ctx for the method in the abstract origin has a valid
6440                                        // clang decl context.
6441                                        class_type->GetClangForwardType();
6442
6443                                        DWARFCompileUnitSP abs_cu_sp;
6444                                        const DWARFDebugInfoEntry* abs_die = DebugInfo()->GetDIEPtr(abstract_origin_die_offset, &abs_cu_sp);
6445                                        clang::DeclContext *abs_clang_decl_ctx = GetClangDeclContextForDIE (sc, dwarf_cu, abs_die);
6446                                        if (abs_clang_decl_ctx)
6447                                        {
6448                                            LinkDeclContextToDIE (abs_clang_decl_ctx, die);
6449                                        }
6450                                        else
6451                                        {
6452                                            GetObjectFile()->GetModule()->ReportWarning ("0x%8.8" PRIx64 ": DW_AT_abstract_origin(0x%8.8x) has no decl\n",
6453                                                                                         MakeUserID(die->GetOffset()),
6454                                                                                         abstract_origin_die_offset);
6455                                        }
6456                                        type_handled = true;
6457                                    }
6458                                    else
6459                                    {
6460                                        clang_type_t class_opaque_type = class_type->GetClangForwardType();
6461                                        if (ClangASTContext::IsCXXClassType (class_opaque_type))
6462                                        {
6463                                            if (ClangASTContext::IsBeingDefined (class_opaque_type))
6464                                            {
6465                                                // Neither GCC 4.2 nor clang++ currently set a valid accessibility
6466                                                // in the DWARF for C++ methods... Default to public for now...
6467                                                if (accessibility == eAccessNone)
6468                                                    accessibility = eAccessPublic;
6469
6470                                                if (!is_static && !die->HasChildren())
6471                                                {
6472                                                    // We have a C++ member function with no children (this pointer!)
6473                                                    // and clang will get mad if we try and make a function that isn't
6474                                                    // well formed in the DWARF, so we will just skip it...
6475                                                    type_handled = true;
6476                                                }
6477                                                else
6478                                                {
6479                                                    clang::CXXMethodDecl *cxx_method_decl;
6480                                                    // REMOVE THE CRASH DESCRIPTION BELOW
6481                                                    Host::SetCrashDescriptionWithFormat ("SymbolFileDWARF::ParseType() is adding a method %s to class %s in DIE 0x%8.8" PRIx64 " from %s/%s",
6482                                                                                         type_name_cstr,
6483                                                                                         class_type->GetName().GetCString(),
6484                                                                                         MakeUserID(die->GetOffset()),
6485                                                                                         m_obj_file->GetFileSpec().GetDirectory().GetCString(),
6486                                                                                         m_obj_file->GetFileSpec().GetFilename().GetCString());
6487
6488                                                    const bool is_attr_used = false;
6489
6490                                                    cxx_method_decl = ast.AddMethodToCXXRecordType (class_opaque_type,
6491                                                                                                    type_name_cstr,
6492                                                                                                    clang_type,
6493                                                                                                    accessibility,
6494                                                                                                    is_virtual,
6495                                                                                                    is_static,
6496                                                                                                    is_inline,
6497                                                                                                    is_explicit,
6498                                                                                                    is_attr_used,
6499                                                                                                    is_artificial);
6500
6501                                                    type_handled = cxx_method_decl != NULL;
6502
6503                                                    if (type_handled)
6504                                                    {
6505                                                        LinkDeclContextToDIE(ClangASTContext::GetAsDeclContext(cxx_method_decl), die);
6506
6507                                                        Host::SetCrashDescription (NULL);
6508
6509
6510                                                        ClangASTMetadata metadata;
6511                                                        metadata.SetUserID(MakeUserID(die->GetOffset()));
6512
6513                                                        if (!object_pointer_name.empty())
6514                                                        {
6515                                                            metadata.SetObjectPtrName(object_pointer_name.c_str());
6516                                                            if (log)
6517                                                                log->Printf ("Setting object pointer name: %s on method object %p.\n",
6518                                                                             object_pointer_name.c_str(),
6519                                                                             cxx_method_decl);
6520                                                        }
6521                                                        GetClangASTContext().SetMetadata (cxx_method_decl, metadata);
6522                                                    }
6523                                                    else
6524                                                    {
6525                                                        return TypeSP();
6526                                                    }
6527                                                }
6528                                            }
6529                                            else
6530                                            {
6531                                                // We were asked to parse the type for a method in a class, yet the
6532                                                // class hasn't been asked to complete itself through the
6533                                                // clang::ExternalASTSource protocol, so we need to just have the
6534                                                // class complete itself and do things the right way, then our
6535                                                // DIE should then have an entry in the m_die_to_type map. First
6536                                                // we need to modify the m_die_to_type so it doesn't think we are
6537                                                // trying to parse this DIE anymore...
6538                                                m_die_to_type[die] = NULL;
6539
6540                                                // Now we get the full type to force our class type to complete itself
6541                                                // using the clang::ExternalASTSource protocol which will parse all
6542                                                // base classes and all methods (including the method for this DIE).
6543                                                class_type->GetClangFullType();
6544
6545                                                // The type for this DIE should have been filled in the function call above
6546                                                type_ptr = m_die_to_type[die];
6547                                                if (type_ptr && type_ptr != DIE_IS_BEING_PARSED)
6548                                                {
6549                                                    type_sp = type_ptr->shared_from_this();
6550                                                    break;
6551                                                }
6552
6553                                                // FIXME This is fixing some even uglier behavior but we really need to
6554                                                // uniq the methods of each class as well as the class itself.
6555                                                // <rdar://problem/11240464>
6556                                                type_handled = true;
6557                                            }
6558                                        }
6559                                    }
6560                                }
6561                            }
6562                        }
6563
6564                        if (!type_handled)
6565                        {
6566                            // We just have a function that isn't part of a class
6567                            clang::FunctionDecl *function_decl = ast.CreateFunctionDeclaration (containing_decl_ctx,
6568                                                                                                type_name_cstr,
6569                                                                                                clang_type,
6570                                                                                                storage,
6571                                                                                                is_inline);
6572
6573//                            if (template_param_infos.GetSize() > 0)
6574//                            {
6575//                                clang::FunctionTemplateDecl *func_template_decl = ast.CreateFunctionTemplateDecl (containing_decl_ctx,
6576//                                                                                                                  function_decl,
6577//                                                                                                                  type_name_cstr,
6578//                                                                                                                  template_param_infos);
6579//
6580//                                ast.CreateFunctionTemplateSpecializationInfo (function_decl,
6581//                                                                              func_template_decl,
6582//                                                                              template_param_infos);
6583//                            }
6584                            // Add the decl to our DIE to decl context map
6585                            assert (function_decl);
6586                            LinkDeclContextToDIE(function_decl, die);
6587                            if (!function_param_decls.empty())
6588                                ast.SetFunctionParameters (function_decl,
6589                                                           &function_param_decls.front(),
6590                                                           function_param_decls.size());
6591
6592                            ClangASTMetadata metadata;
6593                            metadata.SetUserID(MakeUserID(die->GetOffset()));
6594
6595                            if (!object_pointer_name.empty())
6596                            {
6597                                metadata.SetObjectPtrName(object_pointer_name.c_str());
6598                                if (log)
6599                                    log->Printf ("Setting object pointer name: %s on function object %p.",
6600                                                 object_pointer_name.c_str(),
6601                                                function_decl);
6602                            }
6603                            GetClangASTContext().SetMetadata (function_decl, metadata);
6604                        }
6605                    }
6606                    type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6607                                             this,
6608                                             type_name_const_str,
6609                                             0,
6610                                             NULL,
6611                                             LLDB_INVALID_UID,
6612                                             Type::eEncodingIsUID,
6613                                             &decl,
6614                                             clang_type,
6615                                             Type::eResolveStateFull));
6616                    assert(type_sp.get());
6617                }
6618                break;
6619
6620            case DW_TAG_array_type:
6621                {
6622                    // Set a bit that lets us know that we are currently parsing this
6623                    m_die_to_type[die] = DIE_IS_BEING_PARSED;
6624
6625                    lldb::user_id_t type_die_offset = DW_INVALID_OFFSET;
6626                    int64_t first_index = 0;
6627                    uint32_t byte_stride = 0;
6628                    uint32_t bit_stride = 0;
6629                    bool is_vector = false;
6630                    const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6631
6632                    if (num_attributes > 0)
6633                    {
6634                        uint32_t i;
6635                        for (i=0; i<num_attributes; ++i)
6636                        {
6637                            attr = attributes.AttributeAtIndex(i);
6638                            DWARFFormValue form_value;
6639                            if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6640                            {
6641                                switch (attr)
6642                                {
6643                                case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6644                                case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
6645                                case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
6646                                case DW_AT_name:
6647                                    type_name_cstr = form_value.AsCString(&get_debug_str_data());
6648                                    type_name_const_str.SetCString(type_name_cstr);
6649                                    break;
6650
6651                                case DW_AT_type:            type_die_offset = form_value.Reference(dwarf_cu); break;
6652                                case DW_AT_byte_size:       break; // byte_size = form_value.Unsigned(); break;
6653                                case DW_AT_byte_stride:     byte_stride = form_value.Unsigned(); break;
6654                                case DW_AT_bit_stride:      bit_stride = form_value.Unsigned(); break;
6655                                case DW_AT_GNU_vector:      is_vector = form_value.Boolean(); break;
6656                                case DW_AT_accessibility:   break; // accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6657                                case DW_AT_declaration:     break; // is_forward_declaration = form_value.Boolean(); break;
6658                                case DW_AT_allocated:
6659                                case DW_AT_associated:
6660                                case DW_AT_data_location:
6661                                case DW_AT_description:
6662                                case DW_AT_ordering:
6663                                case DW_AT_start_scope:
6664                                case DW_AT_visibility:
6665                                case DW_AT_specification:
6666                                case DW_AT_abstract_origin:
6667                                case DW_AT_sibling:
6668                                    break;
6669                                }
6670                            }
6671                        }
6672
6673                        DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6674
6675                        Type *element_type = ResolveTypeUID(type_die_offset);
6676
6677                        if (element_type)
6678                        {
6679                            std::vector<uint64_t> element_orders;
6680                            ParseChildArrayInfo(sc, dwarf_cu, die, first_index, element_orders, byte_stride, bit_stride);
6681                            if (byte_stride == 0 && bit_stride == 0)
6682                                byte_stride = element_type->GetByteSize();
6683                            clang_type_t array_element_type = element_type->GetClangForwardType();
6684                            uint64_t array_element_bit_stride = byte_stride * 8 + bit_stride;
6685                            uint64_t num_elements = 0;
6686                            std::vector<uint64_t>::const_reverse_iterator pos;
6687                            std::vector<uint64_t>::const_reverse_iterator end = element_orders.rend();
6688                            for (pos = element_orders.rbegin(); pos != end; ++pos)
6689                            {
6690                                num_elements = *pos;
6691                                clang_type = ast.CreateArrayType (array_element_type,
6692                                                                  num_elements,
6693                                                                  is_vector);
6694                                array_element_type = clang_type;
6695                                array_element_bit_stride = num_elements ? array_element_bit_stride * num_elements : array_element_bit_stride;
6696                            }
6697                            ConstString empty_name;
6698                            type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6699                                                     this,
6700                                                     empty_name,
6701                                                     array_element_bit_stride / 8,
6702                                                     NULL,
6703                                                     type_die_offset,
6704                                                     Type::eEncodingIsUID,
6705                                                     &decl,
6706                                                     clang_type,
6707                                                     Type::eResolveStateFull));
6708                            type_sp->SetEncodingType (element_type);
6709                        }
6710                    }
6711                }
6712                break;
6713
6714            case DW_TAG_ptr_to_member_type:
6715                {
6716                    dw_offset_t type_die_offset = DW_INVALID_OFFSET;
6717                    dw_offset_t containing_type_die_offset = DW_INVALID_OFFSET;
6718
6719                    const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6720
6721                    if (num_attributes > 0) {
6722                        uint32_t i;
6723                        for (i=0; i<num_attributes; ++i)
6724                        {
6725                            attr = attributes.AttributeAtIndex(i);
6726                            DWARFFormValue form_value;
6727                            if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6728                            {
6729                                switch (attr)
6730                                {
6731                                    case DW_AT_type:
6732                                        type_die_offset = form_value.Reference(dwarf_cu); break;
6733                                    case DW_AT_containing_type:
6734                                        containing_type_die_offset = form_value.Reference(dwarf_cu); break;
6735                                }
6736                            }
6737                        }
6738
6739                        Type *pointee_type = ResolveTypeUID(type_die_offset);
6740                        Type *class_type = ResolveTypeUID(containing_type_die_offset);
6741
6742                        clang_type_t pointee_clang_type = pointee_type->GetClangForwardType();
6743                        clang_type_t class_clang_type = class_type->GetClangLayoutType();
6744
6745                        clang_type = ast.CreateMemberPointerType(pointee_clang_type,
6746                                                                 class_clang_type);
6747
6748                        byte_size = ClangASTType::GetClangTypeBitWidth (ast.getASTContext(),
6749                                                                       clang_type) / 8;
6750
6751                        type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6752                                                 this,
6753                                                 type_name_const_str,
6754                                                 byte_size,
6755                                                 NULL,
6756                                                 LLDB_INVALID_UID,
6757                                                 Type::eEncodingIsUID,
6758                                                 NULL,
6759                                                 clang_type,
6760                                                 Type::eResolveStateForward));
6761                    }
6762
6763                    break;
6764                }
6765            default:
6766                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",
6767                                                           die->GetOffset(),
6768                                                           tag,
6769                                                           DW_TAG_value_to_name(tag));
6770                break;
6771            }
6772
6773            if (type_sp.get())
6774            {
6775                const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(die);
6776                dw_tag_t sc_parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
6777
6778                SymbolContextScope * symbol_context_scope = NULL;
6779                if (sc_parent_tag == DW_TAG_compile_unit)
6780                {
6781                    symbol_context_scope = sc.comp_unit;
6782                }
6783                else if (sc.function != NULL)
6784                {
6785                    symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
6786                    if (symbol_context_scope == NULL)
6787                        symbol_context_scope = sc.function;
6788                }
6789
6790                if (symbol_context_scope != NULL)
6791                {
6792                    type_sp->SetSymbolContextScope(symbol_context_scope);
6793                }
6794
6795                // We are ready to put this type into the uniqued list up at the module level
6796                type_list->Insert (type_sp);
6797
6798                m_die_to_type[die] = type_sp.get();
6799            }
6800        }
6801        else if (type_ptr != DIE_IS_BEING_PARSED)
6802        {
6803            type_sp = type_ptr->shared_from_this();
6804        }
6805    }
6806    return type_sp;
6807}
6808
6809size_t
6810SymbolFileDWARF::ParseTypes
6811(
6812    const SymbolContext& sc,
6813    DWARFCompileUnit* dwarf_cu,
6814    const DWARFDebugInfoEntry *die,
6815    bool parse_siblings,
6816    bool parse_children
6817)
6818{
6819    size_t types_added = 0;
6820    while (die != NULL)
6821    {
6822        bool type_is_new = false;
6823        if (ParseType(sc, dwarf_cu, die, &type_is_new).get())
6824        {
6825            if (type_is_new)
6826                ++types_added;
6827        }
6828
6829        if (parse_children && die->HasChildren())
6830        {
6831            if (die->Tag() == DW_TAG_subprogram)
6832            {
6833                SymbolContext child_sc(sc);
6834                child_sc.function = sc.comp_unit->FindFunctionByUID(MakeUserID(die->GetOffset())).get();
6835                types_added += ParseTypes(child_sc, dwarf_cu, die->GetFirstChild(), true, true);
6836            }
6837            else
6838                types_added += ParseTypes(sc, dwarf_cu, die->GetFirstChild(), true, true);
6839        }
6840
6841        if (parse_siblings)
6842            die = die->GetSibling();
6843        else
6844            die = NULL;
6845    }
6846    return types_added;
6847}
6848
6849
6850size_t
6851SymbolFileDWARF::ParseFunctionBlocks (const SymbolContext &sc)
6852{
6853    assert(sc.comp_unit && sc.function);
6854    size_t functions_added = 0;
6855    DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
6856    if (dwarf_cu)
6857    {
6858        dw_offset_t function_die_offset = sc.function->GetID();
6859        const DWARFDebugInfoEntry *function_die = dwarf_cu->GetDIEPtr(function_die_offset);
6860        if (function_die)
6861        {
6862            ParseFunctionBlocks(sc, &sc.function->GetBlock (false), dwarf_cu, function_die, LLDB_INVALID_ADDRESS, 0);
6863        }
6864    }
6865
6866    return functions_added;
6867}
6868
6869
6870size_t
6871SymbolFileDWARF::ParseTypes (const SymbolContext &sc)
6872{
6873    // At least a compile unit must be valid
6874    assert(sc.comp_unit);
6875    size_t types_added = 0;
6876    DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
6877    if (dwarf_cu)
6878    {
6879        if (sc.function)
6880        {
6881            dw_offset_t function_die_offset = sc.function->GetID();
6882            const DWARFDebugInfoEntry *func_die = dwarf_cu->GetDIEPtr(function_die_offset);
6883            if (func_die && func_die->HasChildren())
6884            {
6885                types_added = ParseTypes(sc, dwarf_cu, func_die->GetFirstChild(), true, true);
6886            }
6887        }
6888        else
6889        {
6890            const DWARFDebugInfoEntry *dwarf_cu_die = dwarf_cu->DIE();
6891            if (dwarf_cu_die && dwarf_cu_die->HasChildren())
6892            {
6893                types_added = ParseTypes(sc, dwarf_cu, dwarf_cu_die->GetFirstChild(), true, true);
6894            }
6895        }
6896    }
6897
6898    return types_added;
6899}
6900
6901size_t
6902SymbolFileDWARF::ParseVariablesForContext (const SymbolContext& sc)
6903{
6904    if (sc.comp_unit != NULL)
6905    {
6906        DWARFDebugInfo* info = DebugInfo();
6907        if (info == NULL)
6908            return 0;
6909
6910        if (sc.function)
6911        {
6912            DWARFCompileUnit* dwarf_cu = info->GetCompileUnitContainingDIE(sc.function->GetID()).get();
6913
6914            if (dwarf_cu == NULL)
6915                return 0;
6916
6917            const DWARFDebugInfoEntry *function_die = dwarf_cu->GetDIEPtr(sc.function->GetID());
6918
6919            dw_addr_t func_lo_pc = function_die->GetAttributeValueAsUnsigned (this, dwarf_cu, DW_AT_low_pc, LLDB_INVALID_ADDRESS);
6920            if (func_lo_pc != LLDB_INVALID_ADDRESS)
6921            {
6922                const size_t num_variables = ParseVariables(sc, dwarf_cu, func_lo_pc, function_die->GetFirstChild(), true, true);
6923
6924                // Let all blocks know they have parse all their variables
6925                sc.function->GetBlock (false).SetDidParseVariables (true, true);
6926                return num_variables;
6927            }
6928        }
6929        else if (sc.comp_unit)
6930        {
6931            DWARFCompileUnit* dwarf_cu = info->GetCompileUnit(sc.comp_unit->GetID()).get();
6932
6933            if (dwarf_cu == NULL)
6934                return 0;
6935
6936            uint32_t vars_added = 0;
6937            VariableListSP variables (sc.comp_unit->GetVariableList(false));
6938
6939            if (variables.get() == NULL)
6940            {
6941                variables.reset(new VariableList());
6942                sc.comp_unit->SetVariableList(variables);
6943
6944                DWARFCompileUnit* match_dwarf_cu = NULL;
6945                const DWARFDebugInfoEntry* die = NULL;
6946                DIEArray die_offsets;
6947                if (m_using_apple_tables)
6948                {
6949                    if (m_apple_names_ap.get())
6950                    {
6951                        DWARFMappedHash::DIEInfoArray hash_data_array;
6952                        if (m_apple_names_ap->AppendAllDIEsInRange (dwarf_cu->GetOffset(),
6953                                                                    dwarf_cu->GetNextCompileUnitOffset(),
6954                                                                    hash_data_array))
6955                        {
6956                            DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
6957                        }
6958                    }
6959                }
6960                else
6961                {
6962                    // Index if we already haven't to make sure the compile units
6963                    // get indexed and make their global DIE index list
6964                    if (!m_indexed)
6965                        Index ();
6966
6967                    m_global_index.FindAllEntriesForCompileUnit (dwarf_cu->GetOffset(),
6968                                                                 dwarf_cu->GetNextCompileUnitOffset(),
6969                                                                 die_offsets);
6970                }
6971
6972                const size_t num_matches = die_offsets.size();
6973                if (num_matches)
6974                {
6975                    DWARFDebugInfo* debug_info = DebugInfo();
6976                    for (size_t i=0; i<num_matches; ++i)
6977                    {
6978                        const dw_offset_t die_offset = die_offsets[i];
6979                        die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &match_dwarf_cu);
6980                        if (die)
6981                        {
6982                            VariableSP var_sp (ParseVariableDIE(sc, dwarf_cu, die, LLDB_INVALID_ADDRESS));
6983                            if (var_sp)
6984                            {
6985                                variables->AddVariableIfUnique (var_sp);
6986                                ++vars_added;
6987                            }
6988                        }
6989                        else
6990                        {
6991                            if (m_using_apple_tables)
6992                            {
6993                                GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x)\n", die_offset);
6994                            }
6995                        }
6996
6997                    }
6998                }
6999            }
7000            return vars_added;
7001        }
7002    }
7003    return 0;
7004}
7005
7006
7007VariableSP
7008SymbolFileDWARF::ParseVariableDIE
7009(
7010    const SymbolContext& sc,
7011    DWARFCompileUnit* dwarf_cu,
7012    const DWARFDebugInfoEntry *die,
7013    const lldb::addr_t func_low_pc
7014)
7015{
7016
7017    VariableSP var_sp (m_die_to_variable_sp[die]);
7018    if (var_sp)
7019        return var_sp;  // Already been parsed!
7020
7021    const dw_tag_t tag = die->Tag();
7022
7023    if ((tag == DW_TAG_variable) ||
7024        (tag == DW_TAG_constant) ||
7025        (tag == DW_TAG_formal_parameter && sc.function))
7026    {
7027        DWARFDebugInfoEntry::Attributes attributes;
7028        const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
7029        if (num_attributes > 0)
7030        {
7031            const char *name = NULL;
7032            const char *mangled = NULL;
7033            Declaration decl;
7034            uint32_t i;
7035            lldb::user_id_t type_uid = LLDB_INVALID_UID;
7036            DWARFExpression location;
7037            bool is_external = false;
7038            bool is_artificial = false;
7039            bool location_is_const_value_data = false;
7040            bool has_explicit_location = false;
7041            //AccessType accessibility = eAccessNone;
7042
7043            for (i=0; i<num_attributes; ++i)
7044            {
7045                dw_attr_t attr = attributes.AttributeAtIndex(i);
7046                DWARFFormValue form_value;
7047                if (attributes.ExtractFormValueAtIndex(this, i, form_value))
7048                {
7049                    switch (attr)
7050                    {
7051                    case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
7052                    case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
7053                    case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
7054                    case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
7055                    case DW_AT_linkage_name:
7056                    case DW_AT_MIPS_linkage_name: mangled = form_value.AsCString(&get_debug_str_data()); break;
7057                    case DW_AT_type:        type_uid = form_value.Reference(dwarf_cu); break;
7058                    case DW_AT_external:    is_external = form_value.Boolean(); break;
7059                    case DW_AT_const_value:
7060                        // If we have already found a DW_AT_location attribute, ignore this attribute.
7061                        if (!has_explicit_location)
7062                        {
7063                            location_is_const_value_data = true;
7064                            // The constant value will be either a block, a data value or a string.
7065                            const DataExtractor& debug_info_data = get_debug_info_data();
7066                            if (DWARFFormValue::IsBlockForm(form_value.Form()))
7067                            {
7068                                // Retrieve the value as a block expression.
7069                                uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
7070                                uint32_t block_length = form_value.Unsigned();
7071                                location.CopyOpcodeData(debug_info_data, block_offset, block_length);
7072                            }
7073                            else if (DWARFFormValue::IsDataForm(form_value.Form()))
7074                            {
7075                                // Retrieve the value as a data expression.
7076                                const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
7077                                uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
7078                                uint32_t data_length = fixed_form_sizes[form_value.Form()];
7079                                location.CopyOpcodeData(debug_info_data, data_offset, data_length);
7080                            }
7081                            else
7082                            {
7083                                // Retrieve the value as a string expression.
7084                                if (form_value.Form() == DW_FORM_strp)
7085                                {
7086                                    const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
7087                                    uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
7088                                    uint32_t data_length = fixed_form_sizes[form_value.Form()];
7089                                    location.CopyOpcodeData(debug_info_data, data_offset, data_length);
7090                                }
7091                                else
7092                                {
7093                                    const char *str = form_value.AsCString(&debug_info_data);
7094                                    uint32_t string_offset = str - (const char *)debug_info_data.GetDataStart();
7095                                    uint32_t string_length = strlen(str) + 1;
7096                                    location.CopyOpcodeData(debug_info_data, string_offset, string_length);
7097                                }
7098                            }
7099                        }
7100                        break;
7101                    case DW_AT_location:
7102                        {
7103                            location_is_const_value_data = false;
7104                            has_explicit_location = true;
7105                            if (form_value.BlockData())
7106                            {
7107                                const DataExtractor& debug_info_data = get_debug_info_data();
7108
7109                                uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
7110                                uint32_t block_length = form_value.Unsigned();
7111                                location.CopyOpcodeData(get_debug_info_data(), block_offset, block_length);
7112                            }
7113                            else
7114                            {
7115                                const DataExtractor&    debug_loc_data = get_debug_loc_data();
7116                                const dw_offset_t debug_loc_offset = form_value.Unsigned();
7117
7118                                size_t loc_list_length = DWARFLocationList::Size(debug_loc_data, debug_loc_offset);
7119                                if (loc_list_length > 0)
7120                                {
7121                                    location.CopyOpcodeData(debug_loc_data, debug_loc_offset, loc_list_length);
7122                                    assert (func_low_pc != LLDB_INVALID_ADDRESS);
7123                                    location.SetLocationListSlide (func_low_pc - dwarf_cu->GetBaseAddress());
7124                                }
7125                            }
7126                        }
7127                        break;
7128
7129                    case DW_AT_artificial:      is_artificial = form_value.Boolean(); break;
7130                    case DW_AT_accessibility:   break; //accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
7131                    case DW_AT_declaration:
7132                    case DW_AT_description:
7133                    case DW_AT_endianity:
7134                    case DW_AT_segment:
7135                    case DW_AT_start_scope:
7136                    case DW_AT_visibility:
7137                    default:
7138                    case DW_AT_abstract_origin:
7139                    case DW_AT_sibling:
7140                    case DW_AT_specification:
7141                        break;
7142                    }
7143                }
7144            }
7145
7146            if (location.IsValid())
7147            {
7148                ValueType scope = eValueTypeInvalid;
7149
7150                const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(die);
7151                dw_tag_t parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
7152                SymbolContextScope * symbol_context_scope = NULL;
7153
7154                // DWARF doesn't specify if a DW_TAG_variable is a local, global
7155                // or static variable, so we have to do a little digging by
7156                // looking at the location of a varaible to see if it contains
7157                // a DW_OP_addr opcode _somewhere_ in the definition. I say
7158                // somewhere because clang likes to combine small global variables
7159                // into the same symbol and have locations like:
7160                // DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
7161                // So if we don't have a DW_TAG_formal_parameter, we can look at
7162                // the location to see if it contains a DW_OP_addr opcode, and
7163                // then we can correctly classify  our variables.
7164                if (tag == DW_TAG_formal_parameter)
7165                    scope = eValueTypeVariableArgument;
7166                else
7167                {
7168                    bool op_error = false;
7169                    // Check if the location has a DW_OP_addr with any address value...
7170                    lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
7171                    if (!location_is_const_value_data)
7172                    {
7173                        location_DW_OP_addr = location.GetLocation_DW_OP_addr (0, op_error);
7174                        if (op_error)
7175                        {
7176                            StreamString strm;
7177                            location.DumpLocationForAddress (&strm, eDescriptionLevelFull, 0, 0, NULL);
7178                            GetObjectFile()->GetModule()->ReportError ("0x%8.8x: %s has an invalid location: %s", die->GetOffset(), DW_TAG_value_to_name(die->Tag()), strm.GetString().c_str());
7179                        }
7180                    }
7181
7182                    if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
7183                    {
7184                        if (is_external)
7185                            scope = eValueTypeVariableGlobal;
7186                        else
7187                            scope = eValueTypeVariableStatic;
7188
7189
7190                        SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile ();
7191
7192                        if (debug_map_symfile)
7193                        {
7194                            // When leaving the DWARF in the .o files on darwin,
7195                            // when we have a global variable that wasn't initialized,
7196                            // the .o file might not have allocated a virtual
7197                            // address for the global variable. In this case it will
7198                            // have created a symbol for the global variable
7199                            // that is undefined/data and external and the value will
7200                            // be the byte size of the variable. When we do the
7201                            // address map in SymbolFileDWARFDebugMap we rely on
7202                            // having an address, we need to do some magic here
7203                            // so we can get the correct address for our global
7204                            // variable. The address for all of these entries
7205                            // will be zero, and there will be an undefined symbol
7206                            // in this object file, and the executable will have
7207                            // a matching symbol with a good address. So here we
7208                            // dig up the correct address and replace it in the
7209                            // location for the variable, and set the variable's
7210                            // symbol context scope to be that of the main executable
7211                            // so the file address will resolve correctly.
7212                            bool linked_oso_file_addr = false;
7213                            if (is_external && location_DW_OP_addr == 0)
7214                            {
7215
7216                                // we have a possible uninitialized extern global
7217                                ConstString const_name(mangled ? mangled : name);
7218                                ObjectFile *debug_map_objfile = debug_map_symfile->GetObjectFile();
7219                                if (debug_map_objfile)
7220                                {
7221                                    Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
7222                                    if (debug_map_symtab)
7223                                    {
7224                                        Symbol *exe_symbol = debug_map_symtab->FindFirstSymbolWithNameAndType (const_name,
7225                                                                                                               eSymbolTypeData,
7226                                                                                                               Symtab::eDebugYes,
7227                                                                                                               Symtab::eVisibilityExtern);
7228                                        if (exe_symbol)
7229                                        {
7230                                            if (exe_symbol->ValueIsAddress())
7231                                            {
7232                                                const addr_t exe_file_addr = exe_symbol->GetAddress().GetFileAddress();
7233                                                if (exe_file_addr != LLDB_INVALID_ADDRESS)
7234                                                {
7235                                                    if (location.Update_DW_OP_addr (exe_file_addr))
7236                                                    {
7237                                                        linked_oso_file_addr = true;
7238                                                        symbol_context_scope = exe_symbol;
7239                                                    }
7240                                                }
7241                                            }
7242                                        }
7243                                    }
7244                                }
7245                            }
7246
7247                            if (!linked_oso_file_addr)
7248                            {
7249                                // The DW_OP_addr is not zero, but it contains a .o file address which
7250                                // needs to be linked up correctly.
7251                                const lldb::addr_t exe_file_addr = debug_map_symfile->LinkOSOFileAddress(this, location_DW_OP_addr);
7252                                if (exe_file_addr != LLDB_INVALID_ADDRESS)
7253                                {
7254                                    // Update the file address for this variable
7255                                    location.Update_DW_OP_addr (exe_file_addr);
7256                                }
7257                                else
7258                                {
7259                                    // Variable didn't make it into the final executable
7260                                    return var_sp;
7261                                }
7262                            }
7263                        }
7264                    }
7265                    else
7266                    {
7267                        scope = eValueTypeVariableLocal;
7268                    }
7269                }
7270
7271                if (symbol_context_scope == NULL)
7272                {
7273                    switch (parent_tag)
7274                    {
7275                    case DW_TAG_subprogram:
7276                    case DW_TAG_inlined_subroutine:
7277                    case DW_TAG_lexical_block:
7278                        if (sc.function)
7279                        {
7280                            symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
7281                            if (symbol_context_scope == NULL)
7282                                symbol_context_scope = sc.function;
7283                        }
7284                        break;
7285
7286                    default:
7287                        symbol_context_scope = sc.comp_unit;
7288                        break;
7289                    }
7290                }
7291
7292                if (symbol_context_scope)
7293                {
7294                    var_sp.reset (new Variable (MakeUserID(die->GetOffset()),
7295                                                name,
7296                                                mangled,
7297                                                SymbolFileTypeSP (new SymbolFileType(*this, type_uid)),
7298                                                scope,
7299                                                symbol_context_scope,
7300                                                &decl,
7301                                                location,
7302                                                is_external,
7303                                                is_artificial));
7304
7305                    var_sp->SetLocationIsConstantValueData (location_is_const_value_data);
7306                }
7307                else
7308                {
7309                    // Not ready to parse this variable yet. It might be a global
7310                    // or static variable that is in a function scope and the function
7311                    // in the symbol context wasn't filled in yet
7312                    return var_sp;
7313                }
7314            }
7315        }
7316        // Cache var_sp even if NULL (the variable was just a specification or
7317        // was missing vital information to be able to be displayed in the debugger
7318        // (missing location due to optimization, etc)) so we don't re-parse
7319        // this DIE over and over later...
7320        m_die_to_variable_sp[die] = var_sp;
7321    }
7322    return var_sp;
7323}
7324
7325
7326const DWARFDebugInfoEntry *
7327SymbolFileDWARF::FindBlockContainingSpecification (dw_offset_t func_die_offset,
7328                                                   dw_offset_t spec_block_die_offset,
7329                                                   DWARFCompileUnit **result_die_cu_handle)
7330{
7331    // Give the concrete function die specified by "func_die_offset", find the
7332    // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
7333    // to "spec_block_die_offset"
7334    DWARFDebugInfo* info = DebugInfo();
7335
7336    const DWARFDebugInfoEntry *die = info->GetDIEPtrWithCompileUnitHint(func_die_offset, result_die_cu_handle);
7337    if (die)
7338    {
7339        assert (*result_die_cu_handle);
7340        return FindBlockContainingSpecification (*result_die_cu_handle, die, spec_block_die_offset, result_die_cu_handle);
7341    }
7342    return NULL;
7343}
7344
7345
7346const DWARFDebugInfoEntry *
7347SymbolFileDWARF::FindBlockContainingSpecification(DWARFCompileUnit* dwarf_cu,
7348                                                  const DWARFDebugInfoEntry *die,
7349                                                  dw_offset_t spec_block_die_offset,
7350                                                  DWARFCompileUnit **result_die_cu_handle)
7351{
7352    if (die)
7353    {
7354        switch (die->Tag())
7355        {
7356        case DW_TAG_subprogram:
7357        case DW_TAG_inlined_subroutine:
7358        case DW_TAG_lexical_block:
7359            {
7360                if (die->GetAttributeValueAsReference (this, dwarf_cu, DW_AT_specification, DW_INVALID_OFFSET) == spec_block_die_offset)
7361                {
7362                    *result_die_cu_handle = dwarf_cu;
7363                    return die;
7364                }
7365
7366                if (die->GetAttributeValueAsReference (this, dwarf_cu, DW_AT_abstract_origin, DW_INVALID_OFFSET) == spec_block_die_offset)
7367                {
7368                    *result_die_cu_handle = dwarf_cu;
7369                    return die;
7370                }
7371            }
7372            break;
7373        }
7374
7375        // Give the concrete function die specified by "func_die_offset", find the
7376        // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
7377        // to "spec_block_die_offset"
7378        for (const DWARFDebugInfoEntry *child_die = die->GetFirstChild(); child_die != NULL; child_die = child_die->GetSibling())
7379        {
7380            const DWARFDebugInfoEntry *result_die = FindBlockContainingSpecification (dwarf_cu,
7381                                                                                      child_die,
7382                                                                                      spec_block_die_offset,
7383                                                                                      result_die_cu_handle);
7384            if (result_die)
7385                return result_die;
7386        }
7387    }
7388
7389    *result_die_cu_handle = NULL;
7390    return NULL;
7391}
7392
7393size_t
7394SymbolFileDWARF::ParseVariables
7395(
7396    const SymbolContext& sc,
7397    DWARFCompileUnit* dwarf_cu,
7398    const lldb::addr_t func_low_pc,
7399    const DWARFDebugInfoEntry *orig_die,
7400    bool parse_siblings,
7401    bool parse_children,
7402    VariableList* cc_variable_list
7403)
7404{
7405    if (orig_die == NULL)
7406        return 0;
7407
7408    VariableListSP variable_list_sp;
7409
7410    size_t vars_added = 0;
7411    const DWARFDebugInfoEntry *die = orig_die;
7412    while (die != NULL)
7413    {
7414        dw_tag_t tag = die->Tag();
7415
7416        // Check to see if we have already parsed this variable or constant?
7417        if (m_die_to_variable_sp[die])
7418        {
7419            if (cc_variable_list)
7420                cc_variable_list->AddVariableIfUnique (m_die_to_variable_sp[die]);
7421        }
7422        else
7423        {
7424            // We haven't already parsed it, lets do that now.
7425            if ((tag == DW_TAG_variable) ||
7426                (tag == DW_TAG_constant) ||
7427                (tag == DW_TAG_formal_parameter && sc.function))
7428            {
7429                if (variable_list_sp.get() == NULL)
7430                {
7431                    const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(orig_die);
7432                    dw_tag_t parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
7433                    switch (parent_tag)
7434                    {
7435                        case DW_TAG_compile_unit:
7436                            if (sc.comp_unit != NULL)
7437                            {
7438                                variable_list_sp = sc.comp_unit->GetVariableList(false);
7439                                if (variable_list_sp.get() == NULL)
7440                                {
7441                                    variable_list_sp.reset(new VariableList());
7442                                    sc.comp_unit->SetVariableList(variable_list_sp);
7443                                }
7444                            }
7445                            else
7446                            {
7447                                GetObjectFile()->GetModule()->ReportError ("parent 0x%8.8" PRIx64 " %s with no valid compile unit in symbol context for 0x%8.8" PRIx64 " %s.\n",
7448                                                                           MakeUserID(sc_parent_die->GetOffset()),
7449                                                                           DW_TAG_value_to_name (parent_tag),
7450                                                                           MakeUserID(orig_die->GetOffset()),
7451                                                                           DW_TAG_value_to_name (orig_die->Tag()));
7452                            }
7453                            break;
7454
7455                        case DW_TAG_subprogram:
7456                        case DW_TAG_inlined_subroutine:
7457                        case DW_TAG_lexical_block:
7458                            if (sc.function != NULL)
7459                            {
7460                                // Check to see if we already have parsed the variables for the given scope
7461
7462                                Block *block = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
7463                                if (block == NULL)
7464                                {
7465                                    // This must be a specification or abstract origin with
7466                                    // a concrete block couterpart in the current function. We need
7467                                    // to find the concrete block so we can correctly add the
7468                                    // variable to it
7469                                    DWARFCompileUnit *concrete_block_die_cu = dwarf_cu;
7470                                    const DWARFDebugInfoEntry *concrete_block_die = FindBlockContainingSpecification (sc.function->GetID(),
7471                                                                                                                      sc_parent_die->GetOffset(),
7472                                                                                                                      &concrete_block_die_cu);
7473                                    if (concrete_block_die)
7474                                        block = sc.function->GetBlock(true).FindBlockByID(MakeUserID(concrete_block_die->GetOffset()));
7475                                }
7476
7477                                if (block != NULL)
7478                                {
7479                                    const bool can_create = false;
7480                                    variable_list_sp = block->GetBlockVariableList (can_create);
7481                                    if (variable_list_sp.get() == NULL)
7482                                    {
7483                                        variable_list_sp.reset(new VariableList());
7484                                        block->SetVariableList(variable_list_sp);
7485                                    }
7486                                }
7487                            }
7488                            break;
7489
7490                        default:
7491                             GetObjectFile()->GetModule()->ReportError ("didn't find appropriate parent DIE for variable list for 0x%8.8" PRIx64 " %s.\n",
7492                                                                        MakeUserID(orig_die->GetOffset()),
7493                                                                        DW_TAG_value_to_name (orig_die->Tag()));
7494                            break;
7495                    }
7496                }
7497
7498                if (variable_list_sp)
7499                {
7500                    VariableSP var_sp (ParseVariableDIE(sc, dwarf_cu, die, func_low_pc));
7501                    if (var_sp)
7502                    {
7503                        variable_list_sp->AddVariableIfUnique (var_sp);
7504                        if (cc_variable_list)
7505                            cc_variable_list->AddVariableIfUnique (var_sp);
7506                        ++vars_added;
7507                    }
7508                }
7509            }
7510        }
7511
7512        bool skip_children = (sc.function == NULL && tag == DW_TAG_subprogram);
7513
7514        if (!skip_children && parse_children && die->HasChildren())
7515        {
7516            vars_added += ParseVariables(sc, dwarf_cu, func_low_pc, die->GetFirstChild(), true, true, cc_variable_list);
7517        }
7518
7519        if (parse_siblings)
7520            die = die->GetSibling();
7521        else
7522            die = NULL;
7523    }
7524    return vars_added;
7525}
7526
7527//------------------------------------------------------------------
7528// PluginInterface protocol
7529//------------------------------------------------------------------
7530const char *
7531SymbolFileDWARF::GetPluginName()
7532{
7533    return "SymbolFileDWARF";
7534}
7535
7536const char *
7537SymbolFileDWARF::GetShortPluginName()
7538{
7539    return GetPluginNameStatic();
7540}
7541
7542uint32_t
7543SymbolFileDWARF::GetPluginVersion()
7544{
7545    return 1;
7546}
7547
7548void
7549SymbolFileDWARF::CompleteTagDecl (void *baton, clang::TagDecl *decl)
7550{
7551    SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7552    clang_type_t clang_type = symbol_file_dwarf->GetClangASTContext().GetTypeForDecl (decl);
7553    if (clang_type)
7554        symbol_file_dwarf->ResolveClangOpaqueTypeDefinition (clang_type);
7555}
7556
7557void
7558SymbolFileDWARF::CompleteObjCInterfaceDecl (void *baton, clang::ObjCInterfaceDecl *decl)
7559{
7560    SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7561    clang_type_t clang_type = symbol_file_dwarf->GetClangASTContext().GetTypeForDecl (decl);
7562    if (clang_type)
7563        symbol_file_dwarf->ResolveClangOpaqueTypeDefinition (clang_type);
7564}
7565
7566void
7567SymbolFileDWARF::DumpIndexes ()
7568{
7569    StreamFile s(stdout, false);
7570
7571    s.Printf ("DWARF index for (%s) '%s/%s':",
7572              GetObjectFile()->GetModule()->GetArchitecture().GetArchitectureName(),
7573              GetObjectFile()->GetFileSpec().GetDirectory().AsCString(),
7574              GetObjectFile()->GetFileSpec().GetFilename().AsCString());
7575    s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
7576    s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
7577    s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
7578    s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
7579    s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
7580    s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
7581    s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
7582    s.Printf("\nNamepaces:\n");             m_namespace_index.Dump (&s);
7583}
7584
7585void
7586SymbolFileDWARF::SearchDeclContext (const clang::DeclContext *decl_context,
7587                                    const char *name,
7588                                    llvm::SmallVectorImpl <clang::NamedDecl *> *results)
7589{
7590    DeclContextToDIEMap::iterator iter = m_decl_ctx_to_die.find(decl_context);
7591
7592    if (iter == m_decl_ctx_to_die.end())
7593        return;
7594
7595    for (DIEPointerSet::iterator pos = iter->second.begin(), end = iter->second.end(); pos != end; ++pos)
7596    {
7597        const DWARFDebugInfoEntry *context_die = *pos;
7598
7599        if (!results)
7600            return;
7601
7602        DWARFDebugInfo* info = DebugInfo();
7603
7604        DIEArray die_offsets;
7605
7606        DWARFCompileUnit* dwarf_cu = NULL;
7607        const DWARFDebugInfoEntry* die = NULL;
7608
7609        if (m_using_apple_tables)
7610        {
7611            if (m_apple_types_ap.get())
7612                m_apple_types_ap->FindByName (name, die_offsets);
7613        }
7614        else
7615        {
7616            if (!m_indexed)
7617                Index ();
7618
7619            m_type_index.Find (ConstString(name), die_offsets);
7620        }
7621
7622        const size_t num_matches = die_offsets.size();
7623
7624        if (num_matches)
7625        {
7626            for (size_t i = 0; i < num_matches; ++i)
7627            {
7628                const dw_offset_t die_offset = die_offsets[i];
7629                die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
7630
7631                if (die->GetParent() != context_die)
7632                    continue;
7633
7634                Type *matching_type = ResolveType (dwarf_cu, die);
7635
7636                lldb::clang_type_t type = matching_type->GetClangForwardType();
7637                clang::QualType qual_type = clang::QualType::getFromOpaquePtr(type);
7638
7639                if (const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr()))
7640                {
7641                    clang::TagDecl *tag_decl = tag_type->getDecl();
7642                    results->push_back(tag_decl);
7643                }
7644                else if (const clang::TypedefType *typedef_type = llvm::dyn_cast<clang::TypedefType>(qual_type.getTypePtr()))
7645                {
7646                    clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
7647                    results->push_back(typedef_decl);
7648                }
7649            }
7650        }
7651    }
7652}
7653
7654void
7655SymbolFileDWARF::FindExternalVisibleDeclsByName (void *baton,
7656                                                 const clang::DeclContext *decl_context,
7657                                                 clang::DeclarationName decl_name,
7658                                                 llvm::SmallVectorImpl <clang::NamedDecl *> *results)
7659{
7660
7661    switch (decl_context->getDeclKind())
7662    {
7663    case clang::Decl::Namespace:
7664    case clang::Decl::TranslationUnit:
7665        {
7666            SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7667            symbol_file_dwarf->SearchDeclContext (decl_context, decl_name.getAsString().c_str(), results);
7668        }
7669        break;
7670    default:
7671        break;
7672    }
7673}
7674
7675bool
7676SymbolFileDWARF::LayoutRecordType (void *baton,
7677                                   const clang::RecordDecl *record_decl,
7678                                   uint64_t &size,
7679                                   uint64_t &alignment,
7680                                   llvm::DenseMap <const clang::FieldDecl *, uint64_t> &field_offsets,
7681                                   llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &base_offsets,
7682                                   llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &vbase_offsets)
7683{
7684    SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7685    return symbol_file_dwarf->LayoutRecordType (record_decl, size, alignment, field_offsets, base_offsets, vbase_offsets);
7686}
7687
7688
7689bool
7690SymbolFileDWARF::LayoutRecordType (const clang::RecordDecl *record_decl,
7691                                   uint64_t &bit_size,
7692                                   uint64_t &alignment,
7693                                   llvm::DenseMap <const clang::FieldDecl *, uint64_t> &field_offsets,
7694                                   llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &base_offsets,
7695                                   llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &vbase_offsets)
7696{
7697    Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
7698    RecordDeclToLayoutMap::iterator pos = m_record_decl_to_layout_map.find (record_decl);
7699    bool success = false;
7700    base_offsets.clear();
7701    vbase_offsets.clear();
7702    if (pos != m_record_decl_to_layout_map.end())
7703    {
7704        bit_size = pos->second.bit_size;
7705        alignment = pos->second.alignment;
7706        field_offsets.swap(pos->second.field_offsets);
7707        base_offsets.swap (pos->second.base_offsets);
7708        vbase_offsets.swap (pos->second.vbase_offsets);
7709        m_record_decl_to_layout_map.erase(pos);
7710        success = true;
7711    }
7712    else
7713    {
7714        bit_size = 0;
7715        alignment = 0;
7716        field_offsets.clear();
7717    }
7718
7719    if (log)
7720        GetObjectFile()->GetModule()->LogMessage (log,
7721                                                  "SymbolFileDWARF::LayoutRecordType (record_decl = %p, bit_size = %" PRIu64 ", alignment = %" PRIu64 ", field_offsets[%u],base_offsets[%u], vbase_offsets[%u]) success = %i",
7722                                                  record_decl,
7723                                                  bit_size,
7724                                                  alignment,
7725                                                  (uint32_t)field_offsets.size(),
7726                                                  (uint32_t)base_offsets.size(),
7727                                                  (uint32_t)vbase_offsets.size(),
7728                                                  success);
7729    return success;
7730}
7731
7732
7733SymbolFileDWARFDebugMap *
7734SymbolFileDWARF::GetDebugMapSymfile ()
7735{
7736    if (m_debug_map_symfile == NULL && !m_debug_map_module_wp.expired())
7737    {
7738        lldb::ModuleSP module_sp (m_debug_map_module_wp.lock());
7739        if (module_sp)
7740        {
7741            SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
7742            if (sym_vendor)
7743                m_debug_map_symfile = (SymbolFileDWARFDebugMap *)sym_vendor->GetSymbolFile();
7744        }
7745    }
7746    return m_debug_map_symfile;
7747}
7748
7749
7750