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