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