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