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 #include "clang/AST/Type.h"
17 
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/StreamBuffer.h"
21 #include "lldb/Core/StreamFile.h"
22 #include "lldb/Symbol/ClangASTContext.h"
23 #include "lldb/Symbol/ClangASTImporter.h"
24 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
25 #include "lldb/Symbol/ClangUtil.h"
26 #include "lldb/Symbol/CompileUnit.h"
27 #include "lldb/Symbol/LineTable.h"
28 #include "lldb/Symbol/ObjectFile.h"
29 #include "lldb/Symbol/SymbolContext.h"
30 #include "lldb/Symbol/SymbolVendor.h"
31 #include "lldb/Symbol/Variable.h"
32 #include "lldb/Symbol/VariableList.h"
33 
34 #include "llvm/DebugInfo/CodeView/CVRecord.h"
35 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
36 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
37 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
38 #include "llvm/DebugInfo/CodeView/RecordName.h"
39 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
40 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
41 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
42 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
43 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
44 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
45 #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
46 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
47 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
48 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
49 #include "llvm/DebugInfo/PDB/PDBTypes.h"
50 #include "llvm/Demangle/MicrosoftDemangle.h"
51 #include "llvm/Object/COFF.h"
52 #include "llvm/Support/Allocator.h"
53 #include "llvm/Support/BinaryStreamReader.h"
54 #include "llvm/Support/Error.h"
55 #include "llvm/Support/ErrorOr.h"
56 #include "llvm/Support/MemoryBuffer.h"
57 
58 #include "DWARFLocationExpression.h"
59 #include "PdbSymUid.h"
60 #include "PdbUtil.h"
61 #include "UdtRecordCompleter.h"
62 
63 using namespace lldb;
64 using namespace lldb_private;
65 using namespace npdb;
66 using namespace llvm::codeview;
67 using namespace llvm::pdb;
68 
69 static lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
70   switch (lang) {
71   case PDB_Lang::Cpp:
72     return lldb::LanguageType::eLanguageTypeC_plus_plus;
73   case PDB_Lang::C:
74     return lldb::LanguageType::eLanguageTypeC;
75   default:
76     return lldb::LanguageType::eLanguageTypeUnknown;
77   }
78 }
79 
80 static std::unique_ptr<PDBFile> loadPDBFile(std::string PdbPath,
81                                             llvm::BumpPtrAllocator &Allocator) {
82   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ErrorOrBuffer =
83       llvm::MemoryBuffer::getFile(PdbPath, /*FileSize=*/-1,
84                                   /*RequiresNullTerminator=*/false);
85   if (!ErrorOrBuffer)
86     return nullptr;
87   std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(*ErrorOrBuffer);
88 
89   llvm::StringRef Path = Buffer->getBufferIdentifier();
90   auto Stream = llvm::make_unique<llvm::MemoryBufferByteStream>(
91       std::move(Buffer), llvm::support::little);
92 
93   auto File = llvm::make_unique<PDBFile>(Path, std::move(Stream), Allocator);
94   if (auto EC = File->parseFileHeaders()) {
95     llvm::consumeError(std::move(EC));
96     return nullptr;
97   }
98   if (auto EC = File->parseStreamData()) {
99     llvm::consumeError(std::move(EC));
100     return nullptr;
101   }
102 
103   return File;
104 }
105 
106 static std::unique_ptr<PDBFile>
107 loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) {
108   // Try to find a matching PDB for an EXE.
109   using namespace llvm::object;
110   auto expected_binary = createBinary(exe_path);
111 
112   // If the file isn't a PE/COFF executable, fail.
113   if (!expected_binary) {
114     llvm::consumeError(expected_binary.takeError());
115     return nullptr;
116   }
117   OwningBinary<Binary> binary = std::move(*expected_binary);
118 
119   auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary());
120   if (!obj)
121     return nullptr;
122   const llvm::codeview::DebugInfo *pdb_info = nullptr;
123 
124   // If it doesn't have a debug directory, fail.
125   llvm::StringRef pdb_file;
126   auto ec = obj->getDebugPDBInfo(pdb_info, pdb_file);
127   if (ec)
128     return nullptr;
129 
130   // if the file doesn't exist, is not a pdb, or doesn't have a matching guid,
131   // fail.
132   llvm::file_magic magic;
133   ec = llvm::identify_magic(pdb_file, magic);
134   if (ec || magic != llvm::file_magic::pdb)
135     return nullptr;
136   std::unique_ptr<PDBFile> pdb = loadPDBFile(pdb_file, allocator);
137   if (!pdb)
138     return nullptr;
139 
140   auto expected_info = pdb->getPDBInfoStream();
141   if (!expected_info) {
142     llvm::consumeError(expected_info.takeError());
143     return nullptr;
144   }
145   llvm::codeview::GUID guid;
146   memcpy(&guid, pdb_info->PDB70.Signature, 16);
147 
148   if (expected_info->getGuid() != guid)
149     return nullptr;
150   return pdb;
151 }
152 
153 static bool IsFunctionPrologue(const CompilandIndexItem &cci,
154                                lldb::addr_t addr) {
155   // FIXME: Implement this.
156   return false;
157 }
158 
159 static bool IsFunctionEpilogue(const CompilandIndexItem &cci,
160                                lldb::addr_t addr) {
161   // FIXME: Implement this.
162   return false;
163 }
164 
165 static clang::MSInheritanceAttr::Spelling
166 GetMSInheritance(LazyRandomTypeCollection &tpi, const ClassRecord &record) {
167   if (record.DerivationList == TypeIndex::None())
168     return clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance;
169 
170   CVType bases = tpi.getType(record.DerivationList);
171   ArgListRecord base_list;
172   cantFail(TypeDeserializer::deserializeAs<ArgListRecord>(bases, base_list));
173   if (base_list.ArgIndices.empty())
174     return clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance;
175 
176   int base_count = 0;
177   for (TypeIndex ti : base_list.ArgIndices) {
178     CVType base = tpi.getType(ti);
179     if (base.kind() == LF_VBCLASS || base.kind() == LF_IVBCLASS)
180       return clang::MSInheritanceAttr::Spelling::Keyword_virtual_inheritance;
181     ++base_count;
182   }
183 
184   if (base_count > 1)
185     return clang::MSInheritanceAttr::Keyword_multiple_inheritance;
186   return clang::MSInheritanceAttr::Keyword_single_inheritance;
187 }
188 
189 static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) {
190   switch (kind) {
191   case SimpleTypeKind::Boolean128:
192   case SimpleTypeKind::Boolean16:
193   case SimpleTypeKind::Boolean32:
194   case SimpleTypeKind::Boolean64:
195   case SimpleTypeKind::Boolean8:
196     return "bool";
197   case SimpleTypeKind::Byte:
198   case SimpleTypeKind::UnsignedCharacter:
199     return "unsigned char";
200   case SimpleTypeKind::NarrowCharacter:
201     return "char";
202   case SimpleTypeKind::SignedCharacter:
203   case SimpleTypeKind::SByte:
204     return "signed char";
205   case SimpleTypeKind::Character16:
206     return "char16_t";
207   case SimpleTypeKind::Character32:
208     return "char32_t";
209   case SimpleTypeKind::Complex80:
210   case SimpleTypeKind::Complex64:
211   case SimpleTypeKind::Complex32:
212     return "complex";
213   case SimpleTypeKind::Float128:
214   case SimpleTypeKind::Float80:
215     return "long double";
216   case SimpleTypeKind::Float64:
217     return "double";
218   case SimpleTypeKind::Float32:
219     return "float";
220   case SimpleTypeKind::Float16:
221     return "single";
222   case SimpleTypeKind::Int128:
223     return "__int128";
224   case SimpleTypeKind::Int64:
225   case SimpleTypeKind::Int64Quad:
226     return "int64_t";
227   case SimpleTypeKind::Int32:
228     return "int";
229   case SimpleTypeKind::Int16:
230     return "short";
231   case SimpleTypeKind::UInt128:
232     return "unsigned __int128";
233   case SimpleTypeKind::UInt64:
234   case SimpleTypeKind::UInt64Quad:
235     return "uint64_t";
236   case SimpleTypeKind::HResult:
237     return "HRESULT";
238   case SimpleTypeKind::UInt32:
239     return "unsigned";
240   case SimpleTypeKind::UInt16:
241   case SimpleTypeKind::UInt16Short:
242     return "unsigned short";
243   case SimpleTypeKind::Int32Long:
244     return "long";
245   case SimpleTypeKind::UInt32Long:
246     return "unsigned long";
247   case SimpleTypeKind::Void:
248     return "void";
249   case SimpleTypeKind::WideCharacter:
250     return "wchar_t";
251   default:
252     return "";
253   }
254 }
255 
256 static bool IsClassRecord(TypeLeafKind kind) {
257   switch (kind) {
258   case LF_STRUCTURE:
259   case LF_CLASS:
260   case LF_INTERFACE:
261     return true;
262   default:
263     return false;
264   }
265 }
266 
267 static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) {
268   if (args.empty())
269     return false;
270   return args.back() == TypeIndex::None();
271 }
272 
273 static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) {
274   switch (cr.Kind) {
275   case TypeRecordKind::Class:
276     return clang::TTK_Class;
277   case TypeRecordKind::Struct:
278     return clang::TTK_Struct;
279   case TypeRecordKind::Union:
280     return clang::TTK_Union;
281   case TypeRecordKind::Interface:
282     return clang::TTK_Interface;
283   case TypeRecordKind::Enum:
284     return clang::TTK_Enum;
285   default:
286     lldbassert(false && "Invalid tag record kind!");
287     return clang::TTK_Struct;
288   }
289 }
290 
291 static llvm::Optional<clang::CallingConv>
292 TranslateCallingConvention(llvm::codeview::CallingConvention conv) {
293   using CC = llvm::codeview::CallingConvention;
294   switch (conv) {
295 
296   case CC::NearC:
297   case CC::FarC:
298     return clang::CallingConv::CC_C;
299   case CC::NearPascal:
300   case CC::FarPascal:
301     return clang::CallingConv::CC_X86Pascal;
302   case CC::NearFast:
303   case CC::FarFast:
304     return clang::CallingConv::CC_X86FastCall;
305   case CC::NearStdCall:
306   case CC::FarStdCall:
307     return clang::CallingConv::CC_X86StdCall;
308   case CC::ThisCall:
309     return clang::CallingConv::CC_X86ThisCall;
310   case CC::NearVector:
311     return clang::CallingConv::CC_X86VectorCall;
312   default:
313     return llvm::None;
314   }
315 }
316 
317 void SymbolFileNativePDB::Initialize() {
318   PluginManager::RegisterPlugin(GetPluginNameStatic(),
319                                 GetPluginDescriptionStatic(), CreateInstance,
320                                 DebuggerInitialize);
321 }
322 
323 void SymbolFileNativePDB::Terminate() {
324   PluginManager::UnregisterPlugin(CreateInstance);
325 }
326 
327 void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {}
328 
329 ConstString SymbolFileNativePDB::GetPluginNameStatic() {
330   static ConstString g_name("native-pdb");
331   return g_name;
332 }
333 
334 const char *SymbolFileNativePDB::GetPluginDescriptionStatic() {
335   return "Microsoft PDB debug symbol cross-platform file reader.";
336 }
337 
338 SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFile *obj_file) {
339   return new SymbolFileNativePDB(obj_file);
340 }
341 
342 SymbolFileNativePDB::SymbolFileNativePDB(ObjectFile *object_file)
343     : SymbolFile(object_file) {}
344 
345 SymbolFileNativePDB::~SymbolFileNativePDB() {}
346 
347 uint32_t SymbolFileNativePDB::CalculateAbilities() {
348   uint32_t abilities = 0;
349   if (!m_obj_file)
350     return 0;
351 
352   if (!m_index) {
353     // Lazily load and match the PDB file, but only do this once.
354     std::unique_ptr<PDBFile> file_up =
355         loadMatchingPDBFile(m_obj_file->GetFileSpec().GetPath(), m_allocator);
356 
357     if (!file_up) {
358       auto module_sp = m_obj_file->GetModule();
359       if (!module_sp)
360         return 0;
361       // See if any symbol file is specified through `--symfile` option.
362       FileSpec symfile = module_sp->GetSymbolFileFileSpec();
363       if (!symfile)
364         return 0;
365       file_up = loadPDBFile(symfile.GetPath(), m_allocator);
366     }
367 
368     if (!file_up)
369       return 0;
370 
371     auto expected_index = PdbIndex::create(std::move(file_up));
372     if (!expected_index) {
373       llvm::consumeError(expected_index.takeError());
374       return 0;
375     }
376     m_index = std::move(*expected_index);
377   }
378   if (!m_index)
379     return 0;
380 
381   // We don't especially have to be precise here.  We only distinguish between
382   // stripped and not stripped.
383   abilities = kAllAbilities;
384 
385   if (m_index->dbi().isStripped())
386     abilities &= ~(Blocks | LocalVariables);
387   return abilities;
388 }
389 
390 void SymbolFileNativePDB::InitializeObject() {
391   m_obj_load_address = m_obj_file->GetFileOffset();
392   m_index->SetLoadAddress(m_obj_load_address);
393   m_index->ParseSectionContribs();
394 
395   TypeSystem *ts = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
396   m_clang = llvm::dyn_cast_or_null<ClangASTContext>(ts);
397   m_importer = llvm::make_unique<ClangASTImporter>();
398 
399   PreprocessTpiStream();
400   lldbassert(m_clang);
401 }
402 
403 static llvm::Optional<CVTagRecord>
404 GetNestedTagRecord(const NestedTypeRecord &Record, const CVTagRecord &parent,
405                    TpiStream &tpi) {
406   // An LF_NESTTYPE is essentially a nested typedef / using declaration, but it
407   // is also used to indicate the primary definition of a nested class.  That is
408   // to say, if you have:
409   // struct A {
410   //   struct B {};
411   //   using C = B;
412   // };
413   // Then in the debug info, this will appear as:
414   // LF_STRUCTURE `A::B` [type index = N]
415   // LF_STRUCTURE `A`
416   //   LF_NESTTYPE [name = `B`, index = N]
417   //   LF_NESTTYPE [name = `C`, index = N]
418   // In order to accurately reconstruct the decl context hierarchy, we need to
419   // know which ones are actual definitions and which ones are just aliases.
420 
421   // If it's a simple type, then this is something like `using foo = int`.
422   if (Record.Type.isSimple())
423     return llvm::None;
424 
425   CVType cvt = tpi.getType(Record.Type);
426 
427   if (!IsTagRecord(cvt))
428     return llvm::None;
429 
430   // If it's an inner definition, then treat whatever name we have here as a
431   // single component of a mangled name.  So we can inject it into the parent's
432   // mangled name to see if it matches.
433   CVTagRecord child = CVTagRecord::create(cvt);
434   std::string qname = parent.asTag().getUniqueName();
435   if (qname.size() < 4 || child.asTag().getUniqueName().size() < 4)
436     return llvm::None;
437 
438   // qname[3] is the tag type identifier (struct, class, union, etc).  Since the
439   // inner tag type is not necessarily the same as the outer tag type, re-write
440   // it to match the inner tag type.
441   qname[3] = child.asTag().getUniqueName()[3];
442   std::string piece = Record.Name;
443   piece.push_back('@');
444   qname.insert(4, std::move(piece));
445   if (qname != child.asTag().UniqueName)
446     return llvm::None;
447 
448   return std::move(child);
449 }
450 
451 void SymbolFileNativePDB::PreprocessTpiStream() {
452   LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
453 
454   for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
455     CVType type = types.getType(*ti);
456     if (!IsTagRecord(type))
457       continue;
458 
459     CVTagRecord tag = CVTagRecord::create(type);
460     // We're looking for LF_NESTTYPE records in the field list, so ignore
461     // forward references (no field list), and anything without a nested class
462     // (since there won't be any LF_NESTTYPE records).
463     if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass())
464       continue;
465 
466     struct ProcessTpiStream : public TypeVisitorCallbacks {
467       ProcessTpiStream(PdbIndex &index, TypeIndex parent,
468                        const CVTagRecord &parent_cvt,
469                        llvm::DenseMap<TypeIndex, TypeIndex> &parents)
470           : index(index), parents(parents), parent(parent),
471             parent_cvt(parent_cvt) {}
472 
473       PdbIndex &index;
474       llvm::DenseMap<TypeIndex, TypeIndex> &parents;
475       TypeIndex parent;
476       const CVTagRecord &parent_cvt;
477 
478       llvm::Error visitKnownMember(CVMemberRecord &CVR,
479                                    NestedTypeRecord &Record) override {
480         llvm::Optional<CVTagRecord> tag =
481             GetNestedTagRecord(Record, parent_cvt, index.tpi());
482         if (!tag)
483           return llvm::ErrorSuccess();
484 
485         parents[Record.Type] = parent;
486         if (!tag->asTag().isForwardRef())
487           return llvm::ErrorSuccess();
488 
489         llvm::Expected<TypeIndex> full_decl =
490             index.tpi().findFullDeclForForwardRef(Record.Type);
491         if (!full_decl) {
492           llvm::consumeError(full_decl.takeError());
493           return llvm::ErrorSuccess();
494         }
495         parents[*full_decl] = parent;
496         return llvm::ErrorSuccess();
497       }
498     };
499 
500     CVType field_list = m_index->tpi().getType(tag.asTag().FieldList);
501     ProcessTpiStream process(*m_index, *ti, tag, m_parent_types);
502     llvm::Error error = visitMemberRecordStream(field_list.data(), process);
503     if (error)
504       llvm::consumeError(std::move(error));
505   }
506 }
507 
508 uint32_t SymbolFileNativePDB::GetNumCompileUnits() {
509   const DbiModuleList &modules = m_index->dbi().modules();
510   uint32_t count = modules.getModuleCount();
511   if (count == 0)
512     return count;
513 
514   // The linker can inject an additional "dummy" compilation unit into the
515   // PDB. Ignore this special compile unit for our purposes, if it is there.
516   // It is always the last one.
517   DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1);
518   if (last.getModuleName() == "* Linker *")
519     --count;
520   return count;
521 }
522 
523 lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbCompilandSymId func_id,
524                                                      const SymbolContext &sc) {
525   const CompilandIndexItem *cci =
526       m_index->compilands().GetCompiland(func_id.modi);
527   lldbassert(cci);
528   CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset);
529 
530   lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32);
531   SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record);
532 
533   auto file_vm_addr = m_index->MakeVirtualAddress(sol.so);
534   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
535     return nullptr;
536 
537   AddressRange func_range(file_vm_addr, sol.length,
538                           sc.module_sp->GetSectionList());
539   if (!func_range.GetBaseAddress().IsValid())
540     return nullptr;
541 
542   ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind()));
543   cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc));
544   TypeSP func_type = GetOrCreateType(proc.FunctionType);
545 
546   PdbTypeSymId sig_id(proc.FunctionType, false);
547   Mangled mangled(proc.Name);
548   FunctionSP func_sp = std::make_shared<Function>(
549       sc.comp_unit, toOpaqueUid(func_id), toOpaqueUid(sig_id), mangled,
550       func_type.get(), func_range);
551 
552   sc.comp_unit->AddFunction(func_sp);
553 
554   clang::StorageClass storage = clang::SC_None;
555   if (sym_record.kind() == S_LPROC32)
556     storage = clang::SC_Static;
557 
558   // There are two ways we could retrieve the parameter list.  The first is by
559   // iterating the arguments on the function signature type, however that would
560   // only tell us the types of the arguments and not the names.  The second is
561   // to iterate the CVSymbol records that follow the S_GPROC32 / S_LPROC32 until
562   // we have the correct number of arguments as stated by the function
563   // signature. The latter has more potential to go wrong in the face of
564   // improper debug info simply because we're assuming more about the layout of
565   // the records, but it is the only way to get argument names.
566   CVType sig_cvt;
567   CVType arg_list_cvt;
568   ProcedureRecord sig_record;
569   ArgListRecord arg_list_record;
570 
571   sig_cvt = m_index->tpi().getType(proc.FunctionType);
572   if (sig_cvt.kind() != LF_PROCEDURE)
573     return func_sp;
574   cantFail(
575       TypeDeserializer::deserializeAs<ProcedureRecord>(sig_cvt, sig_record));
576 
577   CompilerDeclContext context =
578       GetDeclContextContainingUID(toOpaqueUid(func_id));
579 
580   clang::DeclContext *decl_context =
581       static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext());
582   clang::FunctionDecl *function_decl = m_clang->CreateFunctionDeclaration(
583       decl_context, proc.Name.str().c_str(),
584       func_type->GetForwardCompilerType(), storage, false);
585 
586   lldbassert(m_uid_to_decl.count(toOpaqueUid(func_id)) == 0);
587   m_uid_to_decl[toOpaqueUid(func_id)] = function_decl;
588   CVSymbolArray scope = limitSymbolArrayToScope(
589       cci->m_debug_stream.getSymbolArray(), func_id.offset);
590 
591   uint32_t params_remaining = sig_record.getParameterCount();
592   auto begin = scope.begin();
593   auto end = scope.end();
594   std::vector<clang::ParmVarDecl *> params;
595   while (begin != end && params_remaining > 0) {
596     uint32_t record_offset = begin.offset();
597     CVSymbol sym = *begin++;
598 
599     TypeIndex param_type;
600     llvm::StringRef param_name;
601     switch (sym.kind()) {
602     case S_REGREL32: {
603       RegRelativeSym reg(SymbolRecordKind::RegRelativeSym);
604       cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg));
605       param_type = reg.Type;
606       param_name = reg.Name;
607       break;
608     }
609     case S_REGISTER: {
610       RegisterSym reg(SymbolRecordKind::RegisterSym);
611       cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg));
612       param_type = reg.Index;
613       param_name = reg.Name;
614       break;
615     }
616     case S_LOCAL: {
617       LocalSym local(SymbolRecordKind::LocalSym);
618       cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local));
619       if ((local.Flags & LocalSymFlags::IsParameter) == LocalSymFlags::None)
620         continue;
621       param_type = local.Type;
622       param_name = local.Name;
623       break;
624     }
625     case S_BLOCK32:
626       // All parameters should come before the first block.  If that isn't the
627       // case, then perhaps this is bad debug info that doesn't contain
628       // information about all parameters.
629       params_remaining = 0;
630       continue;
631     default:
632       continue;
633     }
634 
635     PdbCompilandSymId param_uid(func_id.modi, record_offset);
636     TypeSP type_sp = GetOrCreateType(param_type);
637     clang::ParmVarDecl *param = m_clang->CreateParameterDeclaration(
638         param_name.str().c_str(), type_sp->GetForwardCompilerType(),
639         clang::SC_None);
640     lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0);
641 
642     m_uid_to_decl[toOpaqueUid(param_uid)] = param;
643     params.push_back(param);
644     --params_remaining;
645   }
646 
647   if (!params.empty())
648     m_clang->SetFunctionParameters(function_decl, params.data(), params.size());
649 
650   return func_sp;
651 }
652 
653 CompUnitSP
654 SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) {
655   lldb::LanguageType lang =
656       cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage())
657                          : lldb::eLanguageTypeUnknown;
658 
659   LazyBool optimized = eLazyBoolNo;
660   if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations())
661     optimized = eLazyBoolYes;
662 
663   llvm::StringRef source_file_name =
664       m_index->compilands().GetMainSourceFile(cci);
665   FileSpec fs(source_file_name);
666 
667   CompUnitSP cu_sp =
668       std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr, fs,
669                                     toOpaqueUid(cci.m_id), lang, optimized);
670 
671   m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(
672       cci.m_id.modi, cu_sp);
673   return cu_sp;
674 }
675 
676 lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbTypeSymId type_id,
677                                                      const ModifierRecord &mr) {
678   TpiStream &stream = m_index->tpi();
679 
680   TypeSP t = GetOrCreateType(mr.ModifiedType);
681   CompilerType ct = t->GetForwardCompilerType();
682   if ((mr.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
683     ct = ct.AddConstModifier();
684   if ((mr.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
685     ct = ct.AddVolatileModifier();
686   std::string name;
687   if (mr.ModifiedType.isSimple())
688     name = GetSimpleTypeName(mr.ModifiedType.getSimpleKind());
689   else
690     name = computeTypeName(stream.typeCollection(), mr.ModifiedType);
691   Declaration decl;
692   return std::make_shared<Type>(toOpaqueUid(type_id), m_clang->GetSymbolFile(),
693                                 ConstString(name), t->GetByteSize(), nullptr,
694                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
695                                 ct, Type::eResolveStateFull);
696 }
697 
698 lldb::TypeSP SymbolFileNativePDB::CreatePointerType(
699     PdbTypeSymId type_id, const llvm::codeview::PointerRecord &pr) {
700   TypeSP pointee = GetOrCreateType(pr.ReferentType);
701   if (!pointee)
702     return nullptr;
703   CompilerType pointee_ct = pointee->GetForwardCompilerType();
704   lldbassert(pointee_ct);
705   Declaration decl;
706 
707   if (pr.isPointerToMember()) {
708     MemberPointerInfo mpi = pr.getMemberInfo();
709     TypeSP class_type = GetOrCreateType(mpi.ContainingType);
710 
711     CompilerType ct = ClangASTContext::CreateMemberPointerType(
712         class_type->GetLayoutCompilerType(), pointee_ct);
713 
714     return std::make_shared<Type>(
715         toOpaqueUid(type_id), m_clang->GetSymbolFile(), ConstString(),
716         pr.getSize(), nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct,
717         Type::eResolveStateFull);
718   }
719 
720   CompilerType pointer_ct = pointee_ct;
721   if (pr.getMode() == PointerMode::LValueReference)
722     pointer_ct = pointer_ct.GetLValueReferenceType();
723   else if (pr.getMode() == PointerMode::RValueReference)
724     pointer_ct = pointer_ct.GetRValueReferenceType();
725   else
726     pointer_ct = pointer_ct.GetPointerType();
727 
728   if ((pr.getOptions() & PointerOptions::Const) != PointerOptions::None)
729     pointer_ct = pointer_ct.AddConstModifier();
730 
731   if ((pr.getOptions() & PointerOptions::Volatile) != PointerOptions::None)
732     pointer_ct = pointer_ct.AddVolatileModifier();
733 
734   if ((pr.getOptions() & PointerOptions::Restrict) != PointerOptions::None)
735     pointer_ct = pointer_ct.AddRestrictModifier();
736 
737   return std::make_shared<Type>(toOpaqueUid(type_id), m_clang->GetSymbolFile(),
738                                 ConstString(), pr.getSize(), nullptr,
739                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
740                                 pointer_ct, Type::eResolveStateFull);
741 }
742 
743 lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti) {
744   uint64_t uid = toOpaqueUid(PdbTypeSymId(ti, false));
745   if (ti == TypeIndex::NullptrT()) {
746     CompilerType ct = m_clang->GetBasicType(eBasicTypeNullPtr);
747     Declaration decl;
748     return std::make_shared<Type>(
749         uid, this, ConstString("std::nullptr_t"), 0, nullptr, LLDB_INVALID_UID,
750         Type::eEncodingIsUID, decl, ct, Type::eResolveStateFull);
751   }
752 
753   if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
754     TypeSP direct_sp = GetOrCreateType(ti.makeDirect());
755     CompilerType ct = direct_sp->GetFullCompilerType();
756     ct = ct.GetPointerType();
757     uint32_t pointer_size = 0;
758     switch (ti.getSimpleMode()) {
759     case SimpleTypeMode::FarPointer32:
760     case SimpleTypeMode::NearPointer32:
761       pointer_size = 4;
762       break;
763     case SimpleTypeMode::NearPointer64:
764       pointer_size = 8;
765       break;
766     default:
767       // 128-bit and 16-bit pointers unsupported.
768       return nullptr;
769     }
770     Declaration decl;
771     return std::make_shared<Type>(uid, m_clang->GetSymbolFile(), ConstString(),
772                                   pointer_size, nullptr, LLDB_INVALID_UID,
773                                   Type::eEncodingIsUID, decl, ct,
774                                   Type::eResolveStateFull);
775   }
776 
777   if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
778     return nullptr;
779 
780   lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind());
781   if (bt == lldb::eBasicTypeInvalid)
782     return nullptr;
783   CompilerType ct = m_clang->GetBasicType(bt);
784   size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind());
785 
786   llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind());
787 
788   Declaration decl;
789   return std::make_shared<Type>(uid, m_clang->GetSymbolFile(),
790                                 ConstString(type_name), size, nullptr,
791                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
792                                 ct, Type::eResolveStateFull);
793 }
794 
795 static std::string RenderDemanglerNode(llvm::ms_demangle::Node *n) {
796   OutputStream OS;
797   initializeOutputStream(nullptr, nullptr, OS, 1024);
798   n->output(OS, llvm::ms_demangle::OF_Default);
799   OS << '\0';
800   return {OS.getBuffer()};
801 }
802 
803 static bool
804 AnyScopesHaveTemplateParams(llvm::ArrayRef<llvm::ms_demangle::Node *> scopes) {
805   for (llvm::ms_demangle::Node *n : scopes) {
806     auto *idn = static_cast<llvm::ms_demangle::IdentifierNode *>(n);
807     if (idn->TemplateParams)
808       return true;
809   }
810   return false;
811 }
812 
813 std::pair<clang::DeclContext *, std::string>
814 SymbolFileNativePDB::CreateDeclInfoForType(const TagRecord &record,
815                                            TypeIndex ti) {
816   // FIXME: Move this to GetDeclContextContainingUID.
817 
818   llvm::ms_demangle::Demangler demangler;
819   StringView sv(record.UniqueName.begin(), record.UniqueName.size());
820   llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
821   llvm::ms_demangle::IdentifierNode *idn =
822       ttn->QualifiedName->getUnqualifiedIdentifier();
823   std::string uname = RenderDemanglerNode(idn);
824 
825   llvm::ms_demangle::NodeArrayNode *name_components =
826       ttn->QualifiedName->Components;
827   llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes,
828                                                    name_components->Count - 1);
829 
830   clang::DeclContext *context = m_clang->GetTranslationUnitDecl();
831 
832   // If this type doesn't have a parent type in the debug info, then the best we
833   // can do is to say that it's either a series of namespaces (if the scope is
834   // non-empty), or the translation unit (if the scope is empty).
835   auto parent_iter = m_parent_types.find(ti);
836   if (parent_iter == m_parent_types.end()) {
837     if (scopes.empty())
838       return {context, uname};
839 
840     // If there is no parent in the debug info, but some of the scopes have
841     // template params, then this is a case of bad debug info.  See, for
842     // example, llvm.org/pr39607.  We don't want to create an ambiguity between
843     // a NamespaceDecl and a CXXRecordDecl, so instead we create a class at
844     // global scope with the fully qualified name.
845     if (AnyScopesHaveTemplateParams(scopes))
846       return {context, record.Name};
847 
848     for (llvm::ms_demangle::Node *scope : scopes) {
849       auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope);
850       std::string str = RenderDemanglerNode(nii);
851       context = m_clang->GetUniqueNamespaceDeclaration(str.c_str(), context);
852     }
853     return {context, uname};
854   }
855 
856   // Otherwise, all we need to do is get the parent type of this type and
857   // recurse into our lazy type creation / AST reconstruction logic to get an
858   // LLDB TypeSP for the parent.  This will cause the AST to automatically get
859   // the right DeclContext created for any parent.
860   TypeSP parent = GetOrCreateType(parent_iter->second);
861   if (!parent)
862     return {context, uname};
863   CompilerType parent_ct = parent->GetForwardCompilerType();
864   clang::QualType qt = ClangUtil::GetCanonicalQualType(parent_ct);
865   context = clang::TagDecl::castToDeclContext(qt->getAsTagDecl());
866   return {context, uname};
867 }
868 
869 lldb::TypeSP SymbolFileNativePDB::CreateClassStructUnion(
870     PdbTypeSymId type_id, const llvm::codeview::TagRecord &record, size_t size,
871     clang::TagTypeKind ttk, clang::MSInheritanceAttr::Spelling inheritance) {
872 
873   clang::DeclContext *decl_context = nullptr;
874   std::string uname;
875   std::tie(decl_context, uname) = CreateDeclInfoForType(record, type_id.index);
876 
877   lldb::AccessType access =
878       (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic;
879 
880   ClangASTMetadata metadata;
881   metadata.SetUserID(toOpaqueUid(type_id));
882   metadata.SetIsDynamicCXXType(false);
883 
884   CompilerType ct =
885       m_clang->CreateRecordType(decl_context, access, uname.c_str(), ttk,
886                                 lldb::eLanguageTypeC_plus_plus, &metadata);
887 
888   lldbassert(ct.IsValid());
889 
890   clang::CXXRecordDecl *record_decl =
891       m_clang->GetAsCXXRecordDecl(ct.GetOpaqueQualType());
892   lldbassert(record_decl);
893 
894   clang::MSInheritanceAttr *attr = clang::MSInheritanceAttr::CreateImplicit(
895       *m_clang->getASTContext(), inheritance);
896   record_decl->addAttr(attr);
897 
898   ClangASTContext::StartTagDeclarationDefinition(ct);
899 
900   // Even if it's possible, don't complete it at this point. Just mark it
901   // forward resolved, and if/when LLDB needs the full definition, it can
902   // ask us.
903   ClangASTContext::SetHasExternalStorage(ct.GetOpaqueQualType(), true);
904 
905   // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE.
906   Declaration decl;
907   return std::make_shared<Type>(toOpaqueUid(type_id), m_clang->GetSymbolFile(),
908                                 ConstString(uname), size, nullptr,
909                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
910                                 ct, Type::eResolveStateForward);
911 }
912 
913 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
914                                                 const ClassRecord &cr) {
915   clang::TagTypeKind ttk = TranslateUdtKind(cr);
916 
917   clang::MSInheritanceAttr::Spelling inheritance =
918       GetMSInheritance(m_index->tpi().typeCollection(), cr);
919   return CreateClassStructUnion(type_id, cr, cr.getSize(), ttk, inheritance);
920 }
921 
922 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
923                                                 const UnionRecord &ur) {
924   return CreateClassStructUnion(
925       type_id, ur, ur.getSize(), clang::TTK_Union,
926       clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance);
927 }
928 
929 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
930                                                 const EnumRecord &er) {
931   clang::DeclContext *decl_context = nullptr;
932   std::string uname;
933   std::tie(decl_context, uname) = CreateDeclInfoForType(er, type_id.index);
934 
935   Declaration decl;
936   TypeSP underlying_type = GetOrCreateType(er.UnderlyingType);
937   CompilerType enum_ct = m_clang->CreateEnumerationType(
938       uname.c_str(), decl_context, decl, underlying_type->GetFullCompilerType(),
939       er.isScoped());
940 
941   ClangASTContext::StartTagDeclarationDefinition(enum_ct);
942   ClangASTContext::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true);
943 
944   // We're just going to forward resolve this for now.  We'll complete
945   // it only if the user requests.
946   return std::make_shared<lldb_private::Type>(
947       toOpaqueUid(type_id), m_clang->GetSymbolFile(), ConstString(uname),
948       underlying_type->GetByteSize(), nullptr, LLDB_INVALID_UID,
949       lldb_private::Type::eEncodingIsUID, decl, enum_ct,
950       lldb_private::Type::eResolveStateForward);
951 }
952 
953 TypeSP SymbolFileNativePDB::CreateArrayType(PdbTypeSymId type_id,
954                                             const ArrayRecord &ar) {
955   TypeSP element_type = GetOrCreateType(ar.ElementType);
956   uint64_t element_count = ar.Size / element_type->GetByteSize();
957 
958   CompilerType element_ct = element_type->GetFullCompilerType();
959 
960   CompilerType array_ct =
961       m_clang->CreateArrayType(element_ct, element_count, false);
962 
963   Declaration decl;
964   TypeSP array_sp = std::make_shared<lldb_private::Type>(
965       toOpaqueUid(type_id), m_clang->GetSymbolFile(), ConstString(), ar.Size,
966       nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
967       array_ct, lldb_private::Type::eResolveStateFull);
968   array_sp->SetEncodingType(element_type.get());
969   return array_sp;
970 }
971 
972 TypeSP SymbolFileNativePDB::CreateProcedureType(PdbTypeSymId type_id,
973                                                 const ProcedureRecord &pr) {
974   TpiStream &stream = m_index->tpi();
975   CVType args_cvt = stream.getType(pr.ArgumentList);
976   ArgListRecord args;
977   llvm::cantFail(
978       TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args));
979 
980   llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices);
981   bool is_variadic = IsCVarArgsFunction(arg_indices);
982   if (is_variadic)
983     arg_indices = arg_indices.drop_back();
984 
985   std::vector<CompilerType> arg_list;
986   arg_list.reserve(arg_list.size());
987 
988   for (TypeIndex arg_index : arg_indices) {
989     TypeSP arg_sp = GetOrCreateType(arg_index);
990     if (!arg_sp)
991       return nullptr;
992     arg_list.push_back(arg_sp->GetFullCompilerType());
993   }
994 
995   TypeSP return_type_sp = GetOrCreateType(pr.ReturnType);
996   if (!return_type_sp)
997     return nullptr;
998 
999   llvm::Optional<clang::CallingConv> cc =
1000       TranslateCallingConvention(pr.CallConv);
1001   if (!cc)
1002     return nullptr;
1003 
1004   CompilerType return_ct = return_type_sp->GetFullCompilerType();
1005   CompilerType func_sig_ast_type = m_clang->CreateFunctionType(
1006       return_ct, arg_list.data(), arg_list.size(), is_variadic, 0, *cc);
1007 
1008   Declaration decl;
1009   return std::make_shared<lldb_private::Type>(
1010       toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID,
1011       lldb_private::Type::eEncodingIsUID, decl, func_sig_ast_type,
1012       lldb_private::Type::eResolveStateFull);
1013 }
1014 
1015 TypeSP SymbolFileNativePDB::CreateType(PdbTypeSymId type_id) {
1016   if (type_id.index.isSimple())
1017     return CreateSimpleType(type_id.index);
1018 
1019   TpiStream &stream = type_id.is_ipi ? m_index->ipi() : m_index->tpi();
1020   CVType cvt = stream.getType(type_id.index);
1021 
1022   if (cvt.kind() == LF_MODIFIER) {
1023     ModifierRecord modifier;
1024     llvm::cantFail(
1025         TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
1026     return CreateModifierType(type_id, modifier);
1027   }
1028 
1029   if (cvt.kind() == LF_POINTER) {
1030     PointerRecord pointer;
1031     llvm::cantFail(
1032         TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
1033     return CreatePointerType(type_id, pointer);
1034   }
1035 
1036   if (IsClassRecord(cvt.kind())) {
1037     ClassRecord cr;
1038     llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr));
1039     return CreateTagType(type_id, cr);
1040   }
1041 
1042   if (cvt.kind() == LF_ENUM) {
1043     EnumRecord er;
1044     llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er));
1045     return CreateTagType(type_id, er);
1046   }
1047 
1048   if (cvt.kind() == LF_UNION) {
1049     UnionRecord ur;
1050     llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur));
1051     return CreateTagType(type_id, ur);
1052   }
1053 
1054   if (cvt.kind() == LF_ARRAY) {
1055     ArrayRecord ar;
1056     llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
1057     return CreateArrayType(type_id, ar);
1058   }
1059 
1060   if (cvt.kind() == LF_PROCEDURE) {
1061     ProcedureRecord pr;
1062     llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
1063     return CreateProcedureType(type_id, pr);
1064   }
1065 
1066   return nullptr;
1067 }
1068 
1069 TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbTypeSymId type_id) {
1070   // If they search for a UDT which is a forward ref, try and resolve the full
1071   // decl and just map the forward ref uid to the full decl record.
1072   llvm::Optional<PdbTypeSymId> full_decl_uid;
1073   if (IsForwardRefUdt(type_id, m_index->tpi())) {
1074     auto expected_full_ti =
1075         m_index->tpi().findFullDeclForForwardRef(type_id.index);
1076     if (!expected_full_ti)
1077       llvm::consumeError(expected_full_ti.takeError());
1078     else if (*expected_full_ti != type_id.index) {
1079       full_decl_uid = PdbTypeSymId(*expected_full_ti, false);
1080 
1081       // It's possible that a lookup would occur for the full decl causing it
1082       // to be cached, then a second lookup would occur for the forward decl.
1083       // We don't want to create a second full decl, so make sure the full
1084       // decl hasn't already been cached.
1085       auto full_iter = m_types.find(toOpaqueUid(*full_decl_uid));
1086       if (full_iter != m_types.end()) {
1087         TypeSP result = full_iter->second;
1088         // Map the forward decl to the TypeSP for the full decl so we can take
1089         // the fast path next time.
1090         m_types[toOpaqueUid(type_id)] = result;
1091         return result;
1092       }
1093     }
1094   }
1095 
1096   PdbTypeSymId best_decl_id = full_decl_uid ? *full_decl_uid : type_id;
1097   TypeSP result = CreateType(best_decl_id);
1098   if (!result)
1099     return nullptr;
1100 
1101   uint64_t best_uid = toOpaqueUid(best_decl_id);
1102   m_types[best_uid] = result;
1103   // If we had both a forward decl and a full decl, make both point to the new
1104   // type.
1105   if (full_decl_uid)
1106     m_types[toOpaqueUid(type_id)] = result;
1107 
1108   if (IsTagRecord(best_decl_id, m_index->tpi())) {
1109     clang::TagDecl *record_decl =
1110         m_clang->GetAsTagDecl(result->GetForwardCompilerType());
1111     lldbassert(record_decl);
1112 
1113     m_uid_to_decl[best_uid] = record_decl;
1114     m_decl_to_status[record_decl] =
1115         DeclStatus(best_uid, Type::eResolveStateForward);
1116   }
1117   return result;
1118 }
1119 
1120 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbTypeSymId type_id) {
1121   // We can't use try_emplace / overwrite here because the process of creating
1122   // a type could create nested types, which could invalidate iterators.  So
1123   // we have to do a 2-phase lookup / insert.
1124   auto iter = m_types.find(toOpaqueUid(type_id));
1125   if (iter != m_types.end())
1126     return iter->second;
1127 
1128   return CreateAndCacheType(type_id);
1129 }
1130 
1131 VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbGlobalSymId var_id) {
1132   CVSymbol sym = m_index->symrecords().readRecord(var_id.offset);
1133   if (sym.kind() == S_CONSTANT)
1134     return CreateConstantSymbol(var_id, sym);
1135 
1136   lldb::ValueType scope = eValueTypeInvalid;
1137   TypeIndex ti;
1138   llvm::StringRef name;
1139   lldb::addr_t addr = 0;
1140   uint16_t section = 0;
1141   uint32_t offset = 0;
1142   bool is_external = false;
1143   switch (sym.kind()) {
1144   case S_GDATA32:
1145     is_external = true;
1146     LLVM_FALLTHROUGH;
1147   case S_LDATA32: {
1148     DataSym ds(sym.kind());
1149     llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds));
1150     ti = ds.Type;
1151     scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal
1152                                       : eValueTypeVariableStatic;
1153     name = ds.Name;
1154     section = ds.Segment;
1155     offset = ds.DataOffset;
1156     addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset);
1157     break;
1158   }
1159   case S_GTHREAD32:
1160     is_external = true;
1161     LLVM_FALLTHROUGH;
1162   case S_LTHREAD32: {
1163     ThreadLocalDataSym tlds(sym.kind());
1164     llvm::cantFail(
1165         SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds));
1166     ti = tlds.Type;
1167     name = tlds.Name;
1168     section = tlds.Segment;
1169     offset = tlds.DataOffset;
1170     addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset);
1171     scope = eValueTypeVariableThreadLocal;
1172     break;
1173   }
1174   default:
1175     llvm_unreachable("unreachable!");
1176   }
1177 
1178   CompUnitSP comp_unit;
1179   llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr);
1180   if (modi) {
1181     CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi);
1182     comp_unit = GetOrCreateCompileUnit(cci);
1183   }
1184 
1185   Declaration decl;
1186   PdbTypeSymId tid(ti, false);
1187   SymbolFileTypeSP type_sp =
1188       std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
1189   Variable::RangeList ranges;
1190 
1191   DWARFExpression location = MakeGlobalLocationExpression(
1192       section, offset, GetObjectFile()->GetModule());
1193 
1194   std::string global_name("::");
1195   global_name += name;
1196   VariableSP var_sp = std::make_shared<Variable>(
1197       toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp,
1198       scope, comp_unit.get(), ranges, &decl, location, is_external, false,
1199       false);
1200   var_sp->SetLocationIsConstantValueData(false);
1201 
1202   return var_sp;
1203 }
1204 
1205 lldb::VariableSP
1206 SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id,
1207                                           const CVSymbol &cvs) {
1208   TpiStream &tpi = m_index->tpi();
1209   ConstantSym constant(cvs.kind());
1210 
1211   llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant));
1212   std::string global_name("::");
1213   global_name += constant.Name;
1214   PdbTypeSymId tid(constant.Type, false);
1215   SymbolFileTypeSP type_sp =
1216       std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
1217 
1218   Declaration decl;
1219   Variable::RangeList ranges;
1220   ModuleSP module = GetObjectFile()->GetModule();
1221   DWARFExpression location = MakeConstantLocationExpression(
1222       constant.Type, tpi, constant.Value, module);
1223 
1224   VariableSP var_sp = std::make_shared<Variable>(
1225       toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(),
1226       type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location,
1227       false, false, false);
1228   var_sp->SetLocationIsConstantValueData(true);
1229   return var_sp;
1230 }
1231 
1232 VariableSP
1233 SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) {
1234   auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr);
1235   if (emplace_result.second)
1236     emplace_result.first->second = CreateGlobalVariable(var_id);
1237 
1238   return emplace_result.first->second;
1239 }
1240 
1241 lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) {
1242   return GetOrCreateType(PdbTypeSymId(ti, false));
1243 }
1244 
1245 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id,
1246                                                     const SymbolContext &sc) {
1247   auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr);
1248   if (emplace_result.second)
1249     emplace_result.first->second = CreateFunction(func_id, sc);
1250 
1251   lldbassert(emplace_result.first->second);
1252   return emplace_result.first->second;
1253 }
1254 
1255 CompUnitSP
1256 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) {
1257 
1258   auto emplace_result =
1259       m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr);
1260   if (emplace_result.second)
1261     emplace_result.first->second = CreateCompileUnit(cci);
1262 
1263   lldbassert(emplace_result.first->second);
1264   return emplace_result.first->second;
1265 }
1266 
1267 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) {
1268   if (index >= GetNumCompileUnits())
1269     return CompUnitSP();
1270   lldbassert(index < UINT16_MAX);
1271   if (index >= UINT16_MAX)
1272     return nullptr;
1273 
1274   CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
1275 
1276   return GetOrCreateCompileUnit(item);
1277 }
1278 
1279 lldb::LanguageType
1280 SymbolFileNativePDB::ParseCompileUnitLanguage(const SymbolContext &sc) {
1281   // What fields should I expect to be filled out on the SymbolContext?  Is it
1282   // safe to assume that `sc.comp_unit` is valid?
1283   if (!sc.comp_unit)
1284     return lldb::eLanguageTypeUnknown;
1285   PdbSymUid uid(sc.comp_unit->GetID());
1286   lldbassert(uid.kind() == PdbSymUidKind::Compiland);
1287 
1288   CompilandIndexItem *item =
1289       m_index->compilands().GetCompiland(uid.asCompiland().modi);
1290   lldbassert(item);
1291   if (!item->m_compile_opts)
1292     return lldb::eLanguageTypeUnknown;
1293 
1294   return TranslateLanguage(item->m_compile_opts->getLanguage());
1295 }
1296 
1297 size_t SymbolFileNativePDB::ParseCompileUnitFunctions(const SymbolContext &sc) {
1298   lldbassert(sc.comp_unit);
1299   return false;
1300 }
1301 
1302 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
1303   // If any of these flags are set, we need to resolve the compile unit.
1304   uint32_t flags = eSymbolContextCompUnit;
1305   flags |= eSymbolContextVariable;
1306   flags |= eSymbolContextFunction;
1307   flags |= eSymbolContextBlock;
1308   flags |= eSymbolContextLineEntry;
1309   return (resolve_scope & flags) != 0;
1310 }
1311 
1312 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
1313     const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
1314   uint32_t resolved_flags = 0;
1315   lldb::addr_t file_addr = addr.GetFileAddress();
1316 
1317   if (NeedsResolvedCompileUnit(resolve_scope)) {
1318     llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
1319     if (!modi)
1320       return 0;
1321     CompilandIndexItem *cci = m_index->compilands().GetCompiland(*modi);
1322     if (!cci)
1323       return 0;
1324 
1325     sc.comp_unit = GetOrCreateCompileUnit(*cci).get();
1326     resolved_flags |= eSymbolContextCompUnit;
1327   }
1328 
1329   if (resolve_scope & eSymbolContextFunction) {
1330     lldbassert(sc.comp_unit);
1331     std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
1332     for (const auto &match : matches) {
1333       if (match.uid.kind() != PdbSymUidKind::CompilandSym)
1334         continue;
1335       PdbCompilandSymId csid = match.uid.asCompilandSym();
1336       CVSymbol cvs = m_index->ReadSymbolRecord(csid);
1337       if (CVSymToPDBSym(cvs.kind()) != PDB_SymType::Function)
1338         continue;
1339       sc.function = GetOrCreateFunction(csid, sc).get();
1340     }
1341     resolved_flags |= eSymbolContextFunction;
1342   }
1343 
1344   if (resolve_scope & eSymbolContextLineEntry) {
1345     lldbassert(sc.comp_unit);
1346     if (auto *line_table = sc.comp_unit->GetLineTable()) {
1347       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1348         resolved_flags |= eSymbolContextLineEntry;
1349     }
1350   }
1351 
1352   return resolved_flags;
1353 }
1354 
1355 static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence,
1356                                       const CompilandIndexItem &cci,
1357                                       lldb::addr_t base_addr,
1358                                       uint32_t file_number,
1359                                       const LineFragmentHeader &block,
1360                                       const LineNumberEntry &cur) {
1361   LineInfo cur_info(cur.Flags);
1362 
1363   if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1364     return;
1365 
1366   uint64_t addr = base_addr + cur.Offset;
1367 
1368   bool is_statement = cur_info.isStatement();
1369   bool is_prologue = IsFunctionPrologue(cci, addr);
1370   bool is_epilogue = IsFunctionEpilogue(cci, addr);
1371 
1372   uint32_t lno = cur_info.getStartLine();
1373 
1374   table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number,
1375                                   is_statement, false, is_prologue, is_epilogue,
1376                                   false);
1377 }
1378 
1379 static void TerminateLineSequence(LineTable &table,
1380                                   const LineFragmentHeader &block,
1381                                   lldb::addr_t base_addr, uint32_t file_number,
1382                                   uint32_t last_line,
1383                                   std::unique_ptr<LineSequence> seq) {
1384   // The end is always a terminal entry, so insert it regardless.
1385   table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize,
1386                                   last_line, 0, file_number, false, false,
1387                                   false, false, true);
1388   table.InsertSequence(seq.release());
1389 }
1390 
1391 bool SymbolFileNativePDB::ParseCompileUnitLineTable(const SymbolContext &sc) {
1392   // Unfortunately LLDB is set up to parse the entire compile unit line table
1393   // all at once, even if all it really needs is line info for a specific
1394   // function.  In the future it would be nice if it could set the sc.m_function
1395   // member, and we could only get the line info for the function in question.
1396   lldbassert(sc.comp_unit);
1397   PdbSymUid cu_id(sc.comp_unit->GetID());
1398   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1399   CompilandIndexItem *cci =
1400       m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1401   lldbassert(cci);
1402   auto line_table = llvm::make_unique<LineTable>(sc.comp_unit);
1403 
1404   // This is basically a copy of the .debug$S subsections from all original COFF
1405   // object files merged together with address relocations applied.  We are
1406   // looking for all DEBUG_S_LINES subsections.
1407   for (const DebugSubsectionRecord &dssr :
1408        cci->m_debug_stream.getSubsectionsArray()) {
1409     if (dssr.kind() != DebugSubsectionKind::Lines)
1410       continue;
1411 
1412     DebugLinesSubsectionRef lines;
1413     llvm::BinaryStreamReader reader(dssr.getRecordData());
1414     if (auto EC = lines.initialize(reader)) {
1415       llvm::consumeError(std::move(EC));
1416       return false;
1417     }
1418 
1419     const LineFragmentHeader *lfh = lines.header();
1420     uint64_t virtual_addr =
1421         m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1422 
1423     const auto &checksums = cci->m_strings.checksums().getArray();
1424     const auto &strings = cci->m_strings.strings();
1425     for (const LineColumnEntry &group : lines) {
1426       // Indices in this structure are actually offsets of records in the
1427       // DEBUG_S_FILECHECKSUMS subsection.  Those entries then have an index
1428       // into the global PDB string table.
1429       auto iter = checksums.at(group.NameIndex);
1430       if (iter == checksums.end())
1431         continue;
1432 
1433       llvm::Expected<llvm::StringRef> efn =
1434           strings.getString(iter->FileNameOffset);
1435       if (!efn) {
1436         llvm::consumeError(efn.takeError());
1437         continue;
1438       }
1439 
1440       // LLDB wants the index of the file in the list of support files.
1441       auto fn_iter = llvm::find(cci->m_file_list, *efn);
1442       lldbassert(fn_iter != cci->m_file_list.end());
1443       uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter);
1444 
1445       std::unique_ptr<LineSequence> sequence(
1446           line_table->CreateLineSequenceContainer());
1447       lldbassert(!group.LineNumbers.empty());
1448 
1449       for (const LineNumberEntry &entry : group.LineNumbers) {
1450         AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr,
1451                                   file_index, *lfh, entry);
1452       }
1453       LineInfo last_line(group.LineNumbers.back().Flags);
1454       TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index,
1455                             last_line.getEndLine(), std::move(sequence));
1456     }
1457   }
1458 
1459   if (line_table->GetSize() == 0)
1460     return false;
1461 
1462   sc.comp_unit->SetLineTable(line_table.release());
1463   return true;
1464 }
1465 
1466 bool SymbolFileNativePDB::ParseCompileUnitDebugMacros(const SymbolContext &sc) {
1467   // PDB doesn't contain information about macros
1468   return false;
1469 }
1470 
1471 bool SymbolFileNativePDB::ParseCompileUnitSupportFiles(
1472     const SymbolContext &sc, FileSpecList &support_files) {
1473   lldbassert(sc.comp_unit);
1474 
1475   PdbSymUid cu_id(sc.comp_unit->GetID());
1476   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1477   CompilandIndexItem *cci =
1478       m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1479   lldbassert(cci);
1480 
1481   for (llvm::StringRef f : cci->m_file_list) {
1482     FileSpec::Style style =
1483         f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1484     FileSpec spec(f, style);
1485     support_files.Append(spec);
1486   }
1487 
1488   return true;
1489 }
1490 
1491 bool SymbolFileNativePDB::ParseImportedModules(
1492     const SymbolContext &sc, std::vector<ConstString> &imported_modules) {
1493   // PDB does not yet support module debug info
1494   return false;
1495 }
1496 
1497 size_t SymbolFileNativePDB::ParseFunctionBlocks(const SymbolContext &sc) {
1498   lldbassert(sc.comp_unit && sc.function);
1499   return 0;
1500 }
1501 
1502 void SymbolFileNativePDB::DumpClangAST(Stream &s) {
1503   if (!m_clang)
1504     return;
1505   m_clang->Dump(s);
1506 }
1507 
1508 uint32_t SymbolFileNativePDB::FindGlobalVariables(
1509     const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
1510     uint32_t max_matches, VariableList &variables) {
1511   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1512 
1513   std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName(
1514       name.GetStringRef(), m_index->symrecords());
1515   for (const SymbolAndOffset &result : results) {
1516     VariableSP var;
1517     switch (result.second.kind()) {
1518     case SymbolKind::S_GDATA32:
1519     case SymbolKind::S_LDATA32:
1520     case SymbolKind::S_GTHREAD32:
1521     case SymbolKind::S_LTHREAD32:
1522     case SymbolKind::S_CONSTANT: {
1523       PdbGlobalSymId global(result.first, false);
1524       var = GetOrCreateGlobalVariable(global);
1525       variables.AddVariable(var);
1526       break;
1527     }
1528     default:
1529       continue;
1530     }
1531   }
1532   return variables.GetSize();
1533 }
1534 
1535 uint32_t SymbolFileNativePDB::FindFunctions(
1536     const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
1537     FunctionNameType name_type_mask, bool include_inlines, bool append,
1538     SymbolContextList &sc_list) {
1539   // For now we only support lookup by method name.
1540   if (!(name_type_mask & eFunctionNameTypeMethod))
1541     return 0;
1542 
1543   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1544 
1545   std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName(
1546       name.GetStringRef(), m_index->symrecords());
1547   for (const SymbolAndOffset &match : matches) {
1548     if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF)
1549       continue;
1550     ProcRefSym proc(match.second.kind());
1551     cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc));
1552 
1553     if (!IsValidRecord(proc))
1554       continue;
1555 
1556     CompilandIndexItem &cci =
1557         m_index->compilands().GetOrCreateCompiland(proc.modi());
1558     SymbolContext sc;
1559 
1560     sc.comp_unit = GetOrCreateCompileUnit(cci).get();
1561     sc.module_sp = sc.comp_unit->GetModule();
1562     PdbCompilandSymId func_id(proc.modi(), proc.SymOffset);
1563     sc.function = GetOrCreateFunction(func_id, sc).get();
1564 
1565     sc_list.Append(sc);
1566   }
1567 
1568   return sc_list.GetSize();
1569 }
1570 
1571 uint32_t SymbolFileNativePDB::FindFunctions(const RegularExpression &regex,
1572                                             bool include_inlines, bool append,
1573                                             SymbolContextList &sc_list) {
1574   return 0;
1575 }
1576 
1577 uint32_t SymbolFileNativePDB::FindTypes(
1578     const SymbolContext &sc, const ConstString &name,
1579     const CompilerDeclContext *parent_decl_ctx, bool append,
1580     uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1581     TypeMap &types) {
1582   if (!append)
1583     types.Clear();
1584   if (!name)
1585     return 0;
1586 
1587   searched_symbol_files.clear();
1588   searched_symbol_files.insert(this);
1589 
1590   // There is an assumption 'name' is not a regex
1591   size_t match_count = FindTypesByName(name.GetStringRef(), max_matches, types);
1592 
1593   return match_count;
1594 }
1595 
1596 size_t
1597 SymbolFileNativePDB::FindTypes(const std::vector<CompilerContext> &context,
1598                                bool append, TypeMap &types) {
1599   return 0;
1600 }
1601 
1602 size_t SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1603                                             uint32_t max_matches,
1604                                             TypeMap &types) {
1605 
1606   size_t match_count = 0;
1607   std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1608   if (max_matches > 0 && max_matches < matches.size())
1609     matches.resize(max_matches);
1610 
1611   for (TypeIndex ti : matches) {
1612     TypeSP type = GetOrCreateType(ti);
1613     if (!type)
1614       continue;
1615 
1616     types.Insert(type);
1617     ++match_count;
1618   }
1619   return match_count;
1620 }
1621 
1622 size_t SymbolFileNativePDB::ParseTypes(const SymbolContext &sc) { return 0; }
1623 
1624 CompilerDeclContext
1625 SymbolFileNativePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
1626   // FIXME: This should look up the uid, decide if it's a symbol or a type, and
1627   // depending which it is, find the appropriate DeclContext.  Possibilities:
1628   // For classes and typedefs:
1629   //   * Function
1630   //   * Namespace
1631   //   * Global
1632   //   * Block
1633   //   * Class
1634   // For field list members:
1635   //   * Class
1636   // For variables:
1637   //   * Function
1638   //   * Namespace
1639   //   * Global
1640   //   * Block
1641   // For functions:
1642   //   * Namespace
1643   //   * Global
1644   //   * Class
1645   //
1646   // It is an error to call this function with a uid for any other symbol type.
1647   return {m_clang, m_clang->GetTranslationUnitDecl()};
1648 }
1649 
1650 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
1651   auto iter = m_types.find(type_uid);
1652   // lldb should not be passing us non-sensical type uids.  the only way it
1653   // could have a type uid in the first place is if we handed it out, in which
1654   // case we should know about the type.  However, that doesn't mean we've
1655   // instantiated it yet.  We can vend out a UID for a future type.  So if the
1656   // type doesn't exist, let's instantiate it now.
1657   if (iter != m_types.end())
1658     return &*iter->second;
1659 
1660   PdbSymUid uid(type_uid);
1661   lldbassert(uid.kind() == PdbSymUidKind::Type);
1662   PdbTypeSymId type_id = uid.asTypeSym();
1663   if (type_id.index.isNoneType())
1664     return nullptr;
1665 
1666   TypeSP type_sp = CreateAndCacheType(type_id);
1667   return &*type_sp;
1668 }
1669 
1670 llvm::Optional<SymbolFile::ArrayInfo>
1671 SymbolFileNativePDB::GetDynamicArrayInfoForUID(
1672     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1673   return llvm::None;
1674 }
1675 
1676 
1677 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
1678   // If this is not in our map, it's an error.
1679   clang::TagDecl *tag_decl = m_clang->GetAsTagDecl(compiler_type);
1680   lldbassert(tag_decl);
1681   auto status_iter = m_decl_to_status.find(tag_decl);
1682   lldbassert(status_iter != m_decl_to_status.end());
1683 
1684   // If it's already complete, just return.
1685   DeclStatus &status = status_iter->second;
1686   if (status.status == Type::eResolveStateFull)
1687     return true;
1688 
1689   PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym();
1690 
1691   lldbassert(IsTagRecord(type_id, m_index->tpi()));
1692 
1693   ClangASTContext::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),
1694                                          false);
1695 
1696   // In CreateAndCacheType, we already go out of our way to resolve forward
1697   // ref UDTs to full decls, and the uids we vend out always refer to full
1698   // decls if a full decl exists in the debug info.  So if we don't have a full
1699   // decl here, it means one doesn't exist in the debug info, and we can't
1700   // complete the type.
1701   CVType cvt = m_index->tpi().getType(TypeIndex(type_id.index));
1702   if (IsForwardRefUdt(cvt))
1703     return false;
1704 
1705   auto types_iter = m_types.find(status.uid);
1706   lldbassert(types_iter != m_types.end());
1707 
1708   if (cvt.kind() == LF_MODIFIER) {
1709     TypeIndex unmodified_type = LookThroughModifierRecord(cvt);
1710     cvt = m_index->tpi().getType(unmodified_type);
1711     // LF_MODIFIERS usually point to forward decls, so this is the one case
1712     // where we won't have been able to resolve a forward decl to a full decl
1713     // earlier on.  So we need to do that now.
1714     if (IsForwardRefUdt(cvt)) {
1715       llvm::Expected<TypeIndex> expected_full_ti =
1716           m_index->tpi().findFullDeclForForwardRef(unmodified_type);
1717       if (!expected_full_ti) {
1718         llvm::consumeError(expected_full_ti.takeError());
1719         return false;
1720       }
1721       cvt = m_index->tpi().getType(*expected_full_ti);
1722       lldbassert(!IsForwardRefUdt(cvt));
1723       unmodified_type = *expected_full_ti;
1724     }
1725     type_id = PdbTypeSymId(unmodified_type, false);
1726   }
1727   TypeIndex field_list_ti = GetFieldListIndex(cvt);
1728   CVType field_list_cvt = m_index->tpi().getType(field_list_ti);
1729   if (field_list_cvt.kind() != LF_FIELDLIST)
1730     return false;
1731 
1732   // Visit all members of this class, then perform any finalization necessary
1733   // to complete the class.
1734   UdtRecordCompleter completer(type_id, compiler_type, *tag_decl, *this);
1735   auto error =
1736       llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer);
1737   completer.complete();
1738 
1739   status.status = Type::eResolveStateFull;
1740   if (!error)
1741     return true;
1742 
1743   llvm::consumeError(std::move(error));
1744   return false;
1745 }
1746 
1747 size_t SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1748                                      TypeClass type_mask,
1749                                      lldb_private::TypeList &type_list) {
1750   return 0;
1751 }
1752 
1753 CompilerDeclContext
1754 SymbolFileNativePDB::FindNamespace(const SymbolContext &sc,
1755                                    const ConstString &name,
1756                                    const CompilerDeclContext *parent_decl_ctx) {
1757   return {};
1758 }
1759 
1760 TypeSystem *
1761 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1762   auto type_system =
1763       m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
1764   if (type_system)
1765     type_system->SetSymbolFile(this);
1766   return type_system;
1767 }
1768 
1769 ConstString SymbolFileNativePDB::GetPluginName() {
1770   static ConstString g_name("pdb");
1771   return g_name;
1772 }
1773 
1774 uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; }
1775