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