1 //===-- SymbolFileNativePDB.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "SymbolFileNativePDB.h"
10 
11 #include "clang/AST/Attr.h"
12 #include "clang/AST/CharUnits.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclCXX.h"
15 #include "clang/AST/Type.h"
16 
17 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
18 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
19 #include "Plugins/ObjectFile/PDB/ObjectFilePDB.h"
20 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Core/PluginManager.h"
23 #include "lldb/Core/StreamBuffer.h"
24 #include "lldb/Core/StreamFile.h"
25 #include "lldb/Symbol/CompileUnit.h"
26 #include "lldb/Symbol/LineTable.h"
27 #include "lldb/Symbol/ObjectFile.h"
28 #include "lldb/Symbol/SymbolContext.h"
29 #include "lldb/Symbol/SymbolVendor.h"
30 #include "lldb/Symbol/Variable.h"
31 #include "lldb/Symbol/VariableList.h"
32 #include "lldb/Utility/LLDBLog.h"
33 #include "lldb/Utility/Log.h"
34 
35 #include "llvm/DebugInfo/CodeView/CVRecord.h"
36 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
37 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
38 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
39 #include "llvm/DebugInfo/CodeView/RecordName.h"
40 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
41 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
42 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
43 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
44 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
45 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
46 #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
47 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
48 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
49 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
50 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
51 #include "llvm/DebugInfo/PDB/PDB.h"
52 #include "llvm/DebugInfo/PDB/PDBTypes.h"
53 #include "llvm/Demangle/MicrosoftDemangle.h"
54 #include "llvm/Object/COFF.h"
55 #include "llvm/Support/Allocator.h"
56 #include "llvm/Support/BinaryStreamReader.h"
57 #include "llvm/Support/Error.h"
58 #include "llvm/Support/ErrorOr.h"
59 #include "llvm/Support/MemoryBuffer.h"
60 
61 #include "DWARFLocationExpression.h"
62 #include "PdbAstBuilder.h"
63 #include "PdbSymUid.h"
64 #include "PdbUtil.h"
65 #include "UdtRecordCompleter.h"
66 
67 using namespace lldb;
68 using namespace lldb_private;
69 using namespace npdb;
70 using namespace llvm::codeview;
71 using namespace llvm::pdb;
72 
73 char SymbolFileNativePDB::ID;
74 
75 static lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
76   switch (lang) {
77   case PDB_Lang::Cpp:
78     return lldb::LanguageType::eLanguageTypeC_plus_plus;
79   case PDB_Lang::C:
80     return lldb::LanguageType::eLanguageTypeC;
81   case PDB_Lang::Swift:
82     return lldb::LanguageType::eLanguageTypeSwift;
83   case PDB_Lang::Rust:
84     return lldb::LanguageType::eLanguageTypeRust;
85   default:
86     return lldb::LanguageType::eLanguageTypeUnknown;
87   }
88 }
89 
90 static std::unique_ptr<PDBFile>
91 loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) {
92   // Try to find a matching PDB for an EXE.
93   using namespace llvm::object;
94   auto expected_binary = createBinary(exe_path);
95 
96   // If the file isn't a PE/COFF executable, fail.
97   if (!expected_binary) {
98     llvm::consumeError(expected_binary.takeError());
99     return nullptr;
100   }
101   OwningBinary<Binary> binary = std::move(*expected_binary);
102 
103   // TODO: Avoid opening the PE/COFF binary twice by reading this information
104   // directly from the lldb_private::ObjectFile.
105   auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary());
106   if (!obj)
107     return nullptr;
108   const llvm::codeview::DebugInfo *pdb_info = nullptr;
109 
110   // If it doesn't have a debug directory, fail.
111   llvm::StringRef pdb_file;
112   if (llvm::Error e = obj->getDebugPDBInfo(pdb_info, pdb_file)) {
113     consumeError(std::move(e));
114     return nullptr;
115   }
116 
117   // If the file doesn't exist, perhaps the path specified at build time
118   // doesn't match the PDB's current location, so check the location of the
119   // executable.
120   if (!FileSystem::Instance().Exists(pdb_file)) {
121     const auto exe_dir = FileSpec(exe_path).CopyByRemovingLastPathComponent();
122     const auto pdb_name = FileSpec(pdb_file).GetFilename().GetCString();
123     pdb_file = exe_dir.CopyByAppendingPathComponent(pdb_name).GetCString();
124   }
125 
126   // If the file is not a PDB or if it doesn't have a matching GUID, fail.
127   auto pdb = ObjectFilePDB::loadPDBFile(std::string(pdb_file), allocator);
128   if (!pdb)
129     return nullptr;
130 
131   auto expected_info = pdb->getPDBInfoStream();
132   if (!expected_info) {
133     llvm::consumeError(expected_info.takeError());
134     return nullptr;
135   }
136   llvm::codeview::GUID guid;
137   memcpy(&guid, pdb_info->PDB70.Signature, 16);
138 
139   if (expected_info->getGuid() != guid)
140     return nullptr;
141   return pdb;
142 }
143 
144 static bool IsFunctionPrologue(const CompilandIndexItem &cci,
145                                lldb::addr_t addr) {
146   // FIXME: Implement this.
147   return false;
148 }
149 
150 static bool IsFunctionEpilogue(const CompilandIndexItem &cci,
151                                lldb::addr_t addr) {
152   // FIXME: Implement this.
153   return false;
154 }
155 
156 static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) {
157   switch (kind) {
158   case SimpleTypeKind::Boolean128:
159   case SimpleTypeKind::Boolean16:
160   case SimpleTypeKind::Boolean32:
161   case SimpleTypeKind::Boolean64:
162   case SimpleTypeKind::Boolean8:
163     return "bool";
164   case SimpleTypeKind::Byte:
165   case SimpleTypeKind::UnsignedCharacter:
166     return "unsigned char";
167   case SimpleTypeKind::NarrowCharacter:
168     return "char";
169   case SimpleTypeKind::SignedCharacter:
170   case SimpleTypeKind::SByte:
171     return "signed char";
172   case SimpleTypeKind::Character16:
173     return "char16_t";
174   case SimpleTypeKind::Character32:
175     return "char32_t";
176   case SimpleTypeKind::Character8:
177     return "char8_t";
178   case SimpleTypeKind::Complex80:
179   case SimpleTypeKind::Complex64:
180   case SimpleTypeKind::Complex32:
181     return "complex";
182   case SimpleTypeKind::Float128:
183   case SimpleTypeKind::Float80:
184     return "long double";
185   case SimpleTypeKind::Float64:
186     return "double";
187   case SimpleTypeKind::Float32:
188     return "float";
189   case SimpleTypeKind::Float16:
190     return "single";
191   case SimpleTypeKind::Int128:
192     return "__int128";
193   case SimpleTypeKind::Int64:
194   case SimpleTypeKind::Int64Quad:
195     return "int64_t";
196   case SimpleTypeKind::Int32:
197     return "int";
198   case SimpleTypeKind::Int16:
199     return "short";
200   case SimpleTypeKind::UInt128:
201     return "unsigned __int128";
202   case SimpleTypeKind::UInt64:
203   case SimpleTypeKind::UInt64Quad:
204     return "uint64_t";
205   case SimpleTypeKind::HResult:
206     return "HRESULT";
207   case SimpleTypeKind::UInt32:
208     return "unsigned";
209   case SimpleTypeKind::UInt16:
210   case SimpleTypeKind::UInt16Short:
211     return "unsigned short";
212   case SimpleTypeKind::Int32Long:
213     return "long";
214   case SimpleTypeKind::UInt32Long:
215     return "unsigned long";
216   case SimpleTypeKind::Void:
217     return "void";
218   case SimpleTypeKind::WideCharacter:
219     return "wchar_t";
220   default:
221     return "";
222   }
223 }
224 
225 static bool IsClassRecord(TypeLeafKind kind) {
226   switch (kind) {
227   case LF_STRUCTURE:
228   case LF_CLASS:
229   case LF_INTERFACE:
230     return true;
231   default:
232     return false;
233   }
234 }
235 
236 void SymbolFileNativePDB::Initialize() {
237   PluginManager::RegisterPlugin(GetPluginNameStatic(),
238                                 GetPluginDescriptionStatic(), CreateInstance,
239                                 DebuggerInitialize);
240 }
241 
242 void SymbolFileNativePDB::Terminate() {
243   PluginManager::UnregisterPlugin(CreateInstance);
244 }
245 
246 void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {}
247 
248 llvm::StringRef SymbolFileNativePDB::GetPluginDescriptionStatic() {
249   return "Microsoft PDB debug symbol cross-platform file reader.";
250 }
251 
252 SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFileSP objfile_sp) {
253   return new SymbolFileNativePDB(std::move(objfile_sp));
254 }
255 
256 SymbolFileNativePDB::SymbolFileNativePDB(ObjectFileSP objfile_sp)
257     : SymbolFileCommon(std::move(objfile_sp)) {}
258 
259 SymbolFileNativePDB::~SymbolFileNativePDB() = default;
260 
261 uint32_t SymbolFileNativePDB::CalculateAbilities() {
262   uint32_t abilities = 0;
263   if (!m_objfile_sp)
264     return 0;
265 
266   if (!m_index) {
267     // Lazily load and match the PDB file, but only do this once.
268     PDBFile *pdb_file;
269     if (auto *pdb = llvm::dyn_cast<ObjectFilePDB>(m_objfile_sp.get())) {
270       pdb_file = &pdb->GetPDBFile();
271     } else {
272       m_file_up = loadMatchingPDBFile(m_objfile_sp->GetFileSpec().GetPath(),
273                                       m_allocator);
274       pdb_file = m_file_up.get();
275     }
276 
277     if (!pdb_file)
278       return 0;
279 
280     auto expected_index = PdbIndex::create(pdb_file);
281     if (!expected_index) {
282       llvm::consumeError(expected_index.takeError());
283       return 0;
284     }
285     m_index = std::move(*expected_index);
286   }
287   if (!m_index)
288     return 0;
289 
290   // We don't especially have to be precise here.  We only distinguish between
291   // stripped and not stripped.
292   abilities = kAllAbilities;
293 
294   if (m_index->dbi().isStripped())
295     abilities &= ~(Blocks | LocalVariables);
296   return abilities;
297 }
298 
299 void SymbolFileNativePDB::InitializeObject() {
300   m_obj_load_address = m_objfile_sp->GetModule()
301                            ->GetObjectFile()
302                            ->GetBaseAddress()
303                            .GetFileAddress();
304   m_index->SetLoadAddress(m_obj_load_address);
305   m_index->ParseSectionContribs();
306 
307   auto ts_or_err = m_objfile_sp->GetModule()->GetTypeSystemForLanguage(
308       lldb::eLanguageTypeC_plus_plus);
309   if (auto err = ts_or_err.takeError()) {
310     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
311                    "Failed to initialize");
312   } else {
313     ts_or_err->SetSymbolFile(this);
314     auto *clang = llvm::cast_or_null<TypeSystemClang>(&ts_or_err.get());
315     lldbassert(clang);
316     m_ast = std::make_unique<PdbAstBuilder>(*m_objfile_sp, *m_index, *clang);
317   }
318 }
319 
320 uint32_t SymbolFileNativePDB::CalculateNumCompileUnits() {
321   const DbiModuleList &modules = m_index->dbi().modules();
322   uint32_t count = modules.getModuleCount();
323   if (count == 0)
324     return count;
325 
326   // The linker can inject an additional "dummy" compilation unit into the
327   // PDB. Ignore this special compile unit for our purposes, if it is there.
328   // It is always the last one.
329   DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1);
330   if (last.getModuleName() == "* Linker *")
331     --count;
332   return count;
333 }
334 
335 Block &SymbolFileNativePDB::CreateBlock(PdbCompilandSymId block_id) {
336   CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
337   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
338   CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
339   lldb::user_id_t opaque_block_uid = toOpaqueUid(block_id);
340   BlockSP child_block = std::make_shared<Block>(opaque_block_uid);
341 
342   switch (sym.kind()) {
343   case S_GPROC32:
344   case S_LPROC32: {
345     // This is a function.  It must be global.  Creating the Function entry
346     // for it automatically creates a block for it.
347     FunctionSP func = GetOrCreateFunction(block_id, *comp_unit);
348     Block &block = func->GetBlock(false);
349     if (block.GetNumRanges() == 0)
350       block.AddRange(Block::Range(0, func->GetAddressRange().GetByteSize()));
351     return block;
352   }
353   case S_BLOCK32: {
354     // This is a block.  Its parent is either a function or another block.  In
355     // either case, its parent can be viewed as a block (e.g. a function
356     // contains 1 big block.  So just get the parent block and add this block
357     // to it.
358     BlockSym block(static_cast<SymbolRecordKind>(sym.kind()));
359     cantFail(SymbolDeserializer::deserializeAs<BlockSym>(sym, block));
360     lldbassert(block.Parent != 0);
361     PdbCompilandSymId parent_id(block_id.modi, block.Parent);
362     Block &parent_block = GetOrCreateBlock(parent_id);
363     parent_block.AddChild(child_block);
364     m_ast->GetOrCreateBlockDecl(block_id);
365     m_blocks.insert({opaque_block_uid, child_block});
366     break;
367   }
368   case S_INLINESITE: {
369     // This ensures line table is parsed first so we have inline sites info.
370     comp_unit->GetLineTable();
371 
372     std::shared_ptr<InlineSite> inline_site = m_inline_sites[opaque_block_uid];
373     Block &parent_block = GetOrCreateBlock(inline_site->parent_id);
374     parent_block.AddChild(child_block);
375     m_ast->GetOrCreateInlinedFunctionDecl(block_id);
376     // Copy ranges from InlineSite to Block.
377     for (size_t i = 0; i < inline_site->ranges.GetSize(); ++i) {
378       auto *entry = inline_site->ranges.GetEntryAtIndex(i);
379       child_block->AddRange(
380           Block::Range(entry->GetRangeBase(), entry->GetByteSize()));
381     }
382     child_block->FinalizeRanges();
383 
384     // Get the inlined function callsite info.
385     Declaration &decl = inline_site->inline_function_info->GetDeclaration();
386     Declaration &callsite = inline_site->inline_function_info->GetCallSite();
387     child_block->SetInlinedFunctionInfo(
388         inline_site->inline_function_info->GetName().GetCString(), nullptr,
389         &decl, &callsite);
390     m_blocks.insert({opaque_block_uid, child_block});
391     break;
392   }
393   default:
394     lldbassert(false && "Symbol is not a block!");
395   }
396 
397   return *child_block;
398 }
399 
400 lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbCompilandSymId func_id,
401                                                      CompileUnit &comp_unit) {
402   const CompilandIndexItem *cci =
403       m_index->compilands().GetCompiland(func_id.modi);
404   lldbassert(cci);
405   CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset);
406 
407   lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32);
408   SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record);
409 
410   auto file_vm_addr = m_index->MakeVirtualAddress(sol.so);
411   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
412     return nullptr;
413 
414   AddressRange func_range(file_vm_addr, sol.length,
415                           comp_unit.GetModule()->GetSectionList());
416   if (!func_range.GetBaseAddress().IsValid())
417     return nullptr;
418 
419   ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind()));
420   cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc));
421   if (proc.FunctionType == TypeIndex::None())
422     return nullptr;
423   TypeSP func_type = GetOrCreateType(proc.FunctionType);
424   if (!func_type)
425     return nullptr;
426 
427   PdbTypeSymId sig_id(proc.FunctionType, false);
428   Mangled mangled(proc.Name);
429   FunctionSP func_sp = std::make_shared<Function>(
430       &comp_unit, toOpaqueUid(func_id), toOpaqueUid(sig_id), mangled,
431       func_type.get(), func_range);
432 
433   comp_unit.AddFunction(func_sp);
434 
435   m_ast->GetOrCreateFunctionDecl(func_id);
436 
437   return func_sp;
438 }
439 
440 CompUnitSP
441 SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) {
442   lldb::LanguageType lang =
443       cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage())
444                          : lldb::eLanguageTypeUnknown;
445 
446   LazyBool optimized = eLazyBoolNo;
447   if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations())
448     optimized = eLazyBoolYes;
449 
450   llvm::SmallString<64> source_file_name =
451       m_index->compilands().GetMainSourceFile(cci);
452   FileSpec fs(source_file_name);
453 
454   CompUnitSP cu_sp =
455       std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr, fs,
456                                     toOpaqueUid(cci.m_id), lang, optimized);
457 
458   SetCompileUnitAtIndex(cci.m_id.modi, cu_sp);
459   return cu_sp;
460 }
461 
462 lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbTypeSymId type_id,
463                                                      const ModifierRecord &mr,
464                                                      CompilerType ct) {
465   TpiStream &stream = m_index->tpi();
466 
467   std::string name;
468   if (mr.ModifiedType.isSimple())
469     name = std::string(GetSimpleTypeName(mr.ModifiedType.getSimpleKind()));
470   else
471     name = computeTypeName(stream.typeCollection(), mr.ModifiedType);
472   Declaration decl;
473   lldb::TypeSP modified_type = GetOrCreateType(mr.ModifiedType);
474 
475   return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(name),
476                                 modified_type->GetByteSize(nullptr), nullptr,
477                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
478                                 ct, Type::ResolveState::Full);
479 }
480 
481 lldb::TypeSP
482 SymbolFileNativePDB::CreatePointerType(PdbTypeSymId type_id,
483                                        const llvm::codeview::PointerRecord &pr,
484                                        CompilerType ct) {
485   TypeSP pointee = GetOrCreateType(pr.ReferentType);
486   if (!pointee)
487     return nullptr;
488 
489   if (pr.isPointerToMember()) {
490     MemberPointerInfo mpi = pr.getMemberInfo();
491     GetOrCreateType(mpi.ContainingType);
492   }
493 
494   Declaration decl;
495   return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(),
496                                 pr.getSize(), nullptr, LLDB_INVALID_UID,
497                                 Type::eEncodingIsUID, decl, ct,
498                                 Type::ResolveState::Full);
499 }
500 
501 lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti,
502                                                    CompilerType ct) {
503   uint64_t uid = toOpaqueUid(PdbTypeSymId(ti, false));
504   if (ti == TypeIndex::NullptrT()) {
505     Declaration decl;
506     return std::make_shared<Type>(
507         uid, this, ConstString("std::nullptr_t"), 0, nullptr, LLDB_INVALID_UID,
508         Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full);
509   }
510 
511   if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
512     TypeSP direct_sp = GetOrCreateType(ti.makeDirect());
513     uint32_t pointer_size = 0;
514     switch (ti.getSimpleMode()) {
515     case SimpleTypeMode::FarPointer32:
516     case SimpleTypeMode::NearPointer32:
517       pointer_size = 4;
518       break;
519     case SimpleTypeMode::NearPointer64:
520       pointer_size = 8;
521       break;
522     default:
523       // 128-bit and 16-bit pointers unsupported.
524       return nullptr;
525     }
526     Declaration decl;
527     return std::make_shared<Type>(
528         uid, this, ConstString(), pointer_size, nullptr, LLDB_INVALID_UID,
529         Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full);
530   }
531 
532   if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
533     return nullptr;
534 
535   size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind());
536   llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind());
537 
538   Declaration decl;
539   return std::make_shared<Type>(uid, this, ConstString(type_name), size,
540                                 nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID,
541                                 decl, ct, Type::ResolveState::Full);
542 }
543 
544 static std::string GetUnqualifiedTypeName(const TagRecord &record) {
545   if (!record.hasUniqueName()) {
546     MSVCUndecoratedNameParser parser(record.Name);
547     llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers();
548 
549     return std::string(specs.back().GetBaseName());
550   }
551 
552   llvm::ms_demangle::Demangler demangler;
553   StringView sv(record.UniqueName.begin(), record.UniqueName.size());
554   llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
555   if (demangler.Error)
556     return std::string(record.Name);
557 
558   llvm::ms_demangle::IdentifierNode *idn =
559       ttn->QualifiedName->getUnqualifiedIdentifier();
560   return idn->toString();
561 }
562 
563 lldb::TypeSP
564 SymbolFileNativePDB::CreateClassStructUnion(PdbTypeSymId type_id,
565                                             const TagRecord &record,
566                                             size_t size, CompilerType ct) {
567 
568   std::string uname = GetUnqualifiedTypeName(record);
569 
570   // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE.
571   Declaration decl;
572   return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(uname),
573                                 size, nullptr, LLDB_INVALID_UID,
574                                 Type::eEncodingIsUID, decl, ct,
575                                 Type::ResolveState::Forward);
576 }
577 
578 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
579                                                 const ClassRecord &cr,
580                                                 CompilerType ct) {
581   return CreateClassStructUnion(type_id, cr, cr.getSize(), ct);
582 }
583 
584 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
585                                                 const UnionRecord &ur,
586                                                 CompilerType ct) {
587   return CreateClassStructUnion(type_id, ur, ur.getSize(), ct);
588 }
589 
590 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
591                                                 const EnumRecord &er,
592                                                 CompilerType ct) {
593   std::string uname = GetUnqualifiedTypeName(er);
594 
595   Declaration decl;
596   TypeSP underlying_type = GetOrCreateType(er.UnderlyingType);
597 
598   return std::make_shared<lldb_private::Type>(
599       toOpaqueUid(type_id), this, ConstString(uname),
600       underlying_type->GetByteSize(nullptr), nullptr, LLDB_INVALID_UID,
601       lldb_private::Type::eEncodingIsUID, decl, ct,
602       lldb_private::Type::ResolveState::Forward);
603 }
604 
605 TypeSP SymbolFileNativePDB::CreateArrayType(PdbTypeSymId type_id,
606                                             const ArrayRecord &ar,
607                                             CompilerType ct) {
608   TypeSP element_type = GetOrCreateType(ar.ElementType);
609 
610   Declaration decl;
611   TypeSP array_sp = std::make_shared<lldb_private::Type>(
612       toOpaqueUid(type_id), this, ConstString(), ar.Size, nullptr,
613       LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, ct,
614       lldb_private::Type::ResolveState::Full);
615   array_sp->SetEncodingType(element_type.get());
616   return array_sp;
617 }
618 
619 
620 TypeSP SymbolFileNativePDB::CreateFunctionType(PdbTypeSymId type_id,
621                                                const MemberFunctionRecord &mfr,
622                                                CompilerType ct) {
623   Declaration decl;
624   return std::make_shared<lldb_private::Type>(
625       toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID,
626       lldb_private::Type::eEncodingIsUID, decl, ct,
627       lldb_private::Type::ResolveState::Full);
628 }
629 
630 TypeSP SymbolFileNativePDB::CreateProcedureType(PdbTypeSymId type_id,
631                                                 const ProcedureRecord &pr,
632                                                 CompilerType ct) {
633   Declaration decl;
634   return std::make_shared<lldb_private::Type>(
635       toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID,
636       lldb_private::Type::eEncodingIsUID, decl, ct,
637       lldb_private::Type::ResolveState::Full);
638 }
639 
640 TypeSP SymbolFileNativePDB::CreateType(PdbTypeSymId type_id, CompilerType ct) {
641   if (type_id.index.isSimple())
642     return CreateSimpleType(type_id.index, ct);
643 
644   TpiStream &stream = type_id.is_ipi ? m_index->ipi() : m_index->tpi();
645   CVType cvt = stream.getType(type_id.index);
646 
647   if (cvt.kind() == LF_MODIFIER) {
648     ModifierRecord modifier;
649     llvm::cantFail(
650         TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
651     return CreateModifierType(type_id, modifier, ct);
652   }
653 
654   if (cvt.kind() == LF_POINTER) {
655     PointerRecord pointer;
656     llvm::cantFail(
657         TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
658     return CreatePointerType(type_id, pointer, ct);
659   }
660 
661   if (IsClassRecord(cvt.kind())) {
662     ClassRecord cr;
663     llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr));
664     return CreateTagType(type_id, cr, ct);
665   }
666 
667   if (cvt.kind() == LF_ENUM) {
668     EnumRecord er;
669     llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er));
670     return CreateTagType(type_id, er, ct);
671   }
672 
673   if (cvt.kind() == LF_UNION) {
674     UnionRecord ur;
675     llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur));
676     return CreateTagType(type_id, ur, ct);
677   }
678 
679   if (cvt.kind() == LF_ARRAY) {
680     ArrayRecord ar;
681     llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
682     return CreateArrayType(type_id, ar, ct);
683   }
684 
685   if (cvt.kind() == LF_PROCEDURE) {
686     ProcedureRecord pr;
687     llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
688     return CreateProcedureType(type_id, pr, ct);
689   }
690   if (cvt.kind() == LF_MFUNCTION) {
691     MemberFunctionRecord mfr;
692     llvm::cantFail(TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr));
693     return CreateFunctionType(type_id, mfr, ct);
694   }
695 
696   return nullptr;
697 }
698 
699 TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbTypeSymId type_id) {
700   // If they search for a UDT which is a forward ref, try and resolve the full
701   // decl and just map the forward ref uid to the full decl record.
702   llvm::Optional<PdbTypeSymId> full_decl_uid;
703   if (IsForwardRefUdt(type_id, m_index->tpi())) {
704     auto expected_full_ti =
705         m_index->tpi().findFullDeclForForwardRef(type_id.index);
706     if (!expected_full_ti)
707       llvm::consumeError(expected_full_ti.takeError());
708     else if (*expected_full_ti != type_id.index) {
709       full_decl_uid = PdbTypeSymId(*expected_full_ti, false);
710 
711       // It's possible that a lookup would occur for the full decl causing it
712       // to be cached, then a second lookup would occur for the forward decl.
713       // We don't want to create a second full decl, so make sure the full
714       // decl hasn't already been cached.
715       auto full_iter = m_types.find(toOpaqueUid(*full_decl_uid));
716       if (full_iter != m_types.end()) {
717         TypeSP result = full_iter->second;
718         // Map the forward decl to the TypeSP for the full decl so we can take
719         // the fast path next time.
720         m_types[toOpaqueUid(type_id)] = result;
721         return result;
722       }
723     }
724   }
725 
726   PdbTypeSymId best_decl_id = full_decl_uid ? *full_decl_uid : type_id;
727 
728   clang::QualType qt = m_ast->GetOrCreateType(best_decl_id);
729   if (qt.isNull())
730     return nullptr;
731 
732   TypeSP result = CreateType(best_decl_id, m_ast->ToCompilerType(qt));
733   if (!result)
734     return nullptr;
735 
736   uint64_t best_uid = toOpaqueUid(best_decl_id);
737   m_types[best_uid] = result;
738   // If we had both a forward decl and a full decl, make both point to the new
739   // type.
740   if (full_decl_uid)
741     m_types[toOpaqueUid(type_id)] = result;
742 
743   return result;
744 }
745 
746 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbTypeSymId type_id) {
747   // We can't use try_emplace / overwrite here because the process of creating
748   // a type could create nested types, which could invalidate iterators.  So
749   // we have to do a 2-phase lookup / insert.
750   auto iter = m_types.find(toOpaqueUid(type_id));
751   if (iter != m_types.end())
752     return iter->second;
753 
754   TypeSP type = CreateAndCacheType(type_id);
755   if (type)
756     GetTypeList().Insert(type);
757   return type;
758 }
759 
760 VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbGlobalSymId var_id) {
761   CVSymbol sym = m_index->symrecords().readRecord(var_id.offset);
762   if (sym.kind() == S_CONSTANT)
763     return CreateConstantSymbol(var_id, sym);
764 
765   lldb::ValueType scope = eValueTypeInvalid;
766   TypeIndex ti;
767   llvm::StringRef name;
768   lldb::addr_t addr = 0;
769   uint16_t section = 0;
770   uint32_t offset = 0;
771   bool is_external = false;
772   switch (sym.kind()) {
773   case S_GDATA32:
774     is_external = true;
775     LLVM_FALLTHROUGH;
776   case S_LDATA32: {
777     DataSym ds(sym.kind());
778     llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds));
779     ti = ds.Type;
780     scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal
781                                       : eValueTypeVariableStatic;
782     name = ds.Name;
783     section = ds.Segment;
784     offset = ds.DataOffset;
785     addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset);
786     break;
787   }
788   case S_GTHREAD32:
789     is_external = true;
790     LLVM_FALLTHROUGH;
791   case S_LTHREAD32: {
792     ThreadLocalDataSym tlds(sym.kind());
793     llvm::cantFail(
794         SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds));
795     ti = tlds.Type;
796     name = tlds.Name;
797     section = tlds.Segment;
798     offset = tlds.DataOffset;
799     addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset);
800     scope = eValueTypeVariableThreadLocal;
801     break;
802   }
803   default:
804     llvm_unreachable("unreachable!");
805   }
806 
807   CompUnitSP comp_unit;
808   llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr);
809   if (modi) {
810     CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi);
811     comp_unit = GetOrCreateCompileUnit(cci);
812   }
813 
814   Declaration decl;
815   PdbTypeSymId tid(ti, false);
816   SymbolFileTypeSP type_sp =
817       std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
818   Variable::RangeList ranges;
819 
820   m_ast->GetOrCreateVariableDecl(var_id);
821 
822   DWARFExpression location = MakeGlobalLocationExpression(
823       section, offset, GetObjectFile()->GetModule());
824 
825   std::string global_name("::");
826   global_name += name;
827   bool artificial = false;
828   bool location_is_constant_data = false;
829   bool static_member = false;
830   VariableSP var_sp = std::make_shared<Variable>(
831       toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp,
832       scope, comp_unit.get(), ranges, &decl, location, is_external, artificial,
833       location_is_constant_data, static_member);
834 
835   return var_sp;
836 }
837 
838 lldb::VariableSP
839 SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id,
840                                           const CVSymbol &cvs) {
841   TpiStream &tpi = m_index->tpi();
842   ConstantSym constant(cvs.kind());
843 
844   llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant));
845   std::string global_name("::");
846   global_name += constant.Name;
847   PdbTypeSymId tid(constant.Type, false);
848   SymbolFileTypeSP type_sp =
849       std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
850 
851   Declaration decl;
852   Variable::RangeList ranges;
853   ModuleSP module = GetObjectFile()->GetModule();
854   DWARFExpression location = MakeConstantLocationExpression(
855       constant.Type, tpi, constant.Value, module);
856 
857   bool external = false;
858   bool artificial = false;
859   bool location_is_constant_data = true;
860   bool static_member = false;
861   VariableSP var_sp = std::make_shared<Variable>(
862       toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(),
863       type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location,
864       external, artificial, location_is_constant_data, static_member);
865   return var_sp;
866 }
867 
868 VariableSP
869 SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) {
870   auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr);
871   if (emplace_result.second)
872     emplace_result.first->second = CreateGlobalVariable(var_id);
873 
874   return emplace_result.first->second;
875 }
876 
877 lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) {
878   return GetOrCreateType(PdbTypeSymId(ti, false));
879 }
880 
881 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id,
882                                                     CompileUnit &comp_unit) {
883   auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr);
884   if (emplace_result.second)
885     emplace_result.first->second = CreateFunction(func_id, comp_unit);
886 
887   return emplace_result.first->second;
888 }
889 
890 CompUnitSP
891 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) {
892 
893   auto emplace_result =
894       m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr);
895   if (emplace_result.second)
896     emplace_result.first->second = CreateCompileUnit(cci);
897 
898   lldbassert(emplace_result.first->second);
899   return emplace_result.first->second;
900 }
901 
902 Block &SymbolFileNativePDB::GetOrCreateBlock(PdbCompilandSymId block_id) {
903   auto iter = m_blocks.find(toOpaqueUid(block_id));
904   if (iter != m_blocks.end())
905     return *iter->second;
906 
907   return CreateBlock(block_id);
908 }
909 
910 void SymbolFileNativePDB::ParseDeclsForContext(
911     lldb_private::CompilerDeclContext decl_ctx) {
912   clang::DeclContext *context = m_ast->FromCompilerDeclContext(decl_ctx);
913   if (!context)
914     return;
915   m_ast->ParseDeclsForContext(*context);
916 }
917 
918 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) {
919   if (index >= GetNumCompileUnits())
920     return CompUnitSP();
921   lldbassert(index < UINT16_MAX);
922   if (index >= UINT16_MAX)
923     return nullptr;
924 
925   CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
926 
927   return GetOrCreateCompileUnit(item);
928 }
929 
930 lldb::LanguageType SymbolFileNativePDB::ParseLanguage(CompileUnit &comp_unit) {
931   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
932   PdbSymUid uid(comp_unit.GetID());
933   lldbassert(uid.kind() == PdbSymUidKind::Compiland);
934 
935   CompilandIndexItem *item =
936       m_index->compilands().GetCompiland(uid.asCompiland().modi);
937   lldbassert(item);
938   if (!item->m_compile_opts)
939     return lldb::eLanguageTypeUnknown;
940 
941   return TranslateLanguage(item->m_compile_opts->getLanguage());
942 }
943 
944 void SymbolFileNativePDB::AddSymbols(Symtab &symtab) {}
945 
946 size_t SymbolFileNativePDB::ParseFunctions(CompileUnit &comp_unit) {
947   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
948   PdbSymUid uid{comp_unit.GetID()};
949   lldbassert(uid.kind() == PdbSymUidKind::Compiland);
950   uint16_t modi = uid.asCompiland().modi;
951   CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(modi);
952 
953   size_t count = comp_unit.GetNumFunctions();
954   const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
955   for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
956     if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32)
957       continue;
958 
959     PdbCompilandSymId sym_id{modi, iter.offset()};
960 
961     FunctionSP func = GetOrCreateFunction(sym_id, comp_unit);
962   }
963 
964   size_t new_count = comp_unit.GetNumFunctions();
965   lldbassert(new_count >= count);
966   return new_count - count;
967 }
968 
969 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
970   // If any of these flags are set, we need to resolve the compile unit.
971   uint32_t flags = eSymbolContextCompUnit;
972   flags |= eSymbolContextVariable;
973   flags |= eSymbolContextFunction;
974   flags |= eSymbolContextBlock;
975   flags |= eSymbolContextLineEntry;
976   return (resolve_scope & flags) != 0;
977 }
978 
979 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
980     const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
981   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
982   uint32_t resolved_flags = 0;
983   lldb::addr_t file_addr = addr.GetFileAddress();
984 
985   if (NeedsResolvedCompileUnit(resolve_scope)) {
986     llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
987     if (!modi)
988       return 0;
989     CompUnitSP cu_sp = GetCompileUnitAtIndex(modi.getValue());
990     if (!cu_sp)
991       return 0;
992 
993     sc.comp_unit = cu_sp.get();
994     resolved_flags |= eSymbolContextCompUnit;
995   }
996 
997   if (resolve_scope & eSymbolContextFunction ||
998       resolve_scope & eSymbolContextBlock) {
999     lldbassert(sc.comp_unit);
1000     std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
1001     // Search the matches in reverse.  This way if there are multiple matches
1002     // (for example we are 3 levels deep in a nested scope) it will find the
1003     // innermost one first.
1004     for (const auto &match : llvm::reverse(matches)) {
1005       if (match.uid.kind() != PdbSymUidKind::CompilandSym)
1006         continue;
1007 
1008       PdbCompilandSymId csid = match.uid.asCompilandSym();
1009       CVSymbol cvs = m_index->ReadSymbolRecord(csid);
1010       PDB_SymType type = CVSymToPDBSym(cvs.kind());
1011       if (type != PDB_SymType::Function && type != PDB_SymType::Block)
1012         continue;
1013       if (type == PDB_SymType::Function) {
1014         sc.function = GetOrCreateFunction(csid, *sc.comp_unit).get();
1015         Block &block = sc.function->GetBlock(true);
1016         addr_t func_base =
1017             sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
1018         addr_t offset = file_addr - func_base;
1019         sc.block = block.FindInnermostBlockByOffset(offset);
1020       }
1021 
1022       if (type == PDB_SymType::Block) {
1023         sc.block = &GetOrCreateBlock(csid);
1024         sc.function = sc.block->CalculateSymbolContextFunction();
1025       }
1026       if (sc.function)
1027         resolved_flags |= eSymbolContextFunction;
1028       if (sc.block)
1029         resolved_flags |= eSymbolContextBlock;
1030       break;
1031     }
1032   }
1033 
1034   if (resolve_scope & eSymbolContextLineEntry) {
1035     lldbassert(sc.comp_unit);
1036     if (auto *line_table = sc.comp_unit->GetLineTable()) {
1037       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1038         resolved_flags |= eSymbolContextLineEntry;
1039     }
1040   }
1041 
1042   return resolved_flags;
1043 }
1044 
1045 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
1046     const SourceLocationSpec &src_location_spec,
1047     lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
1048   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1049   const uint32_t prev_size = sc_list.GetSize();
1050   if (resolve_scope & eSymbolContextCompUnit) {
1051     for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
1052          ++cu_idx) {
1053       CompileUnit *cu = ParseCompileUnitAtIndex(cu_idx).get();
1054       if (!cu)
1055         continue;
1056 
1057       bool file_spec_matches_cu_file_spec = FileSpec::Match(
1058           src_location_spec.GetFileSpec(), cu->GetPrimaryFile());
1059       if (file_spec_matches_cu_file_spec) {
1060         cu->ResolveSymbolContext(src_location_spec, resolve_scope, sc_list);
1061         break;
1062       }
1063     }
1064   }
1065   return sc_list.GetSize() - prev_size;
1066 }
1067 
1068 bool SymbolFileNativePDB::ParseLineTable(CompileUnit &comp_unit) {
1069   // Unfortunately LLDB is set up to parse the entire compile unit line table
1070   // all at once, even if all it really needs is line info for a specific
1071   // function.  In the future it would be nice if it could set the sc.m_function
1072   // member, and we could only get the line info for the function in question.
1073   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1074   PdbSymUid cu_id(comp_unit.GetID());
1075   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1076   uint16_t modi = cu_id.asCompiland().modi;
1077   CompilandIndexItem *cii = m_index->compilands().GetCompiland(modi);
1078   lldbassert(cii);
1079 
1080   // Parse DEBUG_S_LINES subsections first, then parse all S_INLINESITE records
1081   // in this CU. Add line entries into the set first so that if there are line
1082   // entries with same addres, the later is always more accurate than the
1083   // former.
1084   std::set<LineTable::Entry, LineTableEntryComparator> line_set;
1085 
1086   // This is basically a copy of the .debug$S subsections from all original COFF
1087   // object files merged together with address relocations applied.  We are
1088   // looking for all DEBUG_S_LINES subsections.
1089   for (const DebugSubsectionRecord &dssr :
1090        cii->m_debug_stream.getSubsectionsArray()) {
1091     if (dssr.kind() != DebugSubsectionKind::Lines)
1092       continue;
1093 
1094     DebugLinesSubsectionRef lines;
1095     llvm::BinaryStreamReader reader(dssr.getRecordData());
1096     if (auto EC = lines.initialize(reader)) {
1097       llvm::consumeError(std::move(EC));
1098       return false;
1099     }
1100 
1101     const LineFragmentHeader *lfh = lines.header();
1102     uint64_t virtual_addr =
1103         m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1104 
1105     for (const LineColumnEntry &group : lines) {
1106       llvm::Expected<uint32_t> file_index_or_err =
1107           GetFileIndex(*cii, group.NameIndex);
1108       if (!file_index_or_err)
1109         continue;
1110       uint32_t file_index = file_index_or_err.get();
1111       lldbassert(!group.LineNumbers.empty());
1112       CompilandIndexItem::GlobalLineTable::Entry line_entry(
1113           LLDB_INVALID_ADDRESS, 0);
1114       for (const LineNumberEntry &entry : group.LineNumbers) {
1115         LineInfo cur_info(entry.Flags);
1116 
1117         if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1118           continue;
1119 
1120         uint64_t addr = virtual_addr + entry.Offset;
1121 
1122         bool is_statement = cur_info.isStatement();
1123         bool is_prologue = IsFunctionPrologue(*cii, addr);
1124         bool is_epilogue = IsFunctionEpilogue(*cii, addr);
1125 
1126         uint32_t lno = cur_info.getStartLine();
1127 
1128         LineTable::Entry new_entry(addr, lno, 0, file_index, is_statement, false,
1129                                  is_prologue, is_epilogue, false);
1130         // Terminal entry has lower precedence than new entry.
1131         auto iter = line_set.find(new_entry);
1132         if (iter != line_set.end() && iter->is_terminal_entry)
1133           line_set.erase(iter);
1134         line_set.insert(new_entry);
1135 
1136         if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1137           line_entry.SetRangeEnd(addr);
1138           cii->m_global_line_table.Append(line_entry);
1139         }
1140         line_entry.SetRangeBase(addr);
1141         line_entry.data = {file_index, lno};
1142       }
1143       LineInfo last_line(group.LineNumbers.back().Flags);
1144       line_set.emplace(virtual_addr + lfh->CodeSize, last_line.getEndLine(), 0,
1145                        file_index, false, false, false, false, true);
1146 
1147       if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1148         line_entry.SetRangeEnd(virtual_addr + lfh->CodeSize);
1149         cii->m_global_line_table.Append(line_entry);
1150       }
1151     }
1152   }
1153 
1154   cii->m_global_line_table.Sort();
1155 
1156   // Parse all S_INLINESITE in this CU.
1157   const CVSymbolArray &syms = cii->m_debug_stream.getSymbolArray();
1158   for (auto iter = syms.begin(); iter != syms.end();) {
1159     if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32) {
1160       ++iter;
1161       continue;
1162     }
1163 
1164     uint32_t record_offset = iter.offset();
1165     CVSymbol func_record =
1166         cii->m_debug_stream.readSymbolAtOffset(record_offset);
1167     SegmentOffsetLength sol = GetSegmentOffsetAndLength(func_record);
1168     addr_t file_vm_addr = m_index->MakeVirtualAddress(sol.so);
1169     AddressRange func_range(file_vm_addr, sol.length,
1170                             comp_unit.GetModule()->GetSectionList());
1171     Address func_base = func_range.GetBaseAddress();
1172     PdbCompilandSymId func_id{modi, record_offset};
1173 
1174     // Iterate all S_INLINESITEs in the function.
1175     auto parse_inline_sites = [&](SymbolKind kind, PdbCompilandSymId id) {
1176       if (kind != S_INLINESITE)
1177         return false;
1178 
1179       ParseInlineSite(id, func_base);
1180 
1181       for (const auto &line_entry :
1182            m_inline_sites[toOpaqueUid(id)]->line_entries) {
1183         // If line_entry is not terminal entry, remove previous line entry at
1184         // the same address and insert new one. Terminal entry inside an inline
1185         // site might not be terminal entry for its parent.
1186         if (!line_entry.is_terminal_entry)
1187           line_set.erase(line_entry);
1188         line_set.insert(line_entry);
1189       }
1190       // No longer useful after adding to line_set.
1191       m_inline_sites[toOpaqueUid(id)]->line_entries.clear();
1192       return true;
1193     };
1194     ParseSymbolArrayInScope(func_id, parse_inline_sites);
1195     // Jump to the end of the function record.
1196     iter = syms.at(getScopeEndOffset(func_record));
1197   }
1198 
1199   cii->m_global_line_table.Clear();
1200 
1201   // Add line entries in line_set to line_table.
1202   auto line_table = std::make_unique<LineTable>(&comp_unit);
1203   std::unique_ptr<LineSequence> sequence(
1204       line_table->CreateLineSequenceContainer());
1205   for (const auto &line_entry : line_set) {
1206     line_table->AppendLineEntryToSequence(
1207         sequence.get(), line_entry.file_addr, line_entry.line,
1208         line_entry.column, line_entry.file_idx,
1209         line_entry.is_start_of_statement, line_entry.is_start_of_basic_block,
1210         line_entry.is_prologue_end, line_entry.is_epilogue_begin,
1211         line_entry.is_terminal_entry);
1212   }
1213   line_table->InsertSequence(sequence.get());
1214 
1215   if (line_table->GetSize() == 0)
1216     return false;
1217 
1218   comp_unit.SetLineTable(line_table.release());
1219   return true;
1220 }
1221 
1222 bool SymbolFileNativePDB::ParseDebugMacros(CompileUnit &comp_unit) {
1223   // PDB doesn't contain information about macros
1224   return false;
1225 }
1226 
1227 llvm::Expected<uint32_t>
1228 SymbolFileNativePDB::GetFileIndex(const CompilandIndexItem &cii,
1229                                   uint32_t file_id) {
1230   const auto &checksums = cii.m_strings.checksums().getArray();
1231   const auto &strings = cii.m_strings.strings();
1232   // Indices in this structure are actually offsets of records in the
1233   // DEBUG_S_FILECHECKSUMS subsection.  Those entries then have an index
1234   // into the global PDB string table.
1235   auto iter = checksums.at(file_id);
1236   if (iter == checksums.end())
1237     return llvm::make_error<RawError>(raw_error_code::no_entry);
1238 
1239   llvm::Expected<llvm::StringRef> efn = strings.getString(iter->FileNameOffset);
1240   if (!efn) {
1241     return efn.takeError();
1242   }
1243 
1244   // LLDB wants the index of the file in the list of support files.
1245   auto fn_iter = llvm::find(cii.m_file_list, *efn);
1246   if (fn_iter != cii.m_file_list.end())
1247     return std::distance(cii.m_file_list.begin(), fn_iter);
1248   return llvm::make_error<RawError>(raw_error_code::no_entry);
1249 }
1250 
1251 bool SymbolFileNativePDB::ParseSupportFiles(CompileUnit &comp_unit,
1252                                             FileSpecList &support_files) {
1253   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1254   PdbSymUid cu_id(comp_unit.GetID());
1255   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1256   CompilandIndexItem *cci =
1257       m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1258   lldbassert(cci);
1259 
1260   for (llvm::StringRef f : cci->m_file_list) {
1261     FileSpec::Style style =
1262         f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1263     FileSpec spec(f, style);
1264     support_files.Append(spec);
1265   }
1266   return true;
1267 }
1268 
1269 bool SymbolFileNativePDB::ParseImportedModules(
1270     const SymbolContext &sc, std::vector<SourceModule> &imported_modules) {
1271   // PDB does not yet support module debug info
1272   return false;
1273 }
1274 
1275 void SymbolFileNativePDB::ParseInlineSite(PdbCompilandSymId id,
1276                                           Address func_addr) {
1277   lldb::user_id_t opaque_uid = toOpaqueUid(id);
1278   if (m_inline_sites.find(opaque_uid) != m_inline_sites.end())
1279     return;
1280 
1281   addr_t func_base = func_addr.GetFileAddress();
1282   CompilandIndexItem *cii = m_index->compilands().GetCompiland(id.modi);
1283   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(id.offset);
1284   CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
1285 
1286   InlineSiteSym inline_site(static_cast<SymbolRecordKind>(sym.kind()));
1287   cantFail(SymbolDeserializer::deserializeAs<InlineSiteSym>(sym, inline_site));
1288   PdbCompilandSymId parent_id(id.modi, inline_site.Parent);
1289 
1290   std::shared_ptr<InlineSite> inline_site_sp =
1291       std::make_shared<InlineSite>(parent_id);
1292 
1293   // Get the inlined function declaration info.
1294   auto iter = cii->m_inline_map.find(inline_site.Inlinee);
1295   if (iter == cii->m_inline_map.end())
1296     return;
1297   InlineeSourceLine inlinee_line = iter->second;
1298 
1299   const FileSpecList &files = comp_unit->GetSupportFiles();
1300   FileSpec decl_file;
1301   llvm::Expected<uint32_t> file_index_or_err =
1302       GetFileIndex(*cii, inlinee_line.Header->FileID);
1303   if (!file_index_or_err)
1304     return;
1305   uint32_t file_offset = file_index_or_err.get();
1306   decl_file = files.GetFileSpecAtIndex(file_offset);
1307   uint32_t decl_line = inlinee_line.Header->SourceLineNum;
1308   std::unique_ptr<Declaration> decl_up =
1309       std::make_unique<Declaration>(decl_file, decl_line);
1310 
1311   // Parse range and line info.
1312   uint32_t code_offset = 0;
1313   int32_t line_offset = 0;
1314   llvm::Optional<uint32_t> code_offset_base;
1315   llvm::Optional<uint32_t> code_offset_end;
1316   llvm::Optional<int32_t> cur_line_offset;
1317   llvm::Optional<int32_t> next_line_offset;
1318   llvm::Optional<uint32_t> next_file_offset;
1319 
1320   bool is_terminal_entry = false;
1321   bool is_start_of_statement = true;
1322   // The first instruction is the prologue end.
1323   bool is_prologue_end = true;
1324 
1325   auto update_code_offset = [&](uint32_t code_delta) {
1326     if (!code_offset_base)
1327       code_offset_base = code_offset;
1328     else if (!code_offset_end)
1329       code_offset_end = *code_offset_base + code_delta;
1330   };
1331   auto update_line_offset = [&](int32_t line_delta) {
1332     line_offset += line_delta;
1333     if (!code_offset_base || !cur_line_offset)
1334       cur_line_offset = line_offset;
1335     else
1336       next_line_offset = line_offset;
1337     ;
1338   };
1339   auto update_file_offset = [&](uint32_t offset) {
1340     if (!code_offset_base)
1341       file_offset = offset;
1342     else
1343       next_file_offset = offset;
1344   };
1345 
1346   for (auto &annot : inline_site.annotations()) {
1347     switch (annot.OpCode) {
1348     case BinaryAnnotationsOpCode::CodeOffset:
1349     case BinaryAnnotationsOpCode::ChangeCodeOffset:
1350     case BinaryAnnotationsOpCode::ChangeCodeOffsetBase:
1351       code_offset += annot.U1;
1352       update_code_offset(annot.U1);
1353       break;
1354     case BinaryAnnotationsOpCode::ChangeLineOffset:
1355       update_line_offset(annot.S1);
1356       break;
1357     case BinaryAnnotationsOpCode::ChangeCodeLength:
1358       update_code_offset(annot.U1);
1359       code_offset += annot.U1;
1360       is_terminal_entry = true;
1361       break;
1362     case BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset:
1363       code_offset += annot.U1;
1364       update_code_offset(annot.U1);
1365       update_line_offset(annot.S1);
1366       break;
1367     case BinaryAnnotationsOpCode::ChangeCodeLengthAndCodeOffset:
1368       code_offset += annot.U2;
1369       update_code_offset(annot.U2);
1370       update_code_offset(annot.U1);
1371       code_offset += annot.U1;
1372       is_terminal_entry = true;
1373       break;
1374     case BinaryAnnotationsOpCode::ChangeFile:
1375       update_file_offset(annot.U1);
1376       break;
1377     default:
1378       break;
1379     }
1380 
1381     // Add range if current range is finished.
1382     if (code_offset_base && code_offset_end && cur_line_offset) {
1383       inline_site_sp->ranges.Append(RangeSourceLineVector::Entry(
1384           *code_offset_base, *code_offset_end - *code_offset_base,
1385           decl_line + *cur_line_offset));
1386       // Set base, end, file offset and line offset for next range.
1387       if (next_file_offset)
1388         file_offset = *next_file_offset;
1389       if (next_line_offset) {
1390         cur_line_offset = next_line_offset;
1391         next_line_offset = llvm::None;
1392       }
1393       code_offset_base = is_terminal_entry ? llvm::None : code_offset_end;
1394       code_offset_end = next_file_offset = llvm::None;
1395     }
1396     if (code_offset_base && cur_line_offset) {
1397       if (is_terminal_entry) {
1398         LineTable::Entry line_entry(
1399             func_base + *code_offset_base, decl_line + *cur_line_offset, 0,
1400             file_offset, false, false, false, false, true);
1401         inline_site_sp->line_entries.push_back(line_entry);
1402       } else {
1403         LineTable::Entry line_entry(func_base + *code_offset_base,
1404                                     decl_line + *cur_line_offset, 0,
1405                                     file_offset, is_start_of_statement, false,
1406                                     is_prologue_end, false, false);
1407         inline_site_sp->line_entries.push_back(line_entry);
1408         is_prologue_end = false;
1409         is_start_of_statement = false;
1410       }
1411     }
1412     if (is_terminal_entry)
1413       is_start_of_statement = true;
1414     is_terminal_entry = false;
1415   }
1416 
1417   inline_site_sp->ranges.Sort();
1418 
1419   // Get the inlined function callsite info.
1420   std::unique_ptr<Declaration> callsite_up;
1421   if (!inline_site_sp->ranges.IsEmpty()) {
1422     auto *entry = inline_site_sp->ranges.GetEntryAtIndex(0);
1423     addr_t base_offset = entry->GetRangeBase();
1424     if (cii->m_debug_stream.readSymbolAtOffset(parent_id.offset).kind() ==
1425         S_INLINESITE) {
1426       // Its parent is another inline site, lookup parent site's range vector
1427       // for callsite line.
1428       ParseInlineSite(parent_id, func_base);
1429       std::shared_ptr<InlineSite> parent_site =
1430           m_inline_sites[toOpaqueUid(parent_id)];
1431       FileSpec &parent_decl_file =
1432           parent_site->inline_function_info->GetDeclaration().GetFile();
1433       if (auto *parent_entry =
1434               parent_site->ranges.FindEntryThatContains(base_offset)) {
1435         callsite_up =
1436             std::make_unique<Declaration>(parent_decl_file, parent_entry->data);
1437       }
1438     } else {
1439       // Its parent is a function, lookup global line table for callsite.
1440       if (auto *entry = cii->m_global_line_table.FindEntryThatContains(
1441               func_base + base_offset)) {
1442         const FileSpec &callsite_file =
1443             files.GetFileSpecAtIndex(entry->data.first);
1444         callsite_up =
1445             std::make_unique<Declaration>(callsite_file, entry->data.second);
1446       }
1447     }
1448   }
1449 
1450   // Get the inlined function name.
1451   CVType inlinee_cvt = m_index->ipi().getType(inline_site.Inlinee);
1452   std::string inlinee_name;
1453   if (inlinee_cvt.kind() == LF_MFUNC_ID) {
1454     MemberFuncIdRecord mfr;
1455     cantFail(
1456         TypeDeserializer::deserializeAs<MemberFuncIdRecord>(inlinee_cvt, mfr));
1457     LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1458     inlinee_name.append(std::string(types.getTypeName(mfr.ClassType)));
1459     inlinee_name.append("::");
1460     inlinee_name.append(mfr.getName().str());
1461   } else if (inlinee_cvt.kind() == LF_FUNC_ID) {
1462     FuncIdRecord fir;
1463     cantFail(TypeDeserializer::deserializeAs<FuncIdRecord>(inlinee_cvt, fir));
1464     TypeIndex parent_idx = fir.getParentScope();
1465     if (!parent_idx.isNoneType()) {
1466       LazyRandomTypeCollection &ids = m_index->ipi().typeCollection();
1467       inlinee_name.append(std::string(ids.getTypeName(parent_idx)));
1468       inlinee_name.append("::");
1469     }
1470     inlinee_name.append(fir.getName().str());
1471   }
1472   inline_site_sp->inline_function_info = std::make_shared<InlineFunctionInfo>(
1473       inlinee_name.c_str(), llvm::StringRef(), decl_up.get(),
1474       callsite_up.get());
1475 
1476   m_inline_sites[opaque_uid] = inline_site_sp;
1477 }
1478 
1479 size_t SymbolFileNativePDB::ParseBlocksRecursive(Function &func) {
1480   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1481   PdbCompilandSymId func_id = PdbSymUid(func.GetID()).asCompilandSym();
1482   // After we iterate through inline sites inside the function, we already get
1483   // all the info needed, removing from the map to save memory.
1484   std::set<uint64_t> remove_uids;
1485   auto parse_blocks = [&](SymbolKind kind, PdbCompilandSymId id) {
1486     if (kind == S_GPROC32 || kind == S_LPROC32 || kind == S_BLOCK32 ||
1487         kind == S_INLINESITE) {
1488       GetOrCreateBlock(id);
1489       if (kind == S_INLINESITE)
1490         remove_uids.insert(toOpaqueUid(id));
1491       return true;
1492     }
1493     return false;
1494   };
1495   size_t count = ParseSymbolArrayInScope(func_id, parse_blocks);
1496   for (uint64_t uid : remove_uids) {
1497     m_inline_sites.erase(uid);
1498   }
1499   return count;
1500 }
1501 
1502 size_t SymbolFileNativePDB::ParseSymbolArrayInScope(
1503     PdbCompilandSymId parent_id,
1504     llvm::function_ref<bool(SymbolKind, PdbCompilandSymId)> fn) {
1505   CompilandIndexItem *cii = m_index->compilands().GetCompiland(parent_id.modi);
1506   CVSymbolArray syms =
1507       cii->m_debug_stream.getSymbolArrayForScope(parent_id.offset);
1508 
1509   size_t count = 1;
1510   for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
1511     PdbCompilandSymId child_id(parent_id.modi, iter.offset());
1512     if (fn(iter->kind(), child_id))
1513       ++count;
1514   }
1515 
1516   return count;
1517 }
1518 
1519 void SymbolFileNativePDB::DumpClangAST(Stream &s) { m_ast->Dump(s); }
1520 
1521 void SymbolFileNativePDB::FindGlobalVariables(
1522     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1523     uint32_t max_matches, VariableList &variables) {
1524   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1525   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1526 
1527   std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName(
1528       name.GetStringRef(), m_index->symrecords());
1529   for (const SymbolAndOffset &result : results) {
1530     VariableSP var;
1531     switch (result.second.kind()) {
1532     case SymbolKind::S_GDATA32:
1533     case SymbolKind::S_LDATA32:
1534     case SymbolKind::S_GTHREAD32:
1535     case SymbolKind::S_LTHREAD32:
1536     case SymbolKind::S_CONSTANT: {
1537       PdbGlobalSymId global(result.first, false);
1538       var = GetOrCreateGlobalVariable(global);
1539       variables.AddVariable(var);
1540       break;
1541     }
1542     default:
1543       continue;
1544     }
1545   }
1546 }
1547 
1548 void SymbolFileNativePDB::FindFunctions(
1549     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1550     FunctionNameType name_type_mask, bool include_inlines,
1551     SymbolContextList &sc_list) {
1552   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1553   // For now we only support lookup by method name or full name.
1554   if (!(name_type_mask & eFunctionNameTypeFull ||
1555         name_type_mask & eFunctionNameTypeMethod))
1556     return;
1557 
1558   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1559 
1560   std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName(
1561       name.GetStringRef(), m_index->symrecords());
1562   for (const SymbolAndOffset &match : matches) {
1563     if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF)
1564       continue;
1565     ProcRefSym proc(match.second.kind());
1566     cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc));
1567 
1568     if (!IsValidRecord(proc))
1569       continue;
1570 
1571     CompilandIndexItem &cci =
1572         m_index->compilands().GetOrCreateCompiland(proc.modi());
1573     SymbolContext sc;
1574 
1575     sc.comp_unit = GetOrCreateCompileUnit(cci).get();
1576     PdbCompilandSymId func_id(proc.modi(), proc.SymOffset);
1577     sc.function = GetOrCreateFunction(func_id, *sc.comp_unit).get();
1578 
1579     sc_list.Append(sc);
1580   }
1581 }
1582 
1583 void SymbolFileNativePDB::FindFunctions(const RegularExpression &regex,
1584                                         bool include_inlines,
1585                                         SymbolContextList &sc_list) {}
1586 
1587 void SymbolFileNativePDB::FindTypes(
1588     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1589     uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1590     TypeMap &types) {
1591   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1592   if (!name)
1593     return;
1594 
1595   searched_symbol_files.clear();
1596   searched_symbol_files.insert(this);
1597 
1598   // There is an assumption 'name' is not a regex
1599   FindTypesByName(name.GetStringRef(), max_matches, types);
1600 }
1601 
1602 void SymbolFileNativePDB::FindTypes(
1603     llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1604     llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {}
1605 
1606 void SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1607                                           uint32_t max_matches,
1608                                           TypeMap &types) {
1609 
1610   std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1611   if (max_matches > 0 && max_matches < matches.size())
1612     matches.resize(max_matches);
1613 
1614   for (TypeIndex ti : matches) {
1615     TypeSP type = GetOrCreateType(ti);
1616     if (!type)
1617       continue;
1618 
1619     types.Insert(type);
1620   }
1621 }
1622 
1623 size_t SymbolFileNativePDB::ParseTypes(CompileUnit &comp_unit) {
1624   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1625   // Only do the full type scan the first time.
1626   if (m_done_full_type_scan)
1627     return 0;
1628 
1629   const size_t old_count = GetTypeList().GetSize();
1630   LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1631 
1632   // First process the entire TPI stream.
1633   for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
1634     TypeSP type = GetOrCreateType(*ti);
1635     if (type)
1636       (void)type->GetFullCompilerType();
1637   }
1638 
1639   // Next look for S_UDT records in the globals stream.
1640   for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
1641     PdbGlobalSymId global{gid, false};
1642     CVSymbol sym = m_index->ReadSymbolRecord(global);
1643     if (sym.kind() != S_UDT)
1644       continue;
1645 
1646     UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1647     bool is_typedef = true;
1648     if (IsTagRecord(PdbTypeSymId{udt.Type, false}, m_index->tpi())) {
1649       CVType cvt = m_index->tpi().getType(udt.Type);
1650       llvm::StringRef name = CVTagRecord::create(cvt).name();
1651       if (name == udt.Name)
1652         is_typedef = false;
1653     }
1654 
1655     if (is_typedef)
1656       GetOrCreateTypedef(global);
1657   }
1658 
1659   const size_t new_count = GetTypeList().GetSize();
1660 
1661   m_done_full_type_scan = true;
1662 
1663   return new_count - old_count;
1664 }
1665 
1666 size_t
1667 SymbolFileNativePDB::ParseVariablesForCompileUnit(CompileUnit &comp_unit,
1668                                                   VariableList &variables) {
1669   PdbSymUid sym_uid(comp_unit.GetID());
1670   lldbassert(sym_uid.kind() == PdbSymUidKind::Compiland);
1671   return 0;
1672 }
1673 
1674 VariableSP SymbolFileNativePDB::CreateLocalVariable(PdbCompilandSymId scope_id,
1675                                                     PdbCompilandSymId var_id,
1676                                                     bool is_param) {
1677   ModuleSP module = GetObjectFile()->GetModule();
1678   Block &block = GetOrCreateBlock(scope_id);
1679   VariableInfo var_info =
1680       GetVariableLocationInfo(*m_index, var_id, block, module);
1681   if (!var_info.location || !var_info.ranges)
1682     return nullptr;
1683 
1684   CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi);
1685   CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii);
1686   TypeSP type_sp = GetOrCreateType(var_info.type);
1687   std::string name = var_info.name.str();
1688   Declaration decl;
1689   SymbolFileTypeSP sftype =
1690       std::make_shared<SymbolFileType>(*this, type_sp->GetID());
1691 
1692   is_param |= var_info.is_param;
1693   ValueType var_scope =
1694       is_param ? eValueTypeVariableArgument : eValueTypeVariableLocal;
1695   bool external = false;
1696   bool artificial = false;
1697   bool location_is_constant_data = false;
1698   bool static_member = false;
1699   VariableSP var_sp = std::make_shared<Variable>(
1700       toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope,
1701       &block, *var_info.ranges, &decl, *var_info.location, external,
1702       artificial, location_is_constant_data, static_member);
1703 
1704   if (!is_param)
1705     m_ast->GetOrCreateVariableDecl(scope_id, var_id);
1706 
1707   m_local_variables[toOpaqueUid(var_id)] = var_sp;
1708   return var_sp;
1709 }
1710 
1711 VariableSP SymbolFileNativePDB::GetOrCreateLocalVariable(
1712     PdbCompilandSymId scope_id, PdbCompilandSymId var_id, bool is_param) {
1713   auto iter = m_local_variables.find(toOpaqueUid(var_id));
1714   if (iter != m_local_variables.end())
1715     return iter->second;
1716 
1717   return CreateLocalVariable(scope_id, var_id, is_param);
1718 }
1719 
1720 TypeSP SymbolFileNativePDB::CreateTypedef(PdbGlobalSymId id) {
1721   CVSymbol sym = m_index->ReadSymbolRecord(id);
1722   lldbassert(sym.kind() == SymbolKind::S_UDT);
1723 
1724   UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1725 
1726   TypeSP target_type = GetOrCreateType(udt.Type);
1727 
1728   (void)m_ast->GetOrCreateTypedefDecl(id);
1729 
1730   Declaration decl;
1731   return std::make_shared<lldb_private::Type>(
1732       toOpaqueUid(id), this, ConstString(udt.Name),
1733       target_type->GetByteSize(nullptr), nullptr, target_type->GetID(),
1734       lldb_private::Type::eEncodingIsTypedefUID, decl,
1735       target_type->GetForwardCompilerType(),
1736       lldb_private::Type::ResolveState::Forward);
1737 }
1738 
1739 TypeSP SymbolFileNativePDB::GetOrCreateTypedef(PdbGlobalSymId id) {
1740   auto iter = m_types.find(toOpaqueUid(id));
1741   if (iter != m_types.end())
1742     return iter->second;
1743 
1744   return CreateTypedef(id);
1745 }
1746 
1747 size_t SymbolFileNativePDB::ParseVariablesForBlock(PdbCompilandSymId block_id) {
1748   Block &block = GetOrCreateBlock(block_id);
1749 
1750   size_t count = 0;
1751 
1752   CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
1753   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
1754   uint32_t params_remaining = 0;
1755   switch (sym.kind()) {
1756   case S_GPROC32:
1757   case S_LPROC32: {
1758     ProcSym proc(static_cast<SymbolRecordKind>(sym.kind()));
1759     cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym, proc));
1760     CVType signature = m_index->tpi().getType(proc.FunctionType);
1761     ProcedureRecord sig;
1762     cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(signature, sig));
1763     params_remaining = sig.getParameterCount();
1764     break;
1765   }
1766   case S_BLOCK32:
1767     break;
1768   case S_INLINESITE:
1769     break;
1770   default:
1771     lldbassert(false && "Symbol is not a block!");
1772     return 0;
1773   }
1774 
1775   VariableListSP variables = block.GetBlockVariableList(false);
1776   if (!variables) {
1777     variables = std::make_shared<VariableList>();
1778     block.SetVariableList(variables);
1779   }
1780 
1781   CVSymbolArray syms = limitSymbolArrayToScope(
1782       cii->m_debug_stream.getSymbolArray(), block_id.offset);
1783 
1784   // Skip the first record since it's a PROC32 or BLOCK32, and there's
1785   // no point examining it since we know it's not a local variable.
1786   syms.drop_front();
1787   auto iter = syms.begin();
1788   auto end = syms.end();
1789 
1790   while (iter != end) {
1791     uint32_t record_offset = iter.offset();
1792     CVSymbol variable_cvs = *iter;
1793     PdbCompilandSymId child_sym_id(block_id.modi, record_offset);
1794     ++iter;
1795 
1796     // If this is a block or inline site, recurse into its children and then
1797     // skip it.
1798     if (variable_cvs.kind() == S_BLOCK32 ||
1799         variable_cvs.kind() == S_INLINESITE) {
1800       uint32_t block_end = getScopeEndOffset(variable_cvs);
1801       count += ParseVariablesForBlock(child_sym_id);
1802       iter = syms.at(block_end);
1803       continue;
1804     }
1805 
1806     bool is_param = params_remaining > 0;
1807     VariableSP variable;
1808     switch (variable_cvs.kind()) {
1809     case S_REGREL32:
1810     case S_REGISTER:
1811     case S_LOCAL:
1812       variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param);
1813       if (is_param)
1814         --params_remaining;
1815       if (variable)
1816         variables->AddVariableIfUnique(variable);
1817       break;
1818     default:
1819       break;
1820     }
1821   }
1822 
1823   // Pass false for set_children, since we call this recursively so that the
1824   // children will call this for themselves.
1825   block.SetDidParseVariables(true, false);
1826 
1827   return count;
1828 }
1829 
1830 size_t SymbolFileNativePDB::ParseVariablesForContext(const SymbolContext &sc) {
1831   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1832   lldbassert(sc.function || sc.comp_unit);
1833 
1834   VariableListSP variables;
1835   if (sc.block) {
1836     PdbSymUid block_id(sc.block->GetID());
1837 
1838     size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1839     return count;
1840   }
1841 
1842   if (sc.function) {
1843     PdbSymUid block_id(sc.function->GetID());
1844 
1845     size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1846     return count;
1847   }
1848 
1849   if (sc.comp_unit) {
1850     variables = sc.comp_unit->GetVariableList(false);
1851     if (!variables) {
1852       variables = std::make_shared<VariableList>();
1853       sc.comp_unit->SetVariableList(variables);
1854     }
1855     return ParseVariablesForCompileUnit(*sc.comp_unit, *variables);
1856   }
1857 
1858   llvm_unreachable("Unreachable!");
1859 }
1860 
1861 CompilerDecl SymbolFileNativePDB::GetDeclForUID(lldb::user_id_t uid) {
1862   if (auto decl = m_ast->GetOrCreateDeclForUid(uid))
1863     return decl.getValue();
1864   else
1865     return CompilerDecl();
1866 }
1867 
1868 CompilerDeclContext
1869 SymbolFileNativePDB::GetDeclContextForUID(lldb::user_id_t uid) {
1870   clang::DeclContext *context =
1871       m_ast->GetOrCreateDeclContextForUid(PdbSymUid(uid));
1872   if (!context)
1873     return {};
1874 
1875   return m_ast->ToCompilerDeclContext(*context);
1876 }
1877 
1878 CompilerDeclContext
1879 SymbolFileNativePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
1880   clang::DeclContext *context = m_ast->GetParentDeclContext(PdbSymUid(uid));
1881   return m_ast->ToCompilerDeclContext(*context);
1882 }
1883 
1884 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
1885   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1886   auto iter = m_types.find(type_uid);
1887   // lldb should not be passing us non-sensical type uids.  the only way it
1888   // could have a type uid in the first place is if we handed it out, in which
1889   // case we should know about the type.  However, that doesn't mean we've
1890   // instantiated it yet.  We can vend out a UID for a future type.  So if the
1891   // type doesn't exist, let's instantiate it now.
1892   if (iter != m_types.end())
1893     return &*iter->second;
1894 
1895   PdbSymUid uid(type_uid);
1896   lldbassert(uid.kind() == PdbSymUidKind::Type);
1897   PdbTypeSymId type_id = uid.asTypeSym();
1898   if (type_id.index.isNoneType())
1899     return nullptr;
1900 
1901   TypeSP type_sp = CreateAndCacheType(type_id);
1902   return &*type_sp;
1903 }
1904 
1905 llvm::Optional<SymbolFile::ArrayInfo>
1906 SymbolFileNativePDB::GetDynamicArrayInfoForUID(
1907     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1908   return llvm::None;
1909 }
1910 
1911 
1912 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
1913   clang::QualType qt =
1914       clang::QualType::getFromOpaquePtr(compiler_type.GetOpaqueQualType());
1915 
1916   return m_ast->CompleteType(qt);
1917 }
1918 
1919 void SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1920                                    TypeClass type_mask,
1921                                    lldb_private::TypeList &type_list) {}
1922 
1923 CompilerDeclContext
1924 SymbolFileNativePDB::FindNamespace(ConstString name,
1925                                    const CompilerDeclContext &parent_decl_ctx) {
1926   return {};
1927 }
1928 
1929 llvm::Expected<TypeSystem &>
1930 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1931   auto type_system_or_err =
1932       m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
1933   if (type_system_or_err) {
1934     type_system_or_err->SetSymbolFile(this);
1935   }
1936   return type_system_or_err;
1937 }
1938 
1939 uint64_t SymbolFileNativePDB::GetDebugInfoSize() {
1940   // PDB files are a separate file that contains all debug info.
1941   return m_index->pdb().getFileSize();
1942 }
1943