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