1 //===-- SymbolFilePDB.cpp ---------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "SymbolFilePDB.h"
11 
12 #include "PDBASTParser.h"
13 #include "PDBLocationToDWARFExpression.h"
14 
15 #include "clang/Lex/Lexer.h"
16 
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Symbol/ClangASTContext.h"
20 #include "lldb/Symbol/CompileUnit.h"
21 #include "lldb/Symbol/LineTable.h"
22 #include "lldb/Symbol/ObjectFile.h"
23 #include "lldb/Symbol/SymbolContext.h"
24 #include "lldb/Symbol/SymbolVendor.h"
25 #include "lldb/Symbol/TypeList.h"
26 #include "lldb/Symbol/TypeMap.h"
27 #include "lldb/Symbol/Variable.h"
28 #include "lldb/Utility/RegularExpression.h"
29 
30 #include "llvm/DebugInfo/PDB/GenericError.h"
31 #include "llvm/DebugInfo/PDB/IPDBDataStream.h"
32 #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
33 #include "llvm/DebugInfo/PDB/IPDBLineNumber.h"
34 #include "llvm/DebugInfo/PDB/IPDBSectionContrib.h"
35 #include "llvm/DebugInfo/PDB/IPDBSourceFile.h"
36 #include "llvm/DebugInfo/PDB/IPDBTable.h"
37 #include "llvm/DebugInfo/PDB/PDBSymbol.h"
38 #include "llvm/DebugInfo/PDB/PDBSymbolBlock.h"
39 #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
40 #include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h"
41 #include "llvm/DebugInfo/PDB/PDBSymbolData.h"
42 #include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
43 #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
44 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h"
45 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h"
46 #include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h"
47 #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
48 #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
49 #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
50 
51 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
52 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
53 #include "Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h"
54 
55 #include <regex>
56 
57 using namespace lldb;
58 using namespace lldb_private;
59 using namespace llvm::pdb;
60 
61 namespace {
62 lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
63   switch (lang) {
64   case PDB_Lang::Cpp:
65     return lldb::LanguageType::eLanguageTypeC_plus_plus;
66   case PDB_Lang::C:
67     return lldb::LanguageType::eLanguageTypeC;
68   default:
69     return lldb::LanguageType::eLanguageTypeUnknown;
70   }
71 }
72 
73 bool ShouldAddLine(uint32_t requested_line, uint32_t actual_line,
74                    uint32_t addr_length) {
75   return ((requested_line == 0 || actual_line == requested_line) &&
76           addr_length > 0);
77 }
78 } // namespace
79 
80 static bool ShouldUseNativeReader() {
81 #if !defined(_WIN32)
82   return true;
83 #endif
84   llvm::StringRef use_native = ::getenv("LLDB_USE_NATIVE_PDB_READER");
85   return use_native.equals_lower("on") || use_native.equals_lower("yes") ||
86          use_native.equals_lower("1") || use_native.equals_lower("true");
87 }
88 
89 void SymbolFilePDB::Initialize() {
90   if (ShouldUseNativeReader()) {
91     npdb::SymbolFileNativePDB::Initialize();
92   } else {
93     PluginManager::RegisterPlugin(GetPluginNameStatic(),
94                                   GetPluginDescriptionStatic(), CreateInstance,
95                                   DebuggerInitialize);
96   }
97 }
98 
99 void SymbolFilePDB::Terminate() {
100   if (ShouldUseNativeReader()) {
101     npdb::SymbolFileNativePDB::Terminate();
102   } else {
103     PluginManager::UnregisterPlugin(CreateInstance);
104   }
105 }
106 
107 void SymbolFilePDB::DebuggerInitialize(lldb_private::Debugger &debugger) {}
108 
109 lldb_private::ConstString SymbolFilePDB::GetPluginNameStatic() {
110   static ConstString g_name("pdb");
111   return g_name;
112 }
113 
114 const char *SymbolFilePDB::GetPluginDescriptionStatic() {
115   return "Microsoft PDB debug symbol file reader.";
116 }
117 
118 lldb_private::SymbolFile *
119 SymbolFilePDB::CreateInstance(lldb_private::ObjectFile *obj_file) {
120   return new SymbolFilePDB(obj_file);
121 }
122 
123 SymbolFilePDB::SymbolFilePDB(lldb_private::ObjectFile *object_file)
124     : SymbolFile(object_file), m_session_up(), m_global_scope_up(),
125       m_cached_compile_unit_count(0), m_tu_decl_ctx_up() {}
126 
127 SymbolFilePDB::~SymbolFilePDB() {}
128 
129 uint32_t SymbolFilePDB::CalculateAbilities() {
130   uint32_t abilities = 0;
131   if (!m_obj_file)
132     return 0;
133 
134   if (!m_session_up) {
135     // Lazily load and match the PDB file, but only do this once.
136     std::string exePath = m_obj_file->GetFileSpec().GetPath();
137     auto error = loadDataForEXE(PDB_ReaderType::DIA, llvm::StringRef(exePath),
138                                 m_session_up);
139     if (error) {
140       llvm::consumeError(std::move(error));
141       auto module_sp = m_obj_file->GetModule();
142       if (!module_sp)
143         return 0;
144       // See if any symbol file is specified through `--symfile` option.
145       FileSpec symfile = module_sp->GetSymbolFileFileSpec();
146       if (!symfile)
147         return 0;
148       error = loadDataForPDB(PDB_ReaderType::DIA,
149                              llvm::StringRef(symfile.GetPath()), m_session_up);
150       if (error) {
151         llvm::consumeError(std::move(error));
152         return 0;
153       }
154     }
155   }
156   if (!m_session_up)
157     return 0;
158 
159   auto enum_tables_up = m_session_up->getEnumTables();
160   if (!enum_tables_up)
161     return 0;
162   while (auto table_up = enum_tables_up->getNext()) {
163     if (table_up->getItemCount() == 0)
164       continue;
165     auto type = table_up->getTableType();
166     switch (type) {
167     case PDB_TableType::Symbols:
168       // This table represents a store of symbols with types listed in
169       // PDBSym_Type
170       abilities |= (CompileUnits | Functions | Blocks | GlobalVariables |
171                     LocalVariables | VariableTypes);
172       break;
173     case PDB_TableType::LineNumbers:
174       abilities |= LineTables;
175       break;
176     default:
177       break;
178     }
179   }
180   return abilities;
181 }
182 
183 void SymbolFilePDB::InitializeObject() {
184   lldb::addr_t obj_load_address = m_obj_file->GetFileOffset();
185   lldbassert(obj_load_address && obj_load_address != LLDB_INVALID_ADDRESS);
186   m_session_up->setLoadAddress(obj_load_address);
187   if (!m_global_scope_up)
188     m_global_scope_up = m_session_up->getGlobalScope();
189   lldbassert(m_global_scope_up.get());
190 
191   TypeSystem *type_system =
192       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
193   ClangASTContext *clang_type_system =
194       llvm::dyn_cast_or_null<ClangASTContext>(type_system);
195   lldbassert(clang_type_system);
196   m_tu_decl_ctx_up = llvm::make_unique<CompilerDeclContext>(
197       type_system, clang_type_system->GetTranslationUnitDecl());
198 }
199 
200 uint32_t SymbolFilePDB::GetNumCompileUnits() {
201   if (m_cached_compile_unit_count == 0) {
202     auto compilands = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
203     if (!compilands)
204       return 0;
205 
206     // The linker could link *.dll (compiland language = LINK), or import
207     // *.dll. For example, a compiland with name `Import:KERNEL32.dll` could be
208     // found as a child of the global scope (PDB executable). Usually, such
209     // compilands contain `thunk` symbols in which we are not interested for
210     // now. However we still count them in the compiland list. If we perform
211     // any compiland related activity, like finding symbols through
212     // llvm::pdb::IPDBSession methods, such compilands will all be searched
213     // automatically no matter whether we include them or not.
214     m_cached_compile_unit_count = compilands->getChildCount();
215 
216     // The linker can inject an additional "dummy" compilation unit into the
217     // PDB. Ignore this special compile unit for our purposes, if it is there.
218     // It is always the last one.
219     auto last_compiland_up =
220         compilands->getChildAtIndex(m_cached_compile_unit_count - 1);
221     lldbassert(last_compiland_up.get());
222     std::string name = last_compiland_up->getName();
223     if (name == "* Linker *")
224       --m_cached_compile_unit_count;
225   }
226   return m_cached_compile_unit_count;
227 }
228 
229 void SymbolFilePDB::GetCompileUnitIndex(
230     const llvm::pdb::PDBSymbolCompiland &pdb_compiland, uint32_t &index) {
231   auto results_up = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
232   if (!results_up)
233     return;
234   auto uid = pdb_compiland.getSymIndexId();
235   for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
236     auto compiland_up = results_up->getChildAtIndex(cu_idx);
237     if (!compiland_up)
238       continue;
239     if (compiland_up->getSymIndexId() == uid) {
240       index = cu_idx;
241       return;
242     }
243   }
244   index = UINT32_MAX;
245   return;
246 }
247 
248 std::unique_ptr<llvm::pdb::PDBSymbolCompiland>
249 SymbolFilePDB::GetPDBCompilandByUID(uint32_t uid) {
250   return m_session_up->getConcreteSymbolById<PDBSymbolCompiland>(uid);
251 }
252 
253 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitAtIndex(uint32_t index) {
254   if (index >= GetNumCompileUnits())
255     return CompUnitSP();
256 
257   // Assuming we always retrieve same compilands listed in same order through
258   // `PDBSymbolExe::findAllChildren` method, otherwise using `index` to get a
259   // compile unit makes no sense.
260   auto results = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
261   if (!results)
262     return CompUnitSP();
263   auto compiland_up = results->getChildAtIndex(index);
264   if (!compiland_up)
265     return CompUnitSP();
266   return ParseCompileUnitForUID(compiland_up->getSymIndexId(), index);
267 }
268 
269 lldb::LanguageType
270 SymbolFilePDB::ParseCompileUnitLanguage(const lldb_private::SymbolContext &sc) {
271   // What fields should I expect to be filled out on the SymbolContext?  Is it
272   // safe to assume that `sc.comp_unit` is valid?
273   if (!sc.comp_unit)
274     return lldb::eLanguageTypeUnknown;
275 
276   auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID());
277   if (!compiland_up)
278     return lldb::eLanguageTypeUnknown;
279   auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
280   if (!details)
281     return lldb::eLanguageTypeUnknown;
282   return TranslateLanguage(details->getLanguage());
283 }
284 
285 lldb_private::Function *SymbolFilePDB::ParseCompileUnitFunctionForPDBFunc(
286     const PDBSymbolFunc &pdb_func, const lldb_private::SymbolContext &sc) {
287   lldbassert(sc.comp_unit && sc.module_sp.get());
288 
289   auto file_vm_addr = pdb_func.getVirtualAddress();
290   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
291     return nullptr;
292 
293   auto func_length = pdb_func.getLength();
294   AddressRange func_range =
295       AddressRange(file_vm_addr, func_length, sc.module_sp->GetSectionList());
296   if (!func_range.GetBaseAddress().IsValid())
297     return nullptr;
298 
299   lldb_private::Type *func_type = ResolveTypeUID(pdb_func.getSymIndexId());
300   if (!func_type)
301     return nullptr;
302 
303   user_id_t func_type_uid = pdb_func.getSignatureId();
304 
305   Mangled mangled = GetMangledForPDBFunc(pdb_func);
306 
307   FunctionSP func_sp =
308       std::make_shared<Function>(sc.comp_unit, pdb_func.getSymIndexId(),
309                                  func_type_uid, mangled, func_type, func_range);
310 
311   sc.comp_unit->AddFunction(func_sp);
312   return func_sp.get();
313 }
314 
315 size_t SymbolFilePDB::ParseCompileUnitFunctions(
316     const lldb_private::SymbolContext &sc) {
317   lldbassert(sc.comp_unit);
318   size_t func_added = 0;
319   auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID());
320   if (!compiland_up)
321     return 0;
322   auto results_up = compiland_up->findAllChildren<PDBSymbolFunc>();
323   if (!results_up)
324     return 0;
325   while (auto pdb_func_up = results_up->getNext()) {
326     auto func_sp =
327         sc.comp_unit->FindFunctionByUID(pdb_func_up->getSymIndexId());
328     if (!func_sp) {
329       if (ParseCompileUnitFunctionForPDBFunc(*pdb_func_up, sc))
330         ++func_added;
331     }
332   }
333   return func_added;
334 }
335 
336 bool SymbolFilePDB::ParseCompileUnitLineTable(
337     const lldb_private::SymbolContext &sc) {
338   lldbassert(sc.comp_unit);
339   if (sc.comp_unit->GetLineTable())
340     return true;
341   return ParseCompileUnitLineTable(sc, 0);
342 }
343 
344 bool SymbolFilePDB::ParseCompileUnitDebugMacros(
345     const lldb_private::SymbolContext &sc) {
346   // PDB doesn't contain information about macros
347   return false;
348 }
349 
350 bool SymbolFilePDB::ParseCompileUnitSupportFiles(
351     const lldb_private::SymbolContext &sc,
352     lldb_private::FileSpecList &support_files) {
353   lldbassert(sc.comp_unit);
354 
355   // In theory this is unnecessary work for us, because all of this information
356   // is easily (and quickly) accessible from DebugInfoPDB, so caching it a
357   // second time seems like a waste.  Unfortunately, there's no good way around
358   // this short of a moderate refactor since SymbolVendor depends on being able
359   // to cache this list.
360   auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID());
361   if (!compiland_up)
362     return false;
363   auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
364   if (!files || files->getChildCount() == 0)
365     return false;
366 
367   while (auto file = files->getNext()) {
368     FileSpec spec(file->getFileName(), FileSpec::Style::windows);
369     support_files.AppendIfUnique(spec);
370   }
371 
372   // LLDB uses the DWARF-like file numeration (one based),
373   // the zeroth file is the compile unit itself
374   support_files.Insert(0, *sc.comp_unit);
375 
376   return true;
377 }
378 
379 bool SymbolFilePDB::ParseImportedModules(
380     const lldb_private::SymbolContext &sc,
381     std::vector<lldb_private::ConstString> &imported_modules) {
382   // PDB does not yet support module debug info
383   return false;
384 }
385 
386 static size_t ParseFunctionBlocksForPDBSymbol(
387     const lldb_private::SymbolContext &sc, uint64_t func_file_vm_addr,
388     const llvm::pdb::PDBSymbol *pdb_symbol, lldb_private::Block *parent_block,
389     bool is_top_parent) {
390   assert(pdb_symbol && parent_block);
391 
392   size_t num_added = 0;
393   switch (pdb_symbol->getSymTag()) {
394   case PDB_SymType::Block:
395   case PDB_SymType::Function: {
396     Block *block = nullptr;
397     auto &raw_sym = pdb_symbol->getRawSymbol();
398     if (auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(pdb_symbol)) {
399       if (pdb_func->hasNoInlineAttribute())
400         break;
401       if (is_top_parent)
402         block = parent_block;
403       else
404         break;
405     } else if (llvm::dyn_cast<PDBSymbolBlock>(pdb_symbol)) {
406       auto uid = pdb_symbol->getSymIndexId();
407       if (parent_block->FindBlockByID(uid))
408         break;
409       if (raw_sym.getVirtualAddress() < func_file_vm_addr)
410         break;
411 
412       auto block_sp = std::make_shared<Block>(pdb_symbol->getSymIndexId());
413       parent_block->AddChild(block_sp);
414       block = block_sp.get();
415     } else
416       llvm_unreachable("Unexpected PDB symbol!");
417 
418     block->AddRange(Block::Range(
419         raw_sym.getVirtualAddress() - func_file_vm_addr, raw_sym.getLength()));
420     block->FinalizeRanges();
421     ++num_added;
422 
423     auto results_up = pdb_symbol->findAllChildren();
424     if (!results_up)
425       break;
426     while (auto symbol_up = results_up->getNext()) {
427       num_added += ParseFunctionBlocksForPDBSymbol(
428           sc, func_file_vm_addr, symbol_up.get(), block, false);
429     }
430   } break;
431   default:
432     break;
433   }
434   return num_added;
435 }
436 
437 size_t
438 SymbolFilePDB::ParseFunctionBlocks(const lldb_private::SymbolContext &sc) {
439   lldbassert(sc.comp_unit && sc.function);
440   size_t num_added = 0;
441   auto uid = sc.function->GetID();
442   auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
443   if (!pdb_func_up)
444     return 0;
445   Block &parent_block = sc.function->GetBlock(false);
446   num_added =
447       ParseFunctionBlocksForPDBSymbol(sc, pdb_func_up->getVirtualAddress(),
448                                       pdb_func_up.get(), &parent_block, true);
449   return num_added;
450 }
451 
452 size_t SymbolFilePDB::ParseTypes(const lldb_private::SymbolContext &sc) {
453   lldbassert(sc.module_sp.get());
454   if (!sc.comp_unit)
455     return 0;
456 
457   size_t num_added = 0;
458   auto compiland = GetPDBCompilandByUID(sc.comp_unit->GetID());
459   if (!compiland)
460     return 0;
461 
462   auto ParseTypesByTagFn = [&num_added, this](const PDBSymbol &raw_sym) {
463     std::unique_ptr<IPDBEnumSymbols> results;
464     PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
465                                     PDB_SymType::UDT};
466     for (auto tag : tags_to_search) {
467       results = raw_sym.findAllChildren(tag);
468       if (!results || results->getChildCount() == 0)
469         continue;
470       while (auto symbol = results->getNext()) {
471         switch (symbol->getSymTag()) {
472         case PDB_SymType::Enum:
473         case PDB_SymType::UDT:
474         case PDB_SymType::Typedef:
475           break;
476         default:
477           continue;
478         }
479 
480         // This should cause the type to get cached and stored in the `m_types`
481         // lookup.
482         if (auto type = ResolveTypeUID(symbol->getSymIndexId())) {
483           // Resolve the type completely to avoid a completion
484           // (and so a list change, which causes an iterators invalidation)
485           // during a TypeList dumping
486           type->GetFullCompilerType();
487           ++num_added;
488         }
489       }
490     }
491   };
492 
493   if (sc.function) {
494     auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(
495         sc.function->GetID());
496     if (!pdb_func)
497       return 0;
498     ParseTypesByTagFn(*pdb_func);
499   } else {
500     ParseTypesByTagFn(*compiland);
501 
502     // Also parse global types particularly coming from this compiland.
503     // Unfortunately, PDB has no compiland information for each global type. We
504     // have to parse them all. But ensure we only do this once.
505     static bool parse_all_global_types = false;
506     if (!parse_all_global_types) {
507       ParseTypesByTagFn(*m_global_scope_up);
508       parse_all_global_types = true;
509     }
510   }
511   return num_added;
512 }
513 
514 size_t
515 SymbolFilePDB::ParseVariablesForContext(const lldb_private::SymbolContext &sc) {
516   if (!sc.comp_unit)
517     return 0;
518 
519   size_t num_added = 0;
520   if (sc.function) {
521     auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(
522         sc.function->GetID());
523     if (!pdb_func)
524       return 0;
525 
526     num_added += ParseVariables(sc, *pdb_func);
527     sc.function->GetBlock(false).SetDidParseVariables(true, true);
528   } else if (sc.comp_unit) {
529     auto compiland = GetPDBCompilandByUID(sc.comp_unit->GetID());
530     if (!compiland)
531       return 0;
532 
533     if (sc.comp_unit->GetVariableList(false))
534       return 0;
535 
536     auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
537     if (results && results->getChildCount()) {
538       while (auto result = results->getNext()) {
539         auto cu_id = GetCompilandId(*result);
540         // FIXME: We are not able to determine variable's compile unit.
541         if (cu_id == 0)
542           continue;
543 
544         if (cu_id == sc.comp_unit->GetID())
545           num_added += ParseVariables(sc, *result);
546       }
547     }
548 
549     // FIXME: A `file static` or `global constant` variable appears both in
550     // compiland's children and global scope's children with unexpectedly
551     // different symbol's Id making it ambiguous.
552 
553     // FIXME: 'local constant', for example, const char var[] = "abc", declared
554     // in a function scope, can't be found in PDB.
555 
556     // Parse variables in this compiland.
557     num_added += ParseVariables(sc, *compiland);
558   }
559 
560   return num_added;
561 }
562 
563 lldb_private::Type *SymbolFilePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
564   auto find_result = m_types.find(type_uid);
565   if (find_result != m_types.end())
566     return find_result->second.get();
567 
568   TypeSystem *type_system =
569       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
570   ClangASTContext *clang_type_system =
571       llvm::dyn_cast_or_null<ClangASTContext>(type_system);
572   if (!clang_type_system)
573     return nullptr;
574   PDBASTParser *pdb = clang_type_system->GetPDBParser();
575   if (!pdb)
576     return nullptr;
577 
578   auto pdb_type = m_session_up->getSymbolById(type_uid);
579   if (pdb_type == nullptr)
580     return nullptr;
581 
582   lldb::TypeSP result = pdb->CreateLLDBTypeFromPDBType(*pdb_type);
583   if (result) {
584     m_types.insert(std::make_pair(type_uid, result));
585     auto type_list = GetTypeList();
586     if (type_list)
587       type_list->Insert(result);
588   }
589   return result.get();
590 }
591 
592 llvm::Optional<SymbolFile::ArrayInfo> SymbolFilePDB::GetDynamicArrayInfoForUID(
593     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
594   return llvm::None;
595 }
596 
597 bool SymbolFilePDB::CompleteType(lldb_private::CompilerType &compiler_type) {
598   std::lock_guard<std::recursive_mutex> guard(
599       GetObjectFile()->GetModule()->GetMutex());
600 
601   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
602       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
603   if (!clang_ast_ctx)
604     return false;
605 
606   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
607   if (!pdb)
608     return false;
609 
610   return pdb->CompleteTypeFromPDB(compiler_type);
611 }
612 
613 lldb_private::CompilerDecl SymbolFilePDB::GetDeclForUID(lldb::user_id_t uid) {
614   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
615       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
616   if (!clang_ast_ctx)
617     return CompilerDecl();
618 
619   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
620   if (!pdb)
621     return CompilerDecl();
622 
623   auto symbol = m_session_up->getSymbolById(uid);
624   if (!symbol)
625     return CompilerDecl();
626 
627   auto decl = pdb->GetDeclForSymbol(*symbol);
628   if (!decl)
629     return CompilerDecl();
630 
631   return CompilerDecl(clang_ast_ctx, decl);
632 }
633 
634 lldb_private::CompilerDeclContext
635 SymbolFilePDB::GetDeclContextForUID(lldb::user_id_t uid) {
636   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
637       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
638   if (!clang_ast_ctx)
639     return CompilerDeclContext();
640 
641   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
642   if (!pdb)
643     return CompilerDeclContext();
644 
645   auto symbol = m_session_up->getSymbolById(uid);
646   if (!symbol)
647     return CompilerDeclContext();
648 
649   auto decl_context = pdb->GetDeclContextForSymbol(*symbol);
650   if (!decl_context)
651     return GetDeclContextContainingUID(uid);
652 
653   return CompilerDeclContext(clang_ast_ctx, decl_context);
654 }
655 
656 lldb_private::CompilerDeclContext
657 SymbolFilePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
658   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
659       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
660   if (!clang_ast_ctx)
661     return CompilerDeclContext();
662 
663   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
664   if (!pdb)
665     return CompilerDeclContext();
666 
667   auto symbol = m_session_up->getSymbolById(uid);
668   if (!symbol)
669     return CompilerDeclContext();
670 
671   auto decl_context = pdb->GetDeclContextContainingSymbol(*symbol);
672   assert(decl_context);
673 
674   return CompilerDeclContext(clang_ast_ctx, decl_context);
675 }
676 
677 void SymbolFilePDB::ParseDeclsForContext(
678     lldb_private::CompilerDeclContext decl_ctx) {
679   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
680       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
681   if (!clang_ast_ctx)
682     return;
683 
684   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
685   if (!pdb)
686     return;
687 
688   pdb->ParseDeclsForDeclContext(
689       static_cast<clang::DeclContext *>(decl_ctx.GetOpaqueDeclContext()));
690 }
691 
692 uint32_t
693 SymbolFilePDB::ResolveSymbolContext(const lldb_private::Address &so_addr,
694                                     SymbolContextItem resolve_scope,
695                                     lldb_private::SymbolContext &sc) {
696   uint32_t resolved_flags = 0;
697   if (resolve_scope & eSymbolContextCompUnit ||
698       resolve_scope & eSymbolContextVariable ||
699       resolve_scope & eSymbolContextFunction ||
700       resolve_scope & eSymbolContextBlock ||
701       resolve_scope & eSymbolContextLineEntry) {
702     auto cu_sp = GetCompileUnitContainsAddress(so_addr);
703     if (!cu_sp) {
704       if (resolved_flags | eSymbolContextVariable) {
705         // TODO: Resolve variables
706       }
707       return 0;
708     }
709     sc.comp_unit = cu_sp.get();
710     resolved_flags |= eSymbolContextCompUnit;
711     lldbassert(sc.module_sp == cu_sp->GetModule());
712   }
713 
714   if (resolve_scope & eSymbolContextFunction ||
715       resolve_scope & eSymbolContextBlock) {
716     addr_t file_vm_addr = so_addr.GetFileAddress();
717     auto symbol_up =
718         m_session_up->findSymbolByAddress(file_vm_addr, PDB_SymType::Function);
719     if (symbol_up) {
720       auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
721       assert(pdb_func);
722       auto func_uid = pdb_func->getSymIndexId();
723       sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
724       if (sc.function == nullptr)
725         sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func, sc);
726       if (sc.function) {
727         resolved_flags |= eSymbolContextFunction;
728         if (resolve_scope & eSymbolContextBlock) {
729           auto block_symbol = m_session_up->findSymbolByAddress(
730               file_vm_addr, PDB_SymType::Block);
731           auto block_id = block_symbol ? block_symbol->getSymIndexId()
732                                        : sc.function->GetID();
733           sc.block = sc.function->GetBlock(true).FindBlockByID(block_id);
734           if (sc.block)
735             resolved_flags |= eSymbolContextBlock;
736         }
737       }
738     }
739   }
740 
741   if (resolve_scope & eSymbolContextLineEntry) {
742     if (auto *line_table = sc.comp_unit->GetLineTable()) {
743       Address addr(so_addr);
744       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
745         resolved_flags |= eSymbolContextLineEntry;
746     }
747   }
748 
749   return resolved_flags;
750 }
751 
752 uint32_t SymbolFilePDB::ResolveSymbolContext(
753     const lldb_private::FileSpec &file_spec, uint32_t line, bool check_inlines,
754     SymbolContextItem resolve_scope, lldb_private::SymbolContextList &sc_list) {
755   const size_t old_size = sc_list.GetSize();
756   if (resolve_scope & lldb::eSymbolContextCompUnit) {
757     // Locate all compilation units with line numbers referencing the specified
758     // file.  For example, if `file_spec` is <vector>, then this should return
759     // all source files and header files that reference <vector>, either
760     // directly or indirectly.
761     auto compilands = m_session_up->findCompilandsForSourceFile(
762         file_spec.GetPath(), PDB_NameSearchFlags::NS_CaseInsensitive);
763 
764     if (!compilands)
765       return 0;
766 
767     // For each one, either find its previously parsed data or parse it afresh
768     // and add it to the symbol context list.
769     while (auto compiland = compilands->getNext()) {
770       // If we're not checking inlines, then don't add line information for
771       // this file unless the FileSpec matches. For inline functions, we don't
772       // have to match the FileSpec since they could be defined in headers
773       // other than file specified in FileSpec.
774       if (!check_inlines) {
775         std::string source_file = compiland->getSourceFileFullPath();
776         if (source_file.empty())
777           continue;
778         FileSpec this_spec(source_file, FileSpec::Style::windows);
779         bool need_full_match = !file_spec.GetDirectory().IsEmpty();
780         if (FileSpec::Compare(file_spec, this_spec, need_full_match) != 0)
781           continue;
782       }
783 
784       SymbolContext sc;
785       auto cu = ParseCompileUnitForUID(compiland->getSymIndexId());
786       if (!cu)
787         continue;
788       sc.comp_unit = cu.get();
789       sc.module_sp = cu->GetModule();
790 
791       // If we were asked to resolve line entries, add all entries to the line
792       // table that match the requested line (or all lines if `line` == 0).
793       if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock |
794                            eSymbolContextLineEntry)) {
795         bool has_line_table = ParseCompileUnitLineTable(sc, line);
796 
797         if ((resolve_scope & eSymbolContextLineEntry) && !has_line_table) {
798           // The query asks for line entries, but we can't get them for the
799           // compile unit. This is not normal for `line` = 0. So just assert
800           // it.
801           assert(line && "Couldn't get all line entries!\n");
802 
803           // Current compiland does not have the requested line. Search next.
804           continue;
805         }
806 
807         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) {
808           if (!has_line_table)
809             continue;
810 
811           auto *line_table = sc.comp_unit->GetLineTable();
812           lldbassert(line_table);
813 
814           uint32_t num_line_entries = line_table->GetSize();
815           // Skip the terminal line entry.
816           --num_line_entries;
817 
818           // If `line `!= 0, see if we can resolve function for each line entry
819           // in the line table.
820           for (uint32_t line_idx = 0; line && line_idx < num_line_entries;
821                ++line_idx) {
822             if (!line_table->GetLineEntryAtIndex(line_idx, sc.line_entry))
823               continue;
824 
825             auto file_vm_addr =
826                 sc.line_entry.range.GetBaseAddress().GetFileAddress();
827             if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
828               continue;
829 
830             auto symbol_up = m_session_up->findSymbolByAddress(
831                 file_vm_addr, PDB_SymType::Function);
832             if (symbol_up) {
833               auto func_uid = symbol_up->getSymIndexId();
834               sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
835               if (sc.function == nullptr) {
836                 auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
837                 assert(pdb_func);
838                 sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func, sc);
839               }
840               if (sc.function && (resolve_scope & eSymbolContextBlock)) {
841                 Block &block = sc.function->GetBlock(true);
842                 sc.block = block.FindBlockByID(sc.function->GetID());
843               }
844             }
845             sc_list.Append(sc);
846           }
847         } else if (has_line_table) {
848           // We can parse line table for the compile unit. But no query to
849           // resolve function or block. We append `sc` to the list anyway.
850           sc_list.Append(sc);
851         }
852       } else {
853         // No query for line entry, function or block. But we have a valid
854         // compile unit, append `sc` to the list.
855         sc_list.Append(sc);
856       }
857     }
858   }
859   return sc_list.GetSize() - old_size;
860 }
861 
862 std::string SymbolFilePDB::GetMangledForPDBData(const PDBSymbolData &pdb_data) {
863   // Cache public names at first
864   if (m_public_names.empty())
865     if (auto result_up =
866             m_global_scope_up->findAllChildren(PDB_SymType::PublicSymbol))
867       while (auto symbol_up = result_up->getNext())
868         if (auto addr = symbol_up->getRawSymbol().getVirtualAddress())
869           m_public_names[addr] = symbol_up->getRawSymbol().getName();
870 
871   // Look up the name in the cache
872   return m_public_names.lookup(pdb_data.getVirtualAddress());
873 }
874 
875 VariableSP SymbolFilePDB::ParseVariableForPDBData(
876     const lldb_private::SymbolContext &sc,
877     const llvm::pdb::PDBSymbolData &pdb_data) {
878   VariableSP var_sp;
879   uint32_t var_uid = pdb_data.getSymIndexId();
880   auto result = m_variables.find(var_uid);
881   if (result != m_variables.end())
882     return result->second;
883 
884   ValueType scope = eValueTypeInvalid;
885   bool is_static_member = false;
886   bool is_external = false;
887   bool is_artificial = false;
888 
889   switch (pdb_data.getDataKind()) {
890   case PDB_DataKind::Global:
891     scope = eValueTypeVariableGlobal;
892     is_external = true;
893     break;
894   case PDB_DataKind::Local:
895     scope = eValueTypeVariableLocal;
896     break;
897   case PDB_DataKind::FileStatic:
898     scope = eValueTypeVariableStatic;
899     break;
900   case PDB_DataKind::StaticMember:
901     is_static_member = true;
902     scope = eValueTypeVariableStatic;
903     break;
904   case PDB_DataKind::Member:
905     scope = eValueTypeVariableStatic;
906     break;
907   case PDB_DataKind::Param:
908     scope = eValueTypeVariableArgument;
909     break;
910   case PDB_DataKind::Constant:
911     scope = eValueTypeConstResult;
912     break;
913   default:
914     break;
915   }
916 
917   switch (pdb_data.getLocationType()) {
918   case PDB_LocType::TLS:
919     scope = eValueTypeVariableThreadLocal;
920     break;
921   case PDB_LocType::RegRel: {
922     // It is a `this` pointer.
923     if (pdb_data.getDataKind() == PDB_DataKind::ObjectPtr) {
924       scope = eValueTypeVariableArgument;
925       is_artificial = true;
926     }
927   } break;
928   default:
929     break;
930   }
931 
932   Declaration decl;
933   if (!is_artificial && !pdb_data.isCompilerGenerated()) {
934     if (auto lines = pdb_data.getLineNumbers()) {
935       if (auto first_line = lines->getNext()) {
936         uint32_t src_file_id = first_line->getSourceFileId();
937         auto src_file = m_session_up->getSourceFileById(src_file_id);
938         if (src_file) {
939           FileSpec spec(src_file->getFileName());
940           decl.SetFile(spec);
941           decl.SetColumn(first_line->getColumnNumber());
942           decl.SetLine(first_line->getLineNumber());
943         }
944       }
945     }
946   }
947 
948   Variable::RangeList ranges;
949   SymbolContextScope *context_scope = sc.comp_unit;
950   if (scope == eValueTypeVariableLocal) {
951     if (sc.function) {
952       context_scope = sc.function->GetBlock(true).FindBlockByID(
953           pdb_data.getLexicalParentId());
954       if (context_scope == nullptr)
955         context_scope = sc.function;
956     }
957   }
958 
959   SymbolFileTypeSP type_sp =
960       std::make_shared<SymbolFileType>(*this, pdb_data.getTypeId());
961 
962   auto var_name = pdb_data.getName();
963   auto mangled = GetMangledForPDBData(pdb_data);
964   auto mangled_cstr = mangled.empty() ? nullptr : mangled.c_str();
965 
966   bool is_constant;
967   DWARFExpression location = ConvertPDBLocationToDWARFExpression(
968       GetObjectFile()->GetModule(), pdb_data, is_constant);
969 
970   var_sp = std::make_shared<Variable>(
971       var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope,
972       ranges, &decl, location, is_external, is_artificial, is_static_member);
973   var_sp->SetLocationIsConstantValueData(is_constant);
974 
975   m_variables.insert(std::make_pair(var_uid, var_sp));
976   return var_sp;
977 }
978 
979 size_t
980 SymbolFilePDB::ParseVariables(const lldb_private::SymbolContext &sc,
981                               const llvm::pdb::PDBSymbol &pdb_symbol,
982                               lldb_private::VariableList *variable_list) {
983   size_t num_added = 0;
984 
985   if (auto pdb_data = llvm::dyn_cast<PDBSymbolData>(&pdb_symbol)) {
986     VariableListSP local_variable_list_sp;
987 
988     auto result = m_variables.find(pdb_data->getSymIndexId());
989     if (result != m_variables.end()) {
990       if (variable_list)
991         variable_list->AddVariableIfUnique(result->second);
992     } else {
993       // Prepare right VariableList for this variable.
994       if (auto lexical_parent = pdb_data->getLexicalParent()) {
995         switch (lexical_parent->getSymTag()) {
996         case PDB_SymType::Exe:
997           assert(sc.comp_unit);
998           LLVM_FALLTHROUGH;
999         case PDB_SymType::Compiland: {
1000           if (sc.comp_unit) {
1001             local_variable_list_sp = sc.comp_unit->GetVariableList(false);
1002             if (!local_variable_list_sp) {
1003               local_variable_list_sp = std::make_shared<VariableList>();
1004               sc.comp_unit->SetVariableList(local_variable_list_sp);
1005             }
1006           }
1007         } break;
1008         case PDB_SymType::Block:
1009         case PDB_SymType::Function: {
1010           if (sc.function) {
1011             Block *block = sc.function->GetBlock(true).FindBlockByID(
1012                 lexical_parent->getSymIndexId());
1013             if (block) {
1014               local_variable_list_sp = block->GetBlockVariableList(false);
1015               if (!local_variable_list_sp) {
1016                 local_variable_list_sp = std::make_shared<VariableList>();
1017                 block->SetVariableList(local_variable_list_sp);
1018               }
1019             }
1020           }
1021         } break;
1022         default:
1023           break;
1024         }
1025       }
1026 
1027       if (local_variable_list_sp) {
1028         if (auto var_sp = ParseVariableForPDBData(sc, *pdb_data)) {
1029           local_variable_list_sp->AddVariableIfUnique(var_sp);
1030           if (variable_list)
1031             variable_list->AddVariableIfUnique(var_sp);
1032           ++num_added;
1033         }
1034       }
1035     }
1036   }
1037 
1038   if (auto results = pdb_symbol.findAllChildren()) {
1039     while (auto result = results->getNext())
1040       num_added += ParseVariables(sc, *result, variable_list);
1041   }
1042 
1043   return num_added;
1044 }
1045 
1046 uint32_t SymbolFilePDB::FindGlobalVariables(
1047     const lldb_private::ConstString &name,
1048     const lldb_private::CompilerDeclContext *parent_decl_ctx,
1049     uint32_t max_matches, lldb_private::VariableList &variables) {
1050   if (!parent_decl_ctx)
1051     parent_decl_ctx = m_tu_decl_ctx_up.get();
1052   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1053     return 0;
1054   if (name.IsEmpty())
1055     return 0;
1056 
1057   auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1058   if (!results)
1059     return 0;
1060 
1061   uint32_t matches = 0;
1062   size_t old_size = variables.GetSize();
1063   while (auto result = results->getNext()) {
1064     auto pdb_data = llvm::dyn_cast<PDBSymbolData>(result.get());
1065     if (max_matches > 0 && matches >= max_matches)
1066       break;
1067 
1068     SymbolContext sc;
1069     sc.module_sp = m_obj_file->GetModule();
1070     lldbassert(sc.module_sp.get());
1071 
1072     if (!name.GetStringRef().equals(
1073             MSVCUndecoratedNameParser::DropScope(pdb_data->getName())))
1074       continue;
1075 
1076     sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1077     // FIXME: We are not able to determine the compile unit.
1078     if (sc.comp_unit == nullptr)
1079       continue;
1080 
1081     auto actual_parent_decl_ctx =
1082         GetDeclContextContainingUID(result->getSymIndexId());
1083     if (actual_parent_decl_ctx != *parent_decl_ctx)
1084       continue;
1085 
1086     ParseVariables(sc, *pdb_data, &variables);
1087     matches = variables.GetSize() - old_size;
1088   }
1089 
1090   return matches;
1091 }
1092 
1093 uint32_t
1094 SymbolFilePDB::FindGlobalVariables(const lldb_private::RegularExpression &regex,
1095                                    uint32_t max_matches,
1096                                    lldb_private::VariableList &variables) {
1097   if (!regex.IsValid())
1098     return 0;
1099   auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1100   if (!results)
1101     return 0;
1102 
1103   uint32_t matches = 0;
1104   size_t old_size = variables.GetSize();
1105   while (auto pdb_data = results->getNext()) {
1106     if (max_matches > 0 && matches >= max_matches)
1107       break;
1108 
1109     auto var_name = pdb_data->getName();
1110     if (var_name.empty())
1111       continue;
1112     if (!regex.Execute(var_name))
1113       continue;
1114     SymbolContext sc;
1115     sc.module_sp = m_obj_file->GetModule();
1116     lldbassert(sc.module_sp.get());
1117 
1118     sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1119     // FIXME: We are not able to determine the compile unit.
1120     if (sc.comp_unit == nullptr)
1121       continue;
1122 
1123     ParseVariables(sc, *pdb_data, &variables);
1124     matches = variables.GetSize() - old_size;
1125   }
1126 
1127   return matches;
1128 }
1129 
1130 bool SymbolFilePDB::ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func,
1131                                     bool include_inlines,
1132                                     lldb_private::SymbolContextList &sc_list) {
1133   lldb_private::SymbolContext sc;
1134   sc.comp_unit = ParseCompileUnitForUID(pdb_func.getCompilandId()).get();
1135   if (!sc.comp_unit)
1136     return false;
1137   sc.module_sp = sc.comp_unit->GetModule();
1138   sc.function = ParseCompileUnitFunctionForPDBFunc(pdb_func, sc);
1139   if (!sc.function)
1140     return false;
1141 
1142   sc_list.Append(sc);
1143   return true;
1144 }
1145 
1146 bool SymbolFilePDB::ResolveFunction(uint32_t uid, bool include_inlines,
1147                                     lldb_private::SymbolContextList &sc_list) {
1148   auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
1149   if (!pdb_func_up && !(include_inlines && pdb_func_up->hasInlineAttribute()))
1150     return false;
1151   return ResolveFunction(*pdb_func_up, include_inlines, sc_list);
1152 }
1153 
1154 void SymbolFilePDB::CacheFunctionNames() {
1155   if (!m_func_full_names.IsEmpty())
1156     return;
1157 
1158   std::map<uint64_t, uint32_t> addr_ids;
1159 
1160   if (auto results_up = m_global_scope_up->findAllChildren<PDBSymbolFunc>()) {
1161     while (auto pdb_func_up = results_up->getNext()) {
1162       if (pdb_func_up->isCompilerGenerated())
1163         continue;
1164 
1165       auto name = pdb_func_up->getName();
1166       auto demangled_name = pdb_func_up->getUndecoratedName();
1167       if (name.empty() && demangled_name.empty())
1168         continue;
1169 
1170       auto uid = pdb_func_up->getSymIndexId();
1171       if (!demangled_name.empty() && pdb_func_up->getVirtualAddress())
1172         addr_ids.insert(std::make_pair(pdb_func_up->getVirtualAddress(), uid));
1173 
1174       if (auto parent = pdb_func_up->getClassParent()) {
1175 
1176         // PDB have symbols for class/struct methods or static methods in Enum
1177         // Class. We won't bother to check if the parent is UDT or Enum here.
1178         m_func_method_names.Append(ConstString(name), uid);
1179 
1180         // To search a method name, like NS::Class:MemberFunc, LLDB searches
1181         // its base name, i.e. MemberFunc by default. Since PDBSymbolFunc does
1182         // not have inforamtion of this, we extract base names and cache them
1183         // by our own effort.
1184         llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);
1185         if (!basename.empty())
1186           m_func_base_names.Append(ConstString(basename), uid);
1187         else {
1188           m_func_base_names.Append(ConstString(name), uid);
1189         }
1190 
1191         if (!demangled_name.empty())
1192           m_func_full_names.Append(ConstString(demangled_name), uid);
1193 
1194       } else {
1195         // Handle not-method symbols.
1196 
1197         // The function name might contain namespace, or its lexical scope.
1198         llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);
1199         if (!basename.empty())
1200           m_func_base_names.Append(ConstString(basename), uid);
1201         else
1202           m_func_base_names.Append(ConstString(name), uid);
1203 
1204         if (name == "main") {
1205           m_func_full_names.Append(ConstString(name), uid);
1206 
1207           if (!demangled_name.empty() && name != demangled_name) {
1208             m_func_full_names.Append(ConstString(demangled_name), uid);
1209             m_func_base_names.Append(ConstString(demangled_name), uid);
1210           }
1211         } else if (!demangled_name.empty()) {
1212           m_func_full_names.Append(ConstString(demangled_name), uid);
1213         } else {
1214           m_func_full_names.Append(ConstString(name), uid);
1215         }
1216       }
1217     }
1218   }
1219 
1220   if (auto results_up =
1221           m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>()) {
1222     while (auto pub_sym_up = results_up->getNext()) {
1223       if (!pub_sym_up->isFunction())
1224         continue;
1225       auto name = pub_sym_up->getName();
1226       if (name.empty())
1227         continue;
1228 
1229       if (CPlusPlusLanguage::IsCPPMangledName(name.c_str())) {
1230         auto vm_addr = pub_sym_up->getVirtualAddress();
1231 
1232         // PDB public symbol has mangled name for its associated function.
1233         if (vm_addr && addr_ids.find(vm_addr) != addr_ids.end()) {
1234           // Cache mangled name.
1235           m_func_full_names.Append(ConstString(name), addr_ids[vm_addr]);
1236         }
1237       }
1238     }
1239   }
1240   // Sort them before value searching is working properly
1241   m_func_full_names.Sort();
1242   m_func_full_names.SizeToFit();
1243   m_func_method_names.Sort();
1244   m_func_method_names.SizeToFit();
1245   m_func_base_names.Sort();
1246   m_func_base_names.SizeToFit();
1247 }
1248 
1249 uint32_t SymbolFilePDB::FindFunctions(
1250     const lldb_private::ConstString &name,
1251     const lldb_private::CompilerDeclContext *parent_decl_ctx,
1252     FunctionNameType name_type_mask, bool include_inlines, bool append,
1253     lldb_private::SymbolContextList &sc_list) {
1254   if (!append)
1255     sc_list.Clear();
1256   lldbassert((name_type_mask & eFunctionNameTypeAuto) == 0);
1257 
1258   if (name_type_mask == eFunctionNameTypeNone)
1259     return 0;
1260   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1261     return 0;
1262   if (name.IsEmpty())
1263     return 0;
1264 
1265   auto old_size = sc_list.GetSize();
1266   if (name_type_mask & eFunctionNameTypeFull ||
1267       name_type_mask & eFunctionNameTypeBase ||
1268       name_type_mask & eFunctionNameTypeMethod) {
1269     CacheFunctionNames();
1270 
1271     std::set<uint32_t> resolved_ids;
1272     auto ResolveFn = [include_inlines, &name, &sc_list, &resolved_ids,
1273                       this](UniqueCStringMap<uint32_t> &Names) {
1274       std::vector<uint32_t> ids;
1275       if (Names.GetValues(name, ids)) {
1276         for (auto id : ids) {
1277           if (resolved_ids.find(id) == resolved_ids.end()) {
1278             if (ResolveFunction(id, include_inlines, sc_list))
1279               resolved_ids.insert(id);
1280           }
1281         }
1282       }
1283     };
1284     if (name_type_mask & eFunctionNameTypeFull) {
1285       ResolveFn(m_func_full_names);
1286     }
1287     if (name_type_mask & eFunctionNameTypeBase) {
1288       ResolveFn(m_func_base_names);
1289     }
1290     if (name_type_mask & eFunctionNameTypeMethod) {
1291       ResolveFn(m_func_method_names);
1292     }
1293   }
1294   return sc_list.GetSize() - old_size;
1295 }
1296 
1297 uint32_t
1298 SymbolFilePDB::FindFunctions(const lldb_private::RegularExpression &regex,
1299                              bool include_inlines, bool append,
1300                              lldb_private::SymbolContextList &sc_list) {
1301   if (!append)
1302     sc_list.Clear();
1303   if (!regex.IsValid())
1304     return 0;
1305 
1306   auto old_size = sc_list.GetSize();
1307   CacheFunctionNames();
1308 
1309   std::set<uint32_t> resolved_ids;
1310   auto ResolveFn = [&regex, include_inlines, &sc_list, &resolved_ids,
1311                     this](UniqueCStringMap<uint32_t> &Names) {
1312     std::vector<uint32_t> ids;
1313     if (Names.GetValues(regex, ids)) {
1314       for (auto id : ids) {
1315         if (resolved_ids.find(id) == resolved_ids.end())
1316           if (ResolveFunction(id, include_inlines, sc_list))
1317             resolved_ids.insert(id);
1318       }
1319     }
1320   };
1321   ResolveFn(m_func_full_names);
1322   ResolveFn(m_func_base_names);
1323 
1324   return sc_list.GetSize() - old_size;
1325 }
1326 
1327 void SymbolFilePDB::GetMangledNamesForFunction(
1328     const std::string &scope_qualified_name,
1329     std::vector<lldb_private::ConstString> &mangled_names) {}
1330 
1331 uint32_t SymbolFilePDB::FindTypes(
1332     const lldb_private::SymbolContext &sc,
1333     const lldb_private::ConstString &name,
1334     const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append,
1335     uint32_t max_matches,
1336     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1337     lldb_private::TypeMap &types) {
1338   if (!append)
1339     types.Clear();
1340   if (!name)
1341     return 0;
1342   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1343     return 0;
1344 
1345   searched_symbol_files.clear();
1346   searched_symbol_files.insert(this);
1347 
1348   // There is an assumption 'name' is not a regex
1349   FindTypesByName(name.GetStringRef(), parent_decl_ctx, max_matches, types);
1350 
1351   return types.GetSize();
1352 }
1353 
1354 void SymbolFilePDB::DumpClangAST(Stream &s) {
1355   auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1356   auto clang = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1357   if (!clang)
1358     return;
1359   clang->Dump(s);
1360 }
1361 
1362 void SymbolFilePDB::FindTypesByRegex(
1363     const lldb_private::RegularExpression &regex, uint32_t max_matches,
1364     lldb_private::TypeMap &types) {
1365   // When searching by regex, we need to go out of our way to limit the search
1366   // space as much as possible since this searches EVERYTHING in the PDB,
1367   // manually doing regex comparisons.  PDB library isn't optimized for regex
1368   // searches or searches across multiple symbol types at the same time, so the
1369   // best we can do is to search enums, then typedefs, then classes one by one,
1370   // and do a regex comparison against each of them.
1371   PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
1372                                   PDB_SymType::UDT};
1373   std::unique_ptr<IPDBEnumSymbols> results;
1374 
1375   uint32_t matches = 0;
1376 
1377   for (auto tag : tags_to_search) {
1378     results = m_global_scope_up->findAllChildren(tag);
1379     if (!results)
1380       continue;
1381 
1382     while (auto result = results->getNext()) {
1383       if (max_matches > 0 && matches >= max_matches)
1384         break;
1385 
1386       std::string type_name;
1387       if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get()))
1388         type_name = enum_type->getName();
1389       else if (auto typedef_type =
1390                    llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get()))
1391         type_name = typedef_type->getName();
1392       else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get()))
1393         type_name = class_type->getName();
1394       else {
1395         // We're looking only for types that have names.  Skip symbols, as well
1396         // as unnamed types such as arrays, pointers, etc.
1397         continue;
1398       }
1399 
1400       if (!regex.Execute(type_name))
1401         continue;
1402 
1403       // This should cause the type to get cached and stored in the `m_types`
1404       // lookup.
1405       if (!ResolveTypeUID(result->getSymIndexId()))
1406         continue;
1407 
1408       auto iter = m_types.find(result->getSymIndexId());
1409       if (iter == m_types.end())
1410         continue;
1411       types.Insert(iter->second);
1412       ++matches;
1413     }
1414   }
1415 }
1416 
1417 void SymbolFilePDB::FindTypesByName(
1418     llvm::StringRef name,
1419     const lldb_private::CompilerDeclContext *parent_decl_ctx,
1420     uint32_t max_matches, lldb_private::TypeMap &types) {
1421   if (!parent_decl_ctx)
1422     parent_decl_ctx = m_tu_decl_ctx_up.get();
1423   std::unique_ptr<IPDBEnumSymbols> results;
1424   if (name.empty())
1425     return;
1426   results = m_global_scope_up->findAllChildren(PDB_SymType::None);
1427   if (!results)
1428     return;
1429 
1430   uint32_t matches = 0;
1431 
1432   while (auto result = results->getNext()) {
1433     if (max_matches > 0 && matches >= max_matches)
1434       break;
1435 
1436     if (MSVCUndecoratedNameParser::DropScope(
1437             result->getRawSymbol().getName()) != name)
1438       continue;
1439 
1440     switch (result->getSymTag()) {
1441     case PDB_SymType::Enum:
1442     case PDB_SymType::UDT:
1443     case PDB_SymType::Typedef:
1444       break;
1445     default:
1446       // We're looking only for types that have names.  Skip symbols, as well
1447       // as unnamed types such as arrays, pointers, etc.
1448       continue;
1449     }
1450 
1451     // This should cause the type to get cached and stored in the `m_types`
1452     // lookup.
1453     if (!ResolveTypeUID(result->getSymIndexId()))
1454       continue;
1455 
1456     auto actual_parent_decl_ctx =
1457         GetDeclContextContainingUID(result->getSymIndexId());
1458     if (actual_parent_decl_ctx != *parent_decl_ctx)
1459       continue;
1460 
1461     auto iter = m_types.find(result->getSymIndexId());
1462     if (iter == m_types.end())
1463       continue;
1464     types.Insert(iter->second);
1465     ++matches;
1466   }
1467 }
1468 
1469 size_t SymbolFilePDB::FindTypes(
1470     const std::vector<lldb_private::CompilerContext> &contexts, bool append,
1471     lldb_private::TypeMap &types) {
1472   return 0;
1473 }
1474 
1475 lldb_private::TypeList *SymbolFilePDB::GetTypeList() {
1476   return m_obj_file->GetModule()->GetTypeList();
1477 }
1478 
1479 void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol,
1480                                          uint32_t type_mask,
1481                                          TypeCollection &type_collection) {
1482   bool can_parse = false;
1483   switch (pdb_symbol.getSymTag()) {
1484   case PDB_SymType::ArrayType:
1485     can_parse = ((type_mask & eTypeClassArray) != 0);
1486     break;
1487   case PDB_SymType::BuiltinType:
1488     can_parse = ((type_mask & eTypeClassBuiltin) != 0);
1489     break;
1490   case PDB_SymType::Enum:
1491     can_parse = ((type_mask & eTypeClassEnumeration) != 0);
1492     break;
1493   case PDB_SymType::Function:
1494   case PDB_SymType::FunctionSig:
1495     can_parse = ((type_mask & eTypeClassFunction) != 0);
1496     break;
1497   case PDB_SymType::PointerType:
1498     can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer |
1499                                eTypeClassMemberPointer)) != 0);
1500     break;
1501   case PDB_SymType::Typedef:
1502     can_parse = ((type_mask & eTypeClassTypedef) != 0);
1503     break;
1504   case PDB_SymType::UDT: {
1505     auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol);
1506     assert(udt);
1507     can_parse = (udt->getUdtKind() != PDB_UdtType::Interface &&
1508                  ((type_mask & (eTypeClassClass | eTypeClassStruct |
1509                                 eTypeClassUnion)) != 0));
1510   } break;
1511   default:
1512     break;
1513   }
1514 
1515   if (can_parse) {
1516     if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) {
1517       auto result =
1518           std::find(type_collection.begin(), type_collection.end(), type);
1519       if (result == type_collection.end())
1520         type_collection.push_back(type);
1521     }
1522   }
1523 
1524   auto results_up = pdb_symbol.findAllChildren();
1525   while (auto symbol_up = results_up->getNext())
1526     GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection);
1527 }
1528 
1529 size_t SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1530                                TypeClass type_mask,
1531                                lldb_private::TypeList &type_list) {
1532   TypeCollection type_collection;
1533   uint32_t old_size = type_list.GetSize();
1534   CompileUnit *cu =
1535       sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr;
1536   if (cu) {
1537     auto compiland_up = GetPDBCompilandByUID(cu->GetID());
1538     if (!compiland_up)
1539       return 0;
1540     GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1541   } else {
1542     for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
1543       auto cu_sp = ParseCompileUnitAtIndex(cu_idx);
1544       if (cu_sp) {
1545         if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID()))
1546           GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1547       }
1548     }
1549   }
1550 
1551   for (auto type : type_collection) {
1552     type->GetForwardCompilerType();
1553     type_list.Insert(type->shared_from_this());
1554   }
1555   return type_list.GetSize() - old_size;
1556 }
1557 
1558 lldb_private::TypeSystem *
1559 SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1560   auto type_system =
1561       m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
1562   if (type_system)
1563     type_system->SetSymbolFile(this);
1564   return type_system;
1565 }
1566 
1567 lldb_private::CompilerDeclContext SymbolFilePDB::FindNamespace(
1568     const lldb_private::SymbolContext &sc,
1569     const lldb_private::ConstString &name,
1570     const lldb_private::CompilerDeclContext *parent_decl_ctx) {
1571   auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1572   auto clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1573   if (!clang_type_system)
1574     return CompilerDeclContext();
1575 
1576   PDBASTParser *pdb = clang_type_system->GetPDBParser();
1577   if (!pdb)
1578     return CompilerDeclContext();
1579 
1580   clang::DeclContext *decl_context = nullptr;
1581   if (parent_decl_ctx)
1582     decl_context = static_cast<clang::DeclContext *>(
1583         parent_decl_ctx->GetOpaqueDeclContext());
1584 
1585   auto namespace_decl =
1586       pdb->FindNamespaceDecl(decl_context, name.GetStringRef());
1587   if (!namespace_decl)
1588     return CompilerDeclContext();
1589 
1590   return CompilerDeclContext(type_system,
1591                              static_cast<clang::DeclContext *>(namespace_decl));
1592 }
1593 
1594 lldb_private::ConstString SymbolFilePDB::GetPluginName() {
1595   static ConstString g_name("pdb");
1596   return g_name;
1597 }
1598 
1599 uint32_t SymbolFilePDB::GetPluginVersion() { return 1; }
1600 
1601 IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; }
1602 
1603 const IPDBSession &SymbolFilePDB::GetPDBSession() const {
1604   return *m_session_up;
1605 }
1606 
1607 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitForUID(uint32_t id,
1608                                                        uint32_t index) {
1609   auto found_cu = m_comp_units.find(id);
1610   if (found_cu != m_comp_units.end())
1611     return found_cu->second;
1612 
1613   auto compiland_up = GetPDBCompilandByUID(id);
1614   if (!compiland_up)
1615     return CompUnitSP();
1616 
1617   lldb::LanguageType lang;
1618   auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
1619   if (!details)
1620     lang = lldb::eLanguageTypeC_plus_plus;
1621   else
1622     lang = TranslateLanguage(details->getLanguage());
1623 
1624   if (lang == lldb::LanguageType::eLanguageTypeUnknown)
1625     return CompUnitSP();
1626 
1627   std::string path = compiland_up->getSourceFileFullPath();
1628   if (path.empty())
1629     return CompUnitSP();
1630 
1631   // Don't support optimized code for now, DebugInfoPDB does not return this
1632   // information.
1633   LazyBool optimized = eLazyBoolNo;
1634   auto cu_sp = std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr,
1635                                              path.c_str(), id, lang, optimized);
1636 
1637   if (!cu_sp)
1638     return CompUnitSP();
1639 
1640   m_comp_units.insert(std::make_pair(id, cu_sp));
1641   if (index == UINT32_MAX)
1642     GetCompileUnitIndex(*compiland_up, index);
1643   lldbassert(index != UINT32_MAX);
1644   m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(index,
1645                                                                     cu_sp);
1646   return cu_sp;
1647 }
1648 
1649 bool SymbolFilePDB::ParseCompileUnitLineTable(
1650     const lldb_private::SymbolContext &sc, uint32_t match_line) {
1651   lldbassert(sc.comp_unit);
1652 
1653   auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID());
1654   if (!compiland_up)
1655     return false;
1656 
1657   // LineEntry needs the *index* of the file into the list of support files
1658   // returned by ParseCompileUnitSupportFiles.  But the underlying SDK gives us
1659   // a globally unique idenfitifier in the namespace of the PDB.  So, we have
1660   // to do a mapping so that we can hand out indices.
1661   llvm::DenseMap<uint32_t, uint32_t> index_map;
1662   BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map);
1663   auto line_table = llvm::make_unique<LineTable>(sc.comp_unit);
1664 
1665   // Find contributions to `compiland` from all source and header files.
1666   std::string path = sc.comp_unit->GetPath();
1667   auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
1668   if (!files)
1669     return false;
1670 
1671   // For each source and header file, create a LineSequence for contributions
1672   // to the compiland from that file, and add the sequence.
1673   while (auto file = files->getNext()) {
1674     std::unique_ptr<LineSequence> sequence(
1675         line_table->CreateLineSequenceContainer());
1676     auto lines = m_session_up->findLineNumbers(*compiland_up, *file);
1677     if (!lines)
1678       continue;
1679     int entry_count = lines->getChildCount();
1680 
1681     uint64_t prev_addr;
1682     uint32_t prev_length;
1683     uint32_t prev_line;
1684     uint32_t prev_source_idx;
1685 
1686     for (int i = 0; i < entry_count; ++i) {
1687       auto line = lines->getChildAtIndex(i);
1688 
1689       uint64_t lno = line->getLineNumber();
1690       uint64_t addr = line->getVirtualAddress();
1691       uint32_t length = line->getLength();
1692       uint32_t source_id = line->getSourceFileId();
1693       uint32_t col = line->getColumnNumber();
1694       uint32_t source_idx = index_map[source_id];
1695 
1696       // There was a gap between the current entry and the previous entry if
1697       // the addresses don't perfectly line up.
1698       bool is_gap = (i > 0) && (prev_addr + prev_length < addr);
1699 
1700       // Before inserting the current entry, insert a terminal entry at the end
1701       // of the previous entry's address range if the current entry resulted in
1702       // a gap from the previous entry.
1703       if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) {
1704         line_table->AppendLineEntryToSequence(
1705             sequence.get(), prev_addr + prev_length, prev_line, 0,
1706             prev_source_idx, false, false, false, false, true);
1707 
1708         line_table->InsertSequence(sequence.release());
1709         sequence.reset(line_table->CreateLineSequenceContainer());
1710       }
1711 
1712       if (ShouldAddLine(match_line, lno, length)) {
1713         bool is_statement = line->isStatement();
1714         bool is_prologue = false;
1715         bool is_epilogue = false;
1716         auto func =
1717             m_session_up->findSymbolByAddress(addr, PDB_SymType::Function);
1718         if (func) {
1719           auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>();
1720           if (prologue)
1721             is_prologue = (addr == prologue->getVirtualAddress());
1722 
1723           auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>();
1724           if (epilogue)
1725             is_epilogue = (addr == epilogue->getVirtualAddress());
1726         }
1727 
1728         line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col,
1729                                               source_idx, is_statement, false,
1730                                               is_prologue, is_epilogue, false);
1731       }
1732 
1733       prev_addr = addr;
1734       prev_length = length;
1735       prev_line = lno;
1736       prev_source_idx = source_idx;
1737     }
1738 
1739     if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) {
1740       // The end is always a terminal entry, so insert it regardless.
1741       line_table->AppendLineEntryToSequence(
1742           sequence.get(), prev_addr + prev_length, prev_line, 0,
1743           prev_source_idx, false, false, false, false, true);
1744     }
1745 
1746     line_table->InsertSequence(sequence.release());
1747   }
1748 
1749   if (line_table->GetSize()) {
1750     sc.comp_unit->SetLineTable(line_table.release());
1751     return true;
1752   }
1753   return false;
1754 }
1755 
1756 void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap(
1757     const PDBSymbolCompiland &compiland,
1758     llvm::DenseMap<uint32_t, uint32_t> &index_map) const {
1759   // This is a hack, but we need to convert the source id into an index into
1760   // the support files array.  We don't want to do path comparisons to avoid
1761   // basename / full path issues that may or may not even be a problem, so we
1762   // use the globally unique source file identifiers.  Ideally we could use the
1763   // global identifiers everywhere, but LineEntry currently assumes indices.
1764   auto source_files = m_session_up->getSourceFilesForCompiland(compiland);
1765   if (!source_files)
1766     return;
1767 
1768   // LLDB uses the DWARF-like file numeration (one based)
1769   int index = 1;
1770 
1771   while (auto file = source_files->getNext()) {
1772     uint32_t source_id = file->getUniqueId();
1773     index_map[source_id] = index++;
1774   }
1775 }
1776 
1777 lldb::CompUnitSP SymbolFilePDB::GetCompileUnitContainsAddress(
1778     const lldb_private::Address &so_addr) {
1779   lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1780   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
1781     return nullptr;
1782 
1783   // If it is a PDB function's vm addr, this is the first sure bet.
1784   if (auto lines =
1785           m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) {
1786     if (auto first_line = lines->getNext())
1787       return ParseCompileUnitForUID(first_line->getCompilandId());
1788   }
1789 
1790   // Otherwise we resort to section contributions.
1791   if (auto sec_contribs = m_session_up->getSectionContribs()) {
1792     while (auto section = sec_contribs->getNext()) {
1793       auto va = section->getVirtualAddress();
1794       if (file_vm_addr >= va && file_vm_addr < va + section->getLength())
1795         return ParseCompileUnitForUID(section->getCompilandId());
1796     }
1797   }
1798   return nullptr;
1799 }
1800 
1801 Mangled
1802 SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) {
1803   Mangled mangled;
1804   auto func_name = pdb_func.getName();
1805   auto func_undecorated_name = pdb_func.getUndecoratedName();
1806   std::string func_decorated_name;
1807 
1808   // Seek from public symbols for non-static function's decorated name if any.
1809   // For static functions, they don't have undecorated names and aren't exposed
1810   // in Public Symbols either.
1811   if (!func_undecorated_name.empty()) {
1812     auto result_up = m_global_scope_up->findChildren(
1813         PDB_SymType::PublicSymbol, func_undecorated_name,
1814         PDB_NameSearchFlags::NS_UndecoratedName);
1815     if (result_up) {
1816       while (auto symbol_up = result_up->getNext()) {
1817         // For a public symbol, it is unique.
1818         lldbassert(result_up->getChildCount() == 1);
1819         if (auto *pdb_public_sym =
1820                 llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>(
1821                     symbol_up.get())) {
1822           if (pdb_public_sym->isFunction()) {
1823             func_decorated_name = pdb_public_sym->getName();
1824             break;
1825           }
1826         }
1827       }
1828     }
1829   }
1830   if (!func_decorated_name.empty()) {
1831     mangled.SetMangledName(ConstString(func_decorated_name));
1832 
1833     // For MSVC, format of C funciton's decorated name depends on calling
1834     // conventon. Unfortunately none of the format is recognized by current
1835     // LLDB. For example, `_purecall` is a __cdecl C function. From PDB,
1836     // `__purecall` is retrieved as both its decorated and undecorated name
1837     // (using PDBSymbolFunc::getUndecoratedName method). However `__purecall`
1838     // string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix).
1839     // Mangled::GetDemangledName method will fail internally and caches an
1840     // empty string as its undecorated name. So we will face a contradition
1841     // here for the same symbol:
1842     //   non-empty undecorated name from PDB
1843     //   empty undecorated name from LLDB
1844     if (!func_undecorated_name.empty() &&
1845         mangled.GetDemangledName(mangled.GuessLanguage()).IsEmpty())
1846       mangled.SetDemangledName(ConstString(func_undecorated_name));
1847 
1848     // LLDB uses several flags to control how a C++ decorated name is
1849     // undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the
1850     // yielded name could be different from what we retrieve from
1851     // PDB source unless we also apply same flags in getting undecorated
1852     // name through PDBSymbolFunc::getUndecoratedNameEx method.
1853     if (!func_undecorated_name.empty() &&
1854         mangled.GetDemangledName(mangled.GuessLanguage()) !=
1855             ConstString(func_undecorated_name))
1856       mangled.SetDemangledName(ConstString(func_undecorated_name));
1857   } else if (!func_undecorated_name.empty()) {
1858     mangled.SetDemangledName(ConstString(func_undecorated_name));
1859   } else if (!func_name.empty())
1860     mangled.SetValue(ConstString(func_name), false);
1861 
1862   return mangled;
1863 }
1864 
1865 bool SymbolFilePDB::DeclContextMatchesThisSymbolFile(
1866     const lldb_private::CompilerDeclContext *decl_ctx) {
1867   if (decl_ctx == nullptr || !decl_ctx->IsValid())
1868     return true;
1869 
1870   TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
1871   if (!decl_ctx_type_system)
1872     return false;
1873   TypeSystem *type_system = GetTypeSystemForLanguage(
1874       decl_ctx_type_system->GetMinimumLanguage(nullptr));
1875   if (decl_ctx_type_system == type_system)
1876     return true; // The type systems match, return true
1877 
1878   return false;
1879 }
1880 
1881 uint32_t SymbolFilePDB::GetCompilandId(const llvm::pdb::PDBSymbolData &data) {
1882   static const auto pred_upper = [](uint32_t lhs, SecContribInfo rhs) {
1883     return lhs < rhs.Offset;
1884   };
1885 
1886   // Cache section contributions
1887   if (m_sec_contribs.empty()) {
1888     if (auto SecContribs = m_session_up->getSectionContribs()) {
1889       while (auto SectionContrib = SecContribs->getNext()) {
1890         auto comp_id = SectionContrib->getCompilandId();
1891         if (!comp_id)
1892           continue;
1893 
1894         auto sec = SectionContrib->getAddressSection();
1895         auto &sec_cs = m_sec_contribs[sec];
1896 
1897         auto offset = SectionContrib->getAddressOffset();
1898         auto it =
1899             std::upper_bound(sec_cs.begin(), sec_cs.end(), offset, pred_upper);
1900 
1901         auto size = SectionContrib->getLength();
1902         sec_cs.insert(it, {offset, size, comp_id});
1903       }
1904     }
1905   }
1906 
1907   // Check by line number
1908   if (auto Lines = data.getLineNumbers()) {
1909     if (auto FirstLine = Lines->getNext())
1910       return FirstLine->getCompilandId();
1911   }
1912 
1913   // Retrieve section + offset
1914   uint32_t DataSection = data.getAddressSection();
1915   uint32_t DataOffset = data.getAddressOffset();
1916   if (DataSection == 0) {
1917     if (auto RVA = data.getRelativeVirtualAddress())
1918       m_session_up->addressForRVA(RVA, DataSection, DataOffset);
1919   }
1920 
1921   if (DataSection) {
1922     // Search by section contributions
1923     auto &sec_cs = m_sec_contribs[DataSection];
1924     auto it =
1925         std::upper_bound(sec_cs.begin(), sec_cs.end(), DataOffset, pred_upper);
1926     if (it != sec_cs.begin()) {
1927       --it;
1928       if (DataOffset < it->Offset + it->Size)
1929         return it->CompilandId;
1930     }
1931   } else {
1932     // Search in lexical tree
1933     auto LexParentId = data.getLexicalParentId();
1934     while (auto LexParent = m_session_up->getSymbolById(LexParentId)) {
1935       if (LexParent->getSymTag() == PDB_SymType::Exe)
1936         break;
1937       if (LexParent->getSymTag() == PDB_SymType::Compiland)
1938         return LexParentId;
1939       LexParentId = LexParent->getRawSymbol().getLexicalParentId();
1940     }
1941   }
1942 
1943   return 0;
1944 }
1945