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             idx = attributes.FindAttributeIndex(DW_AT_linkage_name);
3279         if (idx != UINT32_MAX)
3280         {
3281             if (attributes.ExtractFormValueAtIndex(this, idx, form_value))
3282             {
3283                 const char *mangled_name = form_value.AsCString(&get_debug_str_data());
3284                 if (mangled_name)
3285                     best_name.SetValue (ConstString(mangled_name), true);
3286             }
3287         }
3288 
3289         if (!best_name)
3290         {
3291             idx = attributes.FindAttributeIndex(DW_AT_name);
3292             if (idx != UINT32_MAX && attributes.ExtractFormValueAtIndex(this, idx, form_value))
3293             {
3294                 const char *name = form_value.AsCString(&get_debug_str_data());
3295                 best_name.SetValue (ConstString(name), false);
3296             }
3297         }
3298 
3299         if (best_name.GetDemangledName())
3300         {
3301             const char *demangled = best_name.GetDemangledName().GetCString();
3302             if (demangled)
3303             {
3304                 std::string name_no_parens(partial_name, base_name_end - partial_name);
3305                 const char *partial_in_demangled = strstr (demangled, name_no_parens.c_str());
3306                 if (partial_in_demangled == NULL)
3307                     return false;
3308                 else
3309                 {
3310                     // Sort out the case where our name is something like "Process::Destroy" and the match is
3311                     // "SBProcess::Destroy" - that shouldn't be a match.  We should really always match on
3312                     // namespace boundaries...
3313 
3314                     if (partial_name[0] == ':'  && partial_name[1] == ':')
3315                     {
3316                         // The partial name was already on a namespace boundary so all matches are good.
3317                         return true;
3318                     }
3319                     else if (partial_in_demangled == demangled)
3320                     {
3321                         // They both start the same, so this is an good match.
3322                         return true;
3323                     }
3324                     else
3325                     {
3326                         if (partial_in_demangled - demangled == 1)
3327                         {
3328                             // Only one character difference, can't be a namespace boundary...
3329                             return false;
3330                         }
3331                         else if (*(partial_in_demangled - 1) == ':' && *(partial_in_demangled - 2) == ':')
3332                         {
3333                             // We are on a namespace boundary, so this is also good.
3334                             return true;
3335                         }
3336                         else
3337                             return false;
3338                     }
3339                 }
3340             }
3341         }
3342     }
3343 
3344     return true;
3345 }
3346 
3347 uint32_t
3348 SymbolFileDWARF::FindFunctions (const ConstString &name,
3349                                 const lldb_private::ClangNamespaceDecl *namespace_decl,
3350                                 uint32_t name_type_mask,
3351                                 bool include_inlines,
3352                                 bool append,
3353                                 SymbolContextList& sc_list)
3354 {
3355     Timer scoped_timer (__PRETTY_FUNCTION__,
3356                         "SymbolFileDWARF::FindFunctions (name = '%s')",
3357                         name.AsCString());
3358 
3359     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3360 
3361     if (log)
3362     {
3363         GetObjectFile()->GetModule()->LogMessage (log.get(),
3364                                                   "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, append=%u, sc_list)",
3365                                                   name.GetCString(),
3366                                                   name_type_mask,
3367                                                   append);
3368     }
3369 
3370     // If we aren't appending the results to this list, then clear the list
3371     if (!append)
3372         sc_list.Clear();
3373 
3374     if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
3375 		return 0;
3376 
3377     // If name is empty then we won't find anything.
3378     if (name.IsEmpty())
3379         return 0;
3380 
3381     // Remember how many sc_list are in the list before we search in case
3382     // we are appending the results to a variable list.
3383 
3384     const uint32_t original_size = sc_list.GetSize();
3385 
3386     const char *name_cstr = name.GetCString();
3387     uint32_t effective_name_type_mask = eFunctionNameTypeNone;
3388     const char *base_name_start = name_cstr;
3389     const char *base_name_end = name_cstr + strlen(name_cstr);
3390 
3391     if (name_type_mask & eFunctionNameTypeAuto)
3392     {
3393         if (CPPLanguageRuntime::IsCPPMangledName (name_cstr))
3394             effective_name_type_mask = eFunctionNameTypeFull;
3395         else if (ObjCLanguageRuntime::IsPossibleObjCMethodName (name_cstr))
3396             effective_name_type_mask = eFunctionNameTypeFull;
3397         else
3398         {
3399             if (ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
3400                 effective_name_type_mask |= eFunctionNameTypeSelector;
3401 
3402             if (CPPLanguageRuntime::IsPossibleCPPCall(name_cstr, base_name_start, base_name_end))
3403                 effective_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
3404         }
3405     }
3406     else
3407     {
3408         effective_name_type_mask = name_type_mask;
3409         if (effective_name_type_mask & eFunctionNameTypeMethod || name_type_mask & eFunctionNameTypeBase)
3410         {
3411             // If they've asked for a CPP method or function name and it can't be that, we don't
3412             // even need to search for CPP methods or names.
3413             if (!CPPLanguageRuntime::IsPossibleCPPCall(name_cstr, base_name_start, base_name_end))
3414             {
3415                 effective_name_type_mask &= ~(eFunctionNameTypeMethod | eFunctionNameTypeBase);
3416                 if (effective_name_type_mask == eFunctionNameTypeNone)
3417                     return 0;
3418             }
3419         }
3420 
3421         if (effective_name_type_mask & eFunctionNameTypeSelector)
3422         {
3423             if (!ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
3424             {
3425                 effective_name_type_mask &= ~(eFunctionNameTypeSelector);
3426                 if (effective_name_type_mask == eFunctionNameTypeNone)
3427                     return 0;
3428             }
3429         }
3430     }
3431 
3432     DWARFDebugInfo* info = DebugInfo();
3433     if (info == NULL)
3434         return 0;
3435 
3436     DWARFCompileUnit *dwarf_cu = NULL;
3437     if (m_using_apple_tables)
3438     {
3439         if (m_apple_names_ap.get())
3440         {
3441 
3442             DIEArray die_offsets;
3443 
3444             uint32_t num_matches = 0;
3445 
3446             if (effective_name_type_mask & eFunctionNameTypeFull)
3447             {
3448                 // If they asked for the full name, match what they typed.  At some point we may
3449                 // want to canonicalize this (strip double spaces, etc.  For now, we just add all the
3450                 // dies that we find by exact match.
3451                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3452                 for (uint32_t i = 0; i < num_matches; i++)
3453                 {
3454                     const dw_offset_t die_offset = die_offsets[i];
3455                     const DWARFDebugInfoEntry *die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3456                     if (die)
3457                     {
3458                         if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3459                             continue;
3460 
3461                         if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3462                             continue;
3463 
3464                         ResolveFunction (dwarf_cu, die, sc_list);
3465                     }
3466                     else
3467                     {
3468                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3469                                                                                    die_offset, name_cstr);
3470                     }
3471                 }
3472             }
3473             else
3474             {
3475                 if (effective_name_type_mask & eFunctionNameTypeSelector)
3476                 {
3477                     if (namespace_decl && *namespace_decl)
3478                         return 0; // no selectors in namespaces
3479 
3480                     num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3481                     // Now make sure these are actually ObjC methods.  In this case we can simply look up the name,
3482                     // and if it is an ObjC method name, we're good.
3483 
3484                     for (uint32_t i = 0; i < num_matches; i++)
3485                     {
3486                         const dw_offset_t die_offset = die_offsets[i];
3487                         const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3488                         if (die)
3489                         {
3490                             const char *die_name = die->GetName(this, dwarf_cu);
3491                             if (ObjCLanguageRuntime::IsPossibleObjCMethodName(die_name))
3492                             {
3493                                 if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3494                                     continue;
3495 
3496                                 ResolveFunction (dwarf_cu, die, sc_list);
3497                             }
3498                         }
3499                         else
3500                         {
3501                             GetObjectFile()->GetModule()->ReportError ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3502                                                                        die_offset, name_cstr);
3503                         }
3504                     }
3505                     die_offsets.clear();
3506                 }
3507 
3508                 if (effective_name_type_mask & eFunctionNameTypeMethod
3509                     || effective_name_type_mask & eFunctionNameTypeBase)
3510                 {
3511                     if ((effective_name_type_mask & eFunctionNameTypeMethod) &&
3512                         (namespace_decl && *namespace_decl))
3513                         return 0; // no methods in namespaces
3514 
3515                     // The apple_names table stores just the "base name" of C++ methods in the table.  So we have to
3516                     // extract the base name, look that up, and if there is any other information in the name we were
3517                     // passed in we have to post-filter based on that.
3518 
3519                     // FIXME: Arrange the logic above so that we don't calculate the base name twice:
3520                     std::string base_name(base_name_start, base_name_end - base_name_start);
3521                     num_matches = m_apple_names_ap->FindByName (base_name.c_str(), die_offsets);
3522 
3523                     for (uint32_t i = 0; i < num_matches; i++)
3524                     {
3525                         const dw_offset_t die_offset = die_offsets[i];
3526                         const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3527                         if (die)
3528                         {
3529                             if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3530                                 continue;
3531 
3532                             if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3533                                 continue;
3534 
3535                             if (!FunctionDieMatchesPartialName(die,
3536                                                                dwarf_cu,
3537                                                                effective_name_type_mask,
3538                                                                name_cstr,
3539                                                                base_name_start,
3540                                                                base_name_end))
3541                                 continue;
3542 
3543                             // If we get to here, the die is good, and we should add it:
3544                             ResolveFunction (dwarf_cu, die, sc_list);
3545                         }
3546                         else
3547                         {
3548                             GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3549                                                                                        die_offset, name_cstr);
3550                         }
3551                     }
3552                     die_offsets.clear();
3553                 }
3554             }
3555         }
3556     }
3557     else
3558     {
3559 
3560         // Index the DWARF if we haven't already
3561         if (!m_indexed)
3562             Index ();
3563 
3564         if (name_type_mask & eFunctionNameTypeFull)
3565             FindFunctions (name, m_function_fullname_index, sc_list);
3566 
3567         std::string base_name(base_name_start, base_name_end - base_name_start);
3568         ConstString base_name_const(base_name.c_str());
3569         DIEArray die_offsets;
3570         DWARFCompileUnit *dwarf_cu = NULL;
3571 
3572         if (effective_name_type_mask & eFunctionNameTypeBase)
3573         {
3574             uint32_t num_base = m_function_basename_index.Find(base_name_const, die_offsets);
3575             for (uint32_t i = 0; i < num_base; i++)
3576             {
3577                 const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offsets[i], &dwarf_cu);
3578                 if (die)
3579                 {
3580                     if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3581                         continue;
3582 
3583                     if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3584                         continue;
3585 
3586                     if (!FunctionDieMatchesPartialName(die,
3587                                                        dwarf_cu,
3588                                                        eFunctionNameTypeBase,
3589                                                        name_cstr,
3590                                                        base_name_start,
3591                                                        base_name_end))
3592                         continue;
3593 
3594                     // If we get to here, the die is good, and we should add it:
3595                     ResolveFunction (dwarf_cu, die, sc_list);
3596                 }
3597             }
3598             die_offsets.clear();
3599         }
3600 
3601         if (effective_name_type_mask & eFunctionNameTypeMethod)
3602         {
3603             if (namespace_decl && *namespace_decl)
3604                 return 0; // no methods in namespaces
3605 
3606             uint32_t num_base = m_function_method_index.Find(base_name_const, die_offsets);
3607             {
3608                 for (uint32_t i = 0; i < num_base; i++)
3609                 {
3610                     const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offsets[i], &dwarf_cu);
3611                     if (die)
3612                     {
3613                         if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3614                             continue;
3615 
3616                         if (!FunctionDieMatchesPartialName(die,
3617                                                            dwarf_cu,
3618                                                            eFunctionNameTypeMethod,
3619                                                            name_cstr,
3620                                                            base_name_start,
3621                                                            base_name_end))
3622                             continue;
3623 
3624                         // If we get to here, the die is good, and we should add it:
3625                         ResolveFunction (dwarf_cu, die, sc_list);
3626                     }
3627                 }
3628             }
3629             die_offsets.clear();
3630         }
3631 
3632         if ((effective_name_type_mask & eFunctionNameTypeSelector) && (!namespace_decl || !*namespace_decl))
3633         {
3634             FindFunctions (name, m_function_selector_index, sc_list);
3635         }
3636 
3637     }
3638 
3639     // Return the number of variable that were appended to the list
3640     const uint32_t num_matches = sc_list.GetSize() - original_size;
3641 
3642     if (log && num_matches > 0)
3643     {
3644         GetObjectFile()->GetModule()->LogMessage (log.get(),
3645                                                   "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, append=%u, sc_list) => %u",
3646                                                   name.GetCString(),
3647                                                   name_type_mask,
3648                                                   append,
3649                                                   num_matches);
3650     }
3651     return num_matches;
3652 }
3653 
3654 uint32_t
3655 SymbolFileDWARF::FindFunctions(const RegularExpression& regex, bool include_inlines, bool append, SymbolContextList& sc_list)
3656 {
3657     Timer scoped_timer (__PRETTY_FUNCTION__,
3658                         "SymbolFileDWARF::FindFunctions (regex = '%s')",
3659                         regex.GetText());
3660 
3661     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3662 
3663     if (log)
3664     {
3665         GetObjectFile()->GetModule()->LogMessage (log.get(),
3666                                                   "SymbolFileDWARF::FindFunctions (regex=\"%s\", append=%u, sc_list)",
3667                                                   regex.GetText(),
3668                                                   append);
3669     }
3670 
3671 
3672     // If we aren't appending the results to this list, then clear the list
3673     if (!append)
3674         sc_list.Clear();
3675 
3676     // Remember how many sc_list are in the list before we search in case
3677     // we are appending the results to a variable list.
3678     uint32_t original_size = sc_list.GetSize();
3679 
3680     if (m_using_apple_tables)
3681     {
3682         if (m_apple_names_ap.get())
3683             FindFunctions (regex, *m_apple_names_ap, sc_list);
3684     }
3685     else
3686     {
3687         // Index the DWARF if we haven't already
3688         if (!m_indexed)
3689             Index ();
3690 
3691         FindFunctions (regex, m_function_basename_index, sc_list);
3692 
3693         FindFunctions (regex, m_function_fullname_index, sc_list);
3694     }
3695 
3696     // Return the number of variable that were appended to the list
3697     return sc_list.GetSize() - original_size;
3698 }
3699 
3700 uint32_t
3701 SymbolFileDWARF::FindTypes (const SymbolContext& sc,
3702                             const ConstString &name,
3703                             const lldb_private::ClangNamespaceDecl *namespace_decl,
3704                             bool append,
3705                             uint32_t max_matches,
3706                             TypeList& types)
3707 {
3708     DWARFDebugInfo* info = DebugInfo();
3709     if (info == NULL)
3710         return 0;
3711 
3712     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3713 
3714     if (log)
3715     {
3716         if (namespace_decl)
3717         {
3718             GetObjectFile()->GetModule()->LogMessage (log.get(),
3719                                                       "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(%p) \"%s\", append=%u, max_matches=%u, type_list)",
3720                                                       name.GetCString(),
3721                                                       namespace_decl->GetNamespaceDecl(),
3722                                                       namespace_decl->GetQualifiedName().c_str(),
3723                                                       append,
3724                                                       max_matches);
3725         }
3726         else
3727         {
3728             GetObjectFile()->GetModule()->LogMessage (log.get(),
3729                                                       "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(NULL), append=%u, max_matches=%u, type_list)",
3730                                                       name.GetCString(),
3731                                                       append,
3732                                                       max_matches);
3733         }
3734     }
3735 
3736     // If we aren't appending the results to this list, then clear the list
3737     if (!append)
3738         types.Clear();
3739 
3740     if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
3741 		return 0;
3742 
3743     DIEArray die_offsets;
3744 
3745     if (m_using_apple_tables)
3746     {
3747         if (m_apple_types_ap.get())
3748         {
3749             const char *name_cstr = name.GetCString();
3750             m_apple_types_ap->FindByName (name_cstr, die_offsets);
3751         }
3752     }
3753     else
3754     {
3755         if (!m_indexed)
3756             Index ();
3757 
3758         m_type_index.Find (name, die_offsets);
3759     }
3760 
3761     const size_t num_die_matches = die_offsets.size();
3762 
3763     if (num_die_matches)
3764     {
3765         const uint32_t initial_types_size = types.GetSize();
3766         DWARFCompileUnit* dwarf_cu = NULL;
3767         const DWARFDebugInfoEntry* die = NULL;
3768         DWARFDebugInfo* debug_info = DebugInfo();
3769         for (size_t i=0; i<num_die_matches; ++i)
3770         {
3771             const dw_offset_t die_offset = die_offsets[i];
3772             die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3773 
3774             if (die)
3775             {
3776                 if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3777                     continue;
3778 
3779                 Type *matching_type = ResolveType (dwarf_cu, die);
3780                 if (matching_type)
3781                 {
3782                     // We found a type pointer, now find the shared pointer form our type list
3783                     types.InsertUnique (matching_type->shared_from_this());
3784                     if (types.GetSize() >= max_matches)
3785                         break;
3786                 }
3787             }
3788             else
3789             {
3790                 if (m_using_apple_tables)
3791                 {
3792                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
3793                                                                                die_offset, name.GetCString());
3794                 }
3795             }
3796 
3797         }
3798         const uint32_t num_matches = types.GetSize() - initial_types_size;
3799         if (log && num_matches)
3800         {
3801             if (namespace_decl)
3802             {
3803                 GetObjectFile()->GetModule()->LogMessage (log.get(),
3804                                                           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(%p) \"%s\", append=%u, max_matches=%u, type_list) => %u",
3805                                                           name.GetCString(),
3806                                                           namespace_decl->GetNamespaceDecl(),
3807                                                           namespace_decl->GetQualifiedName().c_str(),
3808                                                           append,
3809                                                           max_matches,
3810                                                           num_matches);
3811             }
3812             else
3813             {
3814                 GetObjectFile()->GetModule()->LogMessage (log.get(),
3815                                                           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(NULL), append=%u, max_matches=%u, type_list) => %u",
3816                                                           name.GetCString(),
3817                                                           append,
3818                                                           max_matches,
3819                                                           num_matches);
3820             }
3821         }
3822         return num_matches;
3823     }
3824     return 0;
3825 }
3826 
3827 
3828 ClangNamespaceDecl
3829 SymbolFileDWARF::FindNamespace (const SymbolContext& sc,
3830                                 const ConstString &name,
3831                                 const lldb_private::ClangNamespaceDecl *parent_namespace_decl)
3832 {
3833     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3834 
3835     if (log)
3836     {
3837         GetObjectFile()->GetModule()->LogMessage (log.get(),
3838                                                   "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
3839                                                   name.GetCString());
3840     }
3841 
3842     if (!NamespaceDeclMatchesThisSymbolFile(parent_namespace_decl))
3843 		return ClangNamespaceDecl();
3844 
3845     ClangNamespaceDecl namespace_decl;
3846     DWARFDebugInfo* info = DebugInfo();
3847     if (info)
3848     {
3849         DIEArray die_offsets;
3850 
3851         // Index if we already haven't to make sure the compile units
3852         // get indexed and make their global DIE index list
3853         if (m_using_apple_tables)
3854         {
3855             if (m_apple_namespaces_ap.get())
3856             {
3857                 const char *name_cstr = name.GetCString();
3858                 m_apple_namespaces_ap->FindByName (name_cstr, die_offsets);
3859             }
3860         }
3861         else
3862         {
3863             if (!m_indexed)
3864                 Index ();
3865 
3866             m_namespace_index.Find (name, die_offsets);
3867         }
3868 
3869         DWARFCompileUnit* dwarf_cu = NULL;
3870         const DWARFDebugInfoEntry* die = NULL;
3871         const size_t num_matches = die_offsets.size();
3872         if (num_matches)
3873         {
3874             DWARFDebugInfo* debug_info = DebugInfo();
3875             for (size_t i=0; i<num_matches; ++i)
3876             {
3877                 const dw_offset_t die_offset = die_offsets[i];
3878                 die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3879 
3880                 if (die)
3881                 {
3882                     if (parent_namespace_decl && !DIEIsInNamespace (parent_namespace_decl, dwarf_cu, die))
3883                         continue;
3884 
3885                     clang::NamespaceDecl *clang_namespace_decl = ResolveNamespaceDIE (dwarf_cu, die);
3886                     if (clang_namespace_decl)
3887                     {
3888                         namespace_decl.SetASTContext (GetClangASTContext().getASTContext());
3889                         namespace_decl.SetNamespaceDecl (clang_namespace_decl);
3890                         break;
3891                     }
3892                 }
3893                 else
3894                 {
3895                     if (m_using_apple_tables)
3896                     {
3897                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_namespaces accelerator table had bad die 0x%8.8x for '%s')\n",
3898                                                                    die_offset, name.GetCString());
3899                     }
3900                 }
3901 
3902             }
3903         }
3904     }
3905     if (log && namespace_decl.GetNamespaceDecl())
3906     {
3907         GetObjectFile()->GetModule()->LogMessage (log.get(),
3908                                                   "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => clang::NamespaceDecl(%p) \"%s\"",
3909                                                   name.GetCString(),
3910                                                   namespace_decl.GetNamespaceDecl(),
3911                                                   namespace_decl.GetQualifiedName().c_str());
3912     }
3913 
3914     return namespace_decl;
3915 }
3916 
3917 uint32_t
3918 SymbolFileDWARF::FindTypes(std::vector<dw_offset_t> die_offsets, uint32_t max_matches, TypeList& types)
3919 {
3920     // Remember how many sc_list are in the list before we search in case
3921     // we are appending the results to a variable list.
3922     uint32_t original_size = types.GetSize();
3923 
3924     const uint32_t num_die_offsets = die_offsets.size();
3925     // Parse all of the types we found from the pubtypes matches
3926     uint32_t i;
3927     uint32_t num_matches = 0;
3928     for (i = 0; i < num_die_offsets; ++i)
3929     {
3930         Type *matching_type = ResolveTypeUID (die_offsets[i]);
3931         if (matching_type)
3932         {
3933             // We found a type pointer, now find the shared pointer form our type list
3934             types.InsertUnique (matching_type->shared_from_this());
3935             ++num_matches;
3936             if (num_matches >= max_matches)
3937                 break;
3938         }
3939     }
3940 
3941     // Return the number of variable that were appended to the list
3942     return types.GetSize() - original_size;
3943 }
3944 
3945 
3946 size_t
3947 SymbolFileDWARF::ParseChildParameters (const SymbolContext& sc,
3948                                        clang::DeclContext *containing_decl_ctx,
3949                                        DWARFCompileUnit* dwarf_cu,
3950                                        const DWARFDebugInfoEntry *parent_die,
3951                                        bool skip_artificial,
3952                                        bool &is_static,
3953                                        TypeList* type_list,
3954                                        std::vector<clang_type_t>& function_param_types,
3955                                        std::vector<clang::ParmVarDecl*>& function_param_decls,
3956                                        unsigned &type_quals,
3957                                        ClangASTContext::TemplateParameterInfos &template_param_infos)
3958 {
3959     if (parent_die == NULL)
3960         return 0;
3961 
3962     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
3963 
3964     size_t arg_idx = 0;
3965     const DWARFDebugInfoEntry *die;
3966     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
3967     {
3968         dw_tag_t tag = die->Tag();
3969         switch (tag)
3970         {
3971         case DW_TAG_formal_parameter:
3972             {
3973                 DWARFDebugInfoEntry::Attributes attributes;
3974                 const size_t num_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
3975                 if (num_attributes > 0)
3976                 {
3977                     const char *name = NULL;
3978                     Declaration decl;
3979                     dw_offset_t param_type_die_offset = DW_INVALID_OFFSET;
3980                     bool is_artificial = false;
3981                     // one of None, Auto, Register, Extern, Static, PrivateExtern
3982 
3983                     clang::StorageClass storage = clang::SC_None;
3984                     uint32_t i;
3985                     for (i=0; i<num_attributes; ++i)
3986                     {
3987                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
3988                         DWARFFormValue form_value;
3989                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
3990                         {
3991                             switch (attr)
3992                             {
3993                             case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
3994                             case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
3995                             case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
3996                             case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
3997                             case DW_AT_type:        param_type_die_offset = form_value.Reference(dwarf_cu); break;
3998                             case DW_AT_artificial:  is_artificial = form_value.Unsigned() != 0; break;
3999                             case DW_AT_location:
4000     //                          if (form_value.BlockData())
4001     //                          {
4002     //                              const DataExtractor& debug_info_data = debug_info();
4003     //                              uint32_t block_length = form_value.Unsigned();
4004     //                              DataExtractor location(debug_info_data, form_value.BlockData() - debug_info_data.GetDataStart(), block_length);
4005     //                          }
4006     //                          else
4007     //                          {
4008     //                          }
4009     //                          break;
4010                             case DW_AT_const_value:
4011                             case DW_AT_default_value:
4012                             case DW_AT_description:
4013                             case DW_AT_endianity:
4014                             case DW_AT_is_optional:
4015                             case DW_AT_segment:
4016                             case DW_AT_variable_parameter:
4017                             default:
4018                             case DW_AT_abstract_origin:
4019                             case DW_AT_sibling:
4020                                 break;
4021                             }
4022                         }
4023                     }
4024 
4025                     bool skip = false;
4026                     if (skip_artificial)
4027                     {
4028                         if (is_artificial)
4029                         {
4030                             // In order to determine if a C++ member function is
4031                             // "const" we have to look at the const-ness of "this"...
4032                             // Ugly, but that
4033                             if (arg_idx == 0)
4034                             {
4035                                 if (DeclKindIsCXXClass(containing_decl_ctx->getDeclKind()))
4036                                 {
4037                                     // Often times compilers omit the "this" name for the
4038                                     // specification DIEs, so we can't rely upon the name
4039                                     // being in the formal parameter DIE...
4040                                     if (name == NULL || ::strcmp(name, "this")==0)
4041                                     {
4042                                         Type *this_type = ResolveTypeUID (param_type_die_offset);
4043                                         if (this_type)
4044                                         {
4045                                             uint32_t encoding_mask = this_type->GetEncodingMask();
4046                                             if (encoding_mask & Type::eEncodingIsPointerUID)
4047                                             {
4048                                                 is_static = false;
4049 
4050                                                 if (encoding_mask & (1u << Type::eEncodingIsConstUID))
4051                                                     type_quals |= clang::Qualifiers::Const;
4052                                                 if (encoding_mask & (1u << Type::eEncodingIsVolatileUID))
4053                                                     type_quals |= clang::Qualifiers::Volatile;
4054                                             }
4055                                         }
4056                                     }
4057                                 }
4058                             }
4059                             skip = true;
4060                         }
4061                         else
4062                         {
4063 
4064                             // HACK: Objective C formal parameters "self" and "_cmd"
4065                             // are not marked as artificial in the DWARF...
4066                             CompileUnit *comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
4067                             if (comp_unit)
4068                             {
4069                                 switch (comp_unit->GetLanguage())
4070                                 {
4071                                     case eLanguageTypeObjC:
4072                                     case eLanguageTypeObjC_plus_plus:
4073                                         if (name && name[0] && (strcmp (name, "self") == 0 || strcmp (name, "_cmd") == 0))
4074                                             skip = true;
4075                                         break;
4076                                     default:
4077                                         break;
4078                                 }
4079                             }
4080                         }
4081                     }
4082 
4083                     if (!skip)
4084                     {
4085                         Type *type = ResolveTypeUID(param_type_die_offset);
4086                         if (type)
4087                         {
4088                             function_param_types.push_back (type->GetClangForwardType());
4089 
4090                             clang::ParmVarDecl *param_var_decl = GetClangASTContext().CreateParameterDeclaration (name,
4091                                                                                                                   type->GetClangForwardType(),
4092                                                                                                                   storage);
4093                             assert(param_var_decl);
4094                             function_param_decls.push_back(param_var_decl);
4095 
4096                             GetClangASTContext().SetMetadataAsUserID ((uintptr_t)param_var_decl, MakeUserID(die->GetOffset()));
4097                         }
4098                     }
4099                 }
4100                 arg_idx++;
4101             }
4102             break;
4103 
4104         case DW_TAG_template_type_parameter:
4105         case DW_TAG_template_value_parameter:
4106             ParseTemplateDIE (dwarf_cu, die,template_param_infos);
4107             break;
4108 
4109         default:
4110             break;
4111         }
4112     }
4113     return arg_idx;
4114 }
4115 
4116 size_t
4117 SymbolFileDWARF::ParseChildEnumerators
4118 (
4119     const SymbolContext& sc,
4120     clang_type_t  enumerator_clang_type,
4121     uint32_t enumerator_byte_size,
4122     DWARFCompileUnit* dwarf_cu,
4123     const DWARFDebugInfoEntry *parent_die
4124 )
4125 {
4126     if (parent_die == NULL)
4127         return 0;
4128 
4129     size_t enumerators_added = 0;
4130     const DWARFDebugInfoEntry *die;
4131     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
4132 
4133     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
4134     {
4135         const dw_tag_t tag = die->Tag();
4136         if (tag == DW_TAG_enumerator)
4137         {
4138             DWARFDebugInfoEntry::Attributes attributes;
4139             const size_t num_child_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
4140             if (num_child_attributes > 0)
4141             {
4142                 const char *name = NULL;
4143                 bool got_value = false;
4144                 int64_t enum_value = 0;
4145                 Declaration decl;
4146 
4147                 uint32_t i;
4148                 for (i=0; i<num_child_attributes; ++i)
4149                 {
4150                     const dw_attr_t attr = attributes.AttributeAtIndex(i);
4151                     DWARFFormValue form_value;
4152                     if (attributes.ExtractFormValueAtIndex(this, i, form_value))
4153                     {
4154                         switch (attr)
4155                         {
4156                         case DW_AT_const_value:
4157                             got_value = true;
4158                             enum_value = form_value.Unsigned();
4159                             break;
4160 
4161                         case DW_AT_name:
4162                             name = form_value.AsCString(&get_debug_str_data());
4163                             break;
4164 
4165                         case DW_AT_description:
4166                         default:
4167                         case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
4168                         case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
4169                         case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
4170                         case DW_AT_sibling:
4171                             break;
4172                         }
4173                     }
4174                 }
4175 
4176                 if (name && name[0] && got_value)
4177                 {
4178                     GetClangASTContext().AddEnumerationValueToEnumerationType (enumerator_clang_type,
4179                                                                                enumerator_clang_type,
4180                                                                                decl,
4181                                                                                name,
4182                                                                                enum_value,
4183                                                                                enumerator_byte_size * 8);
4184                     ++enumerators_added;
4185                 }
4186             }
4187         }
4188     }
4189     return enumerators_added;
4190 }
4191 
4192 void
4193 SymbolFileDWARF::ParseChildArrayInfo
4194 (
4195     const SymbolContext& sc,
4196     DWARFCompileUnit* dwarf_cu,
4197     const DWARFDebugInfoEntry *parent_die,
4198     int64_t& first_index,
4199     std::vector<uint64_t>& element_orders,
4200     uint32_t& byte_stride,
4201     uint32_t& bit_stride
4202 )
4203 {
4204     if (parent_die == NULL)
4205         return;
4206 
4207     const DWARFDebugInfoEntry *die;
4208     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
4209     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
4210     {
4211         const dw_tag_t tag = die->Tag();
4212         switch (tag)
4213         {
4214         case DW_TAG_subrange_type:
4215             {
4216                 DWARFDebugInfoEntry::Attributes attributes;
4217                 const size_t num_child_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
4218                 if (num_child_attributes > 0)
4219                 {
4220                     uint64_t num_elements = 0;
4221                     uint64_t lower_bound = 0;
4222                     uint64_t upper_bound = 0;
4223                     bool upper_bound_valid = false;
4224                     uint32_t i;
4225                     for (i=0; i<num_child_attributes; ++i)
4226                     {
4227                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
4228                         DWARFFormValue form_value;
4229                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
4230                         {
4231                             switch (attr)
4232                             {
4233                             case DW_AT_name:
4234                                 break;
4235 
4236                             case DW_AT_count:
4237                                 num_elements = form_value.Unsigned();
4238                                 break;
4239 
4240                             case DW_AT_bit_stride:
4241                                 bit_stride = form_value.Unsigned();
4242                                 break;
4243 
4244                             case DW_AT_byte_stride:
4245                                 byte_stride = form_value.Unsigned();
4246                                 break;
4247 
4248                             case DW_AT_lower_bound:
4249                                 lower_bound = form_value.Unsigned();
4250                                 break;
4251 
4252                             case DW_AT_upper_bound:
4253                                 upper_bound_valid = true;
4254                                 upper_bound = form_value.Unsigned();
4255                                 break;
4256 
4257                             default:
4258                             case DW_AT_abstract_origin:
4259                             case DW_AT_accessibility:
4260                             case DW_AT_allocated:
4261                             case DW_AT_associated:
4262                             case DW_AT_data_location:
4263                             case DW_AT_declaration:
4264                             case DW_AT_description:
4265                             case DW_AT_sibling:
4266                             case DW_AT_threads_scaled:
4267                             case DW_AT_type:
4268                             case DW_AT_visibility:
4269                                 break;
4270                             }
4271                         }
4272                     }
4273 
4274                     if (num_elements == 0)
4275                     {
4276                         if (upper_bound_valid && upper_bound >= lower_bound)
4277                             num_elements = upper_bound - lower_bound + 1;
4278                     }
4279 
4280                     element_orders.push_back (num_elements);
4281                 }
4282             }
4283             break;
4284         }
4285     }
4286 }
4287 
4288 TypeSP
4289 SymbolFileDWARF::GetTypeForDIE (DWARFCompileUnit *dwarf_cu, const DWARFDebugInfoEntry* die)
4290 {
4291     TypeSP type_sp;
4292     if (die != NULL)
4293     {
4294         assert(dwarf_cu != NULL);
4295         Type *type_ptr = m_die_to_type.lookup (die);
4296         if (type_ptr == NULL)
4297         {
4298             CompileUnit* lldb_cu = GetCompUnitForDWARFCompUnit(dwarf_cu);
4299             assert (lldb_cu);
4300             SymbolContext sc(lldb_cu);
4301             type_sp = ParseType(sc, dwarf_cu, die, NULL);
4302         }
4303         else if (type_ptr != DIE_IS_BEING_PARSED)
4304         {
4305             // Grab the existing type from the master types lists
4306             type_sp = type_ptr->shared_from_this();
4307         }
4308 
4309     }
4310     return type_sp;
4311 }
4312 
4313 clang::DeclContext *
4314 SymbolFileDWARF::GetClangDeclContextContainingDIEOffset (dw_offset_t die_offset)
4315 {
4316     if (die_offset != DW_INVALID_OFFSET)
4317     {
4318         DWARFCompileUnitSP cu_sp;
4319         const DWARFDebugInfoEntry* die = DebugInfo()->GetDIEPtr(die_offset, &cu_sp);
4320         return GetClangDeclContextContainingDIE (cu_sp.get(), die, NULL);
4321     }
4322     return NULL;
4323 }
4324 
4325 clang::DeclContext *
4326 SymbolFileDWARF::GetClangDeclContextForDIEOffset (const SymbolContext &sc, dw_offset_t die_offset)
4327 {
4328     if (die_offset != DW_INVALID_OFFSET)
4329     {
4330         DWARFDebugInfo* debug_info = DebugInfo();
4331         if (debug_info)
4332         {
4333             DWARFCompileUnitSP cu_sp;
4334             const DWARFDebugInfoEntry* die = debug_info->GetDIEPtr(die_offset, &cu_sp);
4335             if (die)
4336                 return GetClangDeclContextForDIE (sc, cu_sp.get(), die);
4337         }
4338     }
4339     return NULL;
4340 }
4341 
4342 clang::NamespaceDecl *
4343 SymbolFileDWARF::ResolveNamespaceDIE (DWARFCompileUnit *dwarf_cu, const DWARFDebugInfoEntry *die)
4344 {
4345     if (die && die->Tag() == DW_TAG_namespace)
4346     {
4347         // See if we already parsed this namespace DIE and associated it with a
4348         // uniqued namespace declaration
4349         clang::NamespaceDecl *namespace_decl = static_cast<clang::NamespaceDecl *>(m_die_to_decl_ctx[die]);
4350         if (namespace_decl)
4351             return namespace_decl;
4352         else
4353         {
4354             const char *namespace_name = die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_name, NULL);
4355             clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, NULL);
4356             namespace_decl = GetClangASTContext().GetUniqueNamespaceDeclaration (namespace_name, containing_decl_ctx);
4357             LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
4358             if (log)
4359             {
4360                 if (namespace_name)
4361                 {
4362                     GetObjectFile()->GetModule()->LogMessage (log.get(),
4363                                                               "ASTContext => %p: 0x%8.8" PRIx64 ": DW_TAG_namespace with DW_AT_name(\"%s\") => clang::NamespaceDecl *%p (original = %p)",
4364                                                               GetClangASTContext().getASTContext(),
4365                                                               MakeUserID(die->GetOffset()),
4366                                                               namespace_name,
4367                                                               namespace_decl,
4368                                                               namespace_decl->getOriginalNamespace());
4369                 }
4370                 else
4371                 {
4372                     GetObjectFile()->GetModule()->LogMessage (log.get(),
4373                                                               "ASTContext => %p: 0x%8.8" PRIx64 ": DW_TAG_namespace (anonymous) => clang::NamespaceDecl *%p (original = %p)",
4374                                                               GetClangASTContext().getASTContext(),
4375                                                               MakeUserID(die->GetOffset()),
4376                                                               namespace_decl,
4377                                                               namespace_decl->getOriginalNamespace());
4378                 }
4379             }
4380 
4381             if (namespace_decl)
4382                 LinkDeclContextToDIE((clang::DeclContext*)namespace_decl, die);
4383             return namespace_decl;
4384         }
4385     }
4386     return NULL;
4387 }
4388 
4389 clang::DeclContext *
4390 SymbolFileDWARF::GetClangDeclContextForDIE (const SymbolContext &sc, DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
4391 {
4392     clang::DeclContext *clang_decl_ctx = GetCachedClangDeclContextForDIE (die);
4393     if (clang_decl_ctx)
4394         return clang_decl_ctx;
4395     // If this DIE has a specification, or an abstract origin, then trace to those.
4396 
4397     dw_offset_t die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_specification, DW_INVALID_OFFSET);
4398     if (die_offset != DW_INVALID_OFFSET)
4399         return GetClangDeclContextForDIEOffset (sc, die_offset);
4400 
4401     die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_abstract_origin, DW_INVALID_OFFSET);
4402     if (die_offset != DW_INVALID_OFFSET)
4403         return GetClangDeclContextForDIEOffset (sc, die_offset);
4404 
4405     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
4406     if (log)
4407         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));
4408     // This is the DIE we want.  Parse it, then query our map.
4409     bool assert_not_being_parsed = true;
4410     ResolveTypeUID (cu, die, assert_not_being_parsed);
4411 
4412     clang_decl_ctx = GetCachedClangDeclContextForDIE (die);
4413 
4414     return clang_decl_ctx;
4415 }
4416 
4417 clang::DeclContext *
4418 SymbolFileDWARF::GetClangDeclContextContainingDIE (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die, const DWARFDebugInfoEntry **decl_ctx_die_copy)
4419 {
4420     if (m_clang_tu_decl == NULL)
4421         m_clang_tu_decl = GetClangASTContext().getASTContext()->getTranslationUnitDecl();
4422 
4423     const DWARFDebugInfoEntry *decl_ctx_die = GetDeclContextDIEContainingDIE (cu, die);
4424 
4425     if (decl_ctx_die_copy)
4426         *decl_ctx_die_copy = decl_ctx_die;
4427 
4428     if (decl_ctx_die)
4429     {
4430 
4431         DIEToDeclContextMap::iterator pos = m_die_to_decl_ctx.find (decl_ctx_die);
4432         if (pos != m_die_to_decl_ctx.end())
4433             return pos->second;
4434 
4435         switch (decl_ctx_die->Tag())
4436         {
4437         case DW_TAG_compile_unit:
4438             return m_clang_tu_decl;
4439 
4440         case DW_TAG_namespace:
4441             return ResolveNamespaceDIE (cu, decl_ctx_die);
4442             break;
4443 
4444         case DW_TAG_structure_type:
4445         case DW_TAG_union_type:
4446         case DW_TAG_class_type:
4447             {
4448                 Type* type = ResolveType (cu, decl_ctx_die);
4449                 if (type)
4450                 {
4451                     clang::DeclContext *decl_ctx = ClangASTContext::GetDeclContextForType (type->GetClangForwardType ());
4452                     if (decl_ctx)
4453                     {
4454                         LinkDeclContextToDIE (decl_ctx, decl_ctx_die);
4455                         if (decl_ctx)
4456                             return decl_ctx;
4457                     }
4458                 }
4459             }
4460             break;
4461 
4462         default:
4463             break;
4464         }
4465     }
4466     return m_clang_tu_decl;
4467 }
4468 
4469 
4470 const DWARFDebugInfoEntry *
4471 SymbolFileDWARF::GetDeclContextDIEContainingDIE (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
4472 {
4473     if (cu && die)
4474     {
4475         const DWARFDebugInfoEntry * const decl_die = die;
4476 
4477         while (die != NULL)
4478         {
4479             // If this is the original DIE that we are searching for a declaration
4480             // for, then don't look in the cache as we don't want our own decl
4481             // context to be our decl context...
4482             if (decl_die != die)
4483             {
4484                 switch (die->Tag())
4485                 {
4486                     case DW_TAG_compile_unit:
4487                     case DW_TAG_namespace:
4488                     case DW_TAG_structure_type:
4489                     case DW_TAG_union_type:
4490                     case DW_TAG_class_type:
4491                         return die;
4492 
4493                     default:
4494                         break;
4495                 }
4496             }
4497 
4498             dw_offset_t die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_specification, DW_INVALID_OFFSET);
4499             if (die_offset != DW_INVALID_OFFSET)
4500             {
4501                 DWARFCompileUnit *spec_cu = cu;
4502                 const DWARFDebugInfoEntry *spec_die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &spec_cu);
4503                 const DWARFDebugInfoEntry *spec_die_decl_ctx_die = GetDeclContextDIEContainingDIE (spec_cu, spec_die);
4504                 if (spec_die_decl_ctx_die)
4505                     return spec_die_decl_ctx_die;
4506             }
4507 
4508             die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_abstract_origin, DW_INVALID_OFFSET);
4509             if (die_offset != DW_INVALID_OFFSET)
4510             {
4511                 DWARFCompileUnit *abs_cu = cu;
4512                 const DWARFDebugInfoEntry *abs_die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &abs_cu);
4513                 const DWARFDebugInfoEntry *abs_die_decl_ctx_die = GetDeclContextDIEContainingDIE (abs_cu, abs_die);
4514                 if (abs_die_decl_ctx_die)
4515                     return abs_die_decl_ctx_die;
4516             }
4517 
4518             die = die->GetParent();
4519         }
4520     }
4521     return NULL;
4522 }
4523 
4524 
4525 Symbol *
4526 SymbolFileDWARF::GetObjCClassSymbol (const ConstString &objc_class_name)
4527 {
4528     Symbol *objc_class_symbol = NULL;
4529     if (m_obj_file)
4530     {
4531         Symtab *symtab = m_obj_file->GetSymtab();
4532         if (symtab)
4533         {
4534             objc_class_symbol = symtab->FindFirstSymbolWithNameAndType (objc_class_name,
4535                                                                         eSymbolTypeObjCClass,
4536                                                                         Symtab::eDebugNo,
4537                                                                         Symtab::eVisibilityAny);
4538         }
4539     }
4540     return objc_class_symbol;
4541 }
4542 
4543 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If they don't
4544 // then we can end up looking through all class types for a complete type and never find
4545 // the full definition. We need to know if this attribute is supported, so we determine
4546 // this here and cache th result. We also need to worry about the debug map DWARF file
4547 // if we are doing darwin DWARF in .o file debugging.
4548 bool
4549 SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type (DWARFCompileUnit *cu)
4550 {
4551     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate)
4552     {
4553         m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
4554         if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
4555             m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
4556         else
4557         {
4558             DWARFDebugInfo* debug_info = DebugInfo();
4559             const uint32_t num_compile_units = GetNumCompileUnits();
4560             for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
4561             {
4562                 DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
4563                 if (dwarf_cu != cu && dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type())
4564                 {
4565                     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
4566                     break;
4567                 }
4568             }
4569         }
4570         if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo && GetDebugMapSymfile ())
4571             return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type (this);
4572     }
4573     return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
4574 }
4575 
4576 // This function can be used when a DIE is found that is a forward declaration
4577 // DIE and we want to try and find a type that has the complete definition.
4578 TypeSP
4579 SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE (const DWARFDebugInfoEntry *die,
4580                                                        const ConstString &type_name,
4581                                                        bool must_be_implementation)
4582 {
4583 
4584     TypeSP type_sp;
4585 
4586     if (!type_name || (must_be_implementation && !GetObjCClassSymbol (type_name)))
4587         return type_sp;
4588 
4589     DIEArray die_offsets;
4590 
4591     if (m_using_apple_tables)
4592     {
4593         if (m_apple_types_ap.get())
4594         {
4595             const char *name_cstr = type_name.GetCString();
4596             m_apple_types_ap->FindCompleteObjCClassByName (name_cstr, die_offsets, must_be_implementation);
4597         }
4598     }
4599     else
4600     {
4601         if (!m_indexed)
4602             Index ();
4603 
4604         m_type_index.Find (type_name, die_offsets);
4605     }
4606 
4607     const size_t num_matches = die_offsets.size();
4608 
4609     DWARFCompileUnit* type_cu = NULL;
4610     const DWARFDebugInfoEntry* type_die = NULL;
4611     if (num_matches)
4612     {
4613         DWARFDebugInfo* debug_info = DebugInfo();
4614         for (size_t i=0; i<num_matches; ++i)
4615         {
4616             const dw_offset_t die_offset = die_offsets[i];
4617             type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
4618 
4619             if (type_die)
4620             {
4621                 bool try_resolving_type = false;
4622 
4623                 // Don't try and resolve the DIE we are looking for with the DIE itself!
4624                 if (type_die != die)
4625                 {
4626                     switch (type_die->Tag())
4627                     {
4628                         case DW_TAG_class_type:
4629                         case DW_TAG_structure_type:
4630                             try_resolving_type = true;
4631                             break;
4632                         default:
4633                             break;
4634                     }
4635                 }
4636 
4637                 if (try_resolving_type)
4638                 {
4639 					if (must_be_implementation && type_cu->Supports_DW_AT_APPLE_objc_complete_type())
4640 	                    try_resolving_type = type_die->GetAttributeValueAsUnsigned (this, type_cu, DW_AT_APPLE_objc_complete_type, 0);
4641 
4642                     if (try_resolving_type)
4643                     {
4644                         Type *resolved_type = ResolveType (type_cu, type_die, false);
4645                         if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
4646                         {
4647                             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",
4648                                           MakeUserID(die->GetOffset()),
4649                                           MakeUserID(dwarf_cu->GetOffset()),
4650                                           m_obj_file->GetFileSpec().GetFilename().AsCString(),
4651                                           MakeUserID(type_die->GetOffset()),
4652                                           MakeUserID(type_cu->GetOffset()));
4653 
4654                             if (die)
4655                                 m_die_to_type[die] = resolved_type;
4656                             type_sp = resolved_type->shared_from_this();
4657                             break;
4658                         }
4659                     }
4660                 }
4661             }
4662             else
4663             {
4664                 if (m_using_apple_tables)
4665                 {
4666                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
4667                                                                die_offset, type_name.GetCString());
4668                 }
4669             }
4670 
4671         }
4672     }
4673     return type_sp;
4674 }
4675 
4676 
4677 //----------------------------------------------------------------------
4678 // This function helps to ensure that the declaration contexts match for
4679 // two different DIEs. Often times debug information will refer to a
4680 // forward declaration of a type (the equivalent of "struct my_struct;".
4681 // There will often be a declaration of that type elsewhere that has the
4682 // full definition. When we go looking for the full type "my_struct", we
4683 // will find one or more matches in the accelerator tables and we will
4684 // then need to make sure the type was in the same declaration context
4685 // as the original DIE. This function can efficiently compare two DIEs
4686 // and will return true when the declaration context matches, and false
4687 // when they don't.
4688 //----------------------------------------------------------------------
4689 bool
4690 SymbolFileDWARF::DIEDeclContextsMatch (DWARFCompileUnit* cu1, const DWARFDebugInfoEntry *die1,
4691                                        DWARFCompileUnit* cu2, const DWARFDebugInfoEntry *die2)
4692 {
4693     if (die1 == die2)
4694         return true;
4695 
4696 #if defined (LLDB_CONFIGURATION_DEBUG)
4697     // You can't and shouldn't call this function with a compile unit from
4698     // two different SymbolFileDWARF instances.
4699     assert (DebugInfo()->ContainsCompileUnit (cu1));
4700     assert (DebugInfo()->ContainsCompileUnit (cu2));
4701 #endif
4702 
4703     DWARFDIECollection decl_ctx_1;
4704     DWARFDIECollection decl_ctx_2;
4705     //The declaration DIE stack is a stack of the declaration context
4706     // DIEs all the way back to the compile unit. If a type "T" is
4707     // declared inside a class "B", and class "B" is declared inside
4708     // a class "A" and class "A" is in a namespace "lldb", and the
4709     // namespace is in a compile unit, there will be a stack of DIEs:
4710     //
4711     //   [0] DW_TAG_class_type for "B"
4712     //   [1] DW_TAG_class_type for "A"
4713     //   [2] DW_TAG_namespace  for "lldb"
4714     //   [3] DW_TAG_compile_unit for the source file.
4715     //
4716     // We grab both contexts and make sure that everything matches
4717     // all the way back to the compiler unit.
4718 
4719     // First lets grab the decl contexts for both DIEs
4720     die1->GetDeclContextDIEs (this, cu1, decl_ctx_1);
4721     die2->GetDeclContextDIEs (this, cu2, decl_ctx_2);
4722     // Make sure the context arrays have the same size, otherwise
4723     // we are done
4724     const size_t count1 = decl_ctx_1.Size();
4725     const size_t count2 = decl_ctx_2.Size();
4726     if (count1 != count2)
4727         return false;
4728 
4729     // Make sure the DW_TAG values match all the way back up the the
4730     // compile unit. If they don't, then we are done.
4731     const DWARFDebugInfoEntry *decl_ctx_die1;
4732     const DWARFDebugInfoEntry *decl_ctx_die2;
4733     size_t i;
4734     for (i=0; i<count1; i++)
4735     {
4736         decl_ctx_die1 = decl_ctx_1.GetDIEPtrAtIndex (i);
4737         decl_ctx_die2 = decl_ctx_2.GetDIEPtrAtIndex (i);
4738         if (decl_ctx_die1->Tag() != decl_ctx_die2->Tag())
4739             return false;
4740     }
4741 #if defined LLDB_CONFIGURATION_DEBUG
4742 
4743     // Make sure the top item in the decl context die array is always
4744     // DW_TAG_compile_unit. If it isn't then something went wrong in
4745     // the DWARFDebugInfoEntry::GetDeclContextDIEs() function...
4746     assert (decl_ctx_1.GetDIEPtrAtIndex (count1 - 1)->Tag() == DW_TAG_compile_unit);
4747 
4748 #endif
4749     // Always skip the compile unit when comparing by only iterating up to
4750     // "count - 1". Here we compare the names as we go.
4751     for (i=0; i<count1 - 1; i++)
4752     {
4753         decl_ctx_die1 = decl_ctx_1.GetDIEPtrAtIndex (i);
4754         decl_ctx_die2 = decl_ctx_2.GetDIEPtrAtIndex (i);
4755         const char *name1 = decl_ctx_die1->GetName(this, cu1);
4756         const char *name2 = decl_ctx_die2->GetName(this, cu2);
4757         // If the string was from a DW_FORM_strp, then the pointer will often
4758         // be the same!
4759         if (name1 == name2)
4760             continue;
4761 
4762         // Name pointers are not equal, so only compare the strings
4763         // if both are not NULL.
4764         if (name1 && name2)
4765         {
4766             // If the strings don't compare, we are done...
4767             if (strcmp(name1, name2) != 0)
4768                 return false;
4769         }
4770         else
4771         {
4772             // One name was NULL while the other wasn't
4773             return false;
4774         }
4775     }
4776     // We made it through all of the checks and the declaration contexts
4777     // are equal.
4778     return true;
4779 }
4780 
4781 // This function can be used when a DIE is found that is a forward declaration
4782 // DIE and we want to try and find a type that has the complete definition.
4783 // "cu" and "die" must be from this SymbolFileDWARF
4784 TypeSP
4785 SymbolFileDWARF::FindDefinitionTypeForDIE (DWARFCompileUnit* cu,
4786                                            const DWARFDebugInfoEntry *die,
4787                                            const ConstString &type_name)
4788 {
4789     TypeSP type_sp;
4790 
4791 #if defined (LLDB_CONFIGURATION_DEBUG)
4792     // You can't and shouldn't call this function with a compile unit from
4793     // another SymbolFileDWARF instance.
4794     assert (DebugInfo()->ContainsCompileUnit (cu));
4795 #endif
4796 
4797     if (cu == NULL || die == NULL || !type_name)
4798         return type_sp;
4799 
4800     LogSP log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION|DWARF_LOG_LOOKUPS));
4801     if (log)
4802     {
4803         std::string qualified_name;
4804         die->GetQualifiedName(this, cu, qualified_name);
4805         GetObjectFile()->GetModule()->LogMessage (log.get(),
4806                                                   "SymbolFileDWARF::FindDefinitionTypeForDIE(die=0x%8.8x (%s), name='%s')",
4807                                                   die->GetOffset(),
4808                                                   qualified_name.c_str(),
4809                                                   type_name.GetCString());
4810     }
4811 
4812     DIEArray die_offsets;
4813 
4814     if (m_using_apple_tables)
4815     {
4816         if (m_apple_types_ap.get())
4817         {
4818             if (m_apple_types_ap->GetHeader().header_data.atoms.size() > 1)
4819             {
4820                 m_apple_types_ap->FindByNameAndTag (type_name.GetCString(), die->Tag(), die_offsets);
4821             }
4822             else
4823             {
4824                 m_apple_types_ap->FindByName (type_name.GetCString(), die_offsets);
4825             }
4826         }
4827     }
4828     else
4829     {
4830         if (!m_indexed)
4831             Index ();
4832 
4833         m_type_index.Find (type_name, die_offsets);
4834     }
4835 
4836     const size_t num_matches = die_offsets.size();
4837 
4838     const dw_tag_t die_tag = die->Tag();
4839 
4840     DWARFCompileUnit* type_cu = NULL;
4841     const DWARFDebugInfoEntry* type_die = NULL;
4842     if (num_matches)
4843     {
4844         DWARFDebugInfo* debug_info = DebugInfo();
4845         for (size_t i=0; i<num_matches; ++i)
4846         {
4847             const dw_offset_t die_offset = die_offsets[i];
4848             type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
4849 
4850             if (type_die)
4851             {
4852                 bool try_resolving_type = false;
4853 
4854                 // Don't try and resolve the DIE we are looking for with the DIE itself!
4855                 if (type_die != die)
4856                 {
4857                     const dw_tag_t type_die_tag = type_die->Tag();
4858                     // Make sure the tags match
4859                     if (type_die_tag == die_tag)
4860                     {
4861                         // The tags match, lets try resolving this type
4862                         try_resolving_type = true;
4863                     }
4864                     else
4865                     {
4866                         // The tags don't match, but we need to watch our for a
4867                         // forward declaration for a struct and ("struct foo")
4868                         // ends up being a class ("class foo { ... };") or
4869                         // vice versa.
4870                         switch (type_die_tag)
4871                         {
4872                         case DW_TAG_class_type:
4873                             // We had a "class foo", see if we ended up with a "struct foo { ... };"
4874                             try_resolving_type = (die_tag == DW_TAG_structure_type);
4875                             break;
4876                         case DW_TAG_structure_type:
4877                             // We had a "struct foo", see if we ended up with a "class foo { ... };"
4878                             try_resolving_type = (die_tag == DW_TAG_class_type);
4879                             break;
4880                         default:
4881                             // Tags don't match, don't event try to resolve
4882                             // using this type whose name matches....
4883                             break;
4884                         }
4885                     }
4886                 }
4887 
4888                 if (try_resolving_type)
4889                 {
4890                     if (log)
4891                     {
4892                         std::string qualified_name;
4893                         type_die->GetQualifiedName(this, cu, qualified_name);
4894                         GetObjectFile()->GetModule()->LogMessage (log.get(),
4895                                                                   "SymbolFileDWARF::FindDefinitionTypeForDIE(die=0x%8.8x, name='%s') trying die=0x%8.8x (%s)",
4896                                                                   die->GetOffset(),
4897                                                                   type_name.GetCString(),
4898                                                                   type_die->GetOffset(),
4899                                                                   qualified_name.c_str());
4900                     }
4901 
4902                     // Make sure the decl contexts match all the way up
4903                     if (DIEDeclContextsMatch(cu, die, type_cu, type_die))
4904                     {
4905                         Type *resolved_type = ResolveType (type_cu, type_die, false);
4906                         if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
4907                         {
4908                             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",
4909                                           MakeUserID(die->GetOffset()),
4910                                           MakeUserID(dwarf_cu->GetOffset()),
4911                                           m_obj_file->GetFileSpec().GetFilename().AsCString(),
4912                                           MakeUserID(type_die->GetOffset()),
4913                                           MakeUserID(type_cu->GetOffset()));
4914 
4915                             m_die_to_type[die] = resolved_type;
4916                             type_sp = resolved_type->shared_from_this();
4917                             break;
4918                         }
4919                     }
4920                 }
4921                 else
4922                 {
4923                     if (log)
4924                     {
4925                         std::string qualified_name;
4926                         type_die->GetQualifiedName(this, cu, qualified_name);
4927                         GetObjectFile()->GetModule()->LogMessage (log.get(),
4928                                                                   "SymbolFileDWARF::FindDefinitionTypeForDIE(die=0x%8.8x, name='%s') ignoring die=0x%8.8x (%s)",
4929                                                                   die->GetOffset(),
4930                                                                   type_name.GetCString(),
4931                                                                   type_die->GetOffset(),
4932                                                                   qualified_name.c_str());
4933                     }
4934                 }
4935             }
4936             else
4937             {
4938                 if (m_using_apple_tables)
4939                 {
4940                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
4941                                                                                die_offset, type_name.GetCString());
4942                 }
4943             }
4944 
4945         }
4946     }
4947     return type_sp;
4948 }
4949 
4950 TypeSP
4951 SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext (const DWARFDeclContext &dwarf_decl_ctx)
4952 {
4953     TypeSP type_sp;
4954 
4955     const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
4956     if (dwarf_decl_ctx_count > 0)
4957     {
4958         const ConstString type_name(dwarf_decl_ctx[0].name);
4959         const dw_tag_t tag = dwarf_decl_ctx[0].tag;
4960 
4961         if (type_name)
4962         {
4963             LogSP log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION|DWARF_LOG_LOOKUPS));
4964             if (log)
4965             {
4966                 GetObjectFile()->GetModule()->LogMessage (log.get(),
4967                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s')",
4968                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
4969                                                           dwarf_decl_ctx.GetQualifiedName());
4970             }
4971 
4972             DIEArray die_offsets;
4973 
4974             if (m_using_apple_tables)
4975             {
4976                 if (m_apple_types_ap.get())
4977                 {
4978                     if (m_apple_types_ap->GetHeader().header_data.atoms.size() > 1)
4979                     {
4980                         m_apple_types_ap->FindByNameAndTag (type_name.GetCString(), tag, die_offsets);
4981                     }
4982                     else
4983                     {
4984                         m_apple_types_ap->FindByName (type_name.GetCString(), die_offsets);
4985                     }
4986                 }
4987             }
4988             else
4989             {
4990                 if (!m_indexed)
4991                     Index ();
4992 
4993                 m_type_index.Find (type_name, die_offsets);
4994             }
4995 
4996             const size_t num_matches = die_offsets.size();
4997 
4998 
4999             DWARFCompileUnit* type_cu = NULL;
5000             const DWARFDebugInfoEntry* type_die = NULL;
5001             if (num_matches)
5002             {
5003                 DWARFDebugInfo* debug_info = DebugInfo();
5004                 for (size_t i=0; i<num_matches; ++i)
5005                 {
5006                     const dw_offset_t die_offset = die_offsets[i];
5007                     type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
5008 
5009                     if (type_die)
5010                     {
5011                         bool try_resolving_type = false;
5012 
5013                         // Don't try and resolve the DIE we are looking for with the DIE itself!
5014                         const dw_tag_t type_tag = type_die->Tag();
5015                         // Make sure the tags match
5016                         if (type_tag == tag)
5017                         {
5018                             // The tags match, lets try resolving this type
5019                             try_resolving_type = true;
5020                         }
5021                         else
5022                         {
5023                             // The tags don't match, but we need to watch our for a
5024                             // forward declaration for a struct and ("struct foo")
5025                             // ends up being a class ("class foo { ... };") or
5026                             // vice versa.
5027                             switch (type_tag)
5028                             {
5029                                 case DW_TAG_class_type:
5030                                     // We had a "class foo", see if we ended up with a "struct foo { ... };"
5031                                     try_resolving_type = (tag == DW_TAG_structure_type);
5032                                     break;
5033                                 case DW_TAG_structure_type:
5034                                     // We had a "struct foo", see if we ended up with a "class foo { ... };"
5035                                     try_resolving_type = (tag == DW_TAG_class_type);
5036                                     break;
5037                                 default:
5038                                     // Tags don't match, don't event try to resolve
5039                                     // using this type whose name matches....
5040                                     break;
5041                             }
5042                         }
5043 
5044                         if (try_resolving_type)
5045                         {
5046                             DWARFDeclContext type_dwarf_decl_ctx;
5047                             type_die->GetDWARFDeclContext (this, type_cu, type_dwarf_decl_ctx);
5048 
5049                             if (log)
5050                             {
5051                                 GetObjectFile()->GetModule()->LogMessage (log.get(),
5052                                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') trying die=0x%8.8x (%s)",
5053                                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
5054                                                                           dwarf_decl_ctx.GetQualifiedName(),
5055                                                                           type_die->GetOffset(),
5056                                                                           type_dwarf_decl_ctx.GetQualifiedName());
5057                             }
5058 
5059                             // Make sure the decl contexts match all the way up
5060                             if (dwarf_decl_ctx == type_dwarf_decl_ctx)
5061                             {
5062                                 Type *resolved_type = ResolveType (type_cu, type_die, false);
5063                                 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
5064                                 {
5065                                     type_sp = resolved_type->shared_from_this();
5066                                     break;
5067                                 }
5068                             }
5069                         }
5070                         else
5071                         {
5072                             if (log)
5073                             {
5074                                 std::string qualified_name;
5075                                 type_die->GetQualifiedName(this, type_cu, qualified_name);
5076                                 GetObjectFile()->GetModule()->LogMessage (log.get(),
5077                                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') ignoring die=0x%8.8x (%s)",
5078                                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
5079                                                                           dwarf_decl_ctx.GetQualifiedName(),
5080                                                                           type_die->GetOffset(),
5081                                                                           qualified_name.c_str());
5082                             }
5083                         }
5084                     }
5085                     else
5086                     {
5087                         if (m_using_apple_tables)
5088                         {
5089                             GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
5090                                                                                        die_offset, type_name.GetCString());
5091                         }
5092                     }
5093 
5094                 }
5095             }
5096         }
5097     }
5098     return type_sp;
5099 }
5100 
5101 bool
5102 SymbolFileDWARF::CopyUniqueClassMethodTypes (Type *class_type,
5103                                              DWARFCompileUnit* src_cu,
5104                                              const DWARFDebugInfoEntry *src_class_die,
5105                                              DWARFCompileUnit* dst_cu,
5106                                              const DWARFDebugInfoEntry *dst_class_die)
5107 {
5108     if (!class_type || !src_cu || !src_class_die || !dst_cu || !dst_class_die)
5109         return false;
5110     if (src_class_die->Tag() != dst_class_die->Tag())
5111         return false;
5112 
5113     // We need to complete the class type so we can get all of the method types
5114     // parsed so we can then unique those types to their equivalent counterparts
5115     // in "dst_cu" and "dst_class_die"
5116     class_type->GetClangFullType();
5117 
5118     const DWARFDebugInfoEntry *src_die;
5119     const DWARFDebugInfoEntry *dst_die;
5120     UniqueCStringMap<const DWARFDebugInfoEntry *> src_name_to_die;
5121     UniqueCStringMap<const DWARFDebugInfoEntry *> dst_name_to_die;
5122     UniqueCStringMap<const DWARFDebugInfoEntry *> src_name_to_die_artificial;
5123     UniqueCStringMap<const DWARFDebugInfoEntry *> dst_name_to_die_artificial;
5124     for (src_die = src_class_die->GetFirstChild(); src_die != NULL; src_die = src_die->GetSibling())
5125     {
5126         if (src_die->Tag() == DW_TAG_subprogram)
5127         {
5128             // Make sure this is a declaration and not a concrete instance by looking
5129             // for DW_AT_declaration set to 1. Sometimes concrete function instances
5130             // are placed inside the class definitions and shouldn't be included in
5131             // the list of things are are tracking here.
5132             if (src_die->GetAttributeValueAsUnsigned(this, src_cu, DW_AT_declaration, 0) == 1)
5133             {
5134                 const char *src_name = src_die->GetMangledName (this, src_cu);
5135                 if (src_name)
5136                 {
5137                     ConstString src_const_name(src_name);
5138                     if (src_die->GetAttributeValueAsUnsigned(this, src_cu, DW_AT_artificial, 0))
5139                         src_name_to_die_artificial.Append(src_const_name.GetCString(), src_die);
5140                     else
5141                         src_name_to_die.Append(src_const_name.GetCString(), src_die);
5142                 }
5143             }
5144         }
5145     }
5146     for (dst_die = dst_class_die->GetFirstChild(); dst_die != NULL; dst_die = dst_die->GetSibling())
5147     {
5148         if (dst_die->Tag() == DW_TAG_subprogram)
5149         {
5150             // Make sure this is a declaration and not a concrete instance by looking
5151             // for DW_AT_declaration set to 1. Sometimes concrete function instances
5152             // are placed inside the class definitions and shouldn't be included in
5153             // the list of things are are tracking here.
5154             if (dst_die->GetAttributeValueAsUnsigned(this, dst_cu, DW_AT_declaration, 0) == 1)
5155             {
5156                 const char *dst_name = dst_die->GetMangledName (this, dst_cu);
5157                 if (dst_name)
5158                 {
5159                     ConstString dst_const_name(dst_name);
5160                     if (dst_die->GetAttributeValueAsUnsigned(this, dst_cu, DW_AT_artificial, 0))
5161                         dst_name_to_die_artificial.Append(dst_const_name.GetCString(), dst_die);
5162                     else
5163                         dst_name_to_die.Append(dst_const_name.GetCString(), dst_die);
5164                 }
5165             }
5166         }
5167     }
5168     const uint32_t src_size = src_name_to_die.GetSize ();
5169     const uint32_t dst_size = dst_name_to_die.GetSize ();
5170     LogSP log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO | DWARF_LOG_TYPE_COMPLETION));
5171 
5172     if (src_size == dst_size)
5173     {
5174         uint32_t idx;
5175         for (idx = 0; idx < src_size; ++idx)
5176         {
5177             src_die = src_name_to_die.GetValueAtIndexUnchecked (idx);
5178             dst_die = dst_name_to_die.GetValueAtIndexUnchecked (idx);
5179 
5180             if (src_die->Tag() != dst_die->Tag())
5181             {
5182                 if (log)
5183                     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)",
5184                                 src_class_die->GetOffset(),
5185                                 dst_class_die->GetOffset(),
5186                                 src_die->GetOffset(),
5187                                 DW_TAG_value_to_name(src_die->Tag()),
5188                                 dst_die->GetOffset(),
5189                                 DW_TAG_value_to_name(src_die->Tag()));
5190                 return false;
5191             }
5192 
5193             const char *src_name = src_die->GetMangledName (this, src_cu);
5194             const char *dst_name = dst_die->GetMangledName (this, dst_cu);
5195 
5196             // Make sure the names match
5197             if (src_name == dst_name || (strcmp (src_name, dst_name) == 0))
5198                 continue;
5199 
5200             if (log)
5201                 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)",
5202                             src_class_die->GetOffset(),
5203                             dst_class_die->GetOffset(),
5204                             src_die->GetOffset(),
5205                             src_name,
5206                             dst_die->GetOffset(),
5207                             dst_name);
5208 
5209             return false;
5210         }
5211 
5212         for (idx = 0; idx < src_size; ++idx)
5213         {
5214             src_die = src_name_to_die.GetValueAtIndexUnchecked (idx);
5215             dst_die = dst_name_to_die.GetValueAtIndexUnchecked (idx);
5216 
5217             clang::DeclContext *src_decl_ctx = m_die_to_decl_ctx[src_die];
5218             if (src_decl_ctx)
5219             {
5220                 if (log)
5221                     log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x", src_decl_ctx, src_die->GetOffset(), dst_die->GetOffset());
5222                 LinkDeclContextToDIE (src_decl_ctx, dst_die);
5223             }
5224             else
5225             {
5226                 if (log)
5227                     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());
5228             }
5229 
5230             Type *src_child_type = m_die_to_type[src_die];
5231             if (src_child_type)
5232             {
5233                 if (log)
5234                     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());
5235                 m_die_to_type[dst_die] = src_child_type;
5236             }
5237             else
5238             {
5239                 if (log)
5240                     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());
5241             }
5242         }
5243 
5244         const uint32_t src_size_artificial = src_name_to_die_artificial.GetSize ();
5245 
5246         UniqueCStringMap<const DWARFDebugInfoEntry *> name_to_die_artificial_not_in_src;
5247 
5248         for (idx = 0; idx < src_size_artificial; ++idx)
5249         {
5250             const char *src_name_artificial = src_name_to_die_artificial.GetCStringAtIndex(idx);
5251             src_die = src_name_to_die_artificial.GetValueAtIndexUnchecked (idx);
5252             dst_die = dst_name_to_die_artificial.Find(src_name_artificial, NULL);
5253 
5254             if (dst_die)
5255             {
5256                 // Erase this entry from the map
5257                 const size_t num_removed = dst_name_to_die_artificial.Erase (src_name_artificial);
5258                 assert (num_removed == 0 || num_removed == 1); // REMOVE THIS
5259                 // Both classes have the artificial types, link them
5260                 clang::DeclContext *src_decl_ctx = m_die_to_decl_ctx[src_die];
5261                 if (src_decl_ctx)
5262                 {
5263                     if (log)
5264                         log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x", src_decl_ctx, src_die->GetOffset(), dst_die->GetOffset());
5265                     LinkDeclContextToDIE (src_decl_ctx, dst_die);
5266                 }
5267                 else
5268                 {
5269                     if (log)
5270                         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());
5271                 }
5272 
5273                 Type *src_child_type = m_die_to_type[src_die];
5274                 if (src_child_type)
5275                 {
5276                     if (log)
5277                         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());
5278                     m_die_to_type[dst_die] = src_child_type;
5279                 }
5280                 else
5281                 {
5282                     if (log)
5283                         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());
5284                 }
5285             }
5286         }
5287         const uint32_t dst_size_artificial = dst_name_to_die_artificial.GetSize ();
5288 
5289         if (dst_size_artificial)
5290         {
5291             for (idx = 0; idx < dst_size_artificial; ++idx)
5292             {
5293                 const char *dst_name_artificial = dst_name_to_die_artificial.GetCStringAtIndex(idx);
5294                 dst_die = dst_name_to_die_artificial.GetValueAtIndexUnchecked (idx);
5295                 if (log)
5296                     log->Printf ("warning: need to create artificial method for 0x%8.8x for method '%s'", dst_die->GetOffset(), dst_name_artificial);
5297             }
5298         }
5299         return true;
5300     }
5301     else if (src_size != 0 && dst_size != 0)
5302     {
5303         if (log)
5304             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)",
5305                         src_class_die->GetOffset(),
5306                         dst_class_die->GetOffset(),
5307                         src_size,
5308                         dst_size);
5309     }
5310     return false;
5311 }
5312 
5313 TypeSP
5314 SymbolFileDWARF::ParseType (const SymbolContext& sc, DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry *die, bool *type_is_new_ptr)
5315 {
5316     TypeSP type_sp;
5317 
5318     if (type_is_new_ptr)
5319         *type_is_new_ptr = false;
5320 
5321 #if defined(LLDB_CONFIGURATION_DEBUG) or defined(LLDB_CONFIGURATION_RELEASE)
5322     static DIEStack g_die_stack;
5323     DIEStack::ScopedPopper scoped_die_logger(g_die_stack);
5324 #endif
5325 
5326     AccessType accessibility = eAccessNone;
5327     if (die != NULL)
5328     {
5329         LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
5330         if (log)
5331         {
5332             const DWARFDebugInfoEntry *context_die;
5333             clang::DeclContext *context = GetClangDeclContextContainingDIE (dwarf_cu, die, &context_die);
5334 
5335             GetObjectFile()->GetModule()->LogMessage (log.get(), "SymbolFileDWARF::ParseType (die = 0x%8.8x, decl_ctx = %p (die 0x%8.8x)) %s name = '%s')",
5336                         die->GetOffset(),
5337                         context,
5338                         context_die->GetOffset(),
5339                         DW_TAG_value_to_name(die->Tag()),
5340                         die->GetName(this, dwarf_cu));
5341 
5342 #if defined(LLDB_CONFIGURATION_DEBUG) or defined(LLDB_CONFIGURATION_RELEASE)
5343             scoped_die_logger.Push (dwarf_cu, die);
5344             g_die_stack.LogDIEs(log.get(), this);
5345 #endif
5346         }
5347 //
5348 //        LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
5349 //        if (log && dwarf_cu)
5350 //        {
5351 //            StreamString s;
5352 //            die->DumpLocation (this, dwarf_cu, s);
5353 //            GetObjectFile()->GetModule()->LogMessage (log.get(), "SymbolFileDwarf::%s %s", __FUNCTION__, s.GetData());
5354 //
5355 //        }
5356 
5357         Type *type_ptr = m_die_to_type.lookup (die);
5358         TypeList* type_list = GetTypeList();
5359         if (type_ptr == NULL)
5360         {
5361             ClangASTContext &ast = GetClangASTContext();
5362             if (type_is_new_ptr)
5363                 *type_is_new_ptr = true;
5364 
5365             const dw_tag_t tag = die->Tag();
5366 
5367             bool is_forward_declaration = false;
5368             DWARFDebugInfoEntry::Attributes attributes;
5369             const char *type_name_cstr = NULL;
5370             ConstString type_name_const_str;
5371             Type::ResolveState resolve_state = Type::eResolveStateUnresolved;
5372             size_t byte_size = 0;
5373             Declaration decl;
5374 
5375             Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID;
5376             clang_type_t clang_type = NULL;
5377 
5378             dw_attr_t attr;
5379 
5380             switch (tag)
5381             {
5382             case DW_TAG_base_type:
5383             case DW_TAG_pointer_type:
5384             case DW_TAG_reference_type:
5385             case DW_TAG_rvalue_reference_type:
5386             case DW_TAG_typedef:
5387             case DW_TAG_const_type:
5388             case DW_TAG_restrict_type:
5389             case DW_TAG_volatile_type:
5390             case DW_TAG_unspecified_type:
5391                 {
5392                     // Set a bit that lets us know that we are currently parsing this
5393                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
5394 
5395                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
5396                     uint32_t encoding = 0;
5397                     lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
5398 
5399                     if (num_attributes > 0)
5400                     {
5401                         uint32_t i;
5402                         for (i=0; i<num_attributes; ++i)
5403                         {
5404                             attr = attributes.AttributeAtIndex(i);
5405                             DWARFFormValue form_value;
5406                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
5407                             {
5408                                 switch (attr)
5409                                 {
5410                                 case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
5411                                 case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
5412                                 case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
5413                                 case DW_AT_name:
5414 
5415                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
5416                                     // Work around a bug in llvm-gcc where they give a name to a reference type which doesn't
5417                                     // include the "&"...
5418                                     if (tag == DW_TAG_reference_type)
5419                                     {
5420                                         if (strchr (type_name_cstr, '&') == NULL)
5421                                             type_name_cstr = NULL;
5422                                     }
5423                                     if (type_name_cstr)
5424                                         type_name_const_str.SetCString(type_name_cstr);
5425                                     break;
5426                                 case DW_AT_byte_size:   byte_size = form_value.Unsigned(); break;
5427                                 case DW_AT_encoding:    encoding = form_value.Unsigned(); break;
5428                                 case DW_AT_type:        encoding_uid = form_value.Reference(dwarf_cu); break;
5429                                 default:
5430                                 case DW_AT_sibling:
5431                                     break;
5432                                 }
5433                             }
5434                         }
5435                     }
5436 
5437                     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);
5438 
5439                     switch (tag)
5440                     {
5441                     default:
5442                         break;
5443 
5444                     case DW_TAG_unspecified_type:
5445                         if (strcmp(type_name_cstr, "nullptr_t") == 0)
5446                         {
5447                             resolve_state = Type::eResolveStateFull;
5448                             clang_type = ast.getASTContext()->NullPtrTy.getAsOpaquePtr();
5449                             break;
5450                         }
5451                         // Fall through to base type below in case we can handle the type there...
5452 
5453                     case DW_TAG_base_type:
5454                         resolve_state = Type::eResolveStateFull;
5455                         clang_type = ast.GetBuiltinTypeForDWARFEncodingAndBitSize (type_name_cstr,
5456                                                                                    encoding,
5457                                                                                    byte_size * 8);
5458                         break;
5459 
5460                     case DW_TAG_pointer_type:           encoding_data_type = Type::eEncodingIsPointerUID;           break;
5461                     case DW_TAG_reference_type:         encoding_data_type = Type::eEncodingIsLValueReferenceUID;   break;
5462                     case DW_TAG_rvalue_reference_type:  encoding_data_type = Type::eEncodingIsRValueReferenceUID;   break;
5463                     case DW_TAG_typedef:                encoding_data_type = Type::eEncodingIsTypedefUID;           break;
5464                     case DW_TAG_const_type:             encoding_data_type = Type::eEncodingIsConstUID;             break;
5465                     case DW_TAG_restrict_type:          encoding_data_type = Type::eEncodingIsRestrictUID;          break;
5466                     case DW_TAG_volatile_type:          encoding_data_type = Type::eEncodingIsVolatileUID;          break;
5467                     }
5468 
5469                     if (clang_type == NULL && (encoding_data_type == Type::eEncodingIsPointerUID || encoding_data_type == Type::eEncodingIsTypedefUID))
5470                     {
5471                         if (type_name_cstr != NULL && sc.comp_unit != NULL &&
5472                             (sc.comp_unit->GetLanguage() == eLanguageTypeObjC || sc.comp_unit->GetLanguage() == eLanguageTypeObjC_plus_plus))
5473                         {
5474                             static ConstString g_objc_type_name_id("id");
5475                             static ConstString g_objc_type_name_Class("Class");
5476                             static ConstString g_objc_type_name_selector("SEL");
5477 
5478                             if (type_name_const_str == g_objc_type_name_id)
5479                             {
5480                                 if (log)
5481                                     GetObjectFile()->GetModule()->LogMessage (log.get(), "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'id' built-in type.",
5482                                                                               die->GetOffset(),
5483                                                                               DW_TAG_value_to_name(die->Tag()),
5484                                                                               die->GetName(this, dwarf_cu));
5485                                 clang_type = ast.GetBuiltInType_objc_id();
5486                                 encoding_data_type = Type::eEncodingIsUID;
5487                                 encoding_uid = LLDB_INVALID_UID;
5488                                 resolve_state = Type::eResolveStateFull;
5489 
5490                             }
5491                             else if (type_name_const_str == g_objc_type_name_Class)
5492                             {
5493                                 if (log)
5494                                     GetObjectFile()->GetModule()->LogMessage (log.get(), "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'Class' built-in type.",
5495                                                                               die->GetOffset(),
5496                                                                               DW_TAG_value_to_name(die->Tag()),
5497                                                                               die->GetName(this, dwarf_cu));
5498                                 clang_type = ast.GetBuiltInType_objc_Class();
5499                                 encoding_data_type = Type::eEncodingIsUID;
5500                                 encoding_uid = LLDB_INVALID_UID;
5501                                 resolve_state = Type::eResolveStateFull;
5502                             }
5503                             else if (type_name_const_str == g_objc_type_name_selector)
5504                             {
5505                                 if (log)
5506                                     GetObjectFile()->GetModule()->LogMessage (log.get(), "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'selector' built-in type.",
5507                                                                               die->GetOffset(),
5508                                                                               DW_TAG_value_to_name(die->Tag()),
5509                                                                               die->GetName(this, dwarf_cu));
5510                                 clang_type = ast.GetBuiltInType_objc_selector();
5511                                 encoding_data_type = Type::eEncodingIsUID;
5512                                 encoding_uid = LLDB_INVALID_UID;
5513                                 resolve_state = Type::eResolveStateFull;
5514                             }
5515                         }
5516                     }
5517 
5518                     type_sp.reset( new Type (MakeUserID(die->GetOffset()),
5519                                              this,
5520                                              type_name_const_str,
5521                                              byte_size,
5522                                              NULL,
5523                                              encoding_uid,
5524                                              encoding_data_type,
5525                                              &decl,
5526                                              clang_type,
5527                                              resolve_state));
5528 
5529                     m_die_to_type[die] = type_sp.get();
5530 
5531 //                  Type* encoding_type = GetUniquedTypeForDIEOffset(encoding_uid, type_sp, NULL, 0, 0, false);
5532 //                  if (encoding_type != NULL)
5533 //                  {
5534 //                      if (encoding_type != DIE_IS_BEING_PARSED)
5535 //                          type_sp->SetEncodingType(encoding_type);
5536 //                      else
5537 //                          m_indirect_fixups.push_back(type_sp.get());
5538 //                  }
5539                 }
5540                 break;
5541 
5542             case DW_TAG_structure_type:
5543             case DW_TAG_union_type:
5544             case DW_TAG_class_type:
5545                 {
5546                     // Set a bit that lets us know that we are currently parsing this
5547                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
5548                     bool byte_size_valid = false;
5549 
5550                     LanguageType class_language = eLanguageTypeUnknown;
5551                     bool is_complete_objc_class = false;
5552                     //bool struct_is_class = false;
5553                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
5554                     if (num_attributes > 0)
5555                     {
5556                         uint32_t i;
5557                         for (i=0; i<num_attributes; ++i)
5558                         {
5559                             attr = attributes.AttributeAtIndex(i);
5560                             DWARFFormValue form_value;
5561                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
5562                             {
5563                                 switch (attr)
5564                                 {
5565                                 case DW_AT_decl_file:
5566                                     if (dwarf_cu->DW_AT_decl_file_attributes_are_invalid())
5567 									{
5568 										// llvm-gcc outputs invalid DW_AT_decl_file attributes that always
5569 										// point to the compile unit file, so we clear this invalid value
5570 										// so that we can still unique types efficiently.
5571                                         decl.SetFile(FileSpec ("<invalid>", false));
5572 									}
5573                                     else
5574                                         decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned()));
5575                                     break;
5576 
5577                                 case DW_AT_decl_line:
5578                                     decl.SetLine(form_value.Unsigned());
5579                                     break;
5580 
5581                                 case DW_AT_decl_column:
5582                                     decl.SetColumn(form_value.Unsigned());
5583                                     break;
5584 
5585                                 case DW_AT_name:
5586                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
5587                                     type_name_const_str.SetCString(type_name_cstr);
5588                                     break;
5589 
5590                                 case DW_AT_byte_size:
5591                                     byte_size = form_value.Unsigned();
5592                                     byte_size_valid = true;
5593                                     break;
5594 
5595                                 case DW_AT_accessibility:
5596                                     accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
5597                                     break;
5598 
5599                                 case DW_AT_declaration:
5600                                     is_forward_declaration = form_value.Unsigned() != 0;
5601                                     break;
5602 
5603                                 case DW_AT_APPLE_runtime_class:
5604                                     class_language = (LanguageType)form_value.Signed();
5605                                     break;
5606 
5607                                 case DW_AT_APPLE_objc_complete_type:
5608                                     is_complete_objc_class = form_value.Signed();
5609                                     break;
5610 
5611                                 case DW_AT_allocated:
5612                                 case DW_AT_associated:
5613                                 case DW_AT_data_location:
5614                                 case DW_AT_description:
5615                                 case DW_AT_start_scope:
5616                                 case DW_AT_visibility:
5617                                 default:
5618                                 case DW_AT_sibling:
5619                                     break;
5620                                 }
5621                             }
5622                         }
5623                     }
5624 
5625                     UniqueDWARFASTType unique_ast_entry;
5626 
5627                     // Only try and unique the type if it has a name.
5628                     if (type_name_const_str &&
5629                         GetUniqueDWARFASTTypeMap().Find (type_name_const_str,
5630                                                          this,
5631                                                          dwarf_cu,
5632                                                          die,
5633                                                          decl,
5634                                                          byte_size_valid ? byte_size : -1,
5635                                                          unique_ast_entry))
5636                     {
5637                         // We have already parsed this type or from another
5638                         // compile unit. GCC loves to use the "one definition
5639                         // rule" which can result in multiple definitions
5640                         // of the same class over and over in each compile
5641                         // unit.
5642                         type_sp = unique_ast_entry.m_type_sp;
5643                         if (type_sp)
5644                         {
5645                             m_die_to_type[die] = type_sp.get();
5646                             return type_sp;
5647                         }
5648                     }
5649 
5650                     DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
5651 
5652                     int tag_decl_kind = -1;
5653                     AccessType default_accessibility = eAccessNone;
5654                     if (tag == DW_TAG_structure_type)
5655                     {
5656                         tag_decl_kind = clang::TTK_Struct;
5657                         default_accessibility = eAccessPublic;
5658                     }
5659                     else if (tag == DW_TAG_union_type)
5660                     {
5661                         tag_decl_kind = clang::TTK_Union;
5662                         default_accessibility = eAccessPublic;
5663                     }
5664                     else if (tag == DW_TAG_class_type)
5665                     {
5666                         tag_decl_kind = clang::TTK_Class;
5667                         default_accessibility = eAccessPrivate;
5668                     }
5669 
5670                     if (byte_size_valid && byte_size == 0 && type_name_cstr &&
5671                         die->HasChildren() == false &&
5672                         sc.comp_unit->GetLanguage() == eLanguageTypeObjC)
5673                     {
5674                         // Work around an issue with clang at the moment where
5675                         // forward declarations for objective C classes are emitted
5676                         // as:
5677                         //  DW_TAG_structure_type [2]
5678                         //  DW_AT_name( "ForwardObjcClass" )
5679                         //  DW_AT_byte_size( 0x00 )
5680                         //  DW_AT_decl_file( "..." )
5681                         //  DW_AT_decl_line( 1 )
5682                         //
5683                         // Note that there is no DW_AT_declaration and there are
5684                         // no children, and the byte size is zero.
5685                         is_forward_declaration = true;
5686                     }
5687 
5688                     if (class_language == eLanguageTypeObjC ||
5689                         class_language == eLanguageTypeObjC_plus_plus)
5690                     {
5691                         if (!is_complete_objc_class && Supports_DW_AT_APPLE_objc_complete_type(dwarf_cu))
5692                         {
5693                             // We have a valid eSymbolTypeObjCClass class symbol whose
5694                             // name matches the current objective C class that we
5695                             // are trying to find and this DIE isn't the complete
5696                             // definition (we checked is_complete_objc_class above and
5697                             // know it is false), so the real definition is in here somewhere
5698                             type_sp = FindCompleteObjCDefinitionTypeForDIE (die, type_name_const_str, true);
5699 
5700                             if (!type_sp && GetDebugMapSymfile ())
5701                             {
5702                                 // We weren't able to find a full declaration in
5703                                 // this DWARF, see if we have a declaration anywhere
5704                                 // else...
5705                                 type_sp = m_debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE (die, type_name_const_str, true);
5706                             }
5707 
5708                             if (type_sp)
5709                             {
5710                                 if (log)
5711                                 {
5712                                     GetObjectFile()->GetModule()->LogMessage (log.get(),
5713                                                                               "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is an incomplete objc type, complete type is 0x%8.8" PRIx64,
5714                                                                               this,
5715                                                                               die->GetOffset(),
5716                                                                               DW_TAG_value_to_name(tag),
5717                                                                               type_name_cstr,
5718                                                                               type_sp->GetID());
5719                                 }
5720 
5721                                 // We found a real definition for this type elsewhere
5722                                 // so lets use it and cache the fact that we found
5723                                 // a complete type for this die
5724                                 m_die_to_type[die] = type_sp.get();
5725                                 return type_sp;
5726                             }
5727                         }
5728                     }
5729 
5730 
5731                     if (is_forward_declaration)
5732                     {
5733                         // We have a forward declaration to a type and we need
5734                         // to try and find a full declaration. We look in the
5735                         // current type index just in case we have a forward
5736                         // declaration followed by an actual declarations in the
5737                         // DWARF. If this fails, we need to look elsewhere...
5738                         if (log)
5739                         {
5740                             GetObjectFile()->GetModule()->LogMessage (log.get(),
5741                                                                       "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a forward declaration, trying to find complete type",
5742                                                                       this,
5743                                                                       die->GetOffset(),
5744                                                                       DW_TAG_value_to_name(tag),
5745                                                                       type_name_cstr);
5746                         }
5747 
5748                         DWARFDeclContext die_decl_ctx;
5749                         die->GetDWARFDeclContext(this, dwarf_cu, die_decl_ctx);
5750 
5751                         //type_sp = FindDefinitionTypeForDIE (dwarf_cu, die, type_name_const_str);
5752                         type_sp = FindDefinitionTypeForDWARFDeclContext (die_decl_ctx);
5753 
5754                         if (!type_sp && GetDebugMapSymfile ())
5755                         {
5756                             // We weren't able to find a full declaration in
5757                             // this DWARF, see if we have a declaration anywhere
5758                             // else...
5759                             type_sp = m_debug_map_symfile->FindDefinitionTypeForDWARFDeclContext (die_decl_ctx);
5760                         }
5761 
5762                         if (type_sp)
5763                         {
5764                             if (log)
5765                             {
5766                                 GetObjectFile()->GetModule()->LogMessage (log.get(),
5767                                                                           "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a forward declaration, complete type is 0x%8.8" PRIx64,
5768                                                                           this,
5769                                                                           die->GetOffset(),
5770                                                                           DW_TAG_value_to_name(tag),
5771                                                                           type_name_cstr,
5772                                                                           type_sp->GetID());
5773                             }
5774 
5775                             // We found a real definition for this type elsewhere
5776                             // so lets use it and cache the fact that we found
5777                             // a complete type for this die
5778                             m_die_to_type[die] = type_sp.get();
5779                             return type_sp;
5780                         }
5781                     }
5782                     assert (tag_decl_kind != -1);
5783                     bool clang_type_was_created = false;
5784                     clang_type = m_forward_decl_die_to_clang_type.lookup (die);
5785                     if (clang_type == NULL)
5786                     {
5787                         const DWARFDebugInfoEntry *decl_ctx_die;
5788 
5789                         clang::DeclContext *decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, &decl_ctx_die);
5790                         if (accessibility == eAccessNone && decl_ctx)
5791                         {
5792                             // Check the decl context that contains this class/struct/union.
5793                             // If it is a class we must give it an accessability.
5794                             const clang::Decl::Kind containing_decl_kind = decl_ctx->getDeclKind();
5795                             if (DeclKindIsCXXClass (containing_decl_kind))
5796                                 accessibility = default_accessibility;
5797                         }
5798 
5799                         if (type_name_cstr && strchr (type_name_cstr, '<'))
5800                         {
5801                             ClangASTContext::TemplateParameterInfos template_param_infos;
5802                             if (ParseTemplateParameterInfos (dwarf_cu, die, template_param_infos))
5803                             {
5804                                 clang::ClassTemplateDecl *class_template_decl = ParseClassTemplateDecl (decl_ctx,
5805                                                                                                         accessibility,
5806                                                                                                         type_name_cstr,
5807                                                                                                         tag_decl_kind,
5808                                                                                                         template_param_infos);
5809 
5810                                 clang::ClassTemplateSpecializationDecl *class_specialization_decl = ast.CreateClassTemplateSpecializationDecl (decl_ctx,
5811                                                                                                                                                class_template_decl,
5812                                                                                                                                                tag_decl_kind,
5813                                                                                                                                                template_param_infos);
5814                                 clang_type = ast.CreateClassTemplateSpecializationType (class_specialization_decl);
5815                                 clang_type_was_created = true;
5816 
5817                                 GetClangASTContext().SetMetadataAsUserID ((uintptr_t)class_template_decl, MakeUserID(die->GetOffset()));
5818                                 GetClangASTContext().SetMetadataAsUserID ((uintptr_t)class_specialization_decl, MakeUserID(die->GetOffset()));
5819                             }
5820                         }
5821 
5822                         if (!clang_type_was_created)
5823                         {
5824                             clang_type_was_created = true;
5825                             ClangASTMetadata metadata;
5826                             metadata.SetUserID(MakeUserID(die->GetOffset()));
5827                             clang_type = ast.CreateRecordType (decl_ctx,
5828                                                                accessibility,
5829                                                                type_name_cstr,
5830                                                                tag_decl_kind,
5831                                                                class_language,
5832                                                                &metadata);
5833                         }
5834                     }
5835 
5836                     // Store a forward declaration to this class type in case any
5837                     // parameters in any class methods need it for the clang
5838                     // types for function prototypes.
5839                     LinkDeclContextToDIE(ClangASTContext::GetDeclContextForType(clang_type), die);
5840                     type_sp.reset (new Type (MakeUserID(die->GetOffset()),
5841                                              this,
5842                                              type_name_const_str,
5843                                              byte_size,
5844                                              NULL,
5845                                              LLDB_INVALID_UID,
5846                                              Type::eEncodingIsUID,
5847                                              &decl,
5848                                              clang_type,
5849                                              Type::eResolveStateForward));
5850 
5851                     type_sp->SetIsCompleteObjCClass(is_complete_objc_class);
5852 
5853 
5854                     // Add our type to the unique type map so we don't
5855                     // end up creating many copies of the same type over
5856                     // and over in the ASTContext for our module
5857                     unique_ast_entry.m_type_sp = type_sp;
5858                     unique_ast_entry.m_symfile = this;
5859                     unique_ast_entry.m_cu = dwarf_cu;
5860                     unique_ast_entry.m_die = die;
5861                     unique_ast_entry.m_declaration = decl;
5862                     unique_ast_entry.m_byte_size = byte_size;
5863                     GetUniqueDWARFASTTypeMap().Insert (type_name_const_str,
5864                                                        unique_ast_entry);
5865 
5866                     if (!is_forward_declaration)
5867                     {
5868                         // Always start the definition for a class type so that
5869                         // if the class has child classes or types that require
5870                         // the class to be created for use as their decl contexts
5871                         // the class will be ready to accept these child definitions.
5872                         if (die->HasChildren() == false)
5873                         {
5874                             // No children for this struct/union/class, lets finish it
5875                             ast.StartTagDeclarationDefinition (clang_type);
5876                             ast.CompleteTagDeclarationDefinition (clang_type);
5877 
5878                             if (tag == DW_TAG_structure_type) // this only applies in C
5879                             {
5880                                 clang::QualType qual_type = clang::QualType::getFromOpaquePtr (clang_type);
5881                                 const clang::RecordType *record_type = qual_type->getAs<clang::RecordType> ();
5882 
5883                                 if (record_type)
5884                                 {
5885                                     clang::RecordDecl *record_decl = record_type->getDecl();
5886 
5887                                     if (record_decl)
5888                                     {
5889                                         LayoutInfo layout_info;
5890 
5891                                         layout_info.alignment = 0;
5892                                         layout_info.bit_size = 0;
5893 
5894                                         m_record_decl_to_layout_map.insert(std::make_pair(record_decl, layout_info));
5895                                     }
5896                                 }
5897                             }
5898                         }
5899                         else if (clang_type_was_created)
5900                         {
5901                             // Start the definition if the class is not objective C since
5902                             // the underlying decls respond to isCompleteDefinition(). Objective
5903                             // C decls dont' respond to isCompleteDefinition() so we can't
5904                             // start the declaration definition right away. For C++ classs/union/structs
5905                             // we want to start the definition in case the class is needed as the
5906                             // declaration context for a contained class or type without the need
5907                             // to complete that type..
5908 
5909                             if (class_language != eLanguageTypeObjC &&
5910                                 class_language != eLanguageTypeObjC_plus_plus)
5911                                 ast.StartTagDeclarationDefinition (clang_type);
5912 
5913                             // Leave this as a forward declaration until we need
5914                             // to know the details of the type. lldb_private::Type
5915                             // will automatically call the SymbolFile virtual function
5916                             // "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition(Type *)"
5917                             // When the definition needs to be defined.
5918                             m_forward_decl_die_to_clang_type[die] = clang_type;
5919                             m_forward_decl_clang_type_to_die[ClangASTType::RemoveFastQualifiers (clang_type)] = die;
5920                             ClangASTContext::SetHasExternalStorage (clang_type, true);
5921                         }
5922                     }
5923 
5924                 }
5925                 break;
5926 
5927             case DW_TAG_enumeration_type:
5928                 {
5929                     // Set a bit that lets us know that we are currently parsing this
5930                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
5931 
5932                     lldb::user_id_t encoding_uid = DW_INVALID_OFFSET;
5933 
5934                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
5935                     if (num_attributes > 0)
5936                     {
5937                         uint32_t i;
5938 
5939                         for (i=0; i<num_attributes; ++i)
5940                         {
5941                             attr = attributes.AttributeAtIndex(i);
5942                             DWARFFormValue form_value;
5943                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
5944                             {
5945                                 switch (attr)
5946                                 {
5947                                 case DW_AT_decl_file:       decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
5948                                 case DW_AT_decl_line:       decl.SetLine(form_value.Unsigned()); break;
5949                                 case DW_AT_decl_column:     decl.SetColumn(form_value.Unsigned()); break;
5950                                 case DW_AT_name:
5951                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
5952                                     type_name_const_str.SetCString(type_name_cstr);
5953                                     break;
5954                                 case DW_AT_type:            encoding_uid = form_value.Reference(dwarf_cu); break;
5955                                 case DW_AT_byte_size:       byte_size = form_value.Unsigned(); break;
5956                                 case DW_AT_accessibility:   break; //accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
5957                                 case DW_AT_declaration:     break; //is_forward_declaration = form_value.Unsigned() != 0; break;
5958                                 case DW_AT_allocated:
5959                                 case DW_AT_associated:
5960                                 case DW_AT_bit_stride:
5961                                 case DW_AT_byte_stride:
5962                                 case DW_AT_data_location:
5963                                 case DW_AT_description:
5964                                 case DW_AT_start_scope:
5965                                 case DW_AT_visibility:
5966                                 case DW_AT_specification:
5967                                 case DW_AT_abstract_origin:
5968                                 case DW_AT_sibling:
5969                                     break;
5970                                 }
5971                             }
5972                         }
5973 
5974                         DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
5975 
5976                         clang_type_t enumerator_clang_type = NULL;
5977                         clang_type = m_forward_decl_die_to_clang_type.lookup (die);
5978                         if (clang_type == NULL)
5979                         {
5980                             enumerator_clang_type = ast.GetBuiltinTypeForDWARFEncodingAndBitSize (NULL,
5981                                                                                                   DW_ATE_signed,
5982                                                                                                   byte_size * 8);
5983                             clang_type = ast.CreateEnumerationType (type_name_cstr,
5984                                                                     GetClangDeclContextContainingDIE (dwarf_cu, die, NULL),
5985                                                                     decl,
5986                                                                     enumerator_clang_type);
5987                         }
5988                         else
5989                         {
5990                             enumerator_clang_type = ClangASTContext::GetEnumerationIntegerType (clang_type);
5991                             assert (enumerator_clang_type != NULL);
5992                         }
5993 
5994                         LinkDeclContextToDIE(ClangASTContext::GetDeclContextForType(clang_type), die);
5995 
5996                         type_sp.reset( new Type (MakeUserID(die->GetOffset()),
5997                                                  this,
5998                                                  type_name_const_str,
5999                                                  byte_size,
6000                                                  NULL,
6001                                                  encoding_uid,
6002                                                  Type::eEncodingIsUID,
6003                                                  &decl,
6004                                                  clang_type,
6005                                                  Type::eResolveStateForward));
6006 
6007                         ast.StartTagDeclarationDefinition (clang_type);
6008                         if (die->HasChildren())
6009                         {
6010                             SymbolContext cu_sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
6011                             ParseChildEnumerators(cu_sc, clang_type, type_sp->GetByteSize(), dwarf_cu, die);
6012                         }
6013                         ast.CompleteTagDeclarationDefinition (clang_type);
6014                     }
6015                 }
6016                 break;
6017 
6018             case DW_TAG_inlined_subroutine:
6019             case DW_TAG_subprogram:
6020             case DW_TAG_subroutine_type:
6021                 {
6022                     // Set a bit that lets us know that we are currently parsing this
6023                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
6024 
6025                     //const char *mangled = NULL;
6026                     dw_offset_t type_die_offset = DW_INVALID_OFFSET;
6027                     bool is_variadic = false;
6028                     bool is_inline = false;
6029                     bool is_static = false;
6030                     bool is_virtual = false;
6031                     bool is_explicit = false;
6032                     bool is_artificial = false;
6033                     dw_offset_t specification_die_offset = DW_INVALID_OFFSET;
6034                     dw_offset_t abstract_origin_die_offset = DW_INVALID_OFFSET;
6035                     dw_offset_t object_pointer_die_offset = DW_INVALID_OFFSET;
6036 
6037                     unsigned type_quals = 0;
6038                     clang::StorageClass storage = clang::SC_None;//, Extern, Static, PrivateExtern
6039 
6040 
6041                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6042                     if (num_attributes > 0)
6043                     {
6044                         uint32_t i;
6045                         for (i=0; i<num_attributes; ++i)
6046                         {
6047                             attr = attributes.AttributeAtIndex(i);
6048                             DWARFFormValue form_value;
6049                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6050                             {
6051                                 switch (attr)
6052                                 {
6053                                 case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6054                                 case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
6055                                 case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
6056                                 case DW_AT_name:
6057                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
6058                                     type_name_const_str.SetCString(type_name_cstr);
6059                                     break;
6060 
6061                                 case DW_AT_linkage_name:
6062                                 case DW_AT_MIPS_linkage_name:   break; // mangled = form_value.AsCString(&get_debug_str_data()); break;
6063                                 case DW_AT_type:                type_die_offset = form_value.Reference(dwarf_cu); break;
6064                                 case DW_AT_accessibility:       accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6065                                 case DW_AT_declaration:         break; // is_forward_declaration = form_value.Unsigned() != 0; break;
6066                                 case DW_AT_inline:              is_inline = form_value.Unsigned() != 0; break;
6067                                 case DW_AT_virtuality:          is_virtual = form_value.Unsigned() != 0;  break;
6068                                 case DW_AT_explicit:            is_explicit = form_value.Unsigned() != 0;  break;
6069                                 case DW_AT_artificial:          is_artificial = form_value.Unsigned() != 0;  break;
6070 
6071 
6072                                 case DW_AT_external:
6073                                     if (form_value.Unsigned())
6074                                     {
6075                                         if (storage == clang::SC_None)
6076                                             storage = clang::SC_Extern;
6077                                         else
6078                                             storage = clang::SC_PrivateExtern;
6079                                     }
6080                                     break;
6081 
6082                                 case DW_AT_specification:
6083                                     specification_die_offset = form_value.Reference(dwarf_cu);
6084                                     break;
6085 
6086                                 case DW_AT_abstract_origin:
6087                                     abstract_origin_die_offset = form_value.Reference(dwarf_cu);
6088                                     break;
6089 
6090                                 case DW_AT_object_pointer:
6091                                     object_pointer_die_offset = form_value.Reference(dwarf_cu);
6092                                     break;
6093 
6094                                 case DW_AT_allocated:
6095                                 case DW_AT_associated:
6096                                 case DW_AT_address_class:
6097                                 case DW_AT_calling_convention:
6098                                 case DW_AT_data_location:
6099                                 case DW_AT_elemental:
6100                                 case DW_AT_entry_pc:
6101                                 case DW_AT_frame_base:
6102                                 case DW_AT_high_pc:
6103                                 case DW_AT_low_pc:
6104                                 case DW_AT_prototyped:
6105                                 case DW_AT_pure:
6106                                 case DW_AT_ranges:
6107                                 case DW_AT_recursive:
6108                                 case DW_AT_return_addr:
6109                                 case DW_AT_segment:
6110                                 case DW_AT_start_scope:
6111                                 case DW_AT_static_link:
6112                                 case DW_AT_trampoline:
6113                                 case DW_AT_visibility:
6114                                 case DW_AT_vtable_elem_location:
6115                                 case DW_AT_description:
6116                                 case DW_AT_sibling:
6117                                     break;
6118                                 }
6119                             }
6120                         }
6121                     }
6122 
6123                     std::string object_pointer_name;
6124                     if (object_pointer_die_offset != DW_INVALID_OFFSET)
6125                     {
6126                         // Get the name from the object pointer die
6127                         StreamString s;
6128                         if (DWARFDebugInfoEntry::GetName (this, dwarf_cu, object_pointer_die_offset, s))
6129                         {
6130                             object_pointer_name.assign(s.GetData());
6131                         }
6132                     }
6133 
6134                     DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6135 
6136                     clang_type_t return_clang_type = NULL;
6137                     Type *func_type = NULL;
6138 
6139                     if (type_die_offset != DW_INVALID_OFFSET)
6140                         func_type = ResolveTypeUID(type_die_offset);
6141 
6142                     if (func_type)
6143                         return_clang_type = func_type->GetClangForwardType();
6144                     else
6145                         return_clang_type = ast.GetBuiltInType_void();
6146 
6147 
6148                     std::vector<clang_type_t> function_param_types;
6149                     std::vector<clang::ParmVarDecl*> function_param_decls;
6150 
6151                     // Parse the function children for the parameters
6152 
6153                     const DWARFDebugInfoEntry *decl_ctx_die = NULL;
6154                     clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, &decl_ctx_die);
6155                     const clang::Decl::Kind containing_decl_kind = containing_decl_ctx->getDeclKind();
6156 
6157                     const bool is_cxx_method = DeclKindIsCXXClass (containing_decl_kind);
6158                     // Start off static. This will be set to false in ParseChildParameters(...)
6159                     // if we find a "this" paramters as the first parameter
6160                     if (is_cxx_method)
6161                         is_static = true;
6162                     ClangASTContext::TemplateParameterInfos template_param_infos;
6163 
6164                     if (die->HasChildren())
6165                     {
6166                         bool skip_artificial = true;
6167                         ParseChildParameters (sc,
6168                                               containing_decl_ctx,
6169                                               dwarf_cu,
6170                                               die,
6171                                               skip_artificial,
6172                                               is_static,
6173                                               type_list,
6174                                               function_param_types,
6175                                               function_param_decls,
6176                                               type_quals,
6177                                               template_param_infos);
6178                     }
6179 
6180                     // clang_type will get the function prototype clang type after this call
6181                     clang_type = ast.CreateFunctionType (return_clang_type,
6182                                                          function_param_types.data(),
6183                                                          function_param_types.size(),
6184                                                          is_variadic,
6185                                                          type_quals);
6186 
6187                     if (type_name_cstr)
6188                     {
6189                         bool type_handled = false;
6190                         if (tag == DW_TAG_subprogram)
6191                         {
6192                             ConstString class_name;
6193                             ConstString class_name_no_category;
6194                             if (ObjCLanguageRuntime::ParseMethodName (type_name_cstr, &class_name, NULL, NULL, &class_name_no_category))
6195                             {
6196                                 // Use the class name with no category if there is one
6197                                 if (class_name_no_category)
6198                                     class_name = class_name_no_category;
6199 
6200                                 SymbolContext empty_sc;
6201                                 clang_type_t class_opaque_type = NULL;
6202                                 if (class_name)
6203                                 {
6204                                     TypeList types;
6205                                     TypeSP complete_objc_class_type_sp (FindCompleteObjCDefinitionTypeForDIE (NULL, class_name, false));
6206 
6207                                     if (complete_objc_class_type_sp)
6208                                     {
6209                                         clang_type_t type_clang_forward_type = complete_objc_class_type_sp->GetClangForwardType();
6210                                         if (ClangASTContext::IsObjCClassType (type_clang_forward_type))
6211                                             class_opaque_type = type_clang_forward_type;
6212                                     }
6213                                 }
6214 
6215                                 if (class_opaque_type)
6216                                 {
6217                                     // If accessibility isn't set to anything valid, assume public for
6218                                     // now...
6219                                     if (accessibility == eAccessNone)
6220                                         accessibility = eAccessPublic;
6221 
6222                                     clang::ObjCMethodDecl *objc_method_decl = ast.AddMethodToObjCObjectType (class_opaque_type,
6223                                                                                                              type_name_cstr,
6224                                                                                                              clang_type,
6225                                                                                                              accessibility);
6226                                     type_handled = objc_method_decl != NULL;
6227                                     if (type_handled)
6228                                     {
6229                                         LinkDeclContextToDIE(ClangASTContext::GetAsDeclContext(objc_method_decl), die);
6230                                         GetClangASTContext().SetMetadataAsUserID ((uintptr_t)objc_method_decl, MakeUserID(die->GetOffset()));
6231                                     }
6232                                 }
6233                             }
6234                             else if (is_cxx_method)
6235                             {
6236                                 // Look at the parent of this DIE and see if is is
6237                                 // a class or struct and see if this is actually a
6238                                 // C++ method
6239                                 Type *class_type = ResolveType (dwarf_cu, decl_ctx_die);
6240                                 if (class_type)
6241                                 {
6242                                     if (class_type->GetID() != MakeUserID(decl_ctx_die->GetOffset()))
6243                                     {
6244                                         // We uniqued the parent class of this function to another class
6245                                         // so we now need to associate all dies under "decl_ctx_die" to
6246                                         // DIEs in the DIE for "class_type"...
6247                                         DWARFCompileUnitSP class_type_cu_sp;
6248                                         const DWARFDebugInfoEntry *class_type_die = DebugInfo()->GetDIEPtr(class_type->GetID(), &class_type_cu_sp);
6249                                         if (class_type_die)
6250                                         {
6251                                             if (CopyUniqueClassMethodTypes (class_type,
6252                                                                             class_type_cu_sp.get(),
6253                                                                             class_type_die,
6254                                                                             dwarf_cu,
6255                                                                             decl_ctx_die))
6256                                             {
6257                                                 type_ptr = m_die_to_type[die];
6258                                                 if (type_ptr && type_ptr != DIE_IS_BEING_PARSED)
6259                                                 {
6260                                                     type_sp = type_ptr->shared_from_this();
6261                                                     break;
6262                                                 }
6263                                             }
6264                                         }
6265                                     }
6266 
6267                                     if (specification_die_offset != DW_INVALID_OFFSET)
6268                                     {
6269                                         // We have a specification which we are going to base our function
6270                                         // prototype off of, so we need this type to be completed so that the
6271                                         // m_die_to_decl_ctx for the method in the specification has a valid
6272                                         // clang decl context.
6273                                         class_type->GetClangForwardType();
6274                                         // If we have a specification, then the function type should have been
6275                                         // made with the specification and not with this die.
6276                                         DWARFCompileUnitSP spec_cu_sp;
6277                                         const DWARFDebugInfoEntry* spec_die = DebugInfo()->GetDIEPtr(specification_die_offset, &spec_cu_sp);
6278                                         clang::DeclContext *spec_clang_decl_ctx = GetClangDeclContextForDIE (sc, dwarf_cu, spec_die);
6279                                         if (spec_clang_decl_ctx)
6280                                         {
6281                                             LinkDeclContextToDIE(spec_clang_decl_ctx, die);
6282                                         }
6283                                         else
6284                                         {
6285                                             GetObjectFile()->GetModule()->ReportWarning ("0x%8.8" PRIx64 ": DW_AT_specification(0x%8.8x) has no decl\n",
6286                                                                                          MakeUserID(die->GetOffset()),
6287                                                                                          specification_die_offset);
6288                                         }
6289                                         type_handled = true;
6290                                     }
6291                                     else if (abstract_origin_die_offset != DW_INVALID_OFFSET)
6292                                     {
6293                                         // We have a specification which we are going to base our function
6294                                         // prototype off of, so we need this type to be completed so that the
6295                                         // m_die_to_decl_ctx for the method in the abstract origin has a valid
6296                                         // clang decl context.
6297                                         class_type->GetClangForwardType();
6298 
6299                                         DWARFCompileUnitSP abs_cu_sp;
6300                                         const DWARFDebugInfoEntry* abs_die = DebugInfo()->GetDIEPtr(abstract_origin_die_offset, &abs_cu_sp);
6301                                         clang::DeclContext *abs_clang_decl_ctx = GetClangDeclContextForDIE (sc, dwarf_cu, abs_die);
6302                                         if (abs_clang_decl_ctx)
6303                                         {
6304                                             LinkDeclContextToDIE (abs_clang_decl_ctx, die);
6305                                         }
6306                                         else
6307                                         {
6308                                             GetObjectFile()->GetModule()->ReportWarning ("0x%8.8" PRIx64 ": DW_AT_abstract_origin(0x%8.8x) has no decl\n",
6309                                                                                          MakeUserID(die->GetOffset()),
6310                                                                                          abstract_origin_die_offset);
6311                                         }
6312                                         type_handled = true;
6313                                     }
6314                                     else
6315                                     {
6316                                         clang_type_t class_opaque_type = class_type->GetClangForwardType();
6317                                         if (ClangASTContext::IsCXXClassType (class_opaque_type))
6318                                         {
6319                                             if (ClangASTContext::IsBeingDefined (class_opaque_type))
6320                                             {
6321                                                 // Neither GCC 4.2 nor clang++ currently set a valid accessibility
6322                                                 // in the DWARF for C++ methods... Default to public for now...
6323                                                 if (accessibility == eAccessNone)
6324                                                     accessibility = eAccessPublic;
6325 
6326                                                 if (!is_static && !die->HasChildren())
6327                                                 {
6328                                                     // We have a C++ member function with no children (this pointer!)
6329                                                     // and clang will get mad if we try and make a function that isn't
6330                                                     // well formed in the DWARF, so we will just skip it...
6331                                                     type_handled = true;
6332                                                 }
6333                                                 else
6334                                                 {
6335                                                     clang::CXXMethodDecl *cxx_method_decl;
6336                                                     // REMOVE THE CRASH DESCRIPTION BELOW
6337                                                     Host::SetCrashDescriptionWithFormat ("SymbolFileDWARF::ParseType() is adding a method %s to class %s in DIE 0x%8.8" PRIx64 " from %s/%s",
6338                                                                                          type_name_cstr,
6339                                                                                          class_type->GetName().GetCString(),
6340                                                                                          MakeUserID(die->GetOffset()),
6341                                                                                          m_obj_file->GetFileSpec().GetDirectory().GetCString(),
6342                                                                                          m_obj_file->GetFileSpec().GetFilename().GetCString());
6343 
6344                                                     const bool is_attr_used = false;
6345 
6346                                                     cxx_method_decl = ast.AddMethodToCXXRecordType (class_opaque_type,
6347                                                                                                     type_name_cstr,
6348                                                                                                     clang_type,
6349                                                                                                     accessibility,
6350                                                                                                     is_virtual,
6351                                                                                                     is_static,
6352                                                                                                     is_inline,
6353                                                                                                     is_explicit,
6354                                                                                                     is_attr_used,
6355                                                                                                     is_artificial);
6356 
6357                                                     type_handled = cxx_method_decl != NULL;
6358 
6359                                                     if (type_handled)
6360                                                     {
6361                                                         LinkDeclContextToDIE(ClangASTContext::GetAsDeclContext(cxx_method_decl), die);
6362 
6363                                                         Host::SetCrashDescription (NULL);
6364 
6365 
6366                                                         ClangASTMetadata metadata;
6367                                                         metadata.SetUserID(MakeUserID(die->GetOffset()));
6368 
6369                                                         if (!object_pointer_name.empty())
6370                                                         {
6371                                                             metadata.SetObjectPtrName(object_pointer_name.c_str());
6372                                                             if (log)
6373                                                                 log->Printf ("Setting object pointer name: %s on method object 0x%ld.\n",
6374                                                                              object_pointer_name.c_str(),
6375                                                                              (uintptr_t) cxx_method_decl);
6376                                                         }
6377                                                         GetClangASTContext().SetMetadata ((uintptr_t)cxx_method_decl, metadata);
6378                                                     }
6379                                                 }
6380                                             }
6381                                             else
6382                                             {
6383                                                 // We were asked to parse the type for a method in a class, yet the
6384                                                 // class hasn't been asked to complete itself through the
6385                                                 // clang::ExternalASTSource protocol, so we need to just have the
6386                                                 // class complete itself and do things the right way, then our
6387                                                 // DIE should then have an entry in the m_die_to_type map. First
6388                                                 // we need to modify the m_die_to_type so it doesn't think we are
6389                                                 // trying to parse this DIE anymore...
6390                                                 m_die_to_type[die] = NULL;
6391 
6392                                                 // Now we get the full type to force our class type to complete itself
6393                                                 // using the clang::ExternalASTSource protocol which will parse all
6394                                                 // base classes and all methods (including the method for this DIE).
6395                                                 class_type->GetClangFullType();
6396 
6397                                                 // The type for this DIE should have been filled in the function call above
6398                                                 type_ptr = m_die_to_type[die];
6399                                                 if (type_ptr && type_ptr != DIE_IS_BEING_PARSED)
6400                                                 {
6401                                                     type_sp = type_ptr->shared_from_this();
6402                                                     break;
6403                                                 }
6404 
6405                                                 // FIXME This is fixing some even uglier behavior but we really need to
6406                                                 // uniq the methods of each class as well as the class itself.
6407                                                 // <rdar://problem/11240464>
6408                                                 type_handled = true;
6409                                             }
6410                                         }
6411                                     }
6412                                 }
6413                             }
6414                         }
6415 
6416                         if (!type_handled)
6417                         {
6418                             // We just have a function that isn't part of a class
6419                             clang::FunctionDecl *function_decl = ast.CreateFunctionDeclaration (containing_decl_ctx,
6420                                                                                                 type_name_cstr,
6421                                                                                                 clang_type,
6422                                                                                                 storage,
6423                                                                                                 is_inline);
6424 
6425 //                            if (template_param_infos.GetSize() > 0)
6426 //                            {
6427 //                                clang::FunctionTemplateDecl *func_template_decl = ast.CreateFunctionTemplateDecl (containing_decl_ctx,
6428 //                                                                                                                  function_decl,
6429 //                                                                                                                  type_name_cstr,
6430 //                                                                                                                  template_param_infos);
6431 //
6432 //                                ast.CreateFunctionTemplateSpecializationInfo (function_decl,
6433 //                                                                              func_template_decl,
6434 //                                                                              template_param_infos);
6435 //                            }
6436                             // Add the decl to our DIE to decl context map
6437                             assert (function_decl);
6438                             LinkDeclContextToDIE(function_decl, die);
6439                             if (!function_param_decls.empty())
6440                                 ast.SetFunctionParameters (function_decl,
6441                                                            &function_param_decls.front(),
6442                                                            function_param_decls.size());
6443 
6444                             ClangASTMetadata metadata;
6445                             metadata.SetUserID(MakeUserID(die->GetOffset()));
6446 
6447                             if (!object_pointer_name.empty())
6448                             {
6449                                 metadata.SetObjectPtrName(object_pointer_name.c_str());
6450                                 if (log)
6451                                     log->Printf ("Setting object pointer name: %s on function object 0x%ld.\n",
6452                                                  object_pointer_name.c_str(),
6453                                                  (uintptr_t) function_decl);
6454                             }
6455                             GetClangASTContext().SetMetadata ((uintptr_t)function_decl, metadata);
6456                         }
6457                     }
6458                     type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6459                                              this,
6460                                              type_name_const_str,
6461                                              0,
6462                                              NULL,
6463                                              LLDB_INVALID_UID,
6464                                              Type::eEncodingIsUID,
6465                                              &decl,
6466                                              clang_type,
6467                                              Type::eResolveStateFull));
6468                     assert(type_sp.get());
6469                 }
6470                 break;
6471 
6472             case DW_TAG_array_type:
6473                 {
6474                     // Set a bit that lets us know that we are currently parsing this
6475                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
6476 
6477                     lldb::user_id_t type_die_offset = DW_INVALID_OFFSET;
6478                     int64_t first_index = 0;
6479                     uint32_t byte_stride = 0;
6480                     uint32_t bit_stride = 0;
6481                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6482 
6483                     if (num_attributes > 0)
6484                     {
6485                         uint32_t i;
6486                         for (i=0; i<num_attributes; ++i)
6487                         {
6488                             attr = attributes.AttributeAtIndex(i);
6489                             DWARFFormValue form_value;
6490                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6491                             {
6492                                 switch (attr)
6493                                 {
6494                                 case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6495                                 case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
6496                                 case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
6497                                 case DW_AT_name:
6498                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
6499                                     type_name_const_str.SetCString(type_name_cstr);
6500                                     break;
6501 
6502                                 case DW_AT_type:            type_die_offset = form_value.Reference(dwarf_cu); break;
6503                                 case DW_AT_byte_size:       break; // byte_size = form_value.Unsigned(); break;
6504                                 case DW_AT_byte_stride:     byte_stride = form_value.Unsigned(); break;
6505                                 case DW_AT_bit_stride:      bit_stride = form_value.Unsigned(); break;
6506                                 case DW_AT_accessibility:   break; // accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6507                                 case DW_AT_declaration:     break; // is_forward_declaration = form_value.Unsigned() != 0; break;
6508                                 case DW_AT_allocated:
6509                                 case DW_AT_associated:
6510                                 case DW_AT_data_location:
6511                                 case DW_AT_description:
6512                                 case DW_AT_ordering:
6513                                 case DW_AT_start_scope:
6514                                 case DW_AT_visibility:
6515                                 case DW_AT_specification:
6516                                 case DW_AT_abstract_origin:
6517                                 case DW_AT_sibling:
6518                                     break;
6519                                 }
6520                             }
6521                         }
6522 
6523                         DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6524 
6525                         Type *element_type = ResolveTypeUID(type_die_offset);
6526 
6527                         if (element_type)
6528                         {
6529                             std::vector<uint64_t> element_orders;
6530                             ParseChildArrayInfo(sc, dwarf_cu, die, first_index, element_orders, byte_stride, bit_stride);
6531                             if (byte_stride == 0 && bit_stride == 0)
6532                                 byte_stride = element_type->GetByteSize();
6533                             clang_type_t array_element_type = element_type->GetClangForwardType();
6534                             uint64_t array_element_bit_stride = byte_stride * 8 + bit_stride;
6535                             uint64_t num_elements = 0;
6536                             std::vector<uint64_t>::const_reverse_iterator pos;
6537                             std::vector<uint64_t>::const_reverse_iterator end = element_orders.rend();
6538                             for (pos = element_orders.rbegin(); pos != end; ++pos)
6539                             {
6540                                 num_elements = *pos;
6541                                 clang_type = ast.CreateArrayType (array_element_type,
6542                                                                   num_elements);
6543                                 array_element_type = clang_type;
6544                                 array_element_bit_stride = num_elements ? array_element_bit_stride * num_elements : array_element_bit_stride;
6545                             }
6546                             ConstString empty_name;
6547                             type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6548                                                      this,
6549                                                      empty_name,
6550                                                      array_element_bit_stride / 8,
6551                                                      NULL,
6552                                                      type_die_offset,
6553                                                      Type::eEncodingIsUID,
6554                                                      &decl,
6555                                                      clang_type,
6556                                                      Type::eResolveStateFull));
6557                             type_sp->SetEncodingType (element_type);
6558                         }
6559                     }
6560                 }
6561                 break;
6562 
6563             case DW_TAG_ptr_to_member_type:
6564                 {
6565                     dw_offset_t type_die_offset = DW_INVALID_OFFSET;
6566                     dw_offset_t containing_type_die_offset = DW_INVALID_OFFSET;
6567 
6568                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6569 
6570                     if (num_attributes > 0) {
6571                         uint32_t i;
6572                         for (i=0; i<num_attributes; ++i)
6573                         {
6574                             attr = attributes.AttributeAtIndex(i);
6575                             DWARFFormValue form_value;
6576                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6577                             {
6578                                 switch (attr)
6579                                 {
6580                                     case DW_AT_type:
6581                                         type_die_offset = form_value.Reference(dwarf_cu); break;
6582                                     case DW_AT_containing_type:
6583                                         containing_type_die_offset = form_value.Reference(dwarf_cu); break;
6584                                 }
6585                             }
6586                         }
6587 
6588                         Type *pointee_type = ResolveTypeUID(type_die_offset);
6589                         Type *class_type = ResolveTypeUID(containing_type_die_offset);
6590 
6591                         clang_type_t pointee_clang_type = pointee_type->GetClangForwardType();
6592                         clang_type_t class_clang_type = class_type->GetClangLayoutType();
6593 
6594                         clang_type = ast.CreateMemberPointerType(pointee_clang_type,
6595                                                                  class_clang_type);
6596 
6597                         byte_size = ClangASTType::GetClangTypeBitWidth (ast.getASTContext(),
6598                                                                        clang_type) / 8;
6599 
6600                         type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6601                                                  this,
6602                                                  type_name_const_str,
6603                                                  byte_size,
6604                                                  NULL,
6605                                                  LLDB_INVALID_UID,
6606                                                  Type::eEncodingIsUID,
6607                                                  NULL,
6608                                                  clang_type,
6609                                                  Type::eResolveStateForward));
6610                     }
6611 
6612                     break;
6613                 }
6614             default:
6615                 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",
6616                                                            die->GetOffset(),
6617                                                            tag,
6618                                                            DW_TAG_value_to_name(tag));
6619                 break;
6620             }
6621 
6622             if (type_sp.get())
6623             {
6624                 const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(die);
6625                 dw_tag_t sc_parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
6626 
6627                 SymbolContextScope * symbol_context_scope = NULL;
6628                 if (sc_parent_tag == DW_TAG_compile_unit)
6629                 {
6630                     symbol_context_scope = sc.comp_unit;
6631                 }
6632                 else if (sc.function != NULL)
6633                 {
6634                     symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
6635                     if (symbol_context_scope == NULL)
6636                         symbol_context_scope = sc.function;
6637                 }
6638 
6639                 if (symbol_context_scope != NULL)
6640                 {
6641                     type_sp->SetSymbolContextScope(symbol_context_scope);
6642                 }
6643 
6644                 // We are ready to put this type into the uniqued list up at the module level
6645                 type_list->Insert (type_sp);
6646 
6647                 m_die_to_type[die] = type_sp.get();
6648             }
6649         }
6650         else if (type_ptr != DIE_IS_BEING_PARSED)
6651         {
6652             type_sp = type_ptr->shared_from_this();
6653         }
6654     }
6655     return type_sp;
6656 }
6657 
6658 size_t
6659 SymbolFileDWARF::ParseTypes
6660 (
6661     const SymbolContext& sc,
6662     DWARFCompileUnit* dwarf_cu,
6663     const DWARFDebugInfoEntry *die,
6664     bool parse_siblings,
6665     bool parse_children
6666 )
6667 {
6668     size_t types_added = 0;
6669     while (die != NULL)
6670     {
6671         bool type_is_new = false;
6672         if (ParseType(sc, dwarf_cu, die, &type_is_new).get())
6673         {
6674             if (type_is_new)
6675                 ++types_added;
6676         }
6677 
6678         if (parse_children && die->HasChildren())
6679         {
6680             if (die->Tag() == DW_TAG_subprogram)
6681             {
6682                 SymbolContext child_sc(sc);
6683                 child_sc.function = sc.comp_unit->FindFunctionByUID(MakeUserID(die->GetOffset())).get();
6684                 types_added += ParseTypes(child_sc, dwarf_cu, die->GetFirstChild(), true, true);
6685             }
6686             else
6687                 types_added += ParseTypes(sc, dwarf_cu, die->GetFirstChild(), true, true);
6688         }
6689 
6690         if (parse_siblings)
6691             die = die->GetSibling();
6692         else
6693             die = NULL;
6694     }
6695     return types_added;
6696 }
6697 
6698 
6699 size_t
6700 SymbolFileDWARF::ParseFunctionBlocks (const SymbolContext &sc)
6701 {
6702     assert(sc.comp_unit && sc.function);
6703     size_t functions_added = 0;
6704     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
6705     if (dwarf_cu)
6706     {
6707         dw_offset_t function_die_offset = sc.function->GetID();
6708         const DWARFDebugInfoEntry *function_die = dwarf_cu->GetDIEPtr(function_die_offset);
6709         if (function_die)
6710         {
6711             ParseFunctionBlocks(sc, &sc.function->GetBlock (false), dwarf_cu, function_die, LLDB_INVALID_ADDRESS, 0);
6712         }
6713     }
6714 
6715     return functions_added;
6716 }
6717 
6718 
6719 size_t
6720 SymbolFileDWARF::ParseTypes (const SymbolContext &sc)
6721 {
6722     // At least a compile unit must be valid
6723     assert(sc.comp_unit);
6724     size_t types_added = 0;
6725     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
6726     if (dwarf_cu)
6727     {
6728         if (sc.function)
6729         {
6730             dw_offset_t function_die_offset = sc.function->GetID();
6731             const DWARFDebugInfoEntry *func_die = dwarf_cu->GetDIEPtr(function_die_offset);
6732             if (func_die && func_die->HasChildren())
6733             {
6734                 types_added = ParseTypes(sc, dwarf_cu, func_die->GetFirstChild(), true, true);
6735             }
6736         }
6737         else
6738         {
6739             const DWARFDebugInfoEntry *dwarf_cu_die = dwarf_cu->DIE();
6740             if (dwarf_cu_die && dwarf_cu_die->HasChildren())
6741             {
6742                 types_added = ParseTypes(sc, dwarf_cu, dwarf_cu_die->GetFirstChild(), true, true);
6743             }
6744         }
6745     }
6746 
6747     return types_added;
6748 }
6749 
6750 size_t
6751 SymbolFileDWARF::ParseVariablesForContext (const SymbolContext& sc)
6752 {
6753     if (sc.comp_unit != NULL)
6754     {
6755         DWARFDebugInfo* info = DebugInfo();
6756         if (info == NULL)
6757             return 0;
6758 
6759         uint32_t cu_idx = UINT32_MAX;
6760         DWARFCompileUnit* dwarf_cu = info->GetCompileUnit(sc.comp_unit->GetID(), &cu_idx).get();
6761 
6762         if (dwarf_cu == NULL)
6763             return 0;
6764 
6765         if (sc.function)
6766         {
6767             const DWARFDebugInfoEntry *function_die = dwarf_cu->GetDIEPtr(sc.function->GetID());
6768 
6769             dw_addr_t func_lo_pc = function_die->GetAttributeValueAsUnsigned (this, dwarf_cu, DW_AT_low_pc, DW_INVALID_ADDRESS);
6770             if (func_lo_pc != DW_INVALID_ADDRESS)
6771             {
6772                 const size_t num_variables = ParseVariables(sc, dwarf_cu, func_lo_pc, function_die->GetFirstChild(), true, true);
6773 
6774                 // Let all blocks know they have parse all their variables
6775                 sc.function->GetBlock (false).SetDidParseVariables (true, true);
6776                 return num_variables;
6777             }
6778         }
6779         else if (sc.comp_unit)
6780         {
6781             uint32_t vars_added = 0;
6782             VariableListSP variables (sc.comp_unit->GetVariableList(false));
6783 
6784             if (variables.get() == NULL)
6785             {
6786                 variables.reset(new VariableList());
6787                 sc.comp_unit->SetVariableList(variables);
6788 
6789                 DWARFCompileUnit* match_dwarf_cu = NULL;
6790                 const DWARFDebugInfoEntry* die = NULL;
6791                 DIEArray die_offsets;
6792                 if (m_using_apple_tables)
6793                 {
6794                     if (m_apple_names_ap.get())
6795                     {
6796                         DWARFMappedHash::DIEInfoArray hash_data_array;
6797                         if (m_apple_names_ap->AppendAllDIEsInRange (dwarf_cu->GetOffset(),
6798                                                                     dwarf_cu->GetNextCompileUnitOffset(),
6799                                                                     hash_data_array))
6800                         {
6801                             DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
6802                         }
6803                     }
6804                 }
6805                 else
6806                 {
6807                     // Index if we already haven't to make sure the compile units
6808                     // get indexed and make their global DIE index list
6809                     if (!m_indexed)
6810                         Index ();
6811 
6812                     m_global_index.FindAllEntriesForCompileUnit (dwarf_cu->GetOffset(),
6813                                                                  dwarf_cu->GetNextCompileUnitOffset(),
6814                                                                  die_offsets);
6815                 }
6816 
6817                 const size_t num_matches = die_offsets.size();
6818                 if (num_matches)
6819                 {
6820                     DWARFDebugInfo* debug_info = DebugInfo();
6821                     for (size_t i=0; i<num_matches; ++i)
6822                     {
6823                         const dw_offset_t die_offset = die_offsets[i];
6824                         die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &match_dwarf_cu);
6825                         if (die)
6826                         {
6827                             VariableSP var_sp (ParseVariableDIE(sc, dwarf_cu, die, LLDB_INVALID_ADDRESS));
6828                             if (var_sp)
6829                             {
6830                                 variables->AddVariableIfUnique (var_sp);
6831                                 ++vars_added;
6832                             }
6833                         }
6834                         else
6835                         {
6836                             if (m_using_apple_tables)
6837                             {
6838                                 GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x)\n", die_offset);
6839                             }
6840                         }
6841 
6842                     }
6843                 }
6844             }
6845             return vars_added;
6846         }
6847     }
6848     return 0;
6849 }
6850 
6851 
6852 VariableSP
6853 SymbolFileDWARF::ParseVariableDIE
6854 (
6855     const SymbolContext& sc,
6856     DWARFCompileUnit* dwarf_cu,
6857     const DWARFDebugInfoEntry *die,
6858     const lldb::addr_t func_low_pc
6859 )
6860 {
6861 
6862     VariableSP var_sp (m_die_to_variable_sp[die]);
6863     if (var_sp)
6864         return var_sp;  // Already been parsed!
6865 
6866     const dw_tag_t tag = die->Tag();
6867 
6868     if ((tag == DW_TAG_variable) ||
6869         (tag == DW_TAG_constant) ||
6870         (tag == DW_TAG_formal_parameter && sc.function))
6871     {
6872         DWARFDebugInfoEntry::Attributes attributes;
6873         const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6874         if (num_attributes > 0)
6875         {
6876             const char *name = NULL;
6877             const char *mangled = NULL;
6878             Declaration decl;
6879             uint32_t i;
6880             lldb::user_id_t type_uid = LLDB_INVALID_UID;
6881             DWARFExpression location;
6882             bool is_external = false;
6883             bool is_artificial = false;
6884             bool location_is_const_value_data = false;
6885             //AccessType accessibility = eAccessNone;
6886 
6887             for (i=0; i<num_attributes; ++i)
6888             {
6889                 dw_attr_t attr = attributes.AttributeAtIndex(i);
6890                 DWARFFormValue form_value;
6891                 if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6892                 {
6893                     switch (attr)
6894                     {
6895                     case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6896                     case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
6897                     case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
6898                     case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
6899                     case DW_AT_linkage_name:
6900                     case DW_AT_MIPS_linkage_name: mangled = form_value.AsCString(&get_debug_str_data()); break;
6901                     case DW_AT_type:        type_uid = form_value.Reference(dwarf_cu); break;
6902                     case DW_AT_external:    is_external = form_value.Unsigned() != 0; break;
6903                     case DW_AT_const_value:
6904                         location_is_const_value_data = true;
6905                         // Fall through...
6906                     case DW_AT_location:
6907                         {
6908                             if (form_value.BlockData())
6909                             {
6910                                 const DataExtractor& debug_info_data = get_debug_info_data();
6911 
6912                                 uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
6913                                 uint32_t block_length = form_value.Unsigned();
6914                                 location.CopyOpcodeData(get_debug_info_data(), block_offset, block_length);
6915                             }
6916                             else
6917                             {
6918                                 const DataExtractor&    debug_loc_data = get_debug_loc_data();
6919                                 const dw_offset_t debug_loc_offset = form_value.Unsigned();
6920 
6921                                 size_t loc_list_length = DWARFLocationList::Size(debug_loc_data, debug_loc_offset);
6922                                 if (loc_list_length > 0)
6923                                 {
6924                                     location.CopyOpcodeData(debug_loc_data, debug_loc_offset, loc_list_length);
6925                                     assert (func_low_pc != LLDB_INVALID_ADDRESS);
6926                                     location.SetLocationListSlide (func_low_pc - dwarf_cu->GetBaseAddress());
6927                                 }
6928                             }
6929                         }
6930                         break;
6931 
6932                     case DW_AT_artificial:      is_artificial = form_value.Unsigned() != 0; break;
6933                     case DW_AT_accessibility:   break; //accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6934                     case DW_AT_declaration:
6935                     case DW_AT_description:
6936                     case DW_AT_endianity:
6937                     case DW_AT_segment:
6938                     case DW_AT_start_scope:
6939                     case DW_AT_visibility:
6940                     default:
6941                     case DW_AT_abstract_origin:
6942                     case DW_AT_sibling:
6943                     case DW_AT_specification:
6944                         break;
6945                     }
6946                 }
6947             }
6948 
6949             if (location.IsValid())
6950             {
6951                 ValueType scope = eValueTypeInvalid;
6952 
6953                 const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(die);
6954                 dw_tag_t parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
6955                 SymbolContextScope * symbol_context_scope = NULL;
6956 
6957                 // DWARF doesn't specify if a DW_TAG_variable is a local, global
6958                 // or static variable, so we have to do a little digging by
6959                 // looking at the location of a varaible to see if it contains
6960                 // a DW_OP_addr opcode _somewhere_ in the definition. I say
6961                 // somewhere because clang likes to combine small global variables
6962                 // into the same symbol and have locations like:
6963                 // DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
6964                 // So if we don't have a DW_TAG_formal_parameter, we can look at
6965                 // the location to see if it contains a DW_OP_addr opcode, and
6966                 // then we can correctly classify  our variables.
6967                 if (tag == DW_TAG_formal_parameter)
6968                     scope = eValueTypeVariableArgument;
6969                 else
6970                 {
6971                     bool op_error = false;
6972                     // Check if the location has a DW_OP_addr with any address value...
6973                     addr_t location_has_op_addr = false;
6974                     if (!location_is_const_value_data)
6975                     {
6976                         location_has_op_addr = location.LocationContains_DW_OP_addr (LLDB_INVALID_ADDRESS, op_error);
6977                         if (op_error)
6978                         {
6979                             StreamString strm;
6980                             location.DumpLocationForAddress (&strm, eDescriptionLevelFull, 0, 0, NULL);
6981                             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());
6982                         }
6983                     }
6984 
6985                     if (location_has_op_addr)
6986                     {
6987                         if (is_external)
6988                         {
6989                             scope = eValueTypeVariableGlobal;
6990 
6991                             if (GetDebugMapSymfile ())
6992                             {
6993                                 // When leaving the DWARF in the .o files on darwin,
6994                                 // when we have a global variable that wasn't initialized,
6995                                 // the .o file might not have allocated a virtual
6996                                 // address for the global variable. In this case it will
6997                                 // have created a symbol for the global variable
6998                                 // that is undefined and external and the value will
6999                                 // be the byte size of the variable. When we do the
7000                                 // address map in SymbolFileDWARFDebugMap we rely on
7001                                 // having an address, we need to do some magic here
7002                                 // so we can get the correct address for our global
7003                                 // variable. The address for all of these entries
7004                                 // will be zero, and there will be an undefined symbol
7005                                 // in this object file, and the executable will have
7006                                 // a matching symbol with a good address. So here we
7007                                 // dig up the correct address and replace it in the
7008                                 // location for the variable, and set the variable's
7009                                 // symbol context scope to be that of the main executable
7010                                 // so the file address will resolve correctly.
7011                                 if (location.LocationContains_DW_OP_addr (0, op_error))
7012                                 {
7013 
7014                                     // we have a possible uninitialized extern global
7015                                     Symtab *symtab = m_obj_file->GetSymtab();
7016                                     if (symtab)
7017                                     {
7018                                         ConstString const_name(name);
7019                                         Symbol *undefined_symbol = symtab->FindFirstSymbolWithNameAndType (const_name,
7020                                                                                                            eSymbolTypeUndefined,
7021                                                                                                            Symtab::eDebugNo,
7022                                                                                                            Symtab::eVisibilityExtern);
7023 
7024                                         if (undefined_symbol)
7025                                         {
7026                                             ObjectFile *debug_map_objfile = m_debug_map_symfile->GetObjectFile();
7027                                             if (debug_map_objfile)
7028                                             {
7029                                                 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
7030                                                 Symbol *defined_symbol = debug_map_symtab->FindFirstSymbolWithNameAndType (const_name,
7031                                                                                                                            eSymbolTypeData,
7032                                                                                                                            Symtab::eDebugYes,
7033                                                                                                                            Symtab::eVisibilityExtern);
7034                                                 if (defined_symbol)
7035                                                 {
7036                                                     if (defined_symbol->ValueIsAddress())
7037                                                     {
7038                                                         const addr_t defined_addr = defined_symbol->GetAddress().GetFileAddress();
7039                                                         if (defined_addr != LLDB_INVALID_ADDRESS)
7040                                                         {
7041                                                             if (location.Update_DW_OP_addr (defined_addr))
7042                                                             {
7043                                                                 symbol_context_scope = defined_symbol;
7044                                                             }
7045                                                         }
7046                                                     }
7047                                                 }
7048                                             }
7049                                         }
7050                                     }
7051                                 }
7052                             }
7053                         }
7054                         else
7055                         {
7056                             scope = eValueTypeVariableStatic;
7057                         }
7058                     }
7059                     else
7060                     {
7061                         scope = eValueTypeVariableLocal;
7062                     }
7063                 }
7064 
7065                 if (symbol_context_scope == NULL)
7066                 {
7067                     switch (parent_tag)
7068                     {
7069                     case DW_TAG_subprogram:
7070                     case DW_TAG_inlined_subroutine:
7071                     case DW_TAG_lexical_block:
7072                         if (sc.function)
7073                         {
7074                             symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
7075                             if (symbol_context_scope == NULL)
7076                                 symbol_context_scope = sc.function;
7077                         }
7078                         break;
7079 
7080                     default:
7081                         symbol_context_scope = sc.comp_unit;
7082                         break;
7083                     }
7084                 }
7085 
7086                 if (symbol_context_scope)
7087                 {
7088                     var_sp.reset (new Variable (MakeUserID(die->GetOffset()),
7089                                                 name,
7090                                                 mangled,
7091                                                 SymbolFileTypeSP (new SymbolFileType(*this, type_uid)),
7092                                                 scope,
7093                                                 symbol_context_scope,
7094                                                 &decl,
7095                                                 location,
7096                                                 is_external,
7097                                                 is_artificial));
7098 
7099                     var_sp->SetLocationIsConstantValueData (location_is_const_value_data);
7100                 }
7101                 else
7102                 {
7103                     // Not ready to parse this variable yet. It might be a global
7104                     // or static variable that is in a function scope and the function
7105                     // in the symbol context wasn't filled in yet
7106                     return var_sp;
7107                 }
7108             }
7109         }
7110         // Cache var_sp even if NULL (the variable was just a specification or
7111         // was missing vital information to be able to be displayed in the debugger
7112         // (missing location due to optimization, etc)) so we don't re-parse
7113         // this DIE over and over later...
7114         m_die_to_variable_sp[die] = var_sp;
7115     }
7116     return var_sp;
7117 }
7118 
7119 
7120 const DWARFDebugInfoEntry *
7121 SymbolFileDWARF::FindBlockContainingSpecification (dw_offset_t func_die_offset,
7122                                                    dw_offset_t spec_block_die_offset,
7123                                                    DWARFCompileUnit **result_die_cu_handle)
7124 {
7125     // Give the concrete function die specified by "func_die_offset", find the
7126     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
7127     // to "spec_block_die_offset"
7128     DWARFDebugInfo* info = DebugInfo();
7129 
7130     const DWARFDebugInfoEntry *die = info->GetDIEPtrWithCompileUnitHint(func_die_offset, result_die_cu_handle);
7131     if (die)
7132     {
7133         assert (*result_die_cu_handle);
7134         return FindBlockContainingSpecification (*result_die_cu_handle, die, spec_block_die_offset, result_die_cu_handle);
7135     }
7136     return NULL;
7137 }
7138 
7139 
7140 const DWARFDebugInfoEntry *
7141 SymbolFileDWARF::FindBlockContainingSpecification(DWARFCompileUnit* dwarf_cu,
7142                                                   const DWARFDebugInfoEntry *die,
7143                                                   dw_offset_t spec_block_die_offset,
7144                                                   DWARFCompileUnit **result_die_cu_handle)
7145 {
7146     if (die)
7147     {
7148         switch (die->Tag())
7149         {
7150         case DW_TAG_subprogram:
7151         case DW_TAG_inlined_subroutine:
7152         case DW_TAG_lexical_block:
7153             {
7154                 if (die->GetAttributeValueAsReference (this, dwarf_cu, DW_AT_specification, DW_INVALID_OFFSET) == spec_block_die_offset)
7155                 {
7156                     *result_die_cu_handle = dwarf_cu;
7157                     return die;
7158                 }
7159 
7160                 if (die->GetAttributeValueAsReference (this, dwarf_cu, DW_AT_abstract_origin, DW_INVALID_OFFSET) == spec_block_die_offset)
7161                 {
7162                     *result_die_cu_handle = dwarf_cu;
7163                     return die;
7164                 }
7165             }
7166             break;
7167         }
7168 
7169         // Give the concrete function die specified by "func_die_offset", find the
7170         // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
7171         // to "spec_block_die_offset"
7172         for (const DWARFDebugInfoEntry *child_die = die->GetFirstChild(); child_die != NULL; child_die = child_die->GetSibling())
7173         {
7174             const DWARFDebugInfoEntry *result_die = FindBlockContainingSpecification (dwarf_cu,
7175                                                                                       child_die,
7176                                                                                       spec_block_die_offset,
7177                                                                                       result_die_cu_handle);
7178             if (result_die)
7179                 return result_die;
7180         }
7181     }
7182 
7183     *result_die_cu_handle = NULL;
7184     return NULL;
7185 }
7186 
7187 size_t
7188 SymbolFileDWARF::ParseVariables
7189 (
7190     const SymbolContext& sc,
7191     DWARFCompileUnit* dwarf_cu,
7192     const lldb::addr_t func_low_pc,
7193     const DWARFDebugInfoEntry *orig_die,
7194     bool parse_siblings,
7195     bool parse_children,
7196     VariableList* cc_variable_list
7197 )
7198 {
7199     if (orig_die == NULL)
7200         return 0;
7201 
7202     VariableListSP variable_list_sp;
7203 
7204     size_t vars_added = 0;
7205     const DWARFDebugInfoEntry *die = orig_die;
7206     while (die != NULL)
7207     {
7208         dw_tag_t tag = die->Tag();
7209 
7210         // Check to see if we have already parsed this variable or constant?
7211         if (m_die_to_variable_sp[die])
7212         {
7213             if (cc_variable_list)
7214                 cc_variable_list->AddVariableIfUnique (m_die_to_variable_sp[die]);
7215         }
7216         else
7217         {
7218             // We haven't already parsed it, lets do that now.
7219             if ((tag == DW_TAG_variable) ||
7220                 (tag == DW_TAG_constant) ||
7221                 (tag == DW_TAG_formal_parameter && sc.function))
7222             {
7223                 if (variable_list_sp.get() == NULL)
7224                 {
7225                     const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(orig_die);
7226                     dw_tag_t parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
7227                     switch (parent_tag)
7228                     {
7229                         case DW_TAG_compile_unit:
7230                             if (sc.comp_unit != NULL)
7231                             {
7232                                 variable_list_sp = sc.comp_unit->GetVariableList(false);
7233                                 if (variable_list_sp.get() == NULL)
7234                                 {
7235                                     variable_list_sp.reset(new VariableList());
7236                                     sc.comp_unit->SetVariableList(variable_list_sp);
7237                                 }
7238                             }
7239                             else
7240                             {
7241                                 GetObjectFile()->GetModule()->ReportError ("parent 0x%8.8" PRIx64 " %s with no valid compile unit in symbol context for 0x%8.8" PRIx64 " %s.\n",
7242                                                                            MakeUserID(sc_parent_die->GetOffset()),
7243                                                                            DW_TAG_value_to_name (parent_tag),
7244                                                                            MakeUserID(orig_die->GetOffset()),
7245                                                                            DW_TAG_value_to_name (orig_die->Tag()));
7246                             }
7247                             break;
7248 
7249                         case DW_TAG_subprogram:
7250                         case DW_TAG_inlined_subroutine:
7251                         case DW_TAG_lexical_block:
7252                             if (sc.function != NULL)
7253                             {
7254                                 // Check to see if we already have parsed the variables for the given scope
7255 
7256                                 Block *block = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
7257                                 if (block == NULL)
7258                                 {
7259                                     // This must be a specification or abstract origin with
7260                                     // a concrete block couterpart in the current function. We need
7261                                     // to find the concrete block so we can correctly add the
7262                                     // variable to it
7263                                     DWARFCompileUnit *concrete_block_die_cu = dwarf_cu;
7264                                     const DWARFDebugInfoEntry *concrete_block_die = FindBlockContainingSpecification (sc.function->GetID(),
7265                                                                                                                       sc_parent_die->GetOffset(),
7266                                                                                                                       &concrete_block_die_cu);
7267                                     if (concrete_block_die)
7268                                         block = sc.function->GetBlock(true).FindBlockByID(MakeUserID(concrete_block_die->GetOffset()));
7269                                 }
7270 
7271                                 if (block != NULL)
7272                                 {
7273                                     const bool can_create = false;
7274                                     variable_list_sp = block->GetBlockVariableList (can_create);
7275                                     if (variable_list_sp.get() == NULL)
7276                                     {
7277                                         variable_list_sp.reset(new VariableList());
7278                                         block->SetVariableList(variable_list_sp);
7279                                     }
7280                                 }
7281                             }
7282                             break;
7283 
7284                         default:
7285                              GetObjectFile()->GetModule()->ReportError ("didn't find appropriate parent DIE for variable list for 0x%8.8" PRIx64 " %s.\n",
7286                                                                         MakeUserID(orig_die->GetOffset()),
7287                                                                         DW_TAG_value_to_name (orig_die->Tag()));
7288                             break;
7289                     }
7290                 }
7291 
7292                 if (variable_list_sp)
7293                 {
7294                     VariableSP var_sp (ParseVariableDIE(sc, dwarf_cu, die, func_low_pc));
7295                     if (var_sp)
7296                     {
7297                         variable_list_sp->AddVariableIfUnique (var_sp);
7298                         if (cc_variable_list)
7299                             cc_variable_list->AddVariableIfUnique (var_sp);
7300                         ++vars_added;
7301                     }
7302                 }
7303             }
7304         }
7305 
7306         bool skip_children = (sc.function == NULL && tag == DW_TAG_subprogram);
7307 
7308         if (!skip_children && parse_children && die->HasChildren())
7309         {
7310             vars_added += ParseVariables(sc, dwarf_cu, func_low_pc, die->GetFirstChild(), true, true, cc_variable_list);
7311         }
7312 
7313         if (parse_siblings)
7314             die = die->GetSibling();
7315         else
7316             die = NULL;
7317     }
7318     return vars_added;
7319 }
7320 
7321 //------------------------------------------------------------------
7322 // PluginInterface protocol
7323 //------------------------------------------------------------------
7324 const char *
7325 SymbolFileDWARF::GetPluginName()
7326 {
7327     return "SymbolFileDWARF";
7328 }
7329 
7330 const char *
7331 SymbolFileDWARF::GetShortPluginName()
7332 {
7333     return GetPluginNameStatic();
7334 }
7335 
7336 uint32_t
7337 SymbolFileDWARF::GetPluginVersion()
7338 {
7339     return 1;
7340 }
7341 
7342 void
7343 SymbolFileDWARF::CompleteTagDecl (void *baton, clang::TagDecl *decl)
7344 {
7345     SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7346     clang_type_t clang_type = symbol_file_dwarf->GetClangASTContext().GetTypeForDecl (decl);
7347     if (clang_type)
7348         symbol_file_dwarf->ResolveClangOpaqueTypeDefinition (clang_type);
7349 }
7350 
7351 void
7352 SymbolFileDWARF::CompleteObjCInterfaceDecl (void *baton, clang::ObjCInterfaceDecl *decl)
7353 {
7354     SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7355     clang_type_t clang_type = symbol_file_dwarf->GetClangASTContext().GetTypeForDecl (decl);
7356     if (clang_type)
7357         symbol_file_dwarf->ResolveClangOpaqueTypeDefinition (clang_type);
7358 }
7359 
7360 void
7361 SymbolFileDWARF::DumpIndexes ()
7362 {
7363     StreamFile s(stdout, false);
7364 
7365     s.Printf ("DWARF index for (%s) '%s/%s':",
7366               GetObjectFile()->GetModule()->GetArchitecture().GetArchitectureName(),
7367               GetObjectFile()->GetFileSpec().GetDirectory().AsCString(),
7368               GetObjectFile()->GetFileSpec().GetFilename().AsCString());
7369     s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
7370     s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
7371     s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
7372     s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
7373     s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
7374     s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
7375     s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
7376     s.Printf("\nNamepaces:\n");             m_namespace_index.Dump (&s);
7377 }
7378 
7379 void
7380 SymbolFileDWARF::SearchDeclContext (const clang::DeclContext *decl_context,
7381                                     const char *name,
7382                                     llvm::SmallVectorImpl <clang::NamedDecl *> *results)
7383 {
7384     DeclContextToDIEMap::iterator iter = m_decl_ctx_to_die.find(decl_context);
7385 
7386     if (iter == m_decl_ctx_to_die.end())
7387         return;
7388 
7389     for (DIEPointerSet::iterator pos = iter->second.begin(), end = iter->second.end(); pos != end; ++pos)
7390     {
7391         const DWARFDebugInfoEntry *context_die = *pos;
7392 
7393         if (!results)
7394             return;
7395 
7396         DWARFDebugInfo* info = DebugInfo();
7397 
7398         DIEArray die_offsets;
7399 
7400         DWARFCompileUnit* dwarf_cu = NULL;
7401         const DWARFDebugInfoEntry* die = NULL;
7402 
7403         if (m_using_apple_tables)
7404         {
7405             if (m_apple_types_ap.get())
7406                 m_apple_types_ap->FindByName (name, die_offsets);
7407         }
7408         else
7409         {
7410             if (!m_indexed)
7411                 Index ();
7412 
7413             m_type_index.Find (ConstString(name), die_offsets);
7414         }
7415 
7416         const size_t num_matches = die_offsets.size();
7417 
7418         if (num_matches)
7419         {
7420             for (size_t i = 0; i < num_matches; ++i)
7421             {
7422                 const dw_offset_t die_offset = die_offsets[i];
7423                 die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
7424 
7425                 if (die->GetParent() != context_die)
7426                     continue;
7427 
7428                 Type *matching_type = ResolveType (dwarf_cu, die);
7429 
7430                 lldb::clang_type_t type = matching_type->GetClangForwardType();
7431                 clang::QualType qual_type = clang::QualType::getFromOpaquePtr(type);
7432 
7433                 if (const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr()))
7434                 {
7435                     clang::TagDecl *tag_decl = tag_type->getDecl();
7436                     results->push_back(tag_decl);
7437                 }
7438                 else if (const clang::TypedefType *typedef_type = llvm::dyn_cast<clang::TypedefType>(qual_type.getTypePtr()))
7439                 {
7440                     clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
7441                     results->push_back(typedef_decl);
7442                 }
7443             }
7444         }
7445     }
7446 }
7447 
7448 void
7449 SymbolFileDWARF::FindExternalVisibleDeclsByName (void *baton,
7450                                                  const clang::DeclContext *decl_context,
7451                                                  clang::DeclarationName decl_name,
7452                                                  llvm::SmallVectorImpl <clang::NamedDecl *> *results)
7453 {
7454 
7455     switch (decl_context->getDeclKind())
7456     {
7457     case clang::Decl::Namespace:
7458     case clang::Decl::TranslationUnit:
7459         {
7460             SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7461             symbol_file_dwarf->SearchDeclContext (decl_context, decl_name.getAsString().c_str(), results);
7462         }
7463         break;
7464     default:
7465         break;
7466     }
7467 }
7468 
7469 bool
7470 SymbolFileDWARF::LayoutRecordType (void *baton,
7471                                    const clang::RecordDecl *record_decl,
7472                                    uint64_t &size,
7473                                    uint64_t &alignment,
7474                                    llvm::DenseMap <const clang::FieldDecl *, uint64_t> &field_offsets,
7475                                    llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &base_offsets,
7476                                    llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &vbase_offsets)
7477 {
7478     SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7479     return symbol_file_dwarf->LayoutRecordType (record_decl, size, alignment, field_offsets, base_offsets, vbase_offsets);
7480 }
7481 
7482 
7483 bool
7484 SymbolFileDWARF::LayoutRecordType (const clang::RecordDecl *record_decl,
7485                                    uint64_t &bit_size,
7486                                    uint64_t &alignment,
7487                                    llvm::DenseMap <const clang::FieldDecl *, uint64_t> &field_offsets,
7488                                    llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &base_offsets,
7489                                    llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &vbase_offsets)
7490 {
7491     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
7492     RecordDeclToLayoutMap::iterator pos = m_record_decl_to_layout_map.find (record_decl);
7493     bool success = false;
7494     base_offsets.clear();
7495     vbase_offsets.clear();
7496     if (pos != m_record_decl_to_layout_map.end())
7497     {
7498         bit_size = pos->second.bit_size;
7499         alignment = pos->second.alignment;
7500         field_offsets.swap(pos->second.field_offsets);
7501         base_offsets.swap (pos->second.base_offsets);
7502         vbase_offsets.swap (pos->second.vbase_offsets);
7503         m_record_decl_to_layout_map.erase(pos);
7504         success = true;
7505     }
7506     else
7507     {
7508         bit_size = 0;
7509         alignment = 0;
7510         field_offsets.clear();
7511     }
7512 
7513     if (log)
7514         GetObjectFile()->GetModule()->LogMessage (log.get(),
7515                                                   "SymbolFileDWARF::LayoutRecordType (record_decl = %p, bit_size = %" PRIu64 ", alignment = %" PRIu64 ", field_offsets[%u],base_offsets[%u], vbase_offsets[%u]) success = %i",
7516                                                   record_decl,
7517                                                   bit_size,
7518                                                   alignment,
7519                                                   (uint32_t)field_offsets.size(),
7520                                                   (uint32_t)base_offsets.size(),
7521                                                   (uint32_t)vbase_offsets.size(),
7522                                                   success);
7523     return success;
7524 }
7525 
7526 
7527 SymbolFileDWARFDebugMap *
7528 SymbolFileDWARF::GetDebugMapSymfile ()
7529 {
7530     if (m_debug_map_symfile == NULL && !m_debug_map_module_wp.expired())
7531     {
7532         lldb::ModuleSP module_sp (m_debug_map_module_wp.lock());
7533         if (module_sp)
7534         {
7535             SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
7536             if (sym_vendor)
7537                 m_debug_map_symfile = (SymbolFileDWARFDebugMap *)sym_vendor->GetSymbolFile();
7538         }
7539     }
7540     return m_debug_map_symfile;
7541 }
7542 
7543 
7544