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