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