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