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