1 //===-- SymbolFileNativePDB.cpp ---------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "SymbolFileNativePDB.h"
11 
12 #include "clang/AST/Attr.h"
13 #include "clang/AST/CharUnits.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Symbol/ClangASTContext.h"
20 #include "lldb/Symbol/ClangASTImporter.h"
21 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
22 #include "lldb/Symbol/CompileUnit.h"
23 #include "lldb/Symbol/LineTable.h"
24 #include "lldb/Symbol/ObjectFile.h"
25 #include "lldb/Symbol/SymbolContext.h"
26 #include "lldb/Symbol/SymbolVendor.h"
27 
28 #include "llvm/DebugInfo/CodeView/CVRecord.h"
29 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
30 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
31 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
32 #include "llvm/DebugInfo/CodeView/RecordName.h"
33 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
34 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
35 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
36 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
37 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
38 #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
39 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
40 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
41 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
42 #include "llvm/DebugInfo/PDB/PDBTypes.h"
43 #include "llvm/Object/COFF.h"
44 #include "llvm/Support/Allocator.h"
45 #include "llvm/Support/BinaryStreamReader.h"
46 #include "llvm/Support/ErrorOr.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 
49 #include "PdbSymUid.h"
50 #include "PdbUtil.h"
51 #include "UdtRecordCompleter.h"
52 
53 using namespace lldb;
54 using namespace lldb_private;
55 using namespace npdb;
56 using namespace llvm::codeview;
57 using namespace llvm::pdb;
58 
59 static lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
60   switch (lang) {
61   case PDB_Lang::Cpp:
62     return lldb::LanguageType::eLanguageTypeC_plus_plus;
63   case PDB_Lang::C:
64     return lldb::LanguageType::eLanguageTypeC;
65   default:
66     return lldb::LanguageType::eLanguageTypeUnknown;
67   }
68 }
69 
70 static std::unique_ptr<PDBFile> loadPDBFile(std::string PdbPath,
71                                             llvm::BumpPtrAllocator &Allocator) {
72   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ErrorOrBuffer =
73       llvm::MemoryBuffer::getFile(PdbPath, /*FileSize=*/-1,
74                                   /*RequiresNullTerminator=*/false);
75   if (!ErrorOrBuffer)
76     return nullptr;
77   std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(*ErrorOrBuffer);
78 
79   llvm::StringRef Path = Buffer->getBufferIdentifier();
80   auto Stream = llvm::make_unique<llvm::MemoryBufferByteStream>(
81       std::move(Buffer), llvm::support::little);
82 
83   auto File = llvm::make_unique<PDBFile>(Path, std::move(Stream), Allocator);
84   if (auto EC = File->parseFileHeaders()) {
85     llvm::consumeError(std::move(EC));
86     return nullptr;
87   }
88   if (auto EC = File->parseStreamData()) {
89     llvm::consumeError(std::move(EC));
90     return nullptr;
91   }
92 
93   return File;
94 }
95 
96 static std::unique_ptr<PDBFile>
97 loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) {
98   // Try to find a matching PDB for an EXE.
99   using namespace llvm::object;
100   auto expected_binary = createBinary(exe_path);
101 
102   // If the file isn't a PE/COFF executable, fail.
103   if (!expected_binary) {
104     llvm::consumeError(expected_binary.takeError());
105     return nullptr;
106   }
107   OwningBinary<Binary> binary = std::move(*expected_binary);
108 
109   auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary());
110   if (!obj)
111     return nullptr;
112   const llvm::codeview::DebugInfo *pdb_info = nullptr;
113 
114   // If it doesn't have a debug directory, fail.
115   llvm::StringRef pdb_file;
116   auto ec = obj->getDebugPDBInfo(pdb_info, pdb_file);
117   if (ec)
118     return nullptr;
119 
120   // if the file doesn't exist, is not a pdb, or doesn't have a matching guid,
121   // fail.
122   llvm::file_magic magic;
123   ec = llvm::identify_magic(pdb_file, magic);
124   if (ec || magic != llvm::file_magic::pdb)
125     return nullptr;
126   std::unique_ptr<PDBFile> pdb = loadPDBFile(pdb_file, allocator);
127   if (!pdb)
128     return nullptr;
129 
130   auto expected_info = pdb->getPDBInfoStream();
131   if (!expected_info) {
132     llvm::consumeError(expected_info.takeError());
133     return nullptr;
134   }
135   llvm::codeview::GUID guid;
136   memcpy(&guid, pdb_info->PDB70.Signature, 16);
137 
138   if (expected_info->getGuid() != guid)
139     return nullptr;
140   return pdb;
141 }
142 
143 static bool IsFunctionPrologue(const CompilandIndexItem &cci,
144                                lldb::addr_t addr) {
145   // FIXME: Implement this.
146   return false;
147 }
148 
149 static bool IsFunctionEpilogue(const CompilandIndexItem &cci,
150                                lldb::addr_t addr) {
151   // FIXME: Implement this.
152   return false;
153 }
154 
155 static clang::MSInheritanceAttr::Spelling
156 GetMSInheritance(LazyRandomTypeCollection &tpi, const ClassRecord &record) {
157   if (record.DerivationList == TypeIndex::None())
158     return clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance;
159 
160   CVType bases = tpi.getType(record.DerivationList);
161   ArgListRecord base_list;
162   cantFail(TypeDeserializer::deserializeAs<ArgListRecord>(bases, base_list));
163   if (base_list.ArgIndices.empty())
164     return clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance;
165 
166   int base_count = 0;
167   for (TypeIndex ti : base_list.ArgIndices) {
168     CVType base = tpi.getType(ti);
169     if (base.kind() == LF_VBCLASS || base.kind() == LF_IVBCLASS)
170       return clang::MSInheritanceAttr::Spelling::Keyword_virtual_inheritance;
171     ++base_count;
172   }
173 
174   if (base_count > 1)
175     return clang::MSInheritanceAttr::Keyword_multiple_inheritance;
176   return clang::MSInheritanceAttr::Keyword_single_inheritance;
177 }
178 
179 static lldb::BasicType GetCompilerTypeForSimpleKind(SimpleTypeKind kind) {
180   switch (kind) {
181   case SimpleTypeKind::Boolean128:
182   case SimpleTypeKind::Boolean16:
183   case SimpleTypeKind::Boolean32:
184   case SimpleTypeKind::Boolean64:
185   case SimpleTypeKind::Boolean8:
186     return lldb::eBasicTypeBool;
187   case SimpleTypeKind::Byte:
188   case SimpleTypeKind::UnsignedCharacter:
189     return lldb::eBasicTypeUnsignedChar;
190   case SimpleTypeKind::NarrowCharacter:
191     return lldb::eBasicTypeChar;
192   case SimpleTypeKind::SignedCharacter:
193   case SimpleTypeKind::SByte:
194     return lldb::eBasicTypeSignedChar;
195   case SimpleTypeKind::Character16:
196     return lldb::eBasicTypeChar16;
197   case SimpleTypeKind::Character32:
198     return lldb::eBasicTypeChar32;
199   case SimpleTypeKind::Complex80:
200     return lldb::eBasicTypeLongDoubleComplex;
201   case SimpleTypeKind::Complex64:
202     return lldb::eBasicTypeDoubleComplex;
203   case SimpleTypeKind::Complex32:
204     return lldb::eBasicTypeFloatComplex;
205   case SimpleTypeKind::Float128:
206   case SimpleTypeKind::Float80:
207     return lldb::eBasicTypeLongDouble;
208   case SimpleTypeKind::Float64:
209     return lldb::eBasicTypeDouble;
210   case SimpleTypeKind::Float32:
211     return lldb::eBasicTypeFloat;
212   case SimpleTypeKind::Float16:
213     return lldb::eBasicTypeHalf;
214   case SimpleTypeKind::Int128:
215     return lldb::eBasicTypeInt128;
216   case SimpleTypeKind::Int64:
217   case SimpleTypeKind::Int64Quad:
218     return lldb::eBasicTypeLongLong;
219   case SimpleTypeKind::Int32:
220     return lldb::eBasicTypeInt;
221   case SimpleTypeKind::Int16:
222   case SimpleTypeKind::Int16Short:
223     return lldb::eBasicTypeShort;
224   case SimpleTypeKind::UInt128:
225     return lldb::eBasicTypeUnsignedInt128;
226   case SimpleTypeKind::UInt64:
227   case SimpleTypeKind::UInt64Quad:
228     return lldb::eBasicTypeUnsignedLongLong;
229   case SimpleTypeKind::HResult:
230   case SimpleTypeKind::UInt32:
231     return lldb::eBasicTypeUnsignedInt;
232   case SimpleTypeKind::UInt16:
233   case SimpleTypeKind::UInt16Short:
234     return lldb::eBasicTypeUnsignedShort;
235   case SimpleTypeKind::Int32Long:
236     return lldb::eBasicTypeLong;
237   case SimpleTypeKind::UInt32Long:
238     return lldb::eBasicTypeUnsignedLong;
239   case SimpleTypeKind::Void:
240     return lldb::eBasicTypeVoid;
241   case SimpleTypeKind::WideCharacter:
242     return lldb::eBasicTypeWChar;
243   default:
244     return lldb::eBasicTypeInvalid;
245   }
246 }
247 
248 static size_t GetTypeSizeForSimpleKind(SimpleTypeKind kind) {
249   switch (kind) {
250   case SimpleTypeKind::Boolean128:
251   case SimpleTypeKind::Int128:
252   case SimpleTypeKind::UInt128:
253   case SimpleTypeKind::Float128:
254     return 16;
255   case SimpleTypeKind::Complex80:
256   case SimpleTypeKind::Float80:
257     return 10;
258   case SimpleTypeKind::Boolean64:
259   case SimpleTypeKind::Complex64:
260   case SimpleTypeKind::UInt64:
261   case SimpleTypeKind::UInt64Quad:
262   case SimpleTypeKind::Float64:
263   case SimpleTypeKind::Int64:
264   case SimpleTypeKind::Int64Quad:
265     return 8;
266   case SimpleTypeKind::Boolean32:
267   case SimpleTypeKind::Character32:
268   case SimpleTypeKind::Complex32:
269   case SimpleTypeKind::Float32:
270   case SimpleTypeKind::Int32:
271   case SimpleTypeKind::Int32Long:
272   case SimpleTypeKind::UInt32Long:
273   case SimpleTypeKind::HResult:
274   case SimpleTypeKind::UInt32:
275     return 4;
276   case SimpleTypeKind::Boolean16:
277   case SimpleTypeKind::Character16:
278   case SimpleTypeKind::Float16:
279   case SimpleTypeKind::Int16:
280   case SimpleTypeKind::Int16Short:
281   case SimpleTypeKind::UInt16:
282   case SimpleTypeKind::UInt16Short:
283   case SimpleTypeKind::WideCharacter:
284     return 2;
285   case SimpleTypeKind::Boolean8:
286   case SimpleTypeKind::Byte:
287   case SimpleTypeKind::UnsignedCharacter:
288   case SimpleTypeKind::NarrowCharacter:
289   case SimpleTypeKind::SignedCharacter:
290   case SimpleTypeKind::SByte:
291     return 1;
292   case SimpleTypeKind::Void:
293   default:
294     return 0;
295   }
296 }
297 
298 static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) {
299   switch (kind) {
300   case SimpleTypeKind::Boolean128:
301   case SimpleTypeKind::Boolean16:
302   case SimpleTypeKind::Boolean32:
303   case SimpleTypeKind::Boolean64:
304   case SimpleTypeKind::Boolean8:
305     return "bool";
306   case SimpleTypeKind::Byte:
307   case SimpleTypeKind::UnsignedCharacter:
308     return "unsigned char";
309   case SimpleTypeKind::NarrowCharacter:
310     return "char";
311   case SimpleTypeKind::SignedCharacter:
312   case SimpleTypeKind::SByte:
313     return "signed char";
314   case SimpleTypeKind::Character16:
315     return "char16_t";
316   case SimpleTypeKind::Character32:
317     return "char32_t";
318   case SimpleTypeKind::Complex80:
319   case SimpleTypeKind::Complex64:
320   case SimpleTypeKind::Complex32:
321     return "complex";
322   case SimpleTypeKind::Float128:
323   case SimpleTypeKind::Float80:
324     return "long double";
325   case SimpleTypeKind::Float64:
326     return "double";
327   case SimpleTypeKind::Float32:
328     return "float";
329   case SimpleTypeKind::Float16:
330     return "single";
331   case SimpleTypeKind::Int128:
332     return "__int128";
333   case SimpleTypeKind::Int64:
334   case SimpleTypeKind::Int64Quad:
335     return "int64_t";
336   case SimpleTypeKind::Int32:
337     return "int";
338   case SimpleTypeKind::Int16:
339     return "short";
340   case SimpleTypeKind::UInt128:
341     return "unsigned __int128";
342   case SimpleTypeKind::UInt64:
343   case SimpleTypeKind::UInt64Quad:
344     return "uint64_t";
345   case SimpleTypeKind::HResult:
346     return "HRESULT";
347   case SimpleTypeKind::UInt32:
348     return "unsigned";
349   case SimpleTypeKind::UInt16:
350   case SimpleTypeKind::UInt16Short:
351     return "unsigned short";
352   case SimpleTypeKind::Int32Long:
353     return "long";
354   case SimpleTypeKind::UInt32Long:
355     return "unsigned long";
356   case SimpleTypeKind::Void:
357     return "void";
358   case SimpleTypeKind::WideCharacter:
359     return "wchar_t";
360   default:
361     return "";
362   }
363 }
364 
365 static bool IsClassRecord(TypeLeafKind kind) {
366   switch (kind) {
367   case LF_STRUCTURE:
368   case LF_CLASS:
369   case LF_INTERFACE:
370     return true;
371   default:
372     return false;
373   }
374 }
375 
376 static PDB_SymType GetPdbSymType(TpiStream &tpi, TypeIndex ti) {
377   if (ti.isSimple()) {
378     if (ti.getSimpleMode() == SimpleTypeMode::Direct)
379       return PDB_SymType::BuiltinType;
380     return PDB_SymType::PointerType;
381   }
382 
383   CVType cvt = tpi.getType(ti);
384   TypeLeafKind kind = cvt.kind();
385   if (kind != LF_MODIFIER)
386     return CVTypeToPDBType(kind);
387 
388   // If this is an LF_MODIFIER, look through it to get the kind that it
389   // modifies.  Note that it's not possible to have an LF_MODIFIER that
390   // modifies another LF_MODIFIER, although this would handle that anyway.
391   ModifierRecord mr;
392   llvm::cantFail(TypeDeserializer::deserializeAs<ModifierRecord>(cvt, mr));
393   return GetPdbSymType(tpi, mr.ModifiedType);
394 }
395 
396 static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) {
397   switch (cr.Kind) {
398   case TypeRecordKind::Class:
399     return clang::TTK_Class;
400   case TypeRecordKind::Struct:
401     return clang::TTK_Struct;
402   case TypeRecordKind::Union:
403     return clang::TTK_Union;
404   case TypeRecordKind::Interface:
405     return clang::TTK_Interface;
406   case TypeRecordKind::Enum:
407     return clang::TTK_Enum;
408   default:
409     lldbassert(false && "Invalid tag record kind!");
410     return clang::TTK_Struct;
411   }
412 }
413 
414 void SymbolFileNativePDB::Initialize() {
415   PluginManager::RegisterPlugin(GetPluginNameStatic(),
416                                 GetPluginDescriptionStatic(), CreateInstance,
417                                 DebuggerInitialize);
418 }
419 
420 void SymbolFileNativePDB::Terminate() {
421   PluginManager::UnregisterPlugin(CreateInstance);
422 }
423 
424 void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {}
425 
426 ConstString SymbolFileNativePDB::GetPluginNameStatic() {
427   static ConstString g_name("native-pdb");
428   return g_name;
429 }
430 
431 const char *SymbolFileNativePDB::GetPluginDescriptionStatic() {
432   return "Microsoft PDB debug symbol cross-platform file reader.";
433 }
434 
435 SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFile *obj_file) {
436   return new SymbolFileNativePDB(obj_file);
437 }
438 
439 SymbolFileNativePDB::SymbolFileNativePDB(ObjectFile *object_file)
440     : SymbolFile(object_file) {}
441 
442 SymbolFileNativePDB::~SymbolFileNativePDB() {}
443 
444 uint32_t SymbolFileNativePDB::CalculateAbilities() {
445   uint32_t abilities = 0;
446   if (!m_obj_file)
447     return 0;
448 
449   if (!m_index) {
450     // Lazily load and match the PDB file, but only do this once.
451     std::unique_ptr<PDBFile> file_up =
452         loadMatchingPDBFile(m_obj_file->GetFileSpec().GetPath(), m_allocator);
453 
454     if (!file_up) {
455       auto module_sp = m_obj_file->GetModule();
456       if (!module_sp)
457         return 0;
458       // See if any symbol file is specified through `--symfile` option.
459       FileSpec symfile = module_sp->GetSymbolFileFileSpec();
460       if (!symfile)
461         return 0;
462       file_up = loadPDBFile(symfile.GetPath(), m_allocator);
463     }
464 
465     if (!file_up)
466       return 0;
467 
468     auto expected_index = PdbIndex::create(std::move(file_up));
469     if (!expected_index) {
470       llvm::consumeError(expected_index.takeError());
471       return 0;
472     }
473     m_index = std::move(*expected_index);
474   }
475   if (!m_index)
476     return 0;
477 
478   // We don't especially have to be precise here.  We only distinguish between
479   // stripped and not stripped.
480   abilities = kAllAbilities;
481 
482   if (m_index->dbi().isStripped())
483     abilities &= ~(Blocks | LocalVariables);
484   return abilities;
485 }
486 
487 void SymbolFileNativePDB::InitializeObject() {
488   m_obj_load_address = m_obj_file->GetFileOffset();
489   m_index->SetLoadAddress(m_obj_load_address);
490   m_index->ParseSectionContribs();
491 
492   TypeSystem *ts = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
493   m_clang = llvm::dyn_cast_or_null<ClangASTContext>(ts);
494   m_importer = llvm::make_unique<ClangASTImporter>();
495   lldbassert(m_clang);
496 }
497 
498 uint32_t SymbolFileNativePDB::GetNumCompileUnits() {
499   const DbiModuleList &modules = m_index->dbi().modules();
500   uint32_t count = modules.getModuleCount();
501   if (count == 0)
502     return count;
503 
504   // The linker can inject an additional "dummy" compilation unit into the
505   // PDB. Ignore this special compile unit for our purposes, if it is there.
506   // It is always the last one.
507   DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1);
508   if (last.getModuleName() == "* Linker *")
509     --count;
510   return count;
511 }
512 
513 lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbSymUid func_uid,
514                                                      const SymbolContext &sc) {
515   lldbassert(func_uid.tag() == PDB_SymType::Function);
516 
517   PdbSymUid cuid = PdbSymUid::makeCompilandId(func_uid.asCuSym().modi);
518 
519   const CompilandIndexItem *cci = m_index->compilands().GetCompiland(cuid);
520   lldbassert(cci);
521   CVSymbol sym_record =
522       cci->m_debug_stream.readSymbolAtOffset(func_uid.asCuSym().offset);
523 
524   lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32);
525   SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record);
526 
527   auto file_vm_addr = m_index->MakeVirtualAddress(sol.so);
528   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
529     return nullptr;
530 
531   AddressRange func_range(file_vm_addr, sol.length,
532                           sc.module_sp->GetSectionList());
533   if (!func_range.GetBaseAddress().IsValid())
534     return nullptr;
535 
536   Type *func_type = nullptr;
537 
538   // FIXME: Resolve types and mangled names.
539   PdbSymUid sig_uid =
540       PdbSymUid::makeTypeSymId(PDB_SymType::FunctionSig, TypeIndex{0}, false);
541   Mangled mangled(getSymbolName(sym_record));
542 
543   FunctionSP func_sp = std::make_shared<Function>(
544       sc.comp_unit, func_uid.toOpaqueId(), sig_uid.toOpaqueId(), mangled,
545       func_type, func_range);
546 
547   sc.comp_unit->AddFunction(func_sp);
548   return func_sp;
549 }
550 
551 CompUnitSP
552 SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) {
553   lldb::LanguageType lang =
554       cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage())
555                          : lldb::eLanguageTypeUnknown;
556 
557   LazyBool optimized = eLazyBoolNo;
558   if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations())
559     optimized = eLazyBoolYes;
560 
561   llvm::StringRef source_file_name =
562       m_index->compilands().GetMainSourceFile(cci);
563   FileSpec fs(source_file_name, false);
564 
565   CompUnitSP cu_sp =
566       std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr, fs,
567                                     cci.m_uid.toOpaqueId(), lang, optimized);
568 
569   const PdbCompilandId &cuid = cci.m_uid.asCompiland();
570   m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(cuid.modi,
571                                                                     cu_sp);
572   return cu_sp;
573 }
574 
575 lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbSymUid type_uid,
576                                                      const ModifierRecord &mr) {
577   TpiStream &stream = m_index->tpi();
578 
579   TypeSP t = GetOrCreateType(mr.ModifiedType);
580   CompilerType ct = t->GetForwardCompilerType();
581   if ((mr.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
582     ct = ct.AddConstModifier();
583   if ((mr.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
584     ct = ct.AddVolatileModifier();
585   std::string name;
586   if (mr.ModifiedType.isSimple())
587     name = GetSimpleTypeName(mr.ModifiedType.getSimpleKind());
588   else
589     name = computeTypeName(stream.typeCollection(), mr.ModifiedType);
590   Declaration decl;
591   return std::make_shared<Type>(type_uid.toOpaqueId(), m_clang->GetSymbolFile(),
592                                 ConstString(name), t->GetByteSize(), nullptr,
593                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
594                                 ct, Type::eResolveStateFull);
595 }
596 
597 lldb::TypeSP SymbolFileNativePDB::CreatePointerType(
598     PdbSymUid type_uid, const llvm::codeview::PointerRecord &pr) {
599   TypeSP pointee = GetOrCreateType(pr.ReferentType);
600   CompilerType pointee_ct = pointee->GetForwardCompilerType();
601   lldbassert(pointee_ct);
602   Declaration decl;
603 
604   if (pr.isPointerToMember()) {
605     MemberPointerInfo mpi = pr.getMemberInfo();
606     TypeSP class_type = GetOrCreateType(mpi.ContainingType);
607 
608     CompilerType ct = ClangASTContext::CreateMemberPointerType(
609         class_type->GetLayoutCompilerType(), pointee_ct);
610 
611     return std::make_shared<Type>(
612         type_uid.toOpaqueId(), m_clang->GetSymbolFile(), ConstString(),
613         pr.getSize(), nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct,
614         Type::eResolveStateFull);
615   }
616 
617   CompilerType pointer_ct = pointee_ct;
618   if (pr.getMode() == PointerMode::LValueReference)
619     pointer_ct = pointer_ct.GetLValueReferenceType();
620   else if (pr.getMode() == PointerMode::RValueReference)
621     pointer_ct = pointer_ct.GetRValueReferenceType();
622   else
623     pointer_ct = pointer_ct.GetPointerType();
624 
625   if ((pr.getOptions() & PointerOptions::Const) != PointerOptions::None)
626     pointer_ct = pointer_ct.AddConstModifier();
627 
628   if ((pr.getOptions() & PointerOptions::Volatile) != PointerOptions::None)
629     pointer_ct = pointer_ct.AddVolatileModifier();
630 
631   if ((pr.getOptions() & PointerOptions::Restrict) != PointerOptions::None)
632     pointer_ct = pointer_ct.AddRestrictModifier();
633 
634   return std::make_shared<Type>(type_uid.toOpaqueId(), m_clang->GetSymbolFile(),
635                                 ConstString(), pr.getSize(), nullptr,
636                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
637                                 pointer_ct, Type::eResolveStateFull);
638 }
639 
640 lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti) {
641   if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
642     PdbSymUid uid =
643         PdbSymUid::makeTypeSymId(PDB_SymType::PointerType, ti, false);
644     TypeSP direct_sp = GetOrCreateType(ti.makeDirect());
645     CompilerType ct = direct_sp->GetFullCompilerType();
646     ct = ct.GetPointerType();
647     uint32_t pointer_size = 0;
648     switch (ti.getSimpleMode()) {
649     case SimpleTypeMode::FarPointer32:
650     case SimpleTypeMode::NearPointer32:
651       pointer_size = 4;
652       break;
653     case SimpleTypeMode::NearPointer64:
654       pointer_size = 8;
655       break;
656     default:
657       // 128-bit and 16-bit pointers unsupported.
658       return nullptr;
659     }
660     Declaration decl;
661     return std::make_shared<Type>(uid.toOpaqueId(), m_clang->GetSymbolFile(),
662                                   ConstString(), pointer_size, nullptr,
663                                   LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
664                                   ct, Type::eResolveStateFull);
665   }
666 
667   PdbSymUid uid = PdbSymUid::makeTypeSymId(PDB_SymType::BuiltinType, ti, false);
668   if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
669     return nullptr;
670 
671   lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind());
672   lldbassert(bt != lldb::eBasicTypeInvalid);
673   CompilerType ct = m_clang->GetBasicType(bt);
674   size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind());
675 
676   llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind());
677 
678   Declaration decl;
679   return std::make_shared<Type>(uid.toOpaqueId(), m_clang->GetSymbolFile(),
680                                 ConstString(type_name), size, nullptr,
681                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
682                                 ct, Type::eResolveStateFull);
683 }
684 
685 lldb::TypeSP SymbolFileNativePDB::CreateClassStructUnion(
686     PdbSymUid type_uid, llvm::StringRef name, size_t size,
687     clang::TagTypeKind ttk, clang::MSInheritanceAttr::Spelling inheritance) {
688 
689   // Some UDT with trival ctor has zero length. Just ignore.
690   if (size == 0)
691     return nullptr;
692 
693   // Ignore unnamed-tag UDTs.
694   name = DropNameScope(name);
695   if (name.empty())
696     return nullptr;
697 
698   clang::DeclContext *decl_context = m_clang->GetTranslationUnitDecl();
699 
700   lldb::AccessType access =
701       (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic;
702 
703   ClangASTMetadata metadata;
704   metadata.SetUserID(type_uid.toOpaqueId());
705   metadata.SetIsDynamicCXXType(false);
706 
707   CompilerType ct =
708       m_clang->CreateRecordType(decl_context, access, name.str().c_str(), ttk,
709                                 lldb::eLanguageTypeC_plus_plus, &metadata);
710   lldbassert(ct.IsValid());
711 
712   clang::CXXRecordDecl *record_decl =
713       m_clang->GetAsCXXRecordDecl(ct.GetOpaqueQualType());
714   lldbassert(record_decl);
715 
716   clang::MSInheritanceAttr *attr = clang::MSInheritanceAttr::CreateImplicit(
717       *m_clang->getASTContext(), inheritance);
718   record_decl->addAttr(attr);
719 
720   ClangASTContext::StartTagDeclarationDefinition(ct);
721 
722   // Even if it's possible, don't complete it at this point. Just mark it
723   // forward resolved, and if/when LLDB needs the full definition, it can
724   // ask us.
725   ClangASTContext::SetHasExternalStorage(ct.GetOpaqueQualType(), true);
726 
727   // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE.
728   Declaration decl;
729   return std::make_shared<Type>(type_uid.toOpaqueId(), m_clang->GetSymbolFile(),
730                                 ConstString(name), size, nullptr,
731                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
732                                 ct, Type::eResolveStateForward);
733 }
734 
735 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbSymUid type_uid,
736                                                 const ClassRecord &cr) {
737   clang::TagTypeKind ttk = TranslateUdtKind(cr);
738 
739   clang::MSInheritanceAttr::Spelling inheritance =
740       GetMSInheritance(m_index->tpi().typeCollection(), cr);
741   return CreateClassStructUnion(type_uid, cr.getName(), cr.getSize(), ttk,
742                                 inheritance);
743 }
744 
745 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbSymUid type_uid,
746                                                 const UnionRecord &ur) {
747   return CreateClassStructUnion(
748       type_uid, ur.getName(), ur.getSize(), clang::TTK_Union,
749       clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance);
750 }
751 
752 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbSymUid type_uid,
753                                                 const EnumRecord &er) {
754   llvm::StringRef name = DropNameScope(er.getName());
755 
756   clang::DeclContext *decl_context = m_clang->GetTranslationUnitDecl();
757 
758   Declaration decl;
759   TypeSP underlying_type = GetOrCreateType(er.UnderlyingType);
760   CompilerType enum_ct = m_clang->CreateEnumerationType(
761       name.str().c_str(), decl_context, decl,
762       underlying_type->GetFullCompilerType(), er.isScoped());
763 
764   ClangASTContext::StartTagDeclarationDefinition(enum_ct);
765 
766   // We're just going to forward resolve this for now.  We'll complete
767   // it only if the user requests.
768   return std::make_shared<lldb_private::Type>(
769       type_uid.toOpaqueId(), m_clang->GetSymbolFile(), ConstString(name),
770       underlying_type->GetByteSize(), nullptr, LLDB_INVALID_UID,
771       lldb_private::Type::eEncodingIsUID, decl, enum_ct,
772       lldb_private::Type::eResolveStateForward);
773 }
774 
775 TypeSP SymbolFileNativePDB::CreateType(PdbSymUid type_uid) {
776   const PdbTypeSymId &tsid = type_uid.asTypeSym();
777   TypeIndex index(tsid.index);
778 
779   if (index.getIndex() < TypeIndex::FirstNonSimpleIndex)
780     return CreateSimpleType(index);
781 
782   TpiStream &stream = tsid.is_ipi ? m_index->ipi() : m_index->tpi();
783   CVType cvt = stream.getType(index);
784 
785   if (cvt.kind() == LF_MODIFIER) {
786     ModifierRecord modifier;
787     llvm::cantFail(
788         TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
789     return CreateModifierType(type_uid, modifier);
790   }
791 
792   if (cvt.kind() == LF_POINTER) {
793     PointerRecord pointer;
794     llvm::cantFail(
795         TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
796     return CreatePointerType(type_uid, pointer);
797   }
798 
799   if (IsClassRecord(cvt.kind())) {
800     ClassRecord cr;
801     llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr));
802     return CreateTagType(type_uid, cr);
803   }
804 
805   if (cvt.kind() == LF_ENUM) {
806     EnumRecord er;
807     llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er));
808     return CreateTagType(type_uid, er);
809   }
810 
811   if (cvt.kind() == LF_UNION) {
812     UnionRecord ur;
813     llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur));
814     return CreateTagType(type_uid, ur);
815   }
816 
817   return nullptr;
818 }
819 
820 TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbSymUid type_uid) {
821   // If they search for a UDT which is a forward ref, try and resolve the full
822   // decl and just map the forward ref uid to the full decl record.
823   llvm::Optional<PdbSymUid> full_decl_uid;
824   if (type_uid.tag() == PDB_SymType::UDT ||
825       type_uid.tag() == PDB_SymType::Enum) {
826     const PdbTypeSymId &type_id = type_uid.asTypeSym();
827     TypeIndex ti(type_id.index);
828     lldbassert(!ti.isSimple());
829     CVType cvt = m_index->tpi().getType(ti);
830 
831     if (IsForwardRefUdt(cvt)) {
832       auto expected_full_ti = m_index->tpi().findFullDeclForForwardRef(ti);
833       if (!expected_full_ti)
834         llvm::consumeError(expected_full_ti.takeError());
835       else {
836         full_decl_uid = PdbSymUid::makeTypeSymId(
837             type_uid.tag(), *expected_full_ti, type_id.is_ipi);
838 
839         // It's possible that a lookup would occur for the full decl causing it
840         // to be cached, then a second lookup would occur for the forward decl.
841         // We don't want to create a second full decl, so make sure the full
842         // decl hasn't already been cached.
843         auto full_iter = m_types.find(full_decl_uid->toOpaqueId());
844         if (full_iter != m_types.end()) {
845           TypeSP result = full_iter->second;
846           // Map the forward decl to the TypeSP for the full decl so we can take
847           // the fast path next time.
848           m_types[type_uid.toOpaqueId()] = result;
849           return result;
850         }
851       }
852     }
853   }
854 
855   PdbSymUid best_uid = full_decl_uid ? *full_decl_uid : type_uid;
856   TypeSP result = CreateType(best_uid);
857   m_types[best_uid.toOpaqueId()] = result;
858   // If we had both a forward decl and a full decl, make both point to the new
859   // type.
860   if (full_decl_uid)
861     m_types[type_uid.toOpaqueId()] = result;
862 
863   const PdbTypeSymId &type_id = best_uid.asTypeSym();
864   if (best_uid.tag() == PDB_SymType::UDT ||
865       best_uid.tag() == PDB_SymType::Enum) {
866     clang::TagDecl *record_decl =
867         m_clang->GetAsTagDecl(result->GetForwardCompilerType());
868     lldbassert(record_decl);
869 
870     TypeIndex ti(type_id.index);
871     m_uid_to_decl[best_uid.toOpaqueId()] = record_decl;
872     m_decl_to_status[record_decl] =
873         DeclStatus(best_uid.toOpaqueId(), Type::eResolveStateForward);
874   }
875   return result;
876 }
877 
878 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbSymUid type_uid) {
879   lldbassert(PdbSymUid::isTypeSym(type_uid.tag()));
880   // We can't use try_emplace / overwrite here because the process of creating
881   // a type could create nested types, which could invalidate iterators.  So
882   // we have to do a 2-phase lookup / insert.
883   auto iter = m_types.find(type_uid.toOpaqueId());
884   if (iter != m_types.end())
885     return iter->second;
886 
887   return CreateAndCacheType(type_uid);
888 }
889 
890 lldb::TypeSP
891 SymbolFileNativePDB::GetOrCreateType(llvm::codeview::TypeIndex ti) {
892   PDB_SymType pdbst = GetPdbSymType(m_index->tpi(), ti);
893   PdbSymUid tuid = PdbSymUid::makeTypeSymId(pdbst, ti, false);
894   return GetOrCreateType(tuid);
895 }
896 
897 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbSymUid func_uid,
898                                                     const SymbolContext &sc) {
899   lldbassert(func_uid.tag() == PDB_SymType::Function);
900   auto emplace_result = m_functions.try_emplace(func_uid.toOpaqueId(), nullptr);
901   if (emplace_result.second)
902     emplace_result.first->second = CreateFunction(func_uid, sc);
903 
904   lldbassert(emplace_result.first->second);
905   return emplace_result.first->second;
906 }
907 
908 CompUnitSP
909 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) {
910   auto emplace_result =
911       m_compilands.try_emplace(cci.m_uid.toOpaqueId(), nullptr);
912   if (emplace_result.second)
913     emplace_result.first->second = CreateCompileUnit(cci);
914 
915   lldbassert(emplace_result.first->second);
916   return emplace_result.first->second;
917 }
918 
919 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) {
920   if (index >= GetNumCompileUnits())
921     return CompUnitSP();
922   lldbassert(index < UINT16_MAX);
923   if (index >= UINT16_MAX)
924     return nullptr;
925 
926   CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
927 
928   return GetOrCreateCompileUnit(item);
929 }
930 
931 lldb::LanguageType
932 SymbolFileNativePDB::ParseCompileUnitLanguage(const SymbolContext &sc) {
933   // What fields should I expect to be filled out on the SymbolContext?  Is it
934   // safe to assume that `sc.comp_unit` is valid?
935   if (!sc.comp_unit)
936     return lldb::eLanguageTypeUnknown;
937   PdbSymUid uid = PdbSymUid::fromOpaqueId(sc.comp_unit->GetID());
938   lldbassert(uid.tag() == PDB_SymType::Compiland);
939 
940   CompilandIndexItem *item = m_index->compilands().GetCompiland(uid);
941   lldbassert(item);
942   if (!item->m_compile_opts)
943     return lldb::eLanguageTypeUnknown;
944 
945   return TranslateLanguage(item->m_compile_opts->getLanguage());
946 }
947 
948 size_t SymbolFileNativePDB::ParseCompileUnitFunctions(const SymbolContext &sc) {
949   lldbassert(sc.comp_unit);
950   return false;
951 }
952 
953 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
954   // If any of these flags are set, we need to resolve the compile unit.
955   uint32_t flags = eSymbolContextCompUnit;
956   flags |= eSymbolContextVariable;
957   flags |= eSymbolContextFunction;
958   flags |= eSymbolContextBlock;
959   flags |= eSymbolContextLineEntry;
960   return (resolve_scope & flags) != 0;
961 }
962 
963 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
964     const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
965   uint32_t resolved_flags = 0;
966   lldb::addr_t file_addr = addr.GetFileAddress();
967 
968   if (NeedsResolvedCompileUnit(resolve_scope)) {
969     llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
970     if (!modi)
971       return 0;
972     PdbSymUid cuid = PdbSymUid::makeCompilandId(*modi);
973     CompilandIndexItem *cci = m_index->compilands().GetCompiland(cuid);
974     if (!cci)
975       return 0;
976 
977     sc.comp_unit = GetOrCreateCompileUnit(*cci).get();
978     resolved_flags |= eSymbolContextCompUnit;
979   }
980 
981   if (resolve_scope & eSymbolContextFunction) {
982     lldbassert(sc.comp_unit);
983     std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
984     for (const auto &match : matches) {
985       if (match.uid.tag() != PDB_SymType::Function)
986         continue;
987       sc.function = GetOrCreateFunction(match.uid, sc).get();
988     }
989     resolved_flags |= eSymbolContextFunction;
990   }
991 
992   if (resolve_scope & eSymbolContextLineEntry) {
993     lldbassert(sc.comp_unit);
994     if (auto *line_table = sc.comp_unit->GetLineTable()) {
995       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
996         resolved_flags |= eSymbolContextLineEntry;
997     }
998   }
999 
1000   return resolved_flags;
1001 }
1002 
1003 static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence,
1004                                       const CompilandIndexItem &cci,
1005                                       lldb::addr_t base_addr,
1006                                       uint32_t file_number,
1007                                       const LineFragmentHeader &block,
1008                                       const LineNumberEntry &cur) {
1009   LineInfo cur_info(cur.Flags);
1010 
1011   if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1012     return;
1013 
1014   uint64_t addr = base_addr + cur.Offset;
1015 
1016   bool is_statement = cur_info.isStatement();
1017   bool is_prologue = IsFunctionPrologue(cci, addr);
1018   bool is_epilogue = IsFunctionEpilogue(cci, addr);
1019 
1020   uint32_t lno = cur_info.getStartLine();
1021 
1022   table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number,
1023                                   is_statement, false, is_prologue, is_epilogue,
1024                                   false);
1025 }
1026 
1027 static void TerminateLineSequence(LineTable &table,
1028                                   const LineFragmentHeader &block,
1029                                   lldb::addr_t base_addr, uint32_t file_number,
1030                                   uint32_t last_line,
1031                                   std::unique_ptr<LineSequence> seq) {
1032   // The end is always a terminal entry, so insert it regardless.
1033   table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize,
1034                                   last_line, 0, file_number, false, false,
1035                                   false, false, true);
1036   table.InsertSequence(seq.release());
1037 }
1038 
1039 bool SymbolFileNativePDB::ParseCompileUnitLineTable(const SymbolContext &sc) {
1040   // Unfortunately LLDB is set up to parse the entire compile unit line table
1041   // all at once, even if all it really needs is line info for a specific
1042   // function.  In the future it would be nice if it could set the sc.m_function
1043   // member, and we could only get the line info for the function in question.
1044   lldbassert(sc.comp_unit);
1045   PdbSymUid cu_id = PdbSymUid::fromOpaqueId(sc.comp_unit->GetID());
1046   lldbassert(cu_id.isCompiland());
1047   CompilandIndexItem *cci = m_index->compilands().GetCompiland(cu_id);
1048   lldbassert(cci);
1049   auto line_table = llvm::make_unique<LineTable>(sc.comp_unit);
1050 
1051   // This is basically a copy of the .debug$S subsections from all original COFF
1052   // object files merged together with address relocations applied.  We are
1053   // looking for all DEBUG_S_LINES subsections.
1054   for (const DebugSubsectionRecord &dssr :
1055        cci->m_debug_stream.getSubsectionsArray()) {
1056     if (dssr.kind() != DebugSubsectionKind::Lines)
1057       continue;
1058 
1059     DebugLinesSubsectionRef lines;
1060     llvm::BinaryStreamReader reader(dssr.getRecordData());
1061     if (auto EC = lines.initialize(reader)) {
1062       llvm::consumeError(std::move(EC));
1063       return false;
1064     }
1065 
1066     const LineFragmentHeader *lfh = lines.header();
1067     uint64_t virtual_addr =
1068         m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1069 
1070     const auto &checksums = cci->m_strings.checksums().getArray();
1071     const auto &strings = cci->m_strings.strings();
1072     for (const LineColumnEntry &group : lines) {
1073       // Indices in this structure are actually offsets of records in the
1074       // DEBUG_S_FILECHECKSUMS subsection.  Those entries then have an index
1075       // into the global PDB string table.
1076       auto iter = checksums.at(group.NameIndex);
1077       if (iter == checksums.end())
1078         continue;
1079 
1080       llvm::Expected<llvm::StringRef> efn =
1081           strings.getString(iter->FileNameOffset);
1082       if (!efn) {
1083         llvm::consumeError(efn.takeError());
1084         continue;
1085       }
1086 
1087       // LLDB wants the index of the file in the list of support files.
1088       auto fn_iter = llvm::find(cci->m_file_list, *efn);
1089       lldbassert(fn_iter != cci->m_file_list.end());
1090       uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter);
1091 
1092       std::unique_ptr<LineSequence> sequence(
1093           line_table->CreateLineSequenceContainer());
1094       lldbassert(!group.LineNumbers.empty());
1095 
1096       for (const LineNumberEntry &entry : group.LineNumbers) {
1097         AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr,
1098                                   file_index, *lfh, entry);
1099       }
1100       LineInfo last_line(group.LineNumbers.back().Flags);
1101       TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index,
1102                             last_line.getEndLine(), std::move(sequence));
1103     }
1104   }
1105 
1106   if (line_table->GetSize() == 0)
1107     return false;
1108 
1109   sc.comp_unit->SetLineTable(line_table.release());
1110   return true;
1111 }
1112 
1113 bool SymbolFileNativePDB::ParseCompileUnitDebugMacros(const SymbolContext &sc) {
1114   // PDB doesn't contain information about macros
1115   return false;
1116 }
1117 
1118 bool SymbolFileNativePDB::ParseCompileUnitSupportFiles(
1119     const SymbolContext &sc, FileSpecList &support_files) {
1120   lldbassert(sc.comp_unit);
1121 
1122   PdbSymUid comp_uid = PdbSymUid::fromOpaqueId(sc.comp_unit->GetID());
1123   lldbassert(comp_uid.tag() == PDB_SymType::Compiland);
1124 
1125   const CompilandIndexItem *cci = m_index->compilands().GetCompiland(comp_uid);
1126   lldbassert(cci);
1127 
1128   for (llvm::StringRef f : cci->m_file_list) {
1129     FileSpec::Style style =
1130         f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1131     FileSpec spec(f, false, style);
1132     support_files.Append(spec);
1133   }
1134 
1135   return true;
1136 }
1137 
1138 bool SymbolFileNativePDB::ParseImportedModules(
1139     const SymbolContext &sc, std::vector<ConstString> &imported_modules) {
1140   // PDB does not yet support module debug info
1141   return false;
1142 }
1143 
1144 size_t SymbolFileNativePDB::ParseFunctionBlocks(const SymbolContext &sc) {
1145   lldbassert(sc.comp_unit && sc.function);
1146   return 0;
1147 }
1148 
1149 uint32_t SymbolFileNativePDB::FindFunctions(
1150     const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
1151     uint32_t name_type_mask, bool include_inlines, bool append,
1152     SymbolContextList &sc_list) {
1153   // For now we only support lookup by method name.
1154   if (!(name_type_mask & eFunctionNameTypeMethod))
1155     return 0;
1156 
1157   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1158 
1159   std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName(
1160       name.GetStringRef(), m_index->symrecords());
1161   for (const SymbolAndOffset &match : matches) {
1162     if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF)
1163       continue;
1164     ProcRefSym proc(match.second.kind());
1165     cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc));
1166 
1167     if (!IsValidRecord(proc))
1168       continue;
1169 
1170     PdbSymUid cuid = PdbSymUid::makeCompilandId(proc);
1171     CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(cuid);
1172     SymbolContext sc;
1173 
1174     sc.comp_unit = GetOrCreateCompileUnit(cci).get();
1175     sc.module_sp = sc.comp_unit->GetModule();
1176     PdbSymUid func_uid = PdbSymUid::makeCuSymId(proc);
1177     sc.function = GetOrCreateFunction(func_uid, sc).get();
1178 
1179     sc_list.Append(sc);
1180   }
1181 
1182   return sc_list.GetSize();
1183 }
1184 
1185 uint32_t SymbolFileNativePDB::FindFunctions(const RegularExpression &regex,
1186                                             bool include_inlines, bool append,
1187                                             SymbolContextList &sc_list) {
1188   return 0;
1189 }
1190 
1191 uint32_t SymbolFileNativePDB::FindTypes(
1192     const SymbolContext &sc, const ConstString &name,
1193     const CompilerDeclContext *parent_decl_ctx, bool append,
1194     uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1195     TypeMap &types) {
1196   if (!append)
1197     types.Clear();
1198   if (!name)
1199     return 0;
1200 
1201   searched_symbol_files.clear();
1202   searched_symbol_files.insert(this);
1203 
1204   // There is an assumption 'name' is not a regex
1205   size_t match_count = FindTypesByName(name.GetStringRef(), max_matches, types);
1206 
1207   return match_count;
1208 }
1209 
1210 size_t
1211 SymbolFileNativePDB::FindTypes(const std::vector<CompilerContext> &context,
1212                                bool append, TypeMap &types) {
1213   return 0;
1214 }
1215 
1216 size_t SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1217                                             uint32_t max_matches,
1218                                             TypeMap &types) {
1219 
1220   size_t match_count = 0;
1221   std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1222   if (max_matches > 0 && max_matches < matches.size())
1223     matches.resize(max_matches);
1224 
1225   for (TypeIndex ti : matches) {
1226     TypeSP type = GetOrCreateType(ti);
1227     if (!type)
1228       continue;
1229 
1230     types.Insert(type);
1231     ++match_count;
1232   }
1233   return match_count;
1234 }
1235 
1236 size_t SymbolFileNativePDB::ParseTypes(const SymbolContext &sc) { return 0; }
1237 
1238 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
1239   auto iter = m_types.find(type_uid);
1240   // lldb should not be passing us non-sensical type uids.  the only way it
1241   // could have a type uid in the first place is if we handed it out, in which
1242   // case we should know about the type.  So this is not a get-or-create type
1243   // operation, it is strictly a get, and the type is guaranteed to exist.
1244   //
1245   // However, since the implementation is not yet complete, we don't currently
1246   // support all possible use cases.  For example, we currently create all
1247   // functions with indices of 0 for the signature type simply because this is
1248   // not yet implemented.  At the time the function object is created we should
1249   // be creating an lldb::TypeSP for this, adding it to the m_types, and
1250   // returning a valid Type object for it and putting it in this map.  Once all
1251   // cases like this are handled, we can promote this to an assert.
1252   if (iter == m_types.end())
1253     return nullptr;
1254   return &*iter->second;
1255 }
1256 
1257 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
1258   // If this is not in our map, it's an error.
1259   clang::TagDecl *tag_decl = m_clang->GetAsTagDecl(compiler_type);
1260   lldbassert(tag_decl);
1261   auto status_iter = m_decl_to_status.find(tag_decl);
1262   lldbassert(status_iter != m_decl_to_status.end());
1263 
1264   // If it's already complete, just return.
1265   DeclStatus &status = status_iter->second;
1266   if (status.status == Type::eResolveStateFull)
1267     return true;
1268 
1269   PdbSymUid uid = PdbSymUid::fromOpaqueId(status.uid);
1270   lldbassert(uid.tag() == PDB_SymType::UDT || uid.tag() == PDB_SymType::Enum);
1271 
1272   const PdbTypeSymId &type_id = uid.asTypeSym();
1273 
1274   ClangASTContext::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),
1275                                          false);
1276 
1277   // In CreateAndCacheType, we already go out of our way to resolve forward
1278   // ref UDTs to full decls, and the uids we vend out always refer to full
1279   // decls if a full decl exists in the debug info.  So if we don't have a full
1280   // decl here, it means one doesn't exist in the debug info, and we can't
1281   // complete the type.
1282   CVType cvt = m_index->tpi().getType(TypeIndex(type_id.index));
1283   if (IsForwardRefUdt(cvt))
1284     return false;
1285 
1286   auto types_iter = m_types.find(uid.toOpaqueId());
1287   lldbassert(types_iter != m_types.end());
1288 
1289   TypeIndex field_list_ti = GetFieldListIndex(cvt);
1290   CVType field_list_cvt = m_index->tpi().getType(field_list_ti);
1291   if (field_list_cvt.kind() != LF_FIELDLIST)
1292     return false;
1293 
1294   // Visit all members of this class, then perform any finalization necessary
1295   // to complete the class.
1296   UdtRecordCompleter completer(uid, compiler_type, *tag_decl, *this);
1297   auto error =
1298       llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer);
1299   completer.complete();
1300 
1301   status.status = Type::eResolveStateFull;
1302   if (!error)
1303     return true;
1304 
1305   llvm::consumeError(std::move(error));
1306   return false;
1307 }
1308 
1309 size_t SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1310                                      uint32_t type_mask,
1311                                      lldb_private::TypeList &type_list) {
1312   return 0;
1313 }
1314 
1315 CompilerDeclContext
1316 SymbolFileNativePDB::FindNamespace(const SymbolContext &sc,
1317                                    const ConstString &name,
1318                                    const CompilerDeclContext *parent_decl_ctx) {
1319   return {};
1320 }
1321 
1322 TypeSystem *
1323 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1324   auto type_system =
1325       m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
1326   if (type_system)
1327     type_system->SetSymbolFile(this);
1328   return type_system;
1329 }
1330 
1331 ConstString SymbolFileNativePDB::GetPluginName() {
1332   static ConstString g_name("pdb");
1333   return g_name;
1334 }
1335 
1336 uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; }
1337