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