1 //===-- SymbolFileDWARF.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "SymbolFileDWARF.h"
10 
11 #include "llvm/ADT/Optional.h"
12 #include "llvm/Support/Casting.h"
13 #include "llvm/Support/Threading.h"
14 
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleList.h"
17 #include "lldb/Core/ModuleSpec.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Core/Section.h"
20 #include "lldb/Core/StreamFile.h"
21 #include "lldb/Core/Value.h"
22 #include "lldb/Utility/ArchSpec.h"
23 #include "lldb/Utility/RegularExpression.h"
24 #include "lldb/Utility/Scalar.h"
25 #include "lldb/Utility/StreamString.h"
26 #include "lldb/Utility/Timer.h"
27 
28 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
29 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
30 
31 #include "lldb/Host/FileSystem.h"
32 #include "lldb/Host/Host.h"
33 
34 #include "lldb/Interpreter/OptionValueFileSpecList.h"
35 #include "lldb/Interpreter/OptionValueProperties.h"
36 
37 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
38 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
39 #include "lldb/Symbol/Block.h"
40 #include "lldb/Symbol/CompileUnit.h"
41 #include "lldb/Symbol/CompilerDecl.h"
42 #include "lldb/Symbol/CompilerDeclContext.h"
43 #include "lldb/Symbol/DebugMacros.h"
44 #include "lldb/Symbol/LineTable.h"
45 #include "lldb/Symbol/LocateSymbolFile.h"
46 #include "lldb/Symbol/ObjectFile.h"
47 #include "lldb/Symbol/SymbolFile.h"
48 #include "lldb/Symbol/TypeMap.h"
49 #include "lldb/Symbol/TypeSystem.h"
50 #include "lldb/Symbol/VariableList.h"
51 
52 #include "lldb/Target/Language.h"
53 #include "lldb/Target/Target.h"
54 
55 #include "AppleDWARFIndex.h"
56 #include "DWARFASTParser.h"
57 #include "DWARFASTParserClang.h"
58 #include "DWARFCompileUnit.h"
59 #include "DWARFDebugAbbrev.h"
60 #include "DWARFDebugAranges.h"
61 #include "DWARFDebugInfo.h"
62 #include "DWARFDebugMacro.h"
63 #include "DWARFDebugRanges.h"
64 #include "DWARFDeclContext.h"
65 #include "DWARFFormValue.h"
66 #include "DWARFTypeUnit.h"
67 #include "DWARFUnit.h"
68 #include "DebugNamesDWARFIndex.h"
69 #include "LogChannelDWARF.h"
70 #include "ManualDWARFIndex.h"
71 #include "SymbolFileDWARFDebugMap.h"
72 #include "SymbolFileDWARFDwo.h"
73 
74 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
75 #include "llvm/Support/FileSystem.h"
76 
77 #include <algorithm>
78 #include <map>
79 #include <memory>
80 
81 #include <ctype.h>
82 #include <string.h>
83 
84 //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
85 
86 #ifdef ENABLE_DEBUG_PRINTF
87 #include <stdio.h>
88 #define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
89 #else
90 #define DEBUG_PRINTF(fmt, ...)
91 #endif
92 
93 using namespace lldb;
94 using namespace lldb_private;
95 
96 LLDB_PLUGIN_DEFINE(SymbolFileDWARF)
97 
98 char SymbolFileDWARF::ID;
99 
100 // static inline bool
101 // child_requires_parent_class_union_or_struct_to_be_completed (dw_tag_t tag)
102 //{
103 //    switch (tag)
104 //    {
105 //    default:
106 //        break;
107 //    case DW_TAG_subprogram:
108 //    case DW_TAG_inlined_subroutine:
109 //    case DW_TAG_class_type:
110 //    case DW_TAG_structure_type:
111 //    case DW_TAG_union_type:
112 //        return true;
113 //    }
114 //    return false;
115 //}
116 //
117 
118 namespace {
119 
120 #define LLDB_PROPERTIES_symbolfiledwarf
121 #include "SymbolFileDWARFProperties.inc"
122 
123 enum {
124 #define LLDB_PROPERTIES_symbolfiledwarf
125 #include "SymbolFileDWARFPropertiesEnum.inc"
126 };
127 
128 class PluginProperties : public Properties {
129 public:
130   static ConstString GetSettingName() {
131     return SymbolFileDWARF::GetPluginNameStatic();
132   }
133 
134   PluginProperties() {
135     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
136     m_collection_sp->Initialize(g_symbolfiledwarf_properties);
137   }
138 
139   bool IgnoreFileIndexes() const {
140     return m_collection_sp->GetPropertyAtIndexAsBoolean(
141         nullptr, ePropertyIgnoreIndexes, false);
142   }
143 };
144 
145 typedef std::shared_ptr<PluginProperties> SymbolFileDWARFPropertiesSP;
146 
147 static const SymbolFileDWARFPropertiesSP &GetGlobalPluginProperties() {
148   static const auto g_settings_sp(std::make_shared<PluginProperties>());
149   return g_settings_sp;
150 }
151 
152 } // namespace
153 
154 static const llvm::DWARFDebugLine::LineTable *
155 ParseLLVMLineTable(lldb_private::DWARFContext &context,
156                    llvm::DWARFDebugLine &line, dw_offset_t line_offset,
157                    dw_offset_t unit_offset) {
158   Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
159 
160   llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVM();
161   llvm::DWARFContext &ctx = context.GetAsLLVM();
162   llvm::Expected<const llvm::DWARFDebugLine::LineTable *> line_table =
163       line.getOrParseLineTable(
164           data, line_offset, ctx, nullptr, [&](llvm::Error e) {
165             LLDB_LOG_ERROR(log, std::move(e),
166                            "SymbolFileDWARF::ParseLineTable failed to parse");
167           });
168 
169   if (!line_table) {
170     LLDB_LOG_ERROR(log, line_table.takeError(),
171                    "SymbolFileDWARF::ParseLineTable failed to parse");
172     return nullptr;
173   }
174   return *line_table;
175 }
176 
177 static llvm::Optional<std::string>
178 GetFileByIndex(const llvm::DWARFDebugLine::Prologue &prologue, size_t idx,
179                llvm::StringRef compile_dir, FileSpec::Style style) {
180   // Try to get an absolute path first.
181   std::string abs_path;
182   auto absolute = llvm::DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath;
183   if (prologue.getFileNameByIndex(idx, compile_dir, absolute, abs_path, style))
184     return std::move(abs_path);
185 
186   // Otherwise ask for a relative path.
187   std::string rel_path;
188   auto relative = llvm::DILineInfoSpecifier::FileLineInfoKind::Default;
189   if (!prologue.getFileNameByIndex(idx, compile_dir, relative, rel_path, style))
190     return {};
191   return std::move(rel_path);
192 }
193 
194 static FileSpecList
195 ParseSupportFilesFromPrologue(const lldb::ModuleSP &module,
196                               const llvm::DWARFDebugLine::Prologue &prologue,
197                               FileSpec::Style style,
198                               llvm::StringRef compile_dir = {}) {
199   FileSpecList support_files;
200   size_t first_file = 0;
201   if (prologue.getVersion() <= 4) {
202     // File index 0 is not valid before DWARF v5. Add a dummy entry to ensure
203     // support file list indices match those we get from the debug info and line
204     // tables.
205     support_files.Append(FileSpec());
206     first_file = 1;
207   }
208 
209   const size_t number_of_files = prologue.FileNames.size();
210   for (size_t idx = first_file; idx <= number_of_files; ++idx) {
211     std::string remapped_file;
212     if (auto file_path = GetFileByIndex(prologue, idx, compile_dir, style))
213       if (!module->RemapSourceFile(llvm::StringRef(*file_path), remapped_file))
214         remapped_file = std::move(*file_path);
215 
216     // Unconditionally add an entry, so the indices match up.
217     support_files.EmplaceBack(remapped_file, style);
218   }
219 
220   return support_files;
221 }
222 
223 void SymbolFileDWARF::Initialize() {
224   LogChannelDWARF::Initialize();
225   PluginManager::RegisterPlugin(GetPluginNameStatic(),
226                                 GetPluginDescriptionStatic(), CreateInstance,
227                                 DebuggerInitialize);
228   SymbolFileDWARFDebugMap::Initialize();
229 }
230 
231 void SymbolFileDWARF::DebuggerInitialize(Debugger &debugger) {
232   if (!PluginManager::GetSettingForSymbolFilePlugin(
233           debugger, PluginProperties::GetSettingName())) {
234     const bool is_global_setting = true;
235     PluginManager::CreateSettingForSymbolFilePlugin(
236         debugger, GetGlobalPluginProperties()->GetValueProperties(),
237         ConstString("Properties for the dwarf symbol-file plug-in."),
238         is_global_setting);
239   }
240 }
241 
242 void SymbolFileDWARF::Terminate() {
243   SymbolFileDWARFDebugMap::Terminate();
244   PluginManager::UnregisterPlugin(CreateInstance);
245   LogChannelDWARF::Terminate();
246 }
247 
248 lldb_private::ConstString SymbolFileDWARF::GetPluginNameStatic() {
249   static ConstString g_name("dwarf");
250   return g_name;
251 }
252 
253 const char *SymbolFileDWARF::GetPluginDescriptionStatic() {
254   return "DWARF and DWARF3 debug symbol file reader.";
255 }
256 
257 SymbolFile *SymbolFileDWARF::CreateInstance(ObjectFileSP objfile_sp) {
258   return new SymbolFileDWARF(std::move(objfile_sp),
259                              /*dwo_section_list*/ nullptr);
260 }
261 
262 TypeList &SymbolFileDWARF::GetTypeList() {
263   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
264   if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
265     return debug_map_symfile->GetTypeList();
266   return SymbolFile::GetTypeList();
267 }
268 void SymbolFileDWARF::GetTypes(const DWARFDIE &die, dw_offset_t min_die_offset,
269                                dw_offset_t max_die_offset, uint32_t type_mask,
270                                TypeSet &type_set) {
271   if (die) {
272     const dw_offset_t die_offset = die.GetOffset();
273 
274     if (die_offset >= max_die_offset)
275       return;
276 
277     if (die_offset >= min_die_offset) {
278       const dw_tag_t tag = die.Tag();
279 
280       bool add_type = false;
281 
282       switch (tag) {
283       case DW_TAG_array_type:
284         add_type = (type_mask & eTypeClassArray) != 0;
285         break;
286       case DW_TAG_unspecified_type:
287       case DW_TAG_base_type:
288         add_type = (type_mask & eTypeClassBuiltin) != 0;
289         break;
290       case DW_TAG_class_type:
291         add_type = (type_mask & eTypeClassClass) != 0;
292         break;
293       case DW_TAG_structure_type:
294         add_type = (type_mask & eTypeClassStruct) != 0;
295         break;
296       case DW_TAG_union_type:
297         add_type = (type_mask & eTypeClassUnion) != 0;
298         break;
299       case DW_TAG_enumeration_type:
300         add_type = (type_mask & eTypeClassEnumeration) != 0;
301         break;
302       case DW_TAG_subroutine_type:
303       case DW_TAG_subprogram:
304       case DW_TAG_inlined_subroutine:
305         add_type = (type_mask & eTypeClassFunction) != 0;
306         break;
307       case DW_TAG_pointer_type:
308         add_type = (type_mask & eTypeClassPointer) != 0;
309         break;
310       case DW_TAG_rvalue_reference_type:
311       case DW_TAG_reference_type:
312         add_type = (type_mask & eTypeClassReference) != 0;
313         break;
314       case DW_TAG_typedef:
315         add_type = (type_mask & eTypeClassTypedef) != 0;
316         break;
317       case DW_TAG_ptr_to_member_type:
318         add_type = (type_mask & eTypeClassMemberPointer) != 0;
319         break;
320       default:
321         break;
322       }
323 
324       if (add_type) {
325         const bool assert_not_being_parsed = true;
326         Type *type = ResolveTypeUID(die, assert_not_being_parsed);
327         if (type) {
328           if (type_set.find(type) == type_set.end())
329             type_set.insert(type);
330         }
331       }
332     }
333 
334     for (DWARFDIE child_die = die.GetFirstChild(); child_die.IsValid();
335          child_die = child_die.GetSibling()) {
336       GetTypes(child_die, min_die_offset, max_die_offset, type_mask, type_set);
337     }
338   }
339 }
340 
341 void SymbolFileDWARF::GetTypes(SymbolContextScope *sc_scope,
342                                TypeClass type_mask, TypeList &type_list)
343 
344 {
345   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
346   TypeSet type_set;
347 
348   CompileUnit *comp_unit = nullptr;
349   DWARFUnit *dwarf_cu = nullptr;
350   if (sc_scope)
351     comp_unit = sc_scope->CalculateSymbolContextCompileUnit();
352 
353   if (comp_unit) {
354     dwarf_cu = GetDWARFCompileUnit(comp_unit);
355     if (!dwarf_cu)
356       return;
357     GetTypes(dwarf_cu->DIE(), dwarf_cu->GetOffset(),
358              dwarf_cu->GetNextUnitOffset(), type_mask, type_set);
359   } else {
360     DWARFDebugInfo *info = DebugInfo();
361     if (info) {
362       const size_t num_cus = info->GetNumUnits();
363       for (size_t cu_idx = 0; cu_idx < num_cus; ++cu_idx) {
364         dwarf_cu = info->GetUnitAtIndex(cu_idx);
365         if (dwarf_cu) {
366           GetTypes(dwarf_cu->DIE(), 0, UINT32_MAX, type_mask, type_set);
367         }
368       }
369     }
370   }
371 
372   std::set<CompilerType> compiler_type_set;
373   for (Type *type : type_set) {
374     CompilerType compiler_type = type->GetForwardCompilerType();
375     if (compiler_type_set.find(compiler_type) == compiler_type_set.end()) {
376       compiler_type_set.insert(compiler_type);
377       type_list.Insert(type->shared_from_this());
378     }
379   }
380 }
381 
382 // Gets the first parent that is a lexical block, function or inlined
383 // subroutine, or compile unit.
384 DWARFDIE
385 SymbolFileDWARF::GetParentSymbolContextDIE(const DWARFDIE &child_die) {
386   DWARFDIE die;
387   for (die = child_die.GetParent(); die; die = die.GetParent()) {
388     dw_tag_t tag = die.Tag();
389 
390     switch (tag) {
391     case DW_TAG_compile_unit:
392     case DW_TAG_partial_unit:
393     case DW_TAG_subprogram:
394     case DW_TAG_inlined_subroutine:
395     case DW_TAG_lexical_block:
396       return die;
397     default:
398       break;
399     }
400   }
401   return DWARFDIE();
402 }
403 
404 SymbolFileDWARF::SymbolFileDWARF(ObjectFileSP objfile_sp,
405                                  SectionList *dwo_section_list)
406     : SymbolFile(std::move(objfile_sp)),
407       UserID(0x7fffffff00000000), // Used by SymbolFileDWARFDebugMap to
408                                   // when this class parses .o files to
409                                   // contain the .o file index/ID
410       m_debug_map_module_wp(), m_debug_map_symfile(nullptr),
411       m_context(m_objfile_sp->GetModule()->GetSectionList(), dwo_section_list),
412       m_fetched_external_modules(false),
413       m_supports_DW_AT_APPLE_objc_complete_type(eLazyBoolCalculate) {}
414 
415 SymbolFileDWARF::~SymbolFileDWARF() {}
416 
417 static ConstString GetDWARFMachOSegmentName() {
418   static ConstString g_dwarf_section_name("__DWARF");
419   return g_dwarf_section_name;
420 }
421 
422 UniqueDWARFASTTypeMap &SymbolFileDWARF::GetUniqueDWARFASTTypeMap() {
423   SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
424   if (debug_map_symfile)
425     return debug_map_symfile->GetUniqueDWARFASTTypeMap();
426   else
427     return m_unique_ast_type_map;
428 }
429 
430 llvm::Expected<TypeSystem &>
431 SymbolFileDWARF::GetTypeSystemForLanguage(LanguageType language) {
432   if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
433     return debug_map_symfile->GetTypeSystemForLanguage(language);
434 
435   auto type_system_or_err =
436       m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
437   if (type_system_or_err) {
438     type_system_or_err->SetSymbolFile(this);
439   }
440   return type_system_or_err;
441 }
442 
443 void SymbolFileDWARF::InitializeObject() {
444   Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
445 
446   if (!GetGlobalPluginProperties()->IgnoreFileIndexes()) {
447     DWARFDataExtractor apple_names, apple_namespaces, apple_types, apple_objc;
448     LoadSectionData(eSectionTypeDWARFAppleNames, apple_names);
449     LoadSectionData(eSectionTypeDWARFAppleNamespaces, apple_namespaces);
450     LoadSectionData(eSectionTypeDWARFAppleTypes, apple_types);
451     LoadSectionData(eSectionTypeDWARFAppleObjC, apple_objc);
452 
453     m_index = AppleDWARFIndex::Create(
454         *GetObjectFile()->GetModule(), apple_names, apple_namespaces,
455         apple_types, apple_objc, m_context.getOrLoadStrData());
456 
457     if (m_index)
458       return;
459 
460     DWARFDataExtractor debug_names;
461     LoadSectionData(eSectionTypeDWARFDebugNames, debug_names);
462     if (debug_names.GetByteSize() > 0) {
463       llvm::Expected<std::unique_ptr<DebugNamesDWARFIndex>> index_or =
464           DebugNamesDWARFIndex::Create(
465               *GetObjectFile()->GetModule(), debug_names,
466               m_context.getOrLoadStrData(), DebugInfo());
467       if (index_or) {
468         m_index = std::move(*index_or);
469         return;
470       }
471       LLDB_LOG_ERROR(log, index_or.takeError(),
472                      "Unable to read .debug_names data: {0}");
473     }
474   }
475 
476   m_index = std::make_unique<ManualDWARFIndex>(*GetObjectFile()->GetModule(),
477                                                 DebugInfo());
478 }
479 
480 bool SymbolFileDWARF::SupportedVersion(uint16_t version) {
481   return version >= 2 && version <= 5;
482 }
483 
484 uint32_t SymbolFileDWARF::CalculateAbilities() {
485   uint32_t abilities = 0;
486   if (m_objfile_sp != nullptr) {
487     const Section *section = nullptr;
488     const SectionList *section_list = m_objfile_sp->GetSectionList();
489     if (section_list == nullptr)
490       return 0;
491 
492     uint64_t debug_abbrev_file_size = 0;
493     uint64_t debug_info_file_size = 0;
494     uint64_t debug_line_file_size = 0;
495 
496     section = section_list->FindSectionByName(GetDWARFMachOSegmentName()).get();
497 
498     if (section)
499       section_list = &section->GetChildren();
500 
501     section =
502         section_list->FindSectionByType(eSectionTypeDWARFDebugInfo, true).get();
503     if (section != nullptr) {
504       debug_info_file_size = section->GetFileSize();
505 
506       section =
507           section_list->FindSectionByType(eSectionTypeDWARFDebugAbbrev, true)
508               .get();
509       if (section)
510         debug_abbrev_file_size = section->GetFileSize();
511 
512       DWARFDebugAbbrev *abbrev = DebugAbbrev();
513       if (abbrev) {
514         std::set<dw_form_t> invalid_forms;
515         abbrev->GetUnsupportedForms(invalid_forms);
516         if (!invalid_forms.empty()) {
517           StreamString error;
518           error.Printf("unsupported DW_FORM value%s:",
519                        invalid_forms.size() > 1 ? "s" : "");
520           for (auto form : invalid_forms)
521             error.Printf(" %#x", form);
522           m_objfile_sp->GetModule()->ReportWarning(
523               "%s", error.GetString().str().c_str());
524           return 0;
525         }
526       }
527 
528       section =
529           section_list->FindSectionByType(eSectionTypeDWARFDebugLine, true)
530               .get();
531       if (section)
532         debug_line_file_size = section->GetFileSize();
533     } else {
534       const char *symfile_dir_cstr =
535           m_objfile_sp->GetFileSpec().GetDirectory().GetCString();
536       if (symfile_dir_cstr) {
537         if (strcasestr(symfile_dir_cstr, ".dsym")) {
538           if (m_objfile_sp->GetType() == ObjectFile::eTypeDebugInfo) {
539             // We have a dSYM file that didn't have a any debug info. If the
540             // string table has a size of 1, then it was made from an
541             // executable with no debug info, or from an executable that was
542             // stripped.
543             section =
544                 section_list->FindSectionByType(eSectionTypeDWARFDebugStr, true)
545                     .get();
546             if (section && section->GetFileSize() == 1) {
547               m_objfile_sp->GetModule()->ReportWarning(
548                   "empty dSYM file detected, dSYM was created with an "
549                   "executable with no debug info.");
550             }
551           }
552         }
553       }
554     }
555 
556     if (debug_abbrev_file_size > 0 && debug_info_file_size > 0)
557       abilities |= CompileUnits | Functions | Blocks | GlobalVariables |
558                    LocalVariables | VariableTypes;
559 
560     if (debug_line_file_size > 0)
561       abilities |= LineTables;
562   }
563   return abilities;
564 }
565 
566 void SymbolFileDWARF::LoadSectionData(lldb::SectionType sect_type,
567                                       DWARFDataExtractor &data) {
568   ModuleSP module_sp(m_objfile_sp->GetModule());
569   const SectionList *section_list = module_sp->GetSectionList();
570   if (!section_list)
571     return;
572 
573   SectionSP section_sp(section_list->FindSectionByType(sect_type, true));
574   if (!section_sp)
575     return;
576 
577   data.Clear();
578   m_objfile_sp->ReadSectionData(section_sp.get(), data);
579 }
580 
581 DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() {
582   if (m_abbr)
583     return m_abbr.get();
584 
585   const DWARFDataExtractor &debug_abbrev_data = m_context.getOrLoadAbbrevData();
586   if (debug_abbrev_data.GetByteSize() == 0)
587     return nullptr;
588 
589   auto abbr = std::make_unique<DWARFDebugAbbrev>();
590   llvm::Error error = abbr->parse(debug_abbrev_data);
591   if (error) {
592     Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
593     LLDB_LOG_ERROR(log, std::move(error),
594                    "Unable to read .debug_abbrev section: {0}");
595     return nullptr;
596   }
597 
598   m_abbr = std::move(abbr);
599   return m_abbr.get();
600 }
601 
602 DWARFDebugInfo *SymbolFileDWARF::DebugInfo() {
603   llvm::call_once(m_info_once_flag, [&] {
604     static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
605     Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
606                        static_cast<void *>(this));
607     if (m_context.getOrLoadDebugInfoData().GetByteSize() > 0)
608       m_info = std::make_unique<DWARFDebugInfo>(*this, m_context);
609   });
610   return m_info.get();
611 }
612 
613 DWARFUnit *
614 SymbolFileDWARF::GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit) {
615   if (!comp_unit)
616     return nullptr;
617 
618   DWARFDebugInfo *info = DebugInfo();
619   if (info) {
620     // The compile unit ID is the index of the DWARF unit.
621     DWARFUnit *dwarf_cu = info->GetUnitAtIndex(comp_unit->GetID());
622     if (dwarf_cu && dwarf_cu->GetUserData() == nullptr)
623       dwarf_cu->SetUserData(comp_unit);
624     return dwarf_cu;
625   }
626   return nullptr;
627 }
628 
629 DWARFDebugRanges *SymbolFileDWARF::GetDebugRanges() {
630   if (!m_ranges) {
631     static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
632     Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
633                        static_cast<void *>(this));
634 
635     if (m_context.getOrLoadRangesData().GetByteSize() > 0)
636       m_ranges.reset(new DWARFDebugRanges());
637 
638     if (m_ranges)
639       m_ranges->Extract(m_context);
640   }
641   return m_ranges.get();
642 }
643 
644 lldb::CompUnitSP SymbolFileDWARF::ParseCompileUnit(DWARFCompileUnit &dwarf_cu) {
645   CompUnitSP cu_sp;
646   CompileUnit *comp_unit = (CompileUnit *)dwarf_cu.GetUserData();
647   if (comp_unit) {
648     // We already parsed this compile unit, had out a shared pointer to it
649     cu_sp = comp_unit->shared_from_this();
650   } else {
651     if (dwarf_cu.GetOffset() == 0 && GetDebugMapSymfile()) {
652       // Let the debug map create the compile unit
653       cu_sp = m_debug_map_symfile->GetCompileUnit(this);
654       dwarf_cu.SetUserData(cu_sp.get());
655     } else {
656       ModuleSP module_sp(m_objfile_sp->GetModule());
657       if (module_sp) {
658         const DWARFBaseDIE cu_die =
659             dwarf_cu.GetNonSkeletonUnit().GetUnitDIEOnly();
660         if (cu_die) {
661           FileSpec cu_file_spec(cu_die.GetName(), dwarf_cu.GetPathStyle());
662           if (cu_file_spec) {
663             // If we have a full path to the compile unit, we don't need to
664             // resolve the file.  This can be expensive e.g. when the source
665             // files are NFS mounted.
666             cu_file_spec.MakeAbsolute(dwarf_cu.GetCompilationDirectory());
667 
668             std::string remapped_file;
669             if (module_sp->RemapSourceFile(cu_file_spec.GetPath(),
670                                            remapped_file))
671               cu_file_spec.SetFile(remapped_file, FileSpec::Style::native);
672           }
673 
674           LanguageType cu_language = SymbolFileDWARF::LanguageTypeFromDWARF(
675               cu_die.GetAttributeValueAsUnsigned(DW_AT_language, 0));
676 
677           bool is_optimized = dwarf_cu.GetNonSkeletonUnit().GetIsOptimized();
678           BuildCuTranslationTable();
679           cu_sp = std::make_shared<CompileUnit>(
680               module_sp, &dwarf_cu, cu_file_spec,
681               *GetDWARFUnitIndex(dwarf_cu.GetID()), cu_language,
682               is_optimized ? eLazyBoolYes : eLazyBoolNo);
683 
684           dwarf_cu.SetUserData(cu_sp.get());
685 
686           SetCompileUnitAtIndex(dwarf_cu.GetID(), cu_sp);
687         }
688       }
689     }
690   }
691   return cu_sp;
692 }
693 
694 void SymbolFileDWARF::BuildCuTranslationTable() {
695   if (!m_lldb_cu_to_dwarf_unit.empty())
696     return;
697 
698   DWARFDebugInfo *info = DebugInfo();
699   if (!info)
700     return;
701 
702   if (!info->ContainsTypeUnits()) {
703     // We can use a 1-to-1 mapping. No need to build a translation table.
704     return;
705   }
706   for (uint32_t i = 0, num = info->GetNumUnits(); i < num; ++i) {
707     if (auto *cu = llvm::dyn_cast<DWARFCompileUnit>(info->GetUnitAtIndex(i))) {
708       cu->SetID(m_lldb_cu_to_dwarf_unit.size());
709       m_lldb_cu_to_dwarf_unit.push_back(i);
710     }
711   }
712 }
713 
714 llvm::Optional<uint32_t> SymbolFileDWARF::GetDWARFUnitIndex(uint32_t cu_idx) {
715   BuildCuTranslationTable();
716   if (m_lldb_cu_to_dwarf_unit.empty())
717     return cu_idx;
718   if (cu_idx >= m_lldb_cu_to_dwarf_unit.size())
719     return llvm::None;
720   return m_lldb_cu_to_dwarf_unit[cu_idx];
721 }
722 
723 uint32_t SymbolFileDWARF::CalculateNumCompileUnits() {
724   DWARFDebugInfo *info = DebugInfo();
725   if (!info)
726     return 0;
727   BuildCuTranslationTable();
728   return m_lldb_cu_to_dwarf_unit.empty() ? info->GetNumUnits()
729                                          : m_lldb_cu_to_dwarf_unit.size();
730 }
731 
732 CompUnitSP SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx) {
733   ASSERT_MODULE_LOCK(this);
734   DWARFDebugInfo *info = DebugInfo();
735   if (!info)
736     return {};
737 
738   if (llvm::Optional<uint32_t> dwarf_idx = GetDWARFUnitIndex(cu_idx)) {
739     if (auto *dwarf_cu = llvm::cast_or_null<DWARFCompileUnit>(
740             info->GetUnitAtIndex(*dwarf_idx)))
741       return ParseCompileUnit(*dwarf_cu);
742   }
743   return {};
744 }
745 
746 Function *SymbolFileDWARF::ParseFunction(CompileUnit &comp_unit,
747                                          const DWARFDIE &die) {
748   ASSERT_MODULE_LOCK(this);
749   if (!die.IsValid())
750     return nullptr;
751 
752   auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU()));
753   if (auto err = type_system_or_err.takeError()) {
754     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
755                    std::move(err), "Unable to parse function");
756     return nullptr;
757   }
758   DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser();
759   if (!dwarf_ast)
760     return nullptr;
761 
762   return dwarf_ast->ParseFunctionFromDWARF(comp_unit, die);
763 }
764 
765 lldb::addr_t SymbolFileDWARF::FixupAddress(lldb::addr_t file_addr) {
766   SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
767   if (debug_map_symfile)
768     return debug_map_symfile->LinkOSOFileAddress(this, file_addr);
769   return file_addr;
770 }
771 
772 bool SymbolFileDWARF::FixupAddress(Address &addr) {
773   SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
774   if (debug_map_symfile) {
775     return debug_map_symfile->LinkOSOAddress(addr);
776   }
777   // This is a normal DWARF file, no address fixups need to happen
778   return true;
779 }
780 lldb::LanguageType SymbolFileDWARF::ParseLanguage(CompileUnit &comp_unit) {
781   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
782   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
783   if (dwarf_cu)
784     return GetLanguage(*dwarf_cu);
785   else
786     return eLanguageTypeUnknown;
787 }
788 
789 size_t SymbolFileDWARF::ParseFunctions(CompileUnit &comp_unit) {
790   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
791   Timer scoped_timer(func_cat, "SymbolFileDWARF::ParseFunctions");
792   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
793   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
794   if (!dwarf_cu)
795     return 0;
796 
797   size_t functions_added = 0;
798   dwarf_cu = &dwarf_cu->GetNonSkeletonUnit();
799   for (DWARFDebugInfoEntry &entry : dwarf_cu->dies()) {
800     if (entry.Tag() != DW_TAG_subprogram)
801       continue;
802 
803     DWARFDIE die(dwarf_cu, &entry);
804     if (comp_unit.FindFunctionByUID(die.GetID()))
805       continue;
806     if (ParseFunction(comp_unit, die))
807       ++functions_added;
808   }
809   // FixupTypes();
810   return functions_added;
811 }
812 
813 bool SymbolFileDWARF::ForEachExternalModule(
814     CompileUnit &comp_unit,
815     llvm::DenseSet<lldb_private::SymbolFile *> &visited_symbol_files,
816     llvm::function_ref<bool(Module &)> lambda) {
817   // Only visit each symbol file once.
818   if (!visited_symbol_files.insert(this).second)
819     return false;
820 
821   UpdateExternalModuleListIfNeeded();
822   for (auto &p : m_external_type_modules) {
823     ModuleSP module = p.second;
824     if (!module)
825       continue;
826 
827     // Invoke the action and potentially early-exit.
828     if (lambda(*module))
829       return true;
830 
831     for (std::size_t i = 0; i < module->GetNumCompileUnits(); ++i) {
832       auto cu = module->GetCompileUnitAtIndex(i);
833       bool early_exit = cu->ForEachExternalModule(visited_symbol_files, lambda);
834       if (early_exit)
835         return true;
836     }
837   }
838   return false;
839 }
840 
841 bool SymbolFileDWARF::ParseSupportFiles(CompileUnit &comp_unit,
842                                         FileSpecList &support_files) {
843   if (!comp_unit.GetLineTable())
844     ParseLineTable(comp_unit);
845   return true;
846 }
847 
848 FileSpec SymbolFileDWARF::GetFile(DWARFUnit &unit, size_t file_idx) {
849   if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit)) {
850     if (CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(*dwarf_cu))
851       return lldb_cu->GetSupportFiles().GetFileSpecAtIndex(file_idx);
852     return FileSpec();
853   }
854 
855   auto &tu = llvm::cast<DWARFTypeUnit>(unit);
856   return GetTypeUnitSupportFiles(tu).GetFileSpecAtIndex(file_idx);
857 }
858 
859 const FileSpecList &
860 SymbolFileDWARF::GetTypeUnitSupportFiles(DWARFTypeUnit &tu) {
861   static FileSpecList empty_list;
862 
863   dw_offset_t offset = tu.GetLineTableOffset();
864   if (offset == DW_INVALID_OFFSET ||
865       offset == llvm::DenseMapInfo<dw_offset_t>::getEmptyKey() ||
866       offset == llvm::DenseMapInfo<dw_offset_t>::getTombstoneKey())
867     return empty_list;
868 
869   // Many type units can share a line table, so parse the support file list
870   // once, and cache it based on the offset field.
871   auto iter_bool = m_type_unit_support_files.try_emplace(offset);
872   FileSpecList &list = iter_bool.first->second;
873   if (iter_bool.second) {
874     uint64_t line_table_offset = offset;
875     llvm::DWARFDataExtractor data = m_context.getOrLoadLineData().GetAsLLVM();
876     llvm::DWARFContext &ctx = m_context.GetAsLLVM();
877     llvm::DWARFDebugLine::Prologue prologue;
878     auto report = [](llvm::Error error) {
879       Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
880       LLDB_LOG_ERROR(log, std::move(error),
881                      "SymbolFileDWARF::GetTypeUnitSupportFiles failed to parse "
882                      "the line table prologue");
883     };
884     llvm::Error error = prologue.parse(data, &line_table_offset, report, ctx);
885     if (error) {
886       report(std::move(error));
887     } else {
888       list = ParseSupportFilesFromPrologue(GetObjectFile()->GetModule(),
889                                            prologue, tu.GetPathStyle());
890     }
891   }
892   return list;
893 }
894 
895 bool SymbolFileDWARF::ParseIsOptimized(CompileUnit &comp_unit) {
896   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
897   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
898   if (dwarf_cu)
899     return dwarf_cu->GetIsOptimized();
900   return false;
901 }
902 
903 bool SymbolFileDWARF::ParseImportedModules(
904     const lldb_private::SymbolContext &sc,
905     std::vector<SourceModule> &imported_modules) {
906   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
907   assert(sc.comp_unit);
908   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
909   if (!dwarf_cu)
910     return false;
911   if (!ClangModulesDeclVendor::LanguageSupportsClangModules(
912           sc.comp_unit->GetLanguage()))
913     return false;
914   UpdateExternalModuleListIfNeeded();
915 
916   const DWARFDIE die = dwarf_cu->DIE();
917   if (!die)
918     return false;
919 
920   for (DWARFDIE child_die = die.GetFirstChild(); child_die;
921        child_die = child_die.GetSibling()) {
922     if (child_die.Tag() != DW_TAG_imported_declaration)
923       continue;
924 
925     DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import);
926     if (module_die.Tag() != DW_TAG_module)
927       continue;
928 
929     if (const char *name =
930             module_die.GetAttributeValueAsString(DW_AT_name, nullptr)) {
931       SourceModule module;
932       module.path.push_back(ConstString(name));
933 
934       DWARFDIE parent_die = module_die;
935       while ((parent_die = parent_die.GetParent())) {
936         if (parent_die.Tag() != DW_TAG_module)
937           break;
938         if (const char *name =
939                 parent_die.GetAttributeValueAsString(DW_AT_name, nullptr))
940           module.path.push_back(ConstString(name));
941       }
942       std::reverse(module.path.begin(), module.path.end());
943       if (const char *include_path = module_die.GetAttributeValueAsString(
944               DW_AT_LLVM_include_path, nullptr))
945         module.search_path = ConstString(include_path);
946       if (const char *sysroot = dwarf_cu->DIE().GetAttributeValueAsString(
947               DW_AT_LLVM_sysroot, nullptr))
948         module.sysroot = ConstString(sysroot);
949       imported_modules.push_back(module);
950     }
951   }
952   return true;
953 }
954 
955 bool SymbolFileDWARF::ParseLineTable(CompileUnit &comp_unit) {
956   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
957   if (comp_unit.GetLineTable() != nullptr)
958     return true;
959 
960   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
961   if (!dwarf_cu)
962     return false;
963 
964   const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
965   if (!dwarf_cu_die)
966     return false;
967 
968   const dw_offset_t cu_line_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(
969       DW_AT_stmt_list, DW_INVALID_OFFSET);
970   if (cu_line_offset == DW_INVALID_OFFSET)
971     return false;
972 
973   llvm::DWARFDebugLine line;
974   const llvm::DWARFDebugLine::LineTable *line_table = ParseLLVMLineTable(
975       m_context, line, cu_line_offset, dwarf_cu->GetOffset());
976 
977   if (!line_table)
978     return false;
979 
980   // FIXME: Rather than parsing the whole line table and then copying it over
981   // into LLDB, we should explore using a callback to populate the line table
982   // while we parse to reduce memory usage.
983   std::unique_ptr<LineSequence> sequence =
984       LineTable::CreateLineSequenceContainer();
985   std::vector<std::unique_ptr<LineSequence>> sequences;
986   for (auto &row : line_table->Rows) {
987     LineTable::AppendLineEntryToSequence(
988         sequence.get(), row.Address.Address, row.Line, row.Column, row.File,
989         row.IsStmt, row.BasicBlock, row.PrologueEnd, row.EpilogueBegin,
990         row.EndSequence);
991     if (row.EndSequence) {
992       sequences.push_back(std::move(sequence));
993       sequence = LineTable::CreateLineSequenceContainer();
994     }
995   }
996 
997   std::unique_ptr<LineTable> line_table_up =
998       std::make_unique<LineTable>(&comp_unit, std::move(sequences));
999 
1000   if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) {
1001     // We have an object file that has a line table with addresses that are not
1002     // linked. We need to link the line table and convert the addresses that
1003     // are relative to the .o file into addresses for the main executable.
1004     comp_unit.SetLineTable(
1005         debug_map_symfile->LinkOSOLineTable(this, line_table_up.get()));
1006   } else {
1007     comp_unit.SetLineTable(line_table_up.release());
1008   }
1009 
1010   comp_unit.SetSupportFiles(ParseSupportFilesFromPrologue(
1011       comp_unit.GetModule(), line_table->Prologue, dwarf_cu->GetPathStyle(),
1012       dwarf_cu->GetCompilationDirectory().GetCString()));
1013 
1014   return true;
1015 }
1016 
1017 lldb_private::DebugMacrosSP
1018 SymbolFileDWARF::ParseDebugMacros(lldb::offset_t *offset) {
1019   auto iter = m_debug_macros_map.find(*offset);
1020   if (iter != m_debug_macros_map.end())
1021     return iter->second;
1022 
1023   const DWARFDataExtractor &debug_macro_data = m_context.getOrLoadMacroData();
1024   if (debug_macro_data.GetByteSize() == 0)
1025     return DebugMacrosSP();
1026 
1027   lldb_private::DebugMacrosSP debug_macros_sp(new lldb_private::DebugMacros());
1028   m_debug_macros_map[*offset] = debug_macros_sp;
1029 
1030   const DWARFDebugMacroHeader &header =
1031       DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset);
1032   DWARFDebugMacroEntry::ReadMacroEntries(
1033       debug_macro_data, m_context.getOrLoadStrData(), header.OffsetIs64Bit(),
1034       offset, this, debug_macros_sp);
1035 
1036   return debug_macros_sp;
1037 }
1038 
1039 bool SymbolFileDWARF::ParseDebugMacros(CompileUnit &comp_unit) {
1040   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1041 
1042   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1043   if (dwarf_cu == nullptr)
1044     return false;
1045 
1046   const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
1047   if (!dwarf_cu_die)
1048     return false;
1049 
1050   lldb::offset_t sect_offset =
1051       dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET);
1052   if (sect_offset == DW_INVALID_OFFSET)
1053     sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros,
1054                                                            DW_INVALID_OFFSET);
1055   if (sect_offset == DW_INVALID_OFFSET)
1056     return false;
1057 
1058   comp_unit.SetDebugMacros(ParseDebugMacros(&sect_offset));
1059 
1060   return true;
1061 }
1062 
1063 size_t SymbolFileDWARF::ParseBlocksRecursive(
1064     lldb_private::CompileUnit &comp_unit, Block *parent_block,
1065     const DWARFDIE &orig_die, addr_t subprogram_low_pc, uint32_t depth) {
1066   size_t blocks_added = 0;
1067   DWARFDIE die = orig_die;
1068   while (die) {
1069     dw_tag_t tag = die.Tag();
1070 
1071     switch (tag) {
1072     case DW_TAG_inlined_subroutine:
1073     case DW_TAG_subprogram:
1074     case DW_TAG_lexical_block: {
1075       Block *block = nullptr;
1076       if (tag == DW_TAG_subprogram) {
1077         // Skip any DW_TAG_subprogram DIEs that are inside of a normal or
1078         // inlined functions. These will be parsed on their own as separate
1079         // entities.
1080 
1081         if (depth > 0)
1082           break;
1083 
1084         block = parent_block;
1085       } else {
1086         BlockSP block_sp(new Block(die.GetID()));
1087         parent_block->AddChild(block_sp);
1088         block = block_sp.get();
1089       }
1090       DWARFRangeList ranges;
1091       const char *name = nullptr;
1092       const char *mangled_name = nullptr;
1093 
1094       int decl_file = 0;
1095       int decl_line = 0;
1096       int decl_column = 0;
1097       int call_file = 0;
1098       int call_line = 0;
1099       int call_column = 0;
1100       if (die.GetDIENamesAndRanges(name, mangled_name, ranges, decl_file,
1101                                    decl_line, decl_column, call_file, call_line,
1102                                    call_column, nullptr)) {
1103         if (tag == DW_TAG_subprogram) {
1104           assert(subprogram_low_pc == LLDB_INVALID_ADDRESS);
1105           subprogram_low_pc = ranges.GetMinRangeBase(0);
1106         } else if (tag == DW_TAG_inlined_subroutine) {
1107           // We get called here for inlined subroutines in two ways. The first
1108           // time is when we are making the Function object for this inlined
1109           // concrete instance.  Since we're creating a top level block at
1110           // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS.  So we
1111           // need to adjust the containing address. The second time is when we
1112           // are parsing the blocks inside the function that contains the
1113           // inlined concrete instance.  Since these will be blocks inside the
1114           // containing "real" function the offset will be for that function.
1115           if (subprogram_low_pc == LLDB_INVALID_ADDRESS) {
1116             subprogram_low_pc = ranges.GetMinRangeBase(0);
1117           }
1118         }
1119 
1120         const size_t num_ranges = ranges.GetSize();
1121         for (size_t i = 0; i < num_ranges; ++i) {
1122           const DWARFRangeList::Entry &range = ranges.GetEntryRef(i);
1123           const addr_t range_base = range.GetRangeBase();
1124           if (range_base >= subprogram_low_pc)
1125             block->AddRange(Block::Range(range_base - subprogram_low_pc,
1126                                          range.GetByteSize()));
1127           else {
1128             GetObjectFile()->GetModule()->ReportError(
1129                 "0x%8.8" PRIx64 ": adding range [0x%" PRIx64 "-0x%" PRIx64
1130                 ") which has a base that is less than the function's low PC "
1131                 "0x%" PRIx64 ". Please file a bug and attach the file at the "
1132                 "start of this error message",
1133                 block->GetID(), range_base, range.GetRangeEnd(),
1134                 subprogram_low_pc);
1135           }
1136         }
1137         block->FinalizeRanges();
1138 
1139         if (tag != DW_TAG_subprogram &&
1140             (name != nullptr || mangled_name != nullptr)) {
1141           std::unique_ptr<Declaration> decl_up;
1142           if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1143             decl_up.reset(new Declaration(
1144                 comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file),
1145                 decl_line, decl_column));
1146 
1147           std::unique_ptr<Declaration> call_up;
1148           if (call_file != 0 || call_line != 0 || call_column != 0)
1149             call_up.reset(new Declaration(
1150                 comp_unit.GetSupportFiles().GetFileSpecAtIndex(call_file),
1151                 call_line, call_column));
1152 
1153           block->SetInlinedFunctionInfo(name, mangled_name, decl_up.get(),
1154                                         call_up.get());
1155         }
1156 
1157         ++blocks_added;
1158 
1159         if (die.HasChildren()) {
1160           blocks_added +=
1161               ParseBlocksRecursive(comp_unit, block, die.GetFirstChild(),
1162                                    subprogram_low_pc, depth + 1);
1163         }
1164       }
1165     } break;
1166     default:
1167       break;
1168     }
1169 
1170     // Only parse siblings of the block if we are not at depth zero. A depth of
1171     // zero indicates we are currently parsing the top level DW_TAG_subprogram
1172     // DIE
1173 
1174     if (depth == 0)
1175       die.Clear();
1176     else
1177       die = die.GetSibling();
1178   }
1179   return blocks_added;
1180 }
1181 
1182 bool SymbolFileDWARF::ClassOrStructIsVirtual(const DWARFDIE &parent_die) {
1183   if (parent_die) {
1184     for (DWARFDIE die = parent_die.GetFirstChild(); die;
1185          die = die.GetSibling()) {
1186       dw_tag_t tag = die.Tag();
1187       bool check_virtuality = false;
1188       switch (tag) {
1189       case DW_TAG_inheritance:
1190       case DW_TAG_subprogram:
1191         check_virtuality = true;
1192         break;
1193       default:
1194         break;
1195       }
1196       if (check_virtuality) {
1197         if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0)
1198           return true;
1199       }
1200     }
1201   }
1202   return false;
1203 }
1204 
1205 void SymbolFileDWARF::ParseDeclsForContext(CompilerDeclContext decl_ctx) {
1206   auto *type_system = decl_ctx.GetTypeSystem();
1207   if (type_system != nullptr)
1208     type_system->GetDWARFParser()->EnsureAllDIEsInDeclContextHaveBeenParsed(
1209         decl_ctx);
1210 }
1211 
1212 user_id_t SymbolFileDWARF::GetUID(DIERef ref) {
1213   if (GetDebugMapSymfile())
1214     return GetID() | ref.die_offset();
1215 
1216   return user_id_t(GetDwoNum().getValueOr(0x7fffffff)) << 32 |
1217          ref.die_offset() |
1218          (lldb::user_id_t(ref.section() == DIERef::Section::DebugTypes) << 63);
1219 }
1220 
1221 llvm::Optional<SymbolFileDWARF::DecodedUID>
1222 SymbolFileDWARF::DecodeUID(lldb::user_id_t uid) {
1223   // This method can be called without going through the symbol vendor so we
1224   // need to lock the module.
1225   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1226   // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we
1227   // must make sure we use the correct DWARF file when resolving things. On
1228   // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple
1229   // SymbolFileDWARF classes, one for each .o file. We can often end up with
1230   // references to other DWARF objects and we must be ready to receive a
1231   // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF
1232   // instance.
1233   if (SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile()) {
1234     SymbolFileDWARF *dwarf = debug_map->GetSymbolFileByOSOIndex(
1235         debug_map->GetOSOIndexFromUserID(uid));
1236     return DecodedUID{
1237         *dwarf, {llvm::None, DIERef::Section::DebugInfo, dw_offset_t(uid)}};
1238   }
1239   dw_offset_t die_offset = uid;
1240   if (die_offset == DW_INVALID_OFFSET)
1241     return llvm::None;
1242 
1243   DIERef::Section section =
1244       uid >> 63 ? DIERef::Section::DebugTypes : DIERef::Section::DebugInfo;
1245 
1246   llvm::Optional<uint32_t> dwo_num = uid >> 32 & 0x7fffffff;
1247   if (*dwo_num == 0x7fffffff)
1248     dwo_num = llvm::None;
1249 
1250   return DecodedUID{*this, {dwo_num, section, die_offset}};
1251 }
1252 
1253 DWARFDIE
1254 SymbolFileDWARF::GetDIE(lldb::user_id_t uid) {
1255   // This method can be called without going through the symbol vendor so we
1256   // need to lock the module.
1257   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1258 
1259   llvm::Optional<DecodedUID> decoded = DecodeUID(uid);
1260 
1261   if (decoded)
1262     return decoded->dwarf.GetDIE(decoded->ref);
1263 
1264   return DWARFDIE();
1265 }
1266 
1267 CompilerDecl SymbolFileDWARF::GetDeclForUID(lldb::user_id_t type_uid) {
1268   // This method can be called without going through the symbol vendor so we
1269   // need to lock the module.
1270   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1271   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1272   // SymbolFileDWARF::GetDIE(). See comments inside the
1273   // SymbolFileDWARF::GetDIE() for details.
1274   if (DWARFDIE die = GetDIE(type_uid))
1275     return GetDecl(die);
1276   return CompilerDecl();
1277 }
1278 
1279 CompilerDeclContext
1280 SymbolFileDWARF::GetDeclContextForUID(lldb::user_id_t type_uid) {
1281   // This method can be called without going through the symbol vendor so we
1282   // need to lock the module.
1283   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1284   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1285   // SymbolFileDWARF::GetDIE(). See comments inside the
1286   // SymbolFileDWARF::GetDIE() for details.
1287   if (DWARFDIE die = GetDIE(type_uid))
1288     return GetDeclContext(die);
1289   return CompilerDeclContext();
1290 }
1291 
1292 CompilerDeclContext
1293 SymbolFileDWARF::GetDeclContextContainingUID(lldb::user_id_t type_uid) {
1294   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1295   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1296   // SymbolFileDWARF::GetDIE(). See comments inside the
1297   // SymbolFileDWARF::GetDIE() for details.
1298   if (DWARFDIE die = GetDIE(type_uid))
1299     return GetContainingDeclContext(die);
1300   return CompilerDeclContext();
1301 }
1302 
1303 Type *SymbolFileDWARF::ResolveTypeUID(lldb::user_id_t type_uid) {
1304   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1305   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1306   // SymbolFileDWARF::GetDIE(). See comments inside the
1307   // SymbolFileDWARF::GetDIE() for details.
1308   if (DWARFDIE type_die = GetDIE(type_uid))
1309     return type_die.ResolveType();
1310   else
1311     return nullptr;
1312 }
1313 
1314 llvm::Optional<SymbolFile::ArrayInfo>
1315 SymbolFileDWARF::GetDynamicArrayInfoForUID(
1316     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1317   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1318   if (DWARFDIE type_die = GetDIE(type_uid))
1319     return DWARFASTParser::ParseChildArrayInfo(type_die, exe_ctx);
1320   else
1321     return llvm::None;
1322 }
1323 
1324 Type *SymbolFileDWARF::ResolveTypeUID(const DIERef &die_ref) {
1325   return ResolveType(GetDIE(die_ref), true);
1326 }
1327 
1328 Type *SymbolFileDWARF::ResolveTypeUID(const DWARFDIE &die,
1329                                       bool assert_not_being_parsed) {
1330   if (die) {
1331     Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
1332     if (log)
1333       GetObjectFile()->GetModule()->LogMessage(
1334           log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
1335           die.GetOffset(), die.GetTagAsCString(), die.GetName());
1336 
1337     // We might be coming in in the middle of a type tree (a class within a
1338     // class, an enum within a class), so parse any needed parent DIEs before
1339     // we get to this one...
1340     DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(die);
1341     if (decl_ctx_die) {
1342       if (log) {
1343         switch (decl_ctx_die.Tag()) {
1344         case DW_TAG_structure_type:
1345         case DW_TAG_union_type:
1346         case DW_TAG_class_type: {
1347           // Get the type, which could be a forward declaration
1348           if (log)
1349             GetObjectFile()->GetModule()->LogMessage(
1350                 log,
1351                 "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' "
1352                 "resolve parent forward type for 0x%8.8x",
1353                 die.GetOffset(), die.GetTagAsCString(), die.GetName(),
1354                 decl_ctx_die.GetOffset());
1355         } break;
1356 
1357         default:
1358           break;
1359         }
1360       }
1361     }
1362     return ResolveType(die);
1363   }
1364   return nullptr;
1365 }
1366 
1367 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
1368 // SymbolFileDWARF objects to detect if this DWARF file is the one that can
1369 // resolve a compiler_type.
1370 bool SymbolFileDWARF::HasForwardDeclForClangType(
1371     const CompilerType &compiler_type) {
1372   CompilerType compiler_type_no_qualifiers =
1373       ClangUtil::RemoveFastQualifiers(compiler_type);
1374   if (GetForwardDeclClangTypeToDie().count(
1375           compiler_type_no_qualifiers.GetOpaqueQualType())) {
1376     return true;
1377   }
1378   TypeSystem *type_system = compiler_type.GetTypeSystem();
1379 
1380   TypeSystemClang *clang_type_system =
1381       llvm::dyn_cast_or_null<TypeSystemClang>(type_system);
1382   if (!clang_type_system)
1383     return false;
1384   DWARFASTParserClang *ast_parser =
1385       static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1386   return ast_parser->GetClangASTImporter().CanImport(compiler_type);
1387 }
1388 
1389 bool SymbolFileDWARF::CompleteType(CompilerType &compiler_type) {
1390   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1391 
1392   TypeSystemClang *clang_type_system =
1393       llvm::dyn_cast_or_null<TypeSystemClang>(compiler_type.GetTypeSystem());
1394   if (clang_type_system) {
1395     DWARFASTParserClang *ast_parser =
1396         static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1397     if (ast_parser &&
1398         ast_parser->GetClangASTImporter().CanImport(compiler_type))
1399       return ast_parser->GetClangASTImporter().CompleteType(compiler_type);
1400   }
1401 
1402   // We have a struct/union/class/enum that needs to be fully resolved.
1403   CompilerType compiler_type_no_qualifiers =
1404       ClangUtil::RemoveFastQualifiers(compiler_type);
1405   auto die_it = GetForwardDeclClangTypeToDie().find(
1406       compiler_type_no_qualifiers.GetOpaqueQualType());
1407   if (die_it == GetForwardDeclClangTypeToDie().end()) {
1408     // We have already resolved this type...
1409     return true;
1410   }
1411 
1412   DWARFDIE dwarf_die = GetDIE(die_it->getSecond());
1413   if (dwarf_die) {
1414     // Once we start resolving this type, remove it from the forward
1415     // declaration map in case anyone child members or other types require this
1416     // type to get resolved. The type will get resolved when all of the calls
1417     // to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition are done.
1418     GetForwardDeclClangTypeToDie().erase(die_it);
1419 
1420     Type *type = GetDIEToType().lookup(dwarf_die.GetDIE());
1421 
1422     Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO |
1423                                           DWARF_LOG_TYPE_COMPLETION));
1424     if (log)
1425       GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
1426           log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
1427           dwarf_die.GetID(), dwarf_die.GetTagAsCString(),
1428           type->GetName().AsCString());
1429     assert(compiler_type);
1430     if (DWARFASTParser *dwarf_ast = GetDWARFParser(*dwarf_die.GetCU()))
1431       return dwarf_ast->CompleteTypeFromDWARF(dwarf_die, type, compiler_type);
1432   }
1433   return false;
1434 }
1435 
1436 Type *SymbolFileDWARF::ResolveType(const DWARFDIE &die,
1437                                    bool assert_not_being_parsed,
1438                                    bool resolve_function_context) {
1439   if (die) {
1440     Type *type = GetTypeForDIE(die, resolve_function_context).get();
1441 
1442     if (assert_not_being_parsed) {
1443       if (type != DIE_IS_BEING_PARSED)
1444         return type;
1445 
1446       GetObjectFile()->GetModule()->ReportError(
1447           "Parsing a die that is being parsed die: 0x%8.8x: %s %s",
1448           die.GetOffset(), die.GetTagAsCString(), die.GetName());
1449 
1450     } else
1451       return type;
1452   }
1453   return nullptr;
1454 }
1455 
1456 CompileUnit *
1457 SymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFCompileUnit &dwarf_cu) {
1458   DWARFCompileUnit *non_dwo_cu =
1459       dwarf_cu.IsDWOUnit()
1460           ? static_cast<DWARFCompileUnit *>(dwarf_cu.GetUserData())
1461           : &dwarf_cu;
1462   // Check if the symbol vendor already knows about this compile unit?
1463   if (non_dwo_cu->GetUserData() == nullptr) {
1464     // The symbol vendor doesn't know about this compile unit, we need to parse
1465     // and add it to the symbol vendor object.
1466     return ParseCompileUnit(*non_dwo_cu).get();
1467   }
1468   return static_cast<CompileUnit *>(non_dwo_cu->GetUserData());
1469 }
1470 
1471 size_t SymbolFileDWARF::GetObjCMethodDIEOffsets(ConstString class_name,
1472                                                 DIEArray &method_die_offsets) {
1473   method_die_offsets.clear();
1474   m_index->GetObjCMethods(class_name, method_die_offsets);
1475   return method_die_offsets.size();
1476 }
1477 
1478 bool SymbolFileDWARF::GetFunction(const DWARFDIE &die, SymbolContext &sc) {
1479   sc.Clear(false);
1480 
1481   if (die && llvm::isa<DWARFCompileUnit>(die.GetCU())) {
1482     // Check if the symbol vendor already knows about this compile unit?
1483     sc.comp_unit =
1484         GetCompUnitForDWARFCompUnit(llvm::cast<DWARFCompileUnit>(*die.GetCU()));
1485 
1486     sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
1487     if (sc.function == nullptr)
1488       sc.function = ParseFunction(*sc.comp_unit, die);
1489 
1490     if (sc.function) {
1491       sc.module_sp = sc.function->CalculateSymbolContextModule();
1492       return true;
1493     }
1494   }
1495 
1496   return false;
1497 }
1498 
1499 lldb::ModuleSP SymbolFileDWARF::GetExternalModule(ConstString name) {
1500   UpdateExternalModuleListIfNeeded();
1501   const auto &pos = m_external_type_modules.find(name);
1502   if (pos != m_external_type_modules.end())
1503     return pos->second;
1504   else
1505     return lldb::ModuleSP();
1506 }
1507 
1508 DWARFDIE
1509 SymbolFileDWARF::GetDIE(const DIERef &die_ref) {
1510   if (die_ref.dwo_num()) {
1511     SymbolFileDWARF *dwarf = *die_ref.dwo_num() == 0x3fffffff
1512                                  ? m_dwp_symfile.get()
1513                                  : this->DebugInfo()
1514                                        ->GetUnitAtIndex(*die_ref.dwo_num())
1515                                        ->GetDwoSymbolFile();
1516     return dwarf->DebugInfo()->GetDIE(die_ref);
1517   }
1518 
1519   DWARFDebugInfo *debug_info = DebugInfo();
1520   if (debug_info)
1521     return debug_info->GetDIE(die_ref);
1522   else
1523     return DWARFDIE();
1524 }
1525 
1526 /// Return the DW_AT_(GNU_)dwo_name.
1527 static const char *GetDWOName(DWARFCompileUnit &dwarf_cu,
1528                               const DWARFDebugInfoEntry &cu_die) {
1529   const char *dwo_name =
1530       cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_GNU_dwo_name, nullptr);
1531   if (!dwo_name)
1532     dwo_name =
1533         cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_dwo_name, nullptr);
1534   return dwo_name;
1535 }
1536 
1537 /// Return the DW_AT_(GNU_)dwo_id.
1538 /// FIXME: Technically 0 is a valid hash.
1539 static uint64_t GetDWOId(DWARFCompileUnit &dwarf_cu,
1540                          const DWARFDebugInfoEntry &cu_die) {
1541   uint64_t dwo_id =
1542       cu_die.GetAttributeValueAsUnsigned(&dwarf_cu, DW_AT_GNU_dwo_id, 0);
1543   if (!dwo_id)
1544     dwo_id = cu_die.GetAttributeValueAsUnsigned(&dwarf_cu, DW_AT_dwo_id, 0);
1545   return dwo_id;
1546 }
1547 
1548 llvm::Optional<uint64_t> SymbolFileDWARF::GetDWOId() {
1549   if (GetNumCompileUnits() == 1) {
1550     if (auto comp_unit = GetCompileUnitAtIndex(0))
1551       if (DWARFCompileUnit *cu = llvm::dyn_cast_or_null<DWARFCompileUnit>(
1552               GetDWARFCompileUnit(comp_unit.get())))
1553         if (DWARFDebugInfoEntry *cu_die = cu->DIE().GetDIE())
1554           if (uint64_t dwo_id = ::GetDWOId(*cu, *cu_die))
1555             return dwo_id;
1556   }
1557   return {};
1558 }
1559 
1560 std::shared_ptr<SymbolFileDWARFDwo>
1561 SymbolFileDWARF::GetDwoSymbolFileForCompileUnit(
1562     DWARFUnit &unit, const DWARFDebugInfoEntry &cu_die) {
1563   // If this is a Darwin-style debug map (non-.dSYM) symbol file,
1564   // never attempt to load ELF-style DWO files since the -gmodules
1565   // support uses the same DWO machanism to specify full debug info
1566   // files for modules. This is handled in
1567   // UpdateExternalModuleListIfNeeded().
1568   if (GetDebugMapSymfile())
1569     return nullptr;
1570 
1571   DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit);
1572   // Only compile units can be split into two parts.
1573   if (!dwarf_cu)
1574     return nullptr;
1575 
1576   const char *dwo_name = GetDWOName(*dwarf_cu, cu_die);
1577   if (!dwo_name)
1578     return nullptr;
1579 
1580   FindDwpSymbolFile();
1581   if (m_dwp_symfile)
1582     return m_dwp_symfile;
1583 
1584   FileSpec dwo_file(dwo_name);
1585   FileSystem::Instance().Resolve(dwo_file);
1586   if (dwo_file.IsRelative()) {
1587     const char *comp_dir =
1588         cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_comp_dir, nullptr);
1589     if (!comp_dir)
1590       return nullptr;
1591 
1592     dwo_file.SetFile(comp_dir, FileSpec::Style::native);
1593     FileSystem::Instance().Resolve(dwo_file);
1594     dwo_file.AppendPathComponent(dwo_name);
1595   }
1596 
1597   if (!FileSystem::Instance().Exists(dwo_file))
1598     return nullptr;
1599 
1600   const lldb::offset_t file_offset = 0;
1601   DataBufferSP dwo_file_data_sp;
1602   lldb::offset_t dwo_file_data_offset = 0;
1603   ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin(
1604       GetObjectFile()->GetModule(), &dwo_file, file_offset,
1605       FileSystem::Instance().GetByteSize(dwo_file), dwo_file_data_sp,
1606       dwo_file_data_offset);
1607   if (dwo_obj_file == nullptr)
1608     return nullptr;
1609 
1610   return std::make_shared<SymbolFileDWARFDwo>(*this, dwo_obj_file,
1611                                               dwarf_cu->GetID());
1612 }
1613 
1614 void SymbolFileDWARF::UpdateExternalModuleListIfNeeded() {
1615   if (m_fetched_external_modules)
1616     return;
1617   m_fetched_external_modules = true;
1618   DWARFDebugInfo *debug_info = DebugInfo();
1619 
1620   // Follow DWO skeleton unit breadcrumbs.
1621   const uint32_t num_compile_units = GetNumCompileUnits();
1622   for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
1623     auto *dwarf_cu =
1624         llvm::dyn_cast<DWARFCompileUnit>(debug_info->GetUnitAtIndex(cu_idx));
1625     if (!dwarf_cu)
1626       continue;
1627 
1628     const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
1629     if (!die || die.HasChildren() || !die.GetDIE())
1630       continue;
1631 
1632     const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr);
1633     if (!name)
1634       continue;
1635 
1636     ConstString const_name(name);
1637     ModuleSP &module_sp = m_external_type_modules[const_name];
1638     if (module_sp)
1639       continue;
1640 
1641     const char *dwo_path = GetDWOName(*dwarf_cu, *die.GetDIE());
1642     if (!dwo_path)
1643       continue;
1644 
1645     ModuleSpec dwo_module_spec;
1646     dwo_module_spec.GetFileSpec().SetFile(dwo_path, FileSpec::Style::native);
1647     if (dwo_module_spec.GetFileSpec().IsRelative()) {
1648       const char *comp_dir =
1649           die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr);
1650       if (comp_dir) {
1651         dwo_module_spec.GetFileSpec().SetFile(comp_dir,
1652                                               FileSpec::Style::native);
1653         FileSystem::Instance().Resolve(dwo_module_spec.GetFileSpec());
1654         dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path);
1655       }
1656     }
1657     dwo_module_spec.GetArchitecture() =
1658         m_objfile_sp->GetModule()->GetArchitecture();
1659 
1660     // When LLDB loads "external" modules it looks at the presence of
1661     // DW_AT_dwo_name. However, when the already created module
1662     // (corresponding to .dwo itself) is being processed, it will see
1663     // the presence of DW_AT_dwo_name (which contains the name of dwo
1664     // file) and will try to call ModuleList::GetSharedModule
1665     // again. In some cases (i.e., for empty files) Clang 4.0
1666     // generates a *.dwo file which has DW_AT_dwo_name, but no
1667     // DW_AT_comp_dir. In this case the method
1668     // ModuleList::GetSharedModule will fail and the warning will be
1669     // printed. However, as one can notice in this case we don't
1670     // actually need to try to load the already loaded module
1671     // (corresponding to .dwo) so we simply skip it.
1672     if (m_objfile_sp->GetFileSpec().GetFileNameExtension() == ".dwo" &&
1673         llvm::StringRef(m_objfile_sp->GetFileSpec().GetPath())
1674             .endswith(dwo_module_spec.GetFileSpec().GetPath())) {
1675       continue;
1676     }
1677 
1678     Status error = ModuleList::GetSharedModule(dwo_module_spec, module_sp,
1679                                                nullptr, nullptr, nullptr);
1680     if (!module_sp) {
1681       GetObjectFile()->GetModule()->ReportWarning(
1682           "0x%8.8x: unable to locate module needed for external types: "
1683           "%s\nerror: %s\nDebugging will be degraded due to missing "
1684           "types. Rebuilding the project will regenerate the needed "
1685           "module files.",
1686           die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str(),
1687           error.AsCString("unknown error"));
1688       continue;
1689     }
1690 
1691     // Verify the DWO hash.
1692     // FIXME: Technically "0" is a valid hash.
1693     uint64_t dwo_id = ::GetDWOId(*dwarf_cu, *die.GetDIE());
1694     if (!dwo_id)
1695       continue;
1696 
1697     auto *dwo_symfile =
1698         llvm::dyn_cast_or_null<SymbolFileDWARF>(module_sp->GetSymbolFile());
1699     if (!dwo_symfile)
1700       continue;
1701     llvm::Optional<uint64_t> dwo_dwo_id = dwo_symfile->GetDWOId();
1702     if (!dwo_dwo_id)
1703       continue;
1704 
1705     if (dwo_id != dwo_dwo_id) {
1706       GetObjectFile()->GetModule()->ReportWarning(
1707           "0x%8.8x: Module %s is out-of-date (hash mismatch). Type information "
1708           "from this module may be incomplete or inconsistent with the rest of "
1709           "the program. Rebuilding the project will regenerate the needed "
1710           "module files.",
1711           die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str());
1712     }
1713   }
1714 }
1715 
1716 SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() {
1717   if (!m_global_aranges_up) {
1718     m_global_aranges_up.reset(new GlobalVariableMap());
1719 
1720     ModuleSP module_sp = GetObjectFile()->GetModule();
1721     if (module_sp) {
1722       const size_t num_cus = module_sp->GetNumCompileUnits();
1723       for (size_t i = 0; i < num_cus; ++i) {
1724         CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
1725         if (cu_sp) {
1726           VariableListSP globals_sp = cu_sp->GetVariableList(true);
1727           if (globals_sp) {
1728             const size_t num_globals = globals_sp->GetSize();
1729             for (size_t g = 0; g < num_globals; ++g) {
1730               VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
1731               if (var_sp && !var_sp->GetLocationIsConstantValueData()) {
1732                 const DWARFExpression &location = var_sp->LocationExpression();
1733                 Value location_result;
1734                 Status error;
1735                 if (location.Evaluate(nullptr, LLDB_INVALID_ADDRESS, nullptr,
1736                                       nullptr, location_result, &error)) {
1737                   if (location_result.GetValueType() ==
1738                       Value::eValueTypeFileAddress) {
1739                     lldb::addr_t file_addr =
1740                         location_result.GetScalar().ULongLong();
1741                     lldb::addr_t byte_size = 1;
1742                     if (var_sp->GetType())
1743                       byte_size =
1744                           var_sp->GetType()->GetByteSize().getValueOr(0);
1745                     m_global_aranges_up->Append(GlobalVariableMap::Entry(
1746                         file_addr, byte_size, var_sp.get()));
1747                   }
1748                 }
1749               }
1750             }
1751           }
1752         }
1753       }
1754     }
1755     m_global_aranges_up->Sort();
1756   }
1757   return *m_global_aranges_up;
1758 }
1759 
1760 void SymbolFileDWARF::ResolveFunctionAndBlock(lldb::addr_t file_vm_addr,
1761                                               bool lookup_block,
1762                                               SymbolContext &sc) {
1763   assert(sc.comp_unit);
1764   DWARFUnit &cu = GetDWARFCompileUnit(sc.comp_unit)->GetNonSkeletonUnit();
1765   DWARFDIE function_die = cu.LookupAddress(file_vm_addr);
1766   DWARFDIE block_die;
1767   if (function_die) {
1768     sc.function = sc.comp_unit->FindFunctionByUID(function_die.GetID()).get();
1769     if (sc.function == nullptr)
1770       sc.function = ParseFunction(*sc.comp_unit, function_die);
1771 
1772     if (sc.function && lookup_block)
1773       block_die = function_die.LookupDeepestBlock(file_vm_addr);
1774   }
1775 
1776   if (!sc.function || ! lookup_block)
1777     return;
1778 
1779   Block &block = sc.function->GetBlock(true);
1780   if (block_die)
1781     sc.block = block.FindBlockByID(block_die.GetID());
1782   else
1783     sc.block = block.FindBlockByID(function_die.GetID());
1784 }
1785 
1786 uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr,
1787                                                SymbolContextItem resolve_scope,
1788                                                SymbolContext &sc) {
1789   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1790   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1791   Timer scoped_timer(func_cat,
1792                      "SymbolFileDWARF::"
1793                      "ResolveSymbolContext (so_addr = { "
1794                      "section = %p, offset = 0x%" PRIx64
1795                      " }, resolve_scope = 0x%8.8x)",
1796                      static_cast<void *>(so_addr.GetSection().get()),
1797                      so_addr.GetOffset(), resolve_scope);
1798   uint32_t resolved = 0;
1799   if (resolve_scope &
1800       (eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextBlock |
1801        eSymbolContextLineEntry | eSymbolContextVariable)) {
1802     lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1803 
1804     DWARFDebugInfo *debug_info = DebugInfo();
1805     if (debug_info) {
1806       llvm::Expected<DWARFDebugAranges &> aranges =
1807           debug_info->GetCompileUnitAranges();
1808       if (!aranges) {
1809         Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
1810         LLDB_LOG_ERROR(log, aranges.takeError(),
1811                        "SymbolFileDWARF::ResolveSymbolContext failed to get cu "
1812                        "aranges.  {0}");
1813         return 0;
1814       }
1815 
1816       const dw_offset_t cu_offset = aranges->FindAddress(file_vm_addr);
1817       if (cu_offset == DW_INVALID_OFFSET) {
1818         // Global variables are not in the compile unit address ranges. The
1819         // only way to currently find global variables is to iterate over the
1820         // .debug_pubnames or the __apple_names table and find all items in
1821         // there that point to DW_TAG_variable DIEs and then find the address
1822         // that matches.
1823         if (resolve_scope & eSymbolContextVariable) {
1824           GlobalVariableMap &map = GetGlobalAranges();
1825           const GlobalVariableMap::Entry *entry =
1826               map.FindEntryThatContains(file_vm_addr);
1827           if (entry && entry->data) {
1828             Variable *variable = entry->data;
1829             SymbolContextScope *scc = variable->GetSymbolContextScope();
1830             if (scc) {
1831               scc->CalculateSymbolContext(&sc);
1832               sc.variable = variable;
1833             }
1834             return sc.GetResolvedMask();
1835           }
1836         }
1837       } else {
1838         uint32_t cu_idx = DW_INVALID_INDEX;
1839         if (auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>(
1840                 debug_info->GetUnitAtOffset(DIERef::Section::DebugInfo,
1841                                             cu_offset, &cu_idx))) {
1842           sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
1843           if (sc.comp_unit) {
1844             resolved |= eSymbolContextCompUnit;
1845 
1846             bool force_check_line_table = false;
1847             if (resolve_scope &
1848                 (eSymbolContextFunction | eSymbolContextBlock)) {
1849               ResolveFunctionAndBlock(file_vm_addr,
1850                                       resolve_scope & eSymbolContextBlock, sc);
1851               if (sc.function)
1852                 resolved |= eSymbolContextFunction;
1853               else {
1854                 // We might have had a compile unit that had discontiguous
1855                 // address ranges where the gaps are symbols that don't have
1856                 // any debug info. Discontiguous compile unit address ranges
1857                 // should only happen when there aren't other functions from
1858                 // other compile units in these gaps. This helps keep the size
1859                 // of the aranges down.
1860                 force_check_line_table = true;
1861               }
1862               if (sc.block)
1863                 resolved |= eSymbolContextBlock;
1864             }
1865 
1866             if ((resolve_scope & eSymbolContextLineEntry) ||
1867                 force_check_line_table) {
1868               LineTable *line_table = sc.comp_unit->GetLineTable();
1869               if (line_table != nullptr) {
1870                 // And address that makes it into this function should be in
1871                 // terms of this debug file if there is no debug map, or it
1872                 // will be an address in the .o file which needs to be fixed up
1873                 // to be in terms of the debug map executable. Either way,
1874                 // calling FixupAddress() will work for us.
1875                 Address exe_so_addr(so_addr);
1876                 if (FixupAddress(exe_so_addr)) {
1877                   if (line_table->FindLineEntryByAddress(exe_so_addr,
1878                                                          sc.line_entry)) {
1879                     resolved |= eSymbolContextLineEntry;
1880                   }
1881                 }
1882               }
1883             }
1884 
1885             if (force_check_line_table &&
1886                 !(resolved & eSymbolContextLineEntry)) {
1887               // We might have had a compile unit that had discontiguous
1888               // address ranges where the gaps are symbols that don't have any
1889               // debug info. Discontiguous compile unit address ranges should
1890               // only happen when there aren't other functions from other
1891               // compile units in these gaps. This helps keep the size of the
1892               // aranges down.
1893               sc.comp_unit = nullptr;
1894               resolved &= ~eSymbolContextCompUnit;
1895             }
1896           } else {
1897             GetObjectFile()->GetModule()->ReportWarning(
1898                 "0x%8.8x: compile unit %u failed to create a valid "
1899                 "lldb_private::CompileUnit class.",
1900                 cu_offset, cu_idx);
1901           }
1902         }
1903       }
1904     }
1905   }
1906   return resolved;
1907 }
1908 
1909 uint32_t SymbolFileDWARF::ResolveSymbolContext(const FileSpec &file_spec,
1910                                                uint32_t line,
1911                                                bool check_inlines,
1912                                                SymbolContextItem resolve_scope,
1913                                                SymbolContextList &sc_list) {
1914   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1915   const uint32_t prev_size = sc_list.GetSize();
1916   if (resolve_scope & eSymbolContextCompUnit) {
1917     for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
1918          ++cu_idx) {
1919       CompileUnit *dc_cu = ParseCompileUnitAtIndex(cu_idx).get();
1920       if (!dc_cu)
1921         continue;
1922 
1923       bool file_spec_matches_cu_file_spec =
1924           FileSpec::Match(file_spec, dc_cu->GetPrimaryFile());
1925       if (check_inlines || file_spec_matches_cu_file_spec) {
1926         SymbolContext sc(m_objfile_sp->GetModule());
1927         sc.comp_unit = dc_cu;
1928         uint32_t file_idx = UINT32_MAX;
1929 
1930         // If we are looking for inline functions only and we don't find it
1931         // in the support files, we are done.
1932         if (check_inlines) {
1933           file_idx =
1934               sc.comp_unit->GetSupportFiles().FindFileIndex(1, file_spec, true);
1935           if (file_idx == UINT32_MAX)
1936             continue;
1937         }
1938 
1939         if (line != 0) {
1940           LineTable *line_table = sc.comp_unit->GetLineTable();
1941 
1942           if (line_table != nullptr && line != 0) {
1943             // We will have already looked up the file index if we are
1944             // searching for inline entries.
1945             if (!check_inlines)
1946               file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex(
1947                   1, file_spec, true);
1948 
1949             if (file_idx != UINT32_MAX) {
1950               uint32_t found_line;
1951               uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex(
1952                   0, file_idx, line, false, &sc.line_entry);
1953               found_line = sc.line_entry.line;
1954 
1955               while (line_idx != UINT32_MAX) {
1956                 sc.function = nullptr;
1957                 sc.block = nullptr;
1958                 if (resolve_scope &
1959                     (eSymbolContextFunction | eSymbolContextBlock)) {
1960                   const lldb::addr_t file_vm_addr =
1961                       sc.line_entry.range.GetBaseAddress().GetFileAddress();
1962                   if (file_vm_addr != LLDB_INVALID_ADDRESS) {
1963                     ResolveFunctionAndBlock(
1964                         file_vm_addr, resolve_scope & eSymbolContextBlock, sc);
1965                   }
1966                 }
1967 
1968                 sc_list.Append(sc);
1969                 line_idx = line_table->FindLineEntryIndexByFileIndex(
1970                     line_idx + 1, file_idx, found_line, true, &sc.line_entry);
1971               }
1972             }
1973           } else if (file_spec_matches_cu_file_spec && !check_inlines) {
1974             // only append the context if we aren't looking for inline call
1975             // sites by file and line and if the file spec matches that of
1976             // the compile unit
1977             sc_list.Append(sc);
1978           }
1979         } else if (file_spec_matches_cu_file_spec && !check_inlines) {
1980           // only append the context if we aren't looking for inline call
1981           // sites by file and line and if the file spec matches that of
1982           // the compile unit
1983           sc_list.Append(sc);
1984         }
1985 
1986         if (!check_inlines)
1987           break;
1988       }
1989     }
1990   }
1991   return sc_list.GetSize() - prev_size;
1992 }
1993 
1994 void SymbolFileDWARF::PreloadSymbols() {
1995   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1996   m_index->Preload();
1997 }
1998 
1999 std::recursive_mutex &SymbolFileDWARF::GetModuleMutex() const {
2000   lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
2001   if (module_sp)
2002     return module_sp->GetMutex();
2003   return GetObjectFile()->GetModule()->GetMutex();
2004 }
2005 
2006 bool SymbolFileDWARF::DeclContextMatchesThisSymbolFile(
2007     const lldb_private::CompilerDeclContext &decl_ctx) {
2008   if (!decl_ctx.IsValid()) {
2009     // Invalid namespace decl which means we aren't matching only things in
2010     // this symbol file, so return true to indicate it matches this symbol
2011     // file.
2012     return true;
2013   }
2014 
2015   TypeSystem *decl_ctx_type_system = decl_ctx.GetTypeSystem();
2016   auto type_system_or_err = GetTypeSystemForLanguage(
2017       decl_ctx_type_system->GetMinimumLanguage(nullptr));
2018   if (auto err = type_system_or_err.takeError()) {
2019     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
2020                    std::move(err),
2021                    "Unable to match namespace decl using TypeSystem");
2022     return false;
2023   }
2024 
2025   if (decl_ctx_type_system == &type_system_or_err.get())
2026     return true; // The type systems match, return true
2027 
2028   // The namespace AST was valid, and it does not match...
2029   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2030 
2031   if (log)
2032     GetObjectFile()->GetModule()->LogMessage(
2033         log, "Valid namespace does not match symbol file");
2034 
2035   return false;
2036 }
2037 
2038 void SymbolFileDWARF::FindGlobalVariables(
2039     ConstString name, const CompilerDeclContext &parent_decl_ctx,
2040     uint32_t max_matches, VariableList &variables) {
2041   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2042   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2043 
2044   if (log)
2045     GetObjectFile()->GetModule()->LogMessage(
2046         log,
2047         "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2048         "parent_decl_ctx=%p, max_matches=%u, variables)",
2049         name.GetCString(), static_cast<const void *>(&parent_decl_ctx),
2050         max_matches);
2051 
2052   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2053     return;
2054 
2055   DWARFDebugInfo *info = DebugInfo();
2056   if (!info)
2057     return;
2058 
2059   // Remember how many variables are in the list before we search.
2060   const uint32_t original_size = variables.GetSize();
2061 
2062   llvm::StringRef basename;
2063   llvm::StringRef context;
2064   bool name_is_mangled = (bool)Mangled(name);
2065 
2066   if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(),
2067                                                       context, basename))
2068     basename = name.GetStringRef();
2069 
2070   DIEArray die_offsets;
2071   m_index->GetGlobalVariables(ConstString(basename), die_offsets);
2072   const size_t num_die_matches = die_offsets.size();
2073   if (num_die_matches) {
2074     SymbolContext sc;
2075     sc.module_sp = m_objfile_sp->GetModule();
2076     assert(sc.module_sp);
2077 
2078     // Loop invariant: Variables up to this index have been checked for context
2079     // matches.
2080     uint32_t pruned_idx = original_size;
2081 
2082     bool done = false;
2083     for (size_t i = 0; i < num_die_matches && !done; ++i) {
2084       const DIERef &die_ref = die_offsets[i];
2085       DWARFDIE die = GetDIE(die_ref);
2086 
2087       if (die) {
2088         switch (die.Tag()) {
2089         default:
2090         case DW_TAG_subprogram:
2091         case DW_TAG_inlined_subroutine:
2092         case DW_TAG_try_block:
2093         case DW_TAG_catch_block:
2094           break;
2095 
2096         case DW_TAG_variable: {
2097           auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2098           if (!dwarf_cu)
2099             continue;
2100           sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2101 
2102           if (parent_decl_ctx) {
2103             if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) {
2104               CompilerDeclContext actual_parent_decl_ctx =
2105                   dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2106               if (!actual_parent_decl_ctx ||
2107                   actual_parent_decl_ctx != parent_decl_ctx)
2108                 continue;
2109             }
2110           }
2111 
2112           ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false,
2113                          &variables);
2114           while (pruned_idx < variables.GetSize()) {
2115             VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx);
2116             if (name_is_mangled ||
2117                 var_sp->GetName().GetStringRef().contains(name.GetStringRef()))
2118               ++pruned_idx;
2119             else
2120               variables.RemoveVariableAtIndex(pruned_idx);
2121           }
2122 
2123           if (variables.GetSize() - original_size >= max_matches)
2124             done = true;
2125         } break;
2126         }
2127       } else {
2128         m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2129       }
2130     }
2131   }
2132 
2133   // Return the number of variable that were appended to the list
2134   const uint32_t num_matches = variables.GetSize() - original_size;
2135   if (log && num_matches > 0) {
2136     GetObjectFile()->GetModule()->LogMessage(
2137         log,
2138         "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2139         "parent_decl_ctx=%p, max_matches=%u, variables) => %u",
2140         name.GetCString(), static_cast<const void *>(&parent_decl_ctx),
2141         max_matches, num_matches);
2142   }
2143 }
2144 
2145 void SymbolFileDWARF::FindGlobalVariables(const RegularExpression &regex,
2146                                           uint32_t max_matches,
2147                                           VariableList &variables) {
2148   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2149   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2150 
2151   if (log) {
2152     GetObjectFile()->GetModule()->LogMessage(
2153         log,
2154         "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", "
2155         "max_matches=%u, variables)",
2156         regex.GetText().str().c_str(), max_matches);
2157   }
2158 
2159   DWARFDebugInfo *info = DebugInfo();
2160   if (!info)
2161     return;
2162 
2163   // Remember how many variables are in the list before we search.
2164   const uint32_t original_size = variables.GetSize();
2165 
2166   DIEArray die_offsets;
2167   m_index->GetGlobalVariables(regex, die_offsets);
2168 
2169   SymbolContext sc;
2170   sc.module_sp = m_objfile_sp->GetModule();
2171   assert(sc.module_sp);
2172 
2173   const size_t num_matches = die_offsets.size();
2174   if (num_matches) {
2175     for (size_t i = 0; i < num_matches; ++i) {
2176       const DIERef &die_ref = die_offsets[i];
2177       DWARFDIE die = GetDIE(die_ref);
2178 
2179       if (die) {
2180         DWARFCompileUnit *dwarf_cu =
2181             llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2182         if (!dwarf_cu)
2183           continue;
2184         sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2185 
2186         ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables);
2187 
2188         if (variables.GetSize() - original_size >= max_matches)
2189           break;
2190       } else
2191         m_index->ReportInvalidDIERef(die_ref, regex.GetText());
2192     }
2193   }
2194 }
2195 
2196 bool SymbolFileDWARF::ResolveFunction(const DWARFDIE &orig_die,
2197                                       bool include_inlines,
2198                                       SymbolContextList &sc_list) {
2199   SymbolContext sc;
2200 
2201   if (!orig_die)
2202     return false;
2203 
2204   // If we were passed a die that is not a function, just return false...
2205   if (!(orig_die.Tag() == DW_TAG_subprogram ||
2206         (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine)))
2207     return false;
2208 
2209   DWARFDIE die = orig_die;
2210   DWARFDIE inlined_die;
2211   if (die.Tag() == DW_TAG_inlined_subroutine) {
2212     inlined_die = die;
2213 
2214     while (true) {
2215       die = die.GetParent();
2216 
2217       if (die) {
2218         if (die.Tag() == DW_TAG_subprogram)
2219           break;
2220       } else
2221         break;
2222     }
2223   }
2224   assert(die && die.Tag() == DW_TAG_subprogram);
2225   if (GetFunction(die, sc)) {
2226     Address addr;
2227     // Parse all blocks if needed
2228     if (inlined_die) {
2229       Block &function_block = sc.function->GetBlock(true);
2230       sc.block = function_block.FindBlockByID(inlined_die.GetID());
2231       if (sc.block == nullptr)
2232         sc.block = function_block.FindBlockByID(inlined_die.GetOffset());
2233       if (sc.block == nullptr || !sc.block->GetStartAddress(addr))
2234         addr.Clear();
2235     } else {
2236       sc.block = nullptr;
2237       addr = sc.function->GetAddressRange().GetBaseAddress();
2238     }
2239 
2240 
2241     if (auto section_sp = addr.GetSection()) {
2242       if (section_sp->GetPermissions() & ePermissionsExecutable) {
2243         sc_list.Append(sc);
2244         return true;
2245       }
2246     }
2247   }
2248 
2249   return false;
2250 }
2251 
2252 bool SymbolFileDWARF::DIEInDeclContext(const CompilerDeclContext &decl_ctx,
2253                                        const DWARFDIE &die) {
2254   // If we have no parent decl context to match this DIE matches, and if the
2255   // parent decl context isn't valid, we aren't trying to look for any
2256   // particular decl context so any die matches.
2257   if (!decl_ctx.IsValid())
2258     return true;
2259 
2260   if (die) {
2261     if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) {
2262       if (CompilerDeclContext actual_decl_ctx =
2263               dwarf_ast->GetDeclContextContainingUIDFromDWARF(die))
2264         return decl_ctx.IsContainedInLookup(actual_decl_ctx);
2265     }
2266   }
2267   return false;
2268 }
2269 
2270 void SymbolFileDWARF::FindFunctions(ConstString name,
2271                                     const CompilerDeclContext &parent_decl_ctx,
2272                                     FunctionNameType name_type_mask,
2273                                     bool include_inlines,
2274                                     SymbolContextList &sc_list) {
2275   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2276   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2277   Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (name = '%s')",
2278                      name.AsCString());
2279 
2280   // eFunctionNameTypeAuto should be pre-resolved by a call to
2281   // Module::LookupInfo::LookupInfo()
2282   assert((name_type_mask & eFunctionNameTypeAuto) == 0);
2283 
2284   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2285 
2286   if (log) {
2287     GetObjectFile()->GetModule()->LogMessage(
2288         log,
2289         "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, sc_list)",
2290         name.GetCString(), name_type_mask);
2291   }
2292 
2293   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2294     return;
2295 
2296   // If name is empty then we won't find anything.
2297   if (name.IsEmpty())
2298     return;
2299 
2300   // Remember how many sc_list are in the list before we search in case we are
2301   // appending the results to a variable list.
2302 
2303   const uint32_t original_size = sc_list.GetSize();
2304 
2305   llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2306   DIEArray offsets;
2307 
2308   std::vector<DWARFDIE> dies;
2309   m_index->GetFunctions(name, *this, parent_decl_ctx, name_type_mask, dies);
2310   for (const DWARFDIE &die : dies) {
2311     if (resolved_dies.insert(die.GetDIE()).second)
2312       ResolveFunction(die, include_inlines, sc_list);
2313   }
2314 
2315   // Return the number of variable that were appended to the list
2316   const uint32_t num_matches = sc_list.GetSize() - original_size;
2317 
2318   if (log && num_matches > 0) {
2319     GetObjectFile()->GetModule()->LogMessage(
2320         log,
2321         "SymbolFileDWARF::FindFunctions (name=\"%s\", "
2322         "name_type_mask=0x%x, include_inlines=%d, sc_list) => %u",
2323         name.GetCString(), name_type_mask, include_inlines,
2324         num_matches);
2325   }
2326 }
2327 
2328 void SymbolFileDWARF::FindFunctions(const RegularExpression &regex,
2329                                     bool include_inlines,
2330                                     SymbolContextList &sc_list) {
2331   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2332   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2333   Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (regex = '%s')",
2334                      regex.GetText().str().c_str());
2335 
2336   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2337 
2338   if (log) {
2339     GetObjectFile()->GetModule()->LogMessage(
2340         log, "SymbolFileDWARF::FindFunctions (regex=\"%s\", sc_list)",
2341         regex.GetText().str().c_str());
2342   }
2343 
2344   DWARFDebugInfo *info = DebugInfo();
2345   if (!info)
2346     return;
2347 
2348   DIEArray offsets;
2349   m_index->GetFunctions(regex, offsets);
2350 
2351   llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2352   for (DIERef ref : offsets) {
2353     DWARFDIE die = info->GetDIE(ref);
2354     if (!die) {
2355       m_index->ReportInvalidDIERef(ref, regex.GetText());
2356       continue;
2357     }
2358     if (resolved_dies.insert(die.GetDIE()).second)
2359       ResolveFunction(die, include_inlines, sc_list);
2360   }
2361 }
2362 
2363 void SymbolFileDWARF::GetMangledNamesForFunction(
2364     const std::string &scope_qualified_name,
2365     std::vector<ConstString> &mangled_names) {
2366   DWARFDebugInfo *info = DebugInfo();
2367   uint32_t num_comp_units = 0;
2368   if (info)
2369     num_comp_units = info->GetNumUnits();
2370 
2371   for (uint32_t i = 0; i < num_comp_units; i++) {
2372     DWARFUnit *cu = info->GetUnitAtIndex(i);
2373     if (cu == nullptr)
2374       continue;
2375 
2376     SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile();
2377     if (dwo)
2378       dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
2379   }
2380 
2381   for (DIERef die_ref :
2382        m_function_scope_qualified_name_map.lookup(scope_qualified_name)) {
2383     DWARFDIE die = GetDIE(die_ref);
2384     mangled_names.push_back(ConstString(die.GetMangledName()));
2385   }
2386 }
2387 
2388 void SymbolFileDWARF::FindTypes(
2389     ConstString name, const CompilerDeclContext &parent_decl_ctx,
2390     uint32_t max_matches,
2391     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
2392     TypeMap &types) {
2393   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2394   // Make sure we haven't already searched this SymbolFile before.
2395   if (!searched_symbol_files.insert(this).second)
2396     return;
2397 
2398   DWARFDebugInfo *info = DebugInfo();
2399   if (!info)
2400     return;
2401 
2402   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2403 
2404   if (log) {
2405     if (parent_decl_ctx)
2406       GetObjectFile()->GetModule()->LogMessage(
2407           log,
2408           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2409           "%p (\"%s\"), max_matches=%u, type_list)",
2410           name.GetCString(), static_cast<const void *>(&parent_decl_ctx),
2411           parent_decl_ctx.GetName().AsCString("<NULL>"), max_matches);
2412     else
2413       GetObjectFile()->GetModule()->LogMessage(
2414           log,
2415           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2416           "NULL, max_matches=%u, type_list)",
2417           name.GetCString(), max_matches);
2418   }
2419 
2420   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2421     return;
2422 
2423   DIEArray die_offsets;
2424   m_index->GetTypes(name, die_offsets);
2425   const size_t num_die_matches = die_offsets.size();
2426 
2427   for (size_t i = 0; i < num_die_matches; ++i) {
2428     const DIERef &die_ref = die_offsets[i];
2429     DWARFDIE die = GetDIE(die_ref);
2430     if (die) {
2431       if (!DIEInDeclContext(parent_decl_ctx, die))
2432         continue; // The containing decl contexts don't match
2433 
2434       Type *matching_type = ResolveType(die, true, true);
2435       if (matching_type) {
2436         // We found a type pointer, now find the shared pointer form our type
2437         // list
2438         types.InsertUnique(matching_type->shared_from_this());
2439         if (types.GetSize() >= max_matches)
2440           break;
2441       }
2442     } else {
2443       m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2444     }
2445   }
2446 
2447   // Next search through the reachable Clang modules. This only applies for
2448   // DWARF objects compiled with -gmodules that haven't been processed by
2449   // dsymutil.
2450   if (num_die_matches < max_matches) {
2451     UpdateExternalModuleListIfNeeded();
2452 
2453     for (const auto &pair : m_external_type_modules)
2454       if (ModuleSP external_module_sp = pair.second)
2455         if (SymbolFile *sym_file = external_module_sp->GetSymbolFile())
2456           sym_file->FindTypes(name, parent_decl_ctx, max_matches,
2457                               searched_symbol_files, types);
2458   }
2459 
2460   if (log && types.GetSize()) {
2461     if (parent_decl_ctx) {
2462       GetObjectFile()->GetModule()->LogMessage(
2463           log,
2464           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2465           "= %p (\"%s\"), max_matches=%u, type_list) => %u",
2466           name.GetCString(), static_cast<const void *>(&parent_decl_ctx),
2467           parent_decl_ctx.GetName().AsCString("<NULL>"), max_matches,
2468           types.GetSize());
2469     } else {
2470       GetObjectFile()->GetModule()->LogMessage(
2471           log,
2472           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2473           "= NULL, max_matches=%u, type_list) => %u",
2474           name.GetCString(), max_matches, types.GetSize());
2475     }
2476   }
2477 }
2478 
2479 void SymbolFileDWARF::FindTypes(
2480     llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
2481     llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {
2482   // Make sure we haven't already searched this SymbolFile before.
2483   if (!searched_symbol_files.insert(this).second)
2484     return;
2485 
2486   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2487   if (pattern.empty())
2488     return;
2489 
2490   ConstString name = pattern.back().name;
2491 
2492   if (!name)
2493     return;
2494 
2495   DIEArray die_offsets;
2496   m_index->GetTypes(name, die_offsets);
2497   const size_t num_die_matches = die_offsets.size();
2498 
2499   for (size_t i = 0; i < num_die_matches; ++i) {
2500     const DIERef &die_ref = die_offsets[i];
2501     DWARFDIE die = GetDIE(die_ref);
2502 
2503     if (!die) {
2504       m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2505       continue;
2506     }
2507     if (!languages[GetLanguage(*die.GetCU())])
2508       continue;
2509 
2510     llvm::SmallVector<CompilerContext, 4> die_context;
2511     die.GetDeclContext(die_context);
2512     if (!contextMatches(die_context, pattern))
2513       continue;
2514 
2515     if (Type *matching_type = ResolveType(die, true, true)) {
2516       // We found a type pointer, now find the shared pointer form our type
2517       // list.
2518       types.InsertUnique(matching_type->shared_from_this());
2519     }
2520   }
2521 
2522   // Next search through the reachable Clang modules. This only applies for
2523   // DWARF objects compiled with -gmodules that haven't been processed by
2524   // dsymutil.
2525   UpdateExternalModuleListIfNeeded();
2526 
2527   for (const auto &pair : m_external_type_modules)
2528     if (ModuleSP external_module_sp = pair.second)
2529       external_module_sp->FindTypes(pattern, languages, searched_symbol_files,
2530                                     types);
2531 }
2532 
2533 CompilerDeclContext
2534 SymbolFileDWARF::FindNamespace(ConstString name,
2535                                const CompilerDeclContext &parent_decl_ctx) {
2536   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2537   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2538 
2539   if (log) {
2540     GetObjectFile()->GetModule()->LogMessage(
2541         log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
2542         name.GetCString());
2543   }
2544 
2545   CompilerDeclContext namespace_decl_ctx;
2546 
2547   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2548     return namespace_decl_ctx;
2549 
2550   DWARFDebugInfo *info = DebugInfo();
2551   if (info) {
2552     DIEArray die_offsets;
2553     m_index->GetNamespaces(name, die_offsets);
2554     const size_t num_matches = die_offsets.size();
2555     if (num_matches) {
2556       for (size_t i = 0; i < num_matches; ++i) {
2557         const DIERef &die_ref = die_offsets[i];
2558         DWARFDIE die = GetDIE(die_ref);
2559 
2560         if (die) {
2561           if (!DIEInDeclContext(parent_decl_ctx, die))
2562             continue; // The containing decl contexts don't match
2563 
2564           if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) {
2565             namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die);
2566             if (namespace_decl_ctx)
2567               break;
2568           }
2569         } else {
2570           m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2571         }
2572       }
2573     }
2574   }
2575   if (log && namespace_decl_ctx) {
2576     GetObjectFile()->GetModule()->LogMessage(
2577         log,
2578         "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => "
2579         "CompilerDeclContext(%p/%p) \"%s\"",
2580         name.GetCString(),
2581         static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()),
2582         static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()),
2583         namespace_decl_ctx.GetName().AsCString("<NULL>"));
2584   }
2585 
2586   return namespace_decl_ctx;
2587 }
2588 
2589 TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die,
2590                                       bool resolve_function_context) {
2591   TypeSP type_sp;
2592   if (die) {
2593     Type *type_ptr = GetDIEToType().lookup(die.GetDIE());
2594     if (type_ptr == nullptr) {
2595       SymbolContextScope *scope;
2596       if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()))
2597         scope = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2598       else
2599         scope = GetObjectFile()->GetModule().get();
2600       assert(scope);
2601       SymbolContext sc(scope);
2602       const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE();
2603       while (parent_die != nullptr) {
2604         if (parent_die->Tag() == DW_TAG_subprogram)
2605           break;
2606         parent_die = parent_die->GetParent();
2607       }
2608       SymbolContext sc_backup = sc;
2609       if (resolve_function_context && parent_die != nullptr &&
2610           !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc))
2611         sc = sc_backup;
2612 
2613       type_sp = ParseType(sc, die, nullptr);
2614     } else if (type_ptr != DIE_IS_BEING_PARSED) {
2615       // Grab the existing type from the master types lists
2616       type_sp = type_ptr->shared_from_this();
2617     }
2618   }
2619   return type_sp;
2620 }
2621 
2622 DWARFDIE
2623 SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
2624   if (orig_die) {
2625     DWARFDIE die = orig_die;
2626 
2627     while (die) {
2628       // If this is the original DIE that we are searching for a declaration
2629       // for, then don't look in the cache as we don't want our own decl
2630       // context to be our decl context...
2631       if (orig_die != die) {
2632         switch (die.Tag()) {
2633         case DW_TAG_compile_unit:
2634         case DW_TAG_partial_unit:
2635         case DW_TAG_namespace:
2636         case DW_TAG_structure_type:
2637         case DW_TAG_union_type:
2638         case DW_TAG_class_type:
2639         case DW_TAG_lexical_block:
2640         case DW_TAG_subprogram:
2641           return die;
2642         case DW_TAG_inlined_subroutine: {
2643           DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2644           if (abs_die) {
2645             return abs_die;
2646           }
2647           break;
2648         }
2649         default:
2650           break;
2651         }
2652       }
2653 
2654       DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
2655       if (spec_die) {
2656         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
2657         if (decl_ctx_die)
2658           return decl_ctx_die;
2659       }
2660 
2661       DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2662       if (abs_die) {
2663         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
2664         if (decl_ctx_die)
2665           return decl_ctx_die;
2666       }
2667 
2668       die = die.GetParent();
2669     }
2670   }
2671   return DWARFDIE();
2672 }
2673 
2674 Symbol *SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) {
2675   Symbol *objc_class_symbol = nullptr;
2676   if (m_objfile_sp) {
2677     Symtab *symtab = m_objfile_sp->GetSymtab();
2678     if (symtab) {
2679       objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(
2680           objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo,
2681           Symtab::eVisibilityAny);
2682     }
2683   }
2684   return objc_class_symbol;
2685 }
2686 
2687 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If
2688 // they don't then we can end up looking through all class types for a complete
2689 // type and never find the full definition. We need to know if this attribute
2690 // is supported, so we determine this here and cache th result. We also need to
2691 // worry about the debug map
2692 // DWARF file
2693 // if we are doing darwin DWARF in .o file debugging.
2694 bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(DWARFUnit *cu) {
2695   if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) {
2696     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
2697     if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
2698       m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2699     else {
2700       DWARFDebugInfo *debug_info = DebugInfo();
2701       const uint32_t num_compile_units = GetNumCompileUnits();
2702       for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
2703         DWARFUnit *dwarf_cu = debug_info->GetUnitAtIndex(cu_idx);
2704         if (dwarf_cu != cu &&
2705             dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) {
2706           m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2707           break;
2708         }
2709       }
2710     }
2711     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo &&
2712         GetDebugMapSymfile())
2713       return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this);
2714   }
2715   return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
2716 }
2717 
2718 // This function can be used when a DIE is found that is a forward declaration
2719 // DIE and we want to try and find a type that has the complete definition.
2720 TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE(
2721     const DWARFDIE &die, ConstString type_name, bool must_be_implementation) {
2722 
2723   TypeSP type_sp;
2724 
2725   if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name)))
2726     return type_sp;
2727 
2728   DIEArray die_offsets;
2729   m_index->GetCompleteObjCClass(type_name, must_be_implementation, die_offsets);
2730 
2731   const size_t num_matches = die_offsets.size();
2732 
2733   if (num_matches) {
2734     for (size_t i = 0; i < num_matches; ++i) {
2735       const DIERef &die_ref = die_offsets[i];
2736       DWARFDIE type_die = GetDIE(die_ref);
2737 
2738       if (type_die) {
2739         bool try_resolving_type = false;
2740 
2741         // Don't try and resolve the DIE we are looking for with the DIE
2742         // itself!
2743         if (type_die != die) {
2744           switch (type_die.Tag()) {
2745           case DW_TAG_class_type:
2746           case DW_TAG_structure_type:
2747             try_resolving_type = true;
2748             break;
2749           default:
2750             break;
2751           }
2752         }
2753 
2754         if (try_resolving_type) {
2755           if (must_be_implementation &&
2756               type_die.Supports_DW_AT_APPLE_objc_complete_type())
2757             try_resolving_type = type_die.GetAttributeValueAsUnsigned(
2758                 DW_AT_APPLE_objc_complete_type, 0);
2759 
2760           if (try_resolving_type) {
2761             Type *resolved_type = ResolveType(type_die, false, true);
2762             if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2763               DEBUG_PRINTF("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64
2764                            " (cu 0x%8.8" PRIx64 ")\n",
2765                            die.GetID(),
2766                            m_objfile_sp->GetFileSpec().GetFilename().AsCString(
2767                                "<Unknown>"),
2768                            type_die.GetID(), type_cu->GetID());
2769 
2770               if (die)
2771                 GetDIEToType()[die.GetDIE()] = resolved_type;
2772               type_sp = resolved_type->shared_from_this();
2773               break;
2774             }
2775           }
2776         }
2777       } else {
2778         m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef());
2779       }
2780     }
2781   }
2782   return type_sp;
2783 }
2784 
2785 // This function helps to ensure that the declaration contexts match for two
2786 // different DIEs. Often times debug information will refer to a forward
2787 // declaration of a type (the equivalent of "struct my_struct;". There will
2788 // often be a declaration of that type elsewhere that has the full definition.
2789 // When we go looking for the full type "my_struct", we will find one or more
2790 // matches in the accelerator tables and we will then need to make sure the
2791 // type was in the same declaration context as the original DIE. This function
2792 // can efficiently compare two DIEs and will return true when the declaration
2793 // context matches, and false when they don't.
2794 bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1,
2795                                            const DWARFDIE &die2) {
2796   if (die1 == die2)
2797     return true;
2798 
2799   std::vector<DWARFDIE> decl_ctx_1;
2800   std::vector<DWARFDIE> decl_ctx_2;
2801   // The declaration DIE stack is a stack of the declaration context DIEs all
2802   // the way back to the compile unit. If a type "T" is declared inside a class
2803   // "B", and class "B" is declared inside a class "A" and class "A" is in a
2804   // namespace "lldb", and the namespace is in a compile unit, there will be a
2805   // stack of DIEs:
2806   //
2807   //   [0] DW_TAG_class_type for "B"
2808   //   [1] DW_TAG_class_type for "A"
2809   //   [2] DW_TAG_namespace  for "lldb"
2810   //   [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file.
2811   //
2812   // We grab both contexts and make sure that everything matches all the way
2813   // back to the compiler unit.
2814 
2815   // First lets grab the decl contexts for both DIEs
2816   decl_ctx_1 = die1.GetDeclContextDIEs();
2817   decl_ctx_2 = die2.GetDeclContextDIEs();
2818   // Make sure the context arrays have the same size, otherwise we are done
2819   const size_t count1 = decl_ctx_1.size();
2820   const size_t count2 = decl_ctx_2.size();
2821   if (count1 != count2)
2822     return false;
2823 
2824   // Make sure the DW_TAG values match all the way back up the compile unit. If
2825   // they don't, then we are done.
2826   DWARFDIE decl_ctx_die1;
2827   DWARFDIE decl_ctx_die2;
2828   size_t i;
2829   for (i = 0; i < count1; i++) {
2830     decl_ctx_die1 = decl_ctx_1[i];
2831     decl_ctx_die2 = decl_ctx_2[i];
2832     if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag())
2833       return false;
2834   }
2835 #ifndef NDEBUG
2836 
2837   // Make sure the top item in the decl context die array is always
2838   // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then
2839   // something went wrong in the DWARFDIE::GetDeclContextDIEs()
2840   // function.
2841   dw_tag_t cu_tag = decl_ctx_1[count1 - 1].Tag();
2842   UNUSED_IF_ASSERT_DISABLED(cu_tag);
2843   assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit);
2844 
2845 #endif
2846   // Always skip the compile unit when comparing by only iterating up to "count
2847   // - 1". Here we compare the names as we go.
2848   for (i = 0; i < count1 - 1; i++) {
2849     decl_ctx_die1 = decl_ctx_1[i];
2850     decl_ctx_die2 = decl_ctx_2[i];
2851     const char *name1 = decl_ctx_die1.GetName();
2852     const char *name2 = decl_ctx_die2.GetName();
2853     // If the string was from a DW_FORM_strp, then the pointer will often be
2854     // the same!
2855     if (name1 == name2)
2856       continue;
2857 
2858     // Name pointers are not equal, so only compare the strings if both are not
2859     // NULL.
2860     if (name1 && name2) {
2861       // If the strings don't compare, we are done...
2862       if (strcmp(name1, name2) != 0)
2863         return false;
2864     } else {
2865       // One name was NULL while the other wasn't
2866       return false;
2867     }
2868   }
2869   // We made it through all of the checks and the declaration contexts are
2870   // equal.
2871   return true;
2872 }
2873 
2874 TypeSP SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(
2875     const DWARFDeclContext &dwarf_decl_ctx) {
2876   TypeSP type_sp;
2877 
2878   const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
2879   if (dwarf_decl_ctx_count > 0) {
2880     const ConstString type_name(dwarf_decl_ctx[0].name);
2881     const dw_tag_t tag = dwarf_decl_ctx[0].tag;
2882 
2883     if (type_name) {
2884       Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION |
2885                                             DWARF_LOG_LOOKUPS));
2886       if (log) {
2887         GetObjectFile()->GetModule()->LogMessage(
2888             log,
2889             "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%"
2890             "s, qualified-name='%s')",
2891             DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2892             dwarf_decl_ctx.GetQualifiedName());
2893       }
2894 
2895       DIEArray die_offsets;
2896       m_index->GetTypes(dwarf_decl_ctx, die_offsets);
2897       const size_t num_matches = die_offsets.size();
2898 
2899       // Get the type system that we are looking to find a type for. We will
2900       // use this to ensure any matches we find are in a language that this
2901       // type system supports
2902       const LanguageType language = dwarf_decl_ctx.GetLanguage();
2903       TypeSystem *type_system = nullptr;
2904       if (language != eLanguageTypeUnknown) {
2905         auto type_system_or_err = GetTypeSystemForLanguage(language);
2906         if (auto err = type_system_or_err.takeError()) {
2907           LLDB_LOG_ERROR(
2908               lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
2909               std::move(err), "Cannot get TypeSystem for language {}",
2910               Language::GetNameForLanguageType(language));
2911         } else {
2912           type_system = &type_system_or_err.get();
2913         }
2914       }
2915       if (num_matches) {
2916         for (size_t i = 0; i < num_matches; ++i) {
2917           const DIERef &die_ref = die_offsets[i];
2918           DWARFDIE type_die = GetDIE(die_ref);
2919 
2920           if (type_die) {
2921             // Make sure type_die's langauge matches the type system we are
2922             // looking for. We don't want to find a "Foo" type from Java if we
2923             // are looking for a "Foo" type for C, C++, ObjC, or ObjC++.
2924             if (type_system &&
2925                 !type_system->SupportsLanguage(GetLanguage(*type_die.GetCU())))
2926               continue;
2927             bool try_resolving_type = false;
2928 
2929             // Don't try and resolve the DIE we are looking for with the DIE
2930             // itself!
2931             const dw_tag_t type_tag = type_die.Tag();
2932             // Make sure the tags match
2933             if (type_tag == tag) {
2934               // The tags match, lets try resolving this type
2935               try_resolving_type = true;
2936             } else {
2937               // The tags don't match, but we need to watch our for a forward
2938               // declaration for a struct and ("struct foo") ends up being a
2939               // class ("class foo { ... };") or vice versa.
2940               switch (type_tag) {
2941               case DW_TAG_class_type:
2942                 // We had a "class foo", see if we ended up with a "struct foo
2943                 // { ... };"
2944                 try_resolving_type = (tag == DW_TAG_structure_type);
2945                 break;
2946               case DW_TAG_structure_type:
2947                 // We had a "struct foo", see if we ended up with a "class foo
2948                 // { ... };"
2949                 try_resolving_type = (tag == DW_TAG_class_type);
2950                 break;
2951               default:
2952                 // Tags don't match, don't event try to resolve using this type
2953                 // whose name matches....
2954                 break;
2955               }
2956             }
2957 
2958             if (try_resolving_type) {
2959               DWARFDeclContext type_dwarf_decl_ctx =
2960                   GetDWARFDeclContext(type_die);
2961 
2962               if (log) {
2963                 GetObjectFile()->GetModule()->LogMessage(
2964                     log,
2965                     "SymbolFileDWARF::"
2966                     "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
2967                     "qualified-name='%s') trying die=0x%8.8x (%s)",
2968                     DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2969                     dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
2970                     type_dwarf_decl_ctx.GetQualifiedName());
2971               }
2972 
2973               // Make sure the decl contexts match all the way up
2974               if (dwarf_decl_ctx == type_dwarf_decl_ctx) {
2975                 Type *resolved_type = ResolveType(type_die, false);
2976                 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2977                   type_sp = resolved_type->shared_from_this();
2978                   break;
2979                 }
2980               }
2981             } else {
2982               if (log) {
2983                 std::string qualified_name;
2984                 type_die.GetQualifiedName(qualified_name);
2985                 GetObjectFile()->GetModule()->LogMessage(
2986                     log,
2987                     "SymbolFileDWARF::"
2988                     "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
2989                     "qualified-name='%s') ignoring die=0x%8.8x (%s)",
2990                     DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2991                     dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
2992                     qualified_name.c_str());
2993               }
2994             }
2995           } else {
2996             m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef());
2997           }
2998         }
2999       }
3000     }
3001   }
3002   return type_sp;
3003 }
3004 
3005 TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die,
3006                                   bool *type_is_new_ptr) {
3007   if (!die)
3008     return {};
3009 
3010   auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU()));
3011   if (auto err = type_system_or_err.takeError()) {
3012     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
3013                    std::move(err), "Unable to parse type");
3014     return {};
3015   }
3016 
3017   DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser();
3018   if (!dwarf_ast)
3019     return {};
3020 
3021   TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, type_is_new_ptr);
3022   if (type_sp) {
3023     GetTypeList().Insert(type_sp);
3024 
3025     if (die.Tag() == DW_TAG_subprogram) {
3026       std::string scope_qualified_name(GetDeclContextForUID(die.GetID())
3027                                            .GetScopeQualifiedName()
3028                                            .AsCString(""));
3029       if (scope_qualified_name.size()) {
3030         m_function_scope_qualified_name_map[scope_qualified_name].insert(
3031             *die.GetDIERef());
3032       }
3033     }
3034   }
3035 
3036   return type_sp;
3037 }
3038 
3039 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc,
3040                                    const DWARFDIE &orig_die,
3041                                    bool parse_siblings, bool parse_children) {
3042   size_t types_added = 0;
3043   DWARFDIE die = orig_die;
3044 
3045   while (die) {
3046     const dw_tag_t tag = die.Tag();
3047     bool type_is_new = false;
3048 
3049     Tag dwarf_tag = static_cast<Tag>(tag);
3050 
3051     // TODO: Currently ParseTypeFromDWARF(...) which is called by ParseType(...)
3052     // does not handle DW_TAG_subrange_type. It is not clear if this is a bug or
3053     // not.
3054     if (isType(dwarf_tag) && tag != DW_TAG_subrange_type)
3055       ParseType(sc, die, &type_is_new);
3056 
3057     if (type_is_new)
3058       ++types_added;
3059 
3060     if (parse_children && die.HasChildren()) {
3061       if (die.Tag() == DW_TAG_subprogram) {
3062         SymbolContext child_sc(sc);
3063         child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3064         types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3065       } else
3066         types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3067     }
3068 
3069     if (parse_siblings)
3070       die = die.GetSibling();
3071     else
3072       die.Clear();
3073   }
3074   return types_added;
3075 }
3076 
3077 size_t SymbolFileDWARF::ParseBlocksRecursive(Function &func) {
3078   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3079   CompileUnit *comp_unit = func.GetCompileUnit();
3080   lldbassert(comp_unit);
3081 
3082   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit);
3083   if (!dwarf_cu)
3084     return 0;
3085 
3086   size_t functions_added = 0;
3087   const dw_offset_t function_die_offset = func.GetID();
3088   DWARFDIE function_die =
3089       dwarf_cu->GetNonSkeletonUnit().GetDIE(function_die_offset);
3090   if (function_die) {
3091     ParseBlocksRecursive(*comp_unit, &func.GetBlock(false), function_die,
3092                          LLDB_INVALID_ADDRESS, 0);
3093   }
3094 
3095   return functions_added;
3096 }
3097 
3098 size_t SymbolFileDWARF::ParseTypes(CompileUnit &comp_unit) {
3099   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3100   size_t types_added = 0;
3101   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
3102   if (dwarf_cu) {
3103     DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3104     if (dwarf_cu_die && dwarf_cu_die.HasChildren()) {
3105       SymbolContext sc;
3106       sc.comp_unit = &comp_unit;
3107       types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3108     }
3109   }
3110 
3111   return types_added;
3112 }
3113 
3114 size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) {
3115   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3116   if (sc.comp_unit != nullptr) {
3117     DWARFDebugInfo *info = DebugInfo();
3118     if (info == nullptr)
3119       return 0;
3120 
3121     if (sc.function) {
3122       DWARFDIE function_die = GetDIE(sc.function->GetID());
3123 
3124       const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress(
3125           DW_AT_low_pc, LLDB_INVALID_ADDRESS);
3126       if (func_lo_pc != LLDB_INVALID_ADDRESS) {
3127         const size_t num_variables = ParseVariables(
3128             sc, function_die.GetFirstChild(), func_lo_pc, true, true);
3129 
3130         // Let all blocks know they have parse all their variables
3131         sc.function->GetBlock(false).SetDidParseVariables(true, true);
3132         return num_variables;
3133       }
3134     } else if (sc.comp_unit) {
3135       DWARFUnit *dwarf_cu = info->GetUnitAtIndex(sc.comp_unit->GetID());
3136 
3137       if (dwarf_cu == nullptr)
3138         return 0;
3139 
3140       uint32_t vars_added = 0;
3141       VariableListSP variables(sc.comp_unit->GetVariableList(false));
3142 
3143       if (variables.get() == nullptr) {
3144         variables = std::make_shared<VariableList>();
3145         sc.comp_unit->SetVariableList(variables);
3146 
3147         DIEArray die_offsets;
3148         m_index->GetGlobalVariables(dwarf_cu->GetNonSkeletonUnit(),
3149                                     die_offsets);
3150         const size_t num_matches = die_offsets.size();
3151         if (num_matches) {
3152           for (size_t i = 0; i < num_matches; ++i) {
3153             const DIERef &die_ref = die_offsets[i];
3154             DWARFDIE die = GetDIE(die_ref);
3155             if (die) {
3156               VariableSP var_sp(
3157                   ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS));
3158               if (var_sp) {
3159                 variables->AddVariableIfUnique(var_sp);
3160                 ++vars_added;
3161               }
3162             } else
3163               m_index->ReportInvalidDIERef(die_ref, "");
3164           }
3165         }
3166       }
3167       return vars_added;
3168     }
3169   }
3170   return 0;
3171 }
3172 
3173 VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc,
3174                                              const DWARFDIE &die,
3175                                              const lldb::addr_t func_low_pc) {
3176   if (die.GetDWARF() != this)
3177     return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
3178 
3179   VariableSP var_sp;
3180   if (!die)
3181     return var_sp;
3182 
3183   var_sp = GetDIEToVariable()[die.GetDIE()];
3184   if (var_sp)
3185     return var_sp; // Already been parsed!
3186 
3187   const dw_tag_t tag = die.Tag();
3188   ModuleSP module = GetObjectFile()->GetModule();
3189 
3190   if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3191       (tag == DW_TAG_formal_parameter && sc.function)) {
3192     DWARFAttributes attributes;
3193     const size_t num_attributes = die.GetAttributes(attributes);
3194     DWARFDIE spec_die;
3195     if (num_attributes > 0) {
3196       const char *name = nullptr;
3197       const char *mangled = nullptr;
3198       Declaration decl;
3199       uint32_t i;
3200       DWARFFormValue type_die_form;
3201       DWARFExpression location;
3202       bool is_external = false;
3203       bool is_artificial = false;
3204       bool location_is_const_value_data = false;
3205       bool has_explicit_location = false;
3206       DWARFFormValue const_value;
3207       Variable::RangeList scope_ranges;
3208       // AccessType accessibility = eAccessNone;
3209 
3210       for (i = 0; i < num_attributes; ++i) {
3211         dw_attr_t attr = attributes.AttributeAtIndex(i);
3212         DWARFFormValue form_value;
3213 
3214         if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3215           switch (attr) {
3216           case DW_AT_decl_file:
3217             decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3218                 form_value.Unsigned()));
3219             break;
3220           case DW_AT_decl_line:
3221             decl.SetLine(form_value.Unsigned());
3222             break;
3223           case DW_AT_decl_column:
3224             decl.SetColumn(form_value.Unsigned());
3225             break;
3226           case DW_AT_name:
3227             name = form_value.AsCString();
3228             break;
3229           case DW_AT_linkage_name:
3230           case DW_AT_MIPS_linkage_name:
3231             mangled = form_value.AsCString();
3232             break;
3233           case DW_AT_type:
3234             type_die_form = form_value;
3235             break;
3236           case DW_AT_external:
3237             is_external = form_value.Boolean();
3238             break;
3239           case DW_AT_const_value:
3240             // If we have already found a DW_AT_location attribute, ignore this
3241             // attribute.
3242             if (!has_explicit_location) {
3243               location_is_const_value_data = true;
3244               // The constant value will be either a block, a data value or a
3245               // string.
3246               auto debug_info_data = die.GetData();
3247               if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3248                 // Retrieve the value as a block expression.
3249                 uint32_t block_offset =
3250                     form_value.BlockData() - debug_info_data.GetDataStart();
3251                 uint32_t block_length = form_value.Unsigned();
3252                 location = DWARFExpression(
3253                     module,
3254                     DataExtractor(debug_info_data, block_offset, block_length),
3255                     die.GetCU());
3256               } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3257                 // Retrieve the value as a data expression.
3258                 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3259                 if (auto data_length = form_value.GetFixedSize())
3260                   location = DWARFExpression(
3261                       module,
3262                       DataExtractor(debug_info_data, data_offset, *data_length),
3263                       die.GetCU());
3264                 else {
3265                   const uint8_t *data_pointer = form_value.BlockData();
3266                   if (data_pointer) {
3267                     form_value.Unsigned();
3268                   } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3269                     // we need to get the byte size of the type later after we
3270                     // create the variable
3271                     const_value = form_value;
3272                   }
3273                 }
3274               } else {
3275                 // Retrieve the value as a string expression.
3276                 if (form_value.Form() == DW_FORM_strp) {
3277                   uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3278                   if (auto data_length = form_value.GetFixedSize())
3279                     location = DWARFExpression(module,
3280                                                DataExtractor(debug_info_data,
3281                                                              data_offset,
3282                                                              *data_length),
3283                                                die.GetCU());
3284                 } else {
3285                   const char *str = form_value.AsCString();
3286                   uint32_t string_offset =
3287                       str - (const char *)debug_info_data.GetDataStart();
3288                   uint32_t string_length = strlen(str) + 1;
3289                   location = DWARFExpression(module,
3290                                              DataExtractor(debug_info_data,
3291                                                            string_offset,
3292                                                            string_length),
3293                                              die.GetCU());
3294                 }
3295               }
3296             }
3297             break;
3298           case DW_AT_location: {
3299             location_is_const_value_data = false;
3300             has_explicit_location = true;
3301             if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3302               auto data = die.GetData();
3303 
3304               uint32_t block_offset =
3305                   form_value.BlockData() - data.GetDataStart();
3306               uint32_t block_length = form_value.Unsigned();
3307               location = DWARFExpression(
3308                   module, DataExtractor(data, block_offset, block_length),
3309                   die.GetCU());
3310             } else {
3311               DataExtractor data = die.GetCU()->GetLocationData();
3312               dw_offset_t offset = form_value.Unsigned();
3313               if (form_value.Form() == DW_FORM_loclistx)
3314                 offset = die.GetCU()->GetLoclistOffset(offset).getValueOr(-1);
3315               if (data.ValidOffset(offset)) {
3316                 data = DataExtractor(data, offset, data.GetByteSize() - offset);
3317                 location = DWARFExpression(module, data, die.GetCU());
3318                 assert(func_low_pc != LLDB_INVALID_ADDRESS);
3319                 location.SetLocationListAddresses(
3320                     attributes.CompileUnitAtIndex(i)->GetBaseAddress(),
3321                     func_low_pc);
3322               }
3323             }
3324           } break;
3325           case DW_AT_specification:
3326             spec_die = form_value.Reference();
3327             break;
3328           case DW_AT_start_scope:
3329             // TODO: Implement this.
3330             break;
3331           case DW_AT_artificial:
3332             is_artificial = form_value.Boolean();
3333             break;
3334           case DW_AT_accessibility:
3335             break; // accessibility =
3336                    // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
3337           case DW_AT_declaration:
3338           case DW_AT_description:
3339           case DW_AT_endianity:
3340           case DW_AT_segment:
3341           case DW_AT_visibility:
3342           default:
3343           case DW_AT_abstract_origin:
3344           case DW_AT_sibling:
3345             break;
3346           }
3347         }
3348       }
3349 
3350       const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
3351       const dw_tag_t parent_tag = die.GetParent().Tag();
3352       bool is_static_member =
3353           (parent_tag == DW_TAG_compile_unit ||
3354            parent_tag == DW_TAG_partial_unit) &&
3355           (parent_context_die.Tag() == DW_TAG_class_type ||
3356            parent_context_die.Tag() == DW_TAG_structure_type);
3357 
3358       ValueType scope = eValueTypeInvalid;
3359 
3360       const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3361       SymbolContextScope *symbol_context_scope = nullptr;
3362 
3363       bool has_explicit_mangled = mangled != nullptr;
3364       if (!mangled) {
3365         // LLDB relies on the mangled name (DW_TAG_linkage_name or
3366         // DW_AT_MIPS_linkage_name) to generate fully qualified names
3367         // of global variables with commands like "frame var j". For
3368         // example, if j were an int variable holding a value 4 and
3369         // declared in a namespace B which in turn is contained in a
3370         // namespace A, the command "frame var j" returns
3371         //   "(int) A::B::j = 4".
3372         // If the compiler does not emit a linkage name, we should be
3373         // able to generate a fully qualified name from the
3374         // declaration context.
3375         if ((parent_tag == DW_TAG_compile_unit ||
3376              parent_tag == DW_TAG_partial_unit) &&
3377             Language::LanguageIsCPlusPlus(GetLanguage(*die.GetCU())))
3378           mangled = GetDWARFDeclContext(die)
3379                         .GetQualifiedNameAsConstString()
3380                         .GetCString();
3381       }
3382 
3383       if (tag == DW_TAG_formal_parameter)
3384         scope = eValueTypeVariableArgument;
3385       else {
3386         // DWARF doesn't specify if a DW_TAG_variable is a local, global
3387         // or static variable, so we have to do a little digging:
3388         // 1) DW_AT_linkage_name implies static lifetime (but may be missing)
3389         // 2) An empty DW_AT_location is an (optimized-out) static lifetime var.
3390         // 3) DW_AT_location containing a DW_OP_addr implies static lifetime.
3391         // Clang likes to combine small global variables into the same symbol
3392         // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
3393         // so we need to look through the whole expression.
3394         bool is_static_lifetime =
3395             has_explicit_mangled ||
3396             (has_explicit_location && !location.IsValid());
3397         // Check if the location has a DW_OP_addr with any address value...
3398         lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
3399         if (!location_is_const_value_data) {
3400           bool op_error = false;
3401           location_DW_OP_addr = location.GetLocation_DW_OP_addr(0, op_error);
3402           if (op_error) {
3403             StreamString strm;
3404             location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0,
3405                                             nullptr);
3406             GetObjectFile()->GetModule()->ReportError(
3407                 "0x%8.8x: %s has an invalid location: %s", die.GetOffset(),
3408                 die.GetTagAsCString(), strm.GetData());
3409           }
3410           if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
3411             is_static_lifetime = true;
3412         }
3413         SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
3414         if (debug_map_symfile)
3415           // Set the module of the expression to the linked module
3416           // instead of the oject file so the relocated address can be
3417           // found there.
3418           location.SetModule(debug_map_symfile->GetObjectFile()->GetModule());
3419 
3420         if (is_static_lifetime) {
3421           if (is_external)
3422             scope = eValueTypeVariableGlobal;
3423           else
3424             scope = eValueTypeVariableStatic;
3425 
3426           if (debug_map_symfile) {
3427             // When leaving the DWARF in the .o files on darwin, when we have a
3428             // global variable that wasn't initialized, the .o file might not
3429             // have allocated a virtual address for the global variable. In
3430             // this case it will have created a symbol for the global variable
3431             // that is undefined/data and external and the value will be the
3432             // byte size of the variable. When we do the address map in
3433             // SymbolFileDWARFDebugMap we rely on having an address, we need to
3434             // do some magic here so we can get the correct address for our
3435             // global variable. The address for all of these entries will be
3436             // zero, and there will be an undefined symbol in this object file,
3437             // and the executable will have a matching symbol with a good
3438             // address. So here we dig up the correct address and replace it in
3439             // the location for the variable, and set the variable's symbol
3440             // context scope to be that of the main executable so the file
3441             // address will resolve correctly.
3442             bool linked_oso_file_addr = false;
3443             if (is_external && location_DW_OP_addr == 0) {
3444               // we have a possible uninitialized extern global
3445               ConstString const_name(mangled ? mangled : name);
3446               ObjectFile *debug_map_objfile =
3447                   debug_map_symfile->GetObjectFile();
3448               if (debug_map_objfile) {
3449                 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
3450                 if (debug_map_symtab) {
3451                   Symbol *exe_symbol =
3452                       debug_map_symtab->FindFirstSymbolWithNameAndType(
3453                           const_name, eSymbolTypeData, Symtab::eDebugYes,
3454                           Symtab::eVisibilityExtern);
3455                   if (exe_symbol) {
3456                     if (exe_symbol->ValueIsAddress()) {
3457                       const addr_t exe_file_addr =
3458                           exe_symbol->GetAddressRef().GetFileAddress();
3459                       if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3460                         if (location.Update_DW_OP_addr(exe_file_addr)) {
3461                           linked_oso_file_addr = true;
3462                           symbol_context_scope = exe_symbol;
3463                         }
3464                       }
3465                     }
3466                   }
3467                 }
3468               }
3469             }
3470 
3471             if (!linked_oso_file_addr) {
3472               // The DW_OP_addr is not zero, but it contains a .o file address
3473               // which needs to be linked up correctly.
3474               const lldb::addr_t exe_file_addr =
3475                   debug_map_symfile->LinkOSOFileAddress(this,
3476                                                         location_DW_OP_addr);
3477               if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3478                 // Update the file address for this variable
3479                 location.Update_DW_OP_addr(exe_file_addr);
3480               } else {
3481                 // Variable didn't make it into the final executable
3482                 return var_sp;
3483               }
3484             }
3485           }
3486         } else {
3487           if (location_is_const_value_data)
3488             scope = eValueTypeVariableStatic;
3489           else {
3490             scope = eValueTypeVariableLocal;
3491             if (debug_map_symfile) {
3492               // We need to check for TLS addresses that we need to fixup
3493               if (location.ContainsThreadLocalStorage()) {
3494                 location.LinkThreadLocalStorage(
3495                     debug_map_symfile->GetObjectFile()->GetModule(),
3496                     [this, debug_map_symfile](
3497                         lldb::addr_t unlinked_file_addr) -> lldb::addr_t {
3498                       return debug_map_symfile->LinkOSOFileAddress(
3499                           this, unlinked_file_addr);
3500                     });
3501                 scope = eValueTypeVariableThreadLocal;
3502               }
3503             }
3504           }
3505         }
3506       }
3507 
3508       if (symbol_context_scope == nullptr) {
3509         switch (parent_tag) {
3510         case DW_TAG_subprogram:
3511         case DW_TAG_inlined_subroutine:
3512         case DW_TAG_lexical_block:
3513           if (sc.function) {
3514             symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(
3515                 sc_parent_die.GetID());
3516             if (symbol_context_scope == nullptr)
3517               symbol_context_scope = sc.function;
3518           }
3519           break;
3520 
3521         default:
3522           symbol_context_scope = sc.comp_unit;
3523           break;
3524         }
3525       }
3526 
3527       if (symbol_context_scope) {
3528         SymbolFileTypeSP type_sp(
3529             new SymbolFileType(*this, GetUID(type_die_form.Reference())));
3530 
3531         if (const_value.Form() && type_sp && type_sp->GetType())
3532           location.UpdateValue(const_value.Unsigned(),
3533                                type_sp->GetType()->GetByteSize().getValueOr(0),
3534                                die.GetCU()->GetAddressByteSize());
3535 
3536         var_sp = std::make_shared<Variable>(
3537             die.GetID(), name, mangled, type_sp, scope, symbol_context_scope,
3538             scope_ranges, &decl, location, is_external, is_artificial,
3539             is_static_member);
3540 
3541         var_sp->SetLocationIsConstantValueData(location_is_const_value_data);
3542       } else {
3543         // Not ready to parse this variable yet. It might be a global or static
3544         // variable that is in a function scope and the function in the symbol
3545         // context wasn't filled in yet
3546         return var_sp;
3547       }
3548     }
3549     // Cache var_sp even if NULL (the variable was just a specification or was
3550     // missing vital information to be able to be displayed in the debugger
3551     // (missing location due to optimization, etc)) so we don't re-parse this
3552     // DIE over and over later...
3553     GetDIEToVariable()[die.GetDIE()] = var_sp;
3554     if (spec_die)
3555       GetDIEToVariable()[spec_die.GetDIE()] = var_sp;
3556   }
3557   return var_sp;
3558 }
3559 
3560 DWARFDIE
3561 SymbolFileDWARF::FindBlockContainingSpecification(
3562     const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) {
3563   // Give the concrete function die specified by "func_die_offset", find the
3564   // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3565   // to "spec_block_die_offset"
3566   return FindBlockContainingSpecification(DebugInfo()->GetDIE(func_die_ref),
3567                                           spec_block_die_offset);
3568 }
3569 
3570 DWARFDIE
3571 SymbolFileDWARF::FindBlockContainingSpecification(
3572     const DWARFDIE &die, dw_offset_t spec_block_die_offset) {
3573   if (die) {
3574     switch (die.Tag()) {
3575     case DW_TAG_subprogram:
3576     case DW_TAG_inlined_subroutine:
3577     case DW_TAG_lexical_block: {
3578       if (die.GetReferencedDIE(DW_AT_specification).GetOffset() ==
3579           spec_block_die_offset)
3580         return die;
3581 
3582       if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() ==
3583           spec_block_die_offset)
3584         return die;
3585     } break;
3586     default:
3587       break;
3588     }
3589 
3590     // Give the concrete function die specified by "func_die_offset", find the
3591     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3592     // to "spec_block_die_offset"
3593     for (DWARFDIE child_die = die.GetFirstChild(); child_die;
3594          child_die = child_die.GetSibling()) {
3595       DWARFDIE result_die =
3596           FindBlockContainingSpecification(child_die, spec_block_die_offset);
3597       if (result_die)
3598         return result_die;
3599     }
3600   }
3601 
3602   return DWARFDIE();
3603 }
3604 
3605 size_t SymbolFileDWARF::ParseVariables(const SymbolContext &sc,
3606                                        const DWARFDIE &orig_die,
3607                                        const lldb::addr_t func_low_pc,
3608                                        bool parse_siblings, bool parse_children,
3609                                        VariableList *cc_variable_list) {
3610   if (!orig_die)
3611     return 0;
3612 
3613   VariableListSP variable_list_sp;
3614 
3615   size_t vars_added = 0;
3616   DWARFDIE die = orig_die;
3617   while (die) {
3618     dw_tag_t tag = die.Tag();
3619 
3620     // Check to see if we have already parsed this variable or constant?
3621     VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
3622     if (var_sp) {
3623       if (cc_variable_list)
3624         cc_variable_list->AddVariableIfUnique(var_sp);
3625     } else {
3626       // We haven't already parsed it, lets do that now.
3627       if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3628           (tag == DW_TAG_formal_parameter && sc.function)) {
3629         if (variable_list_sp.get() == nullptr) {
3630           DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die);
3631           dw_tag_t parent_tag = sc_parent_die.Tag();
3632           switch (parent_tag) {
3633           case DW_TAG_compile_unit:
3634           case DW_TAG_partial_unit:
3635             if (sc.comp_unit != nullptr) {
3636               variable_list_sp = sc.comp_unit->GetVariableList(false);
3637               if (variable_list_sp.get() == nullptr) {
3638                 variable_list_sp = std::make_shared<VariableList>();
3639               }
3640             } else {
3641               GetObjectFile()->GetModule()->ReportError(
3642                   "parent 0x%8.8" PRIx64 " %s with no valid compile unit in "
3643                   "symbol context for 0x%8.8" PRIx64 " %s.\n",
3644                   sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(),
3645                   orig_die.GetID(), orig_die.GetTagAsCString());
3646             }
3647             break;
3648 
3649           case DW_TAG_subprogram:
3650           case DW_TAG_inlined_subroutine:
3651           case DW_TAG_lexical_block:
3652             if (sc.function != nullptr) {
3653               // Check to see if we already have parsed the variables for the
3654               // given scope
3655 
3656               Block *block = sc.function->GetBlock(true).FindBlockByID(
3657                   sc_parent_die.GetID());
3658               if (block == nullptr) {
3659                 // This must be a specification or abstract origin with a
3660                 // concrete block counterpart in the current function. We need
3661                 // to find the concrete block so we can correctly add the
3662                 // variable to it
3663                 const DWARFDIE concrete_block_die =
3664                     FindBlockContainingSpecification(
3665                         GetDIE(sc.function->GetID()),
3666                         sc_parent_die.GetOffset());
3667                 if (concrete_block_die)
3668                   block = sc.function->GetBlock(true).FindBlockByID(
3669                       concrete_block_die.GetID());
3670               }
3671 
3672               if (block != nullptr) {
3673                 const bool can_create = false;
3674                 variable_list_sp = block->GetBlockVariableList(can_create);
3675                 if (variable_list_sp.get() == nullptr) {
3676                   variable_list_sp = std::make_shared<VariableList>();
3677                   block->SetVariableList(variable_list_sp);
3678                 }
3679               }
3680             }
3681             break;
3682 
3683           default:
3684             GetObjectFile()->GetModule()->ReportError(
3685                 "didn't find appropriate parent DIE for variable list for "
3686                 "0x%8.8" PRIx64 " %s.\n",
3687                 orig_die.GetID(), orig_die.GetTagAsCString());
3688             break;
3689           }
3690         }
3691 
3692         if (variable_list_sp) {
3693           VariableSP var_sp(ParseVariableDIE(sc, die, func_low_pc));
3694           if (var_sp) {
3695             variable_list_sp->AddVariableIfUnique(var_sp);
3696             if (cc_variable_list)
3697               cc_variable_list->AddVariableIfUnique(var_sp);
3698             ++vars_added;
3699           }
3700         }
3701       }
3702     }
3703 
3704     bool skip_children = (sc.function == nullptr && tag == DW_TAG_subprogram);
3705 
3706     if (!skip_children && parse_children && die.HasChildren()) {
3707       vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true,
3708                                    true, cc_variable_list);
3709     }
3710 
3711     if (parse_siblings)
3712       die = die.GetSibling();
3713     else
3714       die.Clear();
3715   }
3716   return vars_added;
3717 }
3718 
3719 /// Collect call site parameters in a DW_TAG_call_site DIE.
3720 static CallSiteParameterArray
3721 CollectCallSiteParameters(ModuleSP module, DWARFDIE call_site_die) {
3722   CallSiteParameterArray parameters;
3723   for (DWARFDIE child = call_site_die.GetFirstChild(); child.IsValid();
3724        child = child.GetSibling()) {
3725     if (child.Tag() != DW_TAG_call_site_parameter)
3726       continue;
3727 
3728     llvm::Optional<DWARFExpression> LocationInCallee;
3729     llvm::Optional<DWARFExpression> LocationInCaller;
3730 
3731     DWARFAttributes attributes;
3732     const size_t num_attributes = child.GetAttributes(attributes);
3733 
3734     // Parse the location at index \p attr_index within this call site parameter
3735     // DIE, or return None on failure.
3736     auto parse_simple_location =
3737         [&](int attr_index) -> llvm::Optional<DWARFExpression> {
3738       DWARFFormValue form_value;
3739       if (!attributes.ExtractFormValueAtIndex(attr_index, form_value))
3740         return {};
3741       if (!DWARFFormValue::IsBlockForm(form_value.Form()))
3742         return {};
3743       auto data = child.GetData();
3744       uint32_t block_offset = form_value.BlockData() - data.GetDataStart();
3745       uint32_t block_length = form_value.Unsigned();
3746       return DWARFExpression(module,
3747                              DataExtractor(data, block_offset, block_length),
3748                              child.GetCU());
3749     };
3750 
3751     for (size_t i = 0; i < num_attributes; ++i) {
3752       dw_attr_t attr = attributes.AttributeAtIndex(i);
3753       if (attr == DW_AT_location)
3754         LocationInCallee = parse_simple_location(i);
3755       if (attr == DW_AT_call_value)
3756         LocationInCaller = parse_simple_location(i);
3757     }
3758 
3759     if (LocationInCallee && LocationInCaller) {
3760       CallSiteParameter param = {*LocationInCallee, *LocationInCaller};
3761       parameters.push_back(param);
3762     }
3763   }
3764   return parameters;
3765 }
3766 
3767 /// Collect call graph edges present in a function DIE.
3768 std::vector<std::unique_ptr<lldb_private::CallEdge>>
3769 SymbolFileDWARF::CollectCallEdges(ModuleSP module, DWARFDIE function_die) {
3770   // Check if the function has a supported call site-related attribute.
3771   // TODO: In the future it may be worthwhile to support call_all_source_calls.
3772   uint64_t has_call_edges =
3773       function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0);
3774   if (!has_call_edges)
3775     return {};
3776 
3777   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3778   LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}",
3779            function_die.GetPubname());
3780 
3781   // Scan the DIE for TAG_call_site entries.
3782   // TODO: A recursive scan of all blocks in the subprogram is needed in order
3783   // to be DWARF5-compliant. This may need to be done lazily to be performant.
3784   // For now, assume that all entries are nested directly under the subprogram
3785   // (this is the kind of DWARF LLVM produces) and parse them eagerly.
3786   std::vector<std::unique_ptr<CallEdge>> call_edges;
3787   for (DWARFDIE child = function_die.GetFirstChild(); child.IsValid();
3788        child = child.GetSibling()) {
3789     if (child.Tag() != DW_TAG_call_site)
3790       continue;
3791 
3792     llvm::Optional<DWARFDIE> call_origin;
3793     llvm::Optional<DWARFExpression> call_target;
3794     addr_t return_pc = LLDB_INVALID_ADDRESS;
3795 
3796     DWARFAttributes attributes;
3797     const size_t num_attributes = child.GetAttributes(attributes);
3798     for (size_t i = 0; i < num_attributes; ++i) {
3799       DWARFFormValue form_value;
3800       if (!attributes.ExtractFormValueAtIndex(i, form_value)) {
3801         LLDB_LOG(log, "CollectCallEdges: Could not extract TAG_call_site form");
3802         break;
3803       }
3804 
3805       dw_attr_t attr = attributes.AttributeAtIndex(i);
3806 
3807       // Extract DW_AT_call_origin (the call target's DIE).
3808       if (attr == DW_AT_call_origin) {
3809         call_origin = form_value.Reference();
3810         if (!call_origin->IsValid()) {
3811           LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}",
3812                    function_die.GetPubname());
3813           break;
3814         }
3815       }
3816 
3817       // Extract DW_AT_call_return_pc (the PC the call returns to) if it's
3818       // available. It should only ever be unavailable for tail call edges, in
3819       // which case use LLDB_INVALID_ADDRESS.
3820       if (attr == DW_AT_call_return_pc)
3821         return_pc = form_value.Address();
3822 
3823       // Extract DW_AT_call_target (the location of the address of the indirect
3824       // call).
3825       if (attr == DW_AT_call_target) {
3826         if (!DWARFFormValue::IsBlockForm(form_value.Form())) {
3827           LLDB_LOG(log,
3828                    "CollectCallEdges: AT_call_target does not have block form");
3829           break;
3830         }
3831 
3832         auto data = child.GetData();
3833         uint32_t block_offset = form_value.BlockData() - data.GetDataStart();
3834         uint32_t block_length = form_value.Unsigned();
3835         call_target = DWARFExpression(
3836             module, DataExtractor(data, block_offset, block_length),
3837             child.GetCU());
3838       }
3839     }
3840     if (!call_origin && !call_target) {
3841       LLDB_LOG(log, "CollectCallEdges: call site without any call target");
3842       continue;
3843     }
3844 
3845     // Adjust the return PC. It needs to be fixed up if the main executable
3846     // contains a debug map (i.e. pointers to object files), because we need a
3847     // file address relative to the executable's text section.
3848     return_pc = FixupAddress(return_pc);
3849 
3850     // Extract call site parameters.
3851     CallSiteParameterArray parameters =
3852         CollectCallSiteParameters(module, child);
3853 
3854     std::unique_ptr<CallEdge> edge;
3855     if (call_origin) {
3856       LLDB_LOG(log, "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x})",
3857                call_origin->GetPubname(), return_pc);
3858       edge = std::make_unique<DirectCallEdge>(call_origin->GetMangledName(),
3859                                               return_pc, std::move(parameters));
3860     } else {
3861       if (log) {
3862         StreamString call_target_desc;
3863         call_target->GetDescription(&call_target_desc, eDescriptionLevelBrief,
3864                                     LLDB_INVALID_ADDRESS, nullptr);
3865         LLDB_LOG(log, "CollectCallEdges: Found indirect call target: {0}",
3866                  call_target_desc.GetString());
3867       }
3868       edge = std::make_unique<IndirectCallEdge>(*call_target, return_pc,
3869                                                 std::move(parameters));
3870     }
3871 
3872     if (log && parameters.size()) {
3873       for (const CallSiteParameter &param : parameters) {
3874         StreamString callee_loc_desc, caller_loc_desc;
3875         param.LocationInCallee.GetDescription(&callee_loc_desc,
3876                                               eDescriptionLevelBrief,
3877                                               LLDB_INVALID_ADDRESS, nullptr);
3878         param.LocationInCaller.GetDescription(&caller_loc_desc,
3879                                               eDescriptionLevelBrief,
3880                                               LLDB_INVALID_ADDRESS, nullptr);
3881         LLDB_LOG(log, "CollectCallEdges: \tparam: {0} => {1}",
3882                  callee_loc_desc.GetString(), caller_loc_desc.GetString());
3883       }
3884     }
3885 
3886     call_edges.push_back(std::move(edge));
3887   }
3888   return call_edges;
3889 }
3890 
3891 std::vector<std::unique_ptr<lldb_private::CallEdge>>
3892 SymbolFileDWARF::ParseCallEdgesInFunction(UserID func_id) {
3893   DWARFDIE func_die = GetDIE(func_id.GetID());
3894   if (func_die.IsValid())
3895     return CollectCallEdges(GetObjectFile()->GetModule(), func_die);
3896   return {};
3897 }
3898 
3899 // PluginInterface protocol
3900 ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); }
3901 
3902 uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; }
3903 
3904 void SymbolFileDWARF::Dump(lldb_private::Stream &s) {
3905   SymbolFile::Dump(s);
3906   m_index->Dump(s);
3907 }
3908 
3909 void SymbolFileDWARF::DumpClangAST(Stream &s) {
3910   auto ts_or_err = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
3911   if (!ts_or_err)
3912     return;
3913   TypeSystemClang *clang =
3914       llvm::dyn_cast_or_null<TypeSystemClang>(&ts_or_err.get());
3915   if (!clang)
3916     return;
3917   clang->Dump(s);
3918 }
3919 
3920 SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() {
3921   if (m_debug_map_symfile == nullptr && !m_debug_map_module_wp.expired()) {
3922     lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
3923     if (module_sp) {
3924       m_debug_map_symfile =
3925           (SymbolFileDWARFDebugMap *)module_sp->GetSymbolFile();
3926     }
3927   }
3928   return m_debug_map_symfile;
3929 }
3930 
3931 void SymbolFileDWARF::FindDwpSymbolFile() {
3932   llvm::call_once(m_dwp_symfile_once_flag, [this]() {
3933     ModuleSpec module_spec;
3934     module_spec.GetFileSpec() = m_objfile_sp->GetFileSpec();
3935     module_spec.GetSymbolFileSpec() =
3936         FileSpec(m_objfile_sp->GetFileSpec().GetPath() + ".dwp");
3937 
3938     FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths();
3939     FileSpec dwp_filespec =
3940         Symbols::LocateExecutableSymbolFile(module_spec, search_paths);
3941     if (FileSystem::Instance().Exists(dwp_filespec)) {
3942       DataBufferSP dwp_file_data_sp;
3943       lldb::offset_t dwp_file_data_offset = 0;
3944       ObjectFileSP dwp_obj_file = ObjectFile::FindPlugin(
3945           GetObjectFile()->GetModule(), &dwp_filespec, 0,
3946           FileSystem::Instance().GetByteSize(dwp_filespec), dwp_file_data_sp,
3947           dwp_file_data_offset);
3948       if (!dwp_obj_file)
3949         return;
3950       m_dwp_symfile =
3951           std::make_shared<SymbolFileDWARFDwo>(*this, dwp_obj_file, 0x3fffffff);
3952     }
3953   });
3954 }
3955 
3956 llvm::Expected<TypeSystem &> SymbolFileDWARF::GetTypeSystem(DWARFUnit &unit) {
3957   return unit.GetSymbolFileDWARF().GetTypeSystemForLanguage(GetLanguage(unit));
3958 }
3959 
3960 DWARFASTParser *SymbolFileDWARF::GetDWARFParser(DWARFUnit &unit) {
3961   auto type_system_or_err = GetTypeSystem(unit);
3962   if (auto err = type_system_or_err.takeError()) {
3963     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
3964                    std::move(err), "Unable to get DWARFASTParser");
3965     return nullptr;
3966   }
3967   return type_system_or_err->GetDWARFParser();
3968 }
3969 
3970 CompilerDecl SymbolFileDWARF::GetDecl(const DWARFDIE &die) {
3971   if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()))
3972     return dwarf_ast->GetDeclForUIDFromDWARF(die);
3973   return CompilerDecl();
3974 }
3975 
3976 CompilerDeclContext SymbolFileDWARF::GetDeclContext(const DWARFDIE &die) {
3977   if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()))
3978     return dwarf_ast->GetDeclContextForUIDFromDWARF(die);
3979   return CompilerDeclContext();
3980 }
3981 
3982 CompilerDeclContext
3983 SymbolFileDWARF::GetContainingDeclContext(const DWARFDIE &die) {
3984   if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()))
3985     return dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
3986   return CompilerDeclContext();
3987 }
3988 
3989 DWARFDeclContext SymbolFileDWARF::GetDWARFDeclContext(const DWARFDIE &die) {
3990   if (!die.IsValid())
3991     return {};
3992   DWARFDeclContext dwarf_decl_ctx =
3993       die.GetDIE()->GetDWARFDeclContext(die.GetCU());
3994   dwarf_decl_ctx.SetLanguage(GetLanguage(*die.GetCU()));
3995   return dwarf_decl_ctx;
3996 }
3997 
3998 LanguageType SymbolFileDWARF::LanguageTypeFromDWARF(uint64_t val) {
3999   // Note: user languages between lo_user and hi_user must be handled
4000   // explicitly here.
4001   switch (val) {
4002   case DW_LANG_Mips_Assembler:
4003     return eLanguageTypeMipsAssembler;
4004   case DW_LANG_GOOGLE_RenderScript:
4005     return eLanguageTypeExtRenderScript;
4006   default:
4007     return static_cast<LanguageType>(val);
4008   }
4009 }
4010 
4011 LanguageType SymbolFileDWARF::GetLanguage(DWARFUnit &unit) {
4012   return LanguageTypeFromDWARF(unit.GetDWARFLanguageType());
4013 }
4014