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