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