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