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