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