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