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