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