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