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