1 #include "PdbAstBuilder.h"
2 
3 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
4 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
5 #include "llvm/DebugInfo/CodeView/RecordName.h"
6 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
7 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
8 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
9 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
10 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
11 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
12 #include "llvm/DebugInfo/PDB/Native/PublicsStream.h"
13 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
14 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
15 #include "llvm/Demangle/MicrosoftDemangle.h"
16 
17 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Symbol/ClangASTContext.h"
20 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
21 #include "lldb/Symbol/ClangUtil.h"
22 #include "lldb/Symbol/ObjectFile.h"
23 #include "lldb/Utility/LLDBAssert.h"
24 
25 #include "PdbUtil.h"
26 #include "UdtRecordCompleter.h"
27 
28 using namespace lldb_private;
29 using namespace lldb_private::npdb;
30 using namespace llvm::codeview;
31 using namespace llvm::pdb;
32 
33 static llvm::Optional<PdbCompilandSymId> FindSymbolScope(PdbIndex &index,
34                                                          PdbCompilandSymId id) {
35   CVSymbol sym = index.ReadSymbolRecord(id);
36   if (symbolOpensScope(sym.kind())) {
37     // If this exact symbol opens a scope, we can just directly access its
38     // parent.
39     id.offset = getScopeParentOffset(sym);
40     // Global symbols have parent offset of 0.  Return llvm::None to indicate
41     // this.
42     if (id.offset == 0)
43       return llvm::None;
44     return id;
45   }
46 
47   // Otherwise we need to start at the beginning and iterate forward until we
48   // reach (or pass) this particular symbol
49   CompilandIndexItem &cii = index.compilands().GetOrCreateCompiland(id.modi);
50   const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
51 
52   auto begin = syms.begin();
53   auto end = syms.at(id.offset);
54   std::vector<PdbCompilandSymId> scope_stack;
55 
56   while (begin != end) {
57     if (id.offset == begin.offset()) {
58       // We have a match!  Return the top of the stack
59       if (scope_stack.empty())
60         return llvm::None;
61       return scope_stack.back();
62     }
63     if (begin.offset() > id.offset) {
64       // We passed it.  We couldn't even find this symbol record.
65       lldbassert(false && "Invalid compiland symbol id!");
66       return llvm::None;
67     }
68 
69     // We haven't found the symbol yet.  Check if we need to open or close the
70     // scope stack.
71     if (symbolOpensScope(begin->kind())) {
72       // We can use the end offset of the scope to determine whether or not
73       // we can just outright skip this entire scope.
74       uint32_t scope_end = getScopeEndOffset(*begin);
75       if (scope_end < id.modi) {
76         begin = syms.at(scope_end);
77       } else {
78         // The symbol we're looking for is somewhere in this scope.
79         scope_stack.emplace_back(id.modi, begin.offset());
80       }
81     } else if (symbolEndsScope(begin->kind())) {
82       scope_stack.pop_back();
83     }
84     ++begin;
85   }
86 
87   return llvm::None;
88 }
89 
90 static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) {
91   switch (cr.Kind) {
92   case TypeRecordKind::Class:
93     return clang::TTK_Class;
94   case TypeRecordKind::Struct:
95     return clang::TTK_Struct;
96   case TypeRecordKind::Union:
97     return clang::TTK_Union;
98   case TypeRecordKind::Interface:
99     return clang::TTK_Interface;
100   case TypeRecordKind::Enum:
101     return clang::TTK_Enum;
102   default:
103     lldbassert(false && "Invalid tag record kind!");
104     return clang::TTK_Struct;
105   }
106 }
107 
108 static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) {
109   if (args.empty())
110     return false;
111   return args.back() == TypeIndex::None();
112 }
113 
114 static bool
115 AnyScopesHaveTemplateParams(llvm::ArrayRef<llvm::ms_demangle::Node *> scopes) {
116   for (llvm::ms_demangle::Node *n : scopes) {
117     auto *idn = static_cast<llvm::ms_demangle::IdentifierNode *>(n);
118     if (idn->TemplateParams)
119       return true;
120   }
121   return false;
122 }
123 
124 static ClangASTContext &GetClangASTContext(ObjectFile &obj) {
125   TypeSystem *ts =
126       obj.GetModule()->GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
127   lldbassert(ts);
128   return static_cast<ClangASTContext &>(*ts);
129 }
130 
131 static llvm::Optional<clang::CallingConv>
132 TranslateCallingConvention(llvm::codeview::CallingConvention conv) {
133   using CC = llvm::codeview::CallingConvention;
134   switch (conv) {
135 
136   case CC::NearC:
137   case CC::FarC:
138     return clang::CallingConv::CC_C;
139   case CC::NearPascal:
140   case CC::FarPascal:
141     return clang::CallingConv::CC_X86Pascal;
142   case CC::NearFast:
143   case CC::FarFast:
144     return clang::CallingConv::CC_X86FastCall;
145   case CC::NearStdCall:
146   case CC::FarStdCall:
147     return clang::CallingConv::CC_X86StdCall;
148   case CC::ThisCall:
149     return clang::CallingConv::CC_X86ThisCall;
150   case CC::NearVector:
151     return clang::CallingConv::CC_X86VectorCall;
152   default:
153     return llvm::None;
154   }
155 }
156 
157 static llvm::Optional<CVTagRecord>
158 GetNestedTagDefinition(const NestedTypeRecord &Record,
159                        const CVTagRecord &parent, TpiStream &tpi) {
160   // An LF_NESTTYPE is essentially a nested typedef / using declaration, but it
161   // is also used to indicate the primary definition of a nested class.  That is
162   // to say, if you have:
163   // struct A {
164   //   struct B {};
165   //   using C = B;
166   // };
167   // Then in the debug info, this will appear as:
168   // LF_STRUCTURE `A::B` [type index = N]
169   // LF_STRUCTURE `A`
170   //   LF_NESTTYPE [name = `B`, index = N]
171   //   LF_NESTTYPE [name = `C`, index = N]
172   // In order to accurately reconstruct the decl context hierarchy, we need to
173   // know which ones are actual definitions and which ones are just aliases.
174 
175   // If it's a simple type, then this is something like `using foo = int`.
176   if (Record.Type.isSimple())
177     return llvm::None;
178 
179   CVType cvt = tpi.getType(Record.Type);
180 
181   if (!IsTagRecord(cvt))
182     return llvm::None;
183 
184   // If it's an inner definition, then treat whatever name we have here as a
185   // single component of a mangled name.  So we can inject it into the parent's
186   // mangled name to see if it matches.
187   CVTagRecord child = CVTagRecord::create(cvt);
188   std::string qname = parent.asTag().getUniqueName();
189   if (qname.size() < 4 || child.asTag().getUniqueName().size() < 4)
190     return llvm::None;
191 
192   // qname[3] is the tag type identifier (struct, class, union, etc).  Since the
193   // inner tag type is not necessarily the same as the outer tag type, re-write
194   // it to match the inner tag type.
195   qname[3] = child.asTag().getUniqueName()[3];
196   std::string piece;
197   if (qname[3] == 'W')
198     piece = "4";
199   piece += Record.Name;
200   piece.push_back('@');
201   qname.insert(4, std::move(piece));
202   if (qname != child.asTag().UniqueName)
203     return llvm::None;
204 
205   return std::move(child);
206 }
207 
208 static bool IsAnonymousNamespaceName(llvm::StringRef name) {
209   return name == "`anonymous namespace'" || name == "`anonymous-namespace'";
210 }
211 
212 PdbAstBuilder::PdbAstBuilder(ObjectFile &obj, PdbIndex &index)
213     : m_index(index), m_clang(GetClangASTContext(obj)) {
214   BuildParentMap();
215 }
216 
217 lldb_private::CompilerDeclContext PdbAstBuilder::GetTranslationUnitDecl() {
218   return ToCompilerDeclContext(*m_clang.GetTranslationUnitDecl());
219 }
220 
221 std::pair<clang::DeclContext *, std::string>
222 PdbAstBuilder::CreateDeclInfoForType(const TagRecord &record, TypeIndex ti) {
223   // FIXME: Move this to GetDeclContextContainingUID.
224   if (!record.hasUniqueName())
225     return CreateDeclInfoForUndecoratedName(record.Name);
226 
227   llvm::ms_demangle::Demangler demangler;
228   StringView sv(record.UniqueName.begin(), record.UniqueName.size());
229   llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
230   if (demangler.Error)
231     return {m_clang.GetTranslationUnitDecl(), record.UniqueName};
232 
233   llvm::ms_demangle::IdentifierNode *idn =
234       ttn->QualifiedName->getUnqualifiedIdentifier();
235   std::string uname = idn->toString(llvm::ms_demangle::OF_NoTagSpecifier);
236 
237   llvm::ms_demangle::NodeArrayNode *name_components =
238       ttn->QualifiedName->Components;
239   llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes,
240                                                    name_components->Count - 1);
241 
242   clang::DeclContext *context = m_clang.GetTranslationUnitDecl();
243 
244   // If this type doesn't have a parent type in the debug info, then the best we
245   // can do is to say that it's either a series of namespaces (if the scope is
246   // non-empty), or the translation unit (if the scope is empty).
247   auto parent_iter = m_parent_types.find(ti);
248   if (parent_iter == m_parent_types.end()) {
249     if (scopes.empty())
250       return {context, uname};
251 
252     // If there is no parent in the debug info, but some of the scopes have
253     // template params, then this is a case of bad debug info.  See, for
254     // example, llvm.org/pr39607.  We don't want to create an ambiguity between
255     // a NamespaceDecl and a CXXRecordDecl, so instead we create a class at
256     // global scope with the fully qualified name.
257     if (AnyScopesHaveTemplateParams(scopes))
258       return {context, record.Name};
259 
260     for (llvm::ms_demangle::Node *scope : scopes) {
261       auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope);
262       std::string str = nii->toString();
263       context = GetOrCreateNamespaceDecl(str.c_str(), *context);
264     }
265     return {context, uname};
266   }
267 
268   // Otherwise, all we need to do is get the parent type of this type and
269   // recurse into our lazy type creation / AST reconstruction logic to get an
270   // LLDB TypeSP for the parent.  This will cause the AST to automatically get
271   // the right DeclContext created for any parent.
272   clang::QualType parent_qt = GetOrCreateType(parent_iter->second);
273 
274   context = clang::TagDecl::castToDeclContext(parent_qt->getAsTagDecl());
275   return {context, uname};
276 }
277 
278 void PdbAstBuilder::BuildParentMap() {
279   LazyRandomTypeCollection &types = m_index.tpi().typeCollection();
280 
281   llvm::DenseMap<TypeIndex, TypeIndex> forward_to_full;
282   llvm::DenseMap<TypeIndex, TypeIndex> full_to_forward;
283 
284   struct RecordIndices {
285     TypeIndex forward;
286     TypeIndex full;
287   };
288 
289   llvm::StringMap<RecordIndices> record_indices;
290 
291   for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
292     CVType type = types.getType(*ti);
293     if (!IsTagRecord(type))
294       continue;
295 
296     CVTagRecord tag = CVTagRecord::create(type);
297 
298     RecordIndices &indices = record_indices[tag.asTag().getUniqueName()];
299     if (tag.asTag().isForwardRef())
300       indices.forward = *ti;
301     else
302       indices.full = *ti;
303 
304     if (indices.full != TypeIndex::None() &&
305         indices.forward != TypeIndex::None()) {
306       forward_to_full[indices.forward] = indices.full;
307       full_to_forward[indices.full] = indices.forward;
308     }
309 
310     // We're looking for LF_NESTTYPE records in the field list, so ignore
311     // forward references (no field list), and anything without a nested class
312     // (since there won't be any LF_NESTTYPE records).
313     if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass())
314       continue;
315 
316     struct ProcessTpiStream : public TypeVisitorCallbacks {
317       ProcessTpiStream(PdbIndex &index, TypeIndex parent,
318                        const CVTagRecord &parent_cvt,
319                        llvm::DenseMap<TypeIndex, TypeIndex> &parents)
320           : index(index), parents(parents), parent(parent),
321             parent_cvt(parent_cvt) {}
322 
323       PdbIndex &index;
324       llvm::DenseMap<TypeIndex, TypeIndex> &parents;
325 
326       unsigned unnamed_type_index = 1;
327       TypeIndex parent;
328       const CVTagRecord &parent_cvt;
329 
330       llvm::Error visitKnownMember(CVMemberRecord &CVR,
331                                    NestedTypeRecord &Record) override {
332         std::string unnamed_type_name;
333         if (Record.Name.empty()) {
334           unnamed_type_name =
335               llvm::formatv("<unnamed-type-$S{0}>", unnamed_type_index).str();
336           Record.Name = unnamed_type_name;
337           ++unnamed_type_index;
338         }
339         llvm::Optional<CVTagRecord> tag =
340             GetNestedTagDefinition(Record, parent_cvt, index.tpi());
341         if (!tag)
342           return llvm::ErrorSuccess();
343 
344         parents[Record.Type] = parent;
345         return llvm::ErrorSuccess();
346       }
347     };
348 
349     CVType field_list = m_index.tpi().getType(tag.asTag().FieldList);
350     ProcessTpiStream process(m_index, *ti, tag, m_parent_types);
351     llvm::Error error = visitMemberRecordStream(field_list.data(), process);
352     if (error)
353       llvm::consumeError(std::move(error));
354   }
355 
356   // Now that we know the forward -> full mapping of all type indices, we can
357   // re-write all the indices.  At the end of this process, we want a mapping
358   // consisting of fwd -> full and full -> full for all child -> parent indices.
359   // We can re-write the values in place, but for the keys, we must save them
360   // off so that we don't modify the map in place while also iterating it.
361   std::vector<TypeIndex> full_keys;
362   std::vector<TypeIndex> fwd_keys;
363   for (auto &entry : m_parent_types) {
364     TypeIndex key = entry.first;
365     TypeIndex value = entry.second;
366 
367     auto iter = forward_to_full.find(value);
368     if (iter != forward_to_full.end())
369       entry.second = iter->second;
370 
371     iter = forward_to_full.find(key);
372     if (iter != forward_to_full.end())
373       fwd_keys.push_back(key);
374     else
375       full_keys.push_back(key);
376   }
377   for (TypeIndex fwd : fwd_keys) {
378     TypeIndex full = forward_to_full[fwd];
379     m_parent_types[full] = m_parent_types[fwd];
380   }
381   for (TypeIndex full : full_keys) {
382     TypeIndex fwd = full_to_forward[full];
383     m_parent_types[fwd] = m_parent_types[full];
384   }
385 
386   // Now that
387 }
388 
389 static bool isLocalVariableType(SymbolKind K) {
390   switch (K) {
391   case S_REGISTER:
392   case S_REGREL32:
393   case S_LOCAL:
394     return true;
395   default:
396     break;
397   }
398   return false;
399 }
400 
401 static std::string
402 RenderScopeList(llvm::ArrayRef<llvm::ms_demangle::Node *> nodes) {
403   lldbassert(!nodes.empty());
404 
405   std::string result = nodes.front()->toString();
406   nodes = nodes.drop_front();
407   while (!nodes.empty()) {
408     result += "::";
409     result += nodes.front()->toString(llvm::ms_demangle::OF_NoTagSpecifier);
410     nodes = nodes.drop_front();
411   }
412   return result;
413 }
414 
415 static llvm::Optional<PublicSym32> FindPublicSym(const SegmentOffset &addr,
416                                                  SymbolStream &syms,
417                                                  PublicsStream &publics) {
418   llvm::FixedStreamArray<ulittle32_t> addr_map = publics.getAddressMap();
419   auto iter = std::lower_bound(
420       addr_map.begin(), addr_map.end(), addr,
421       [&](const ulittle32_t &x, const SegmentOffset &y) {
422         CVSymbol s1 = syms.readRecord(x);
423         lldbassert(s1.kind() == S_PUB32);
424         PublicSym32 p1;
425         llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(s1, p1));
426         if (p1.Segment < y.segment)
427           return true;
428         return p1.Offset < y.offset;
429       });
430   if (iter == addr_map.end())
431     return llvm::None;
432   CVSymbol sym = syms.readRecord(*iter);
433   lldbassert(sym.kind() == S_PUB32);
434   PublicSym32 p;
435   llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(sym, p));
436   if (p.Segment == addr.segment && p.Offset == addr.offset)
437     return p;
438   return llvm::None;
439 }
440 
441 clang::Decl *PdbAstBuilder::GetOrCreateSymbolForId(PdbCompilandSymId id) {
442   CVSymbol cvs = m_index.ReadSymbolRecord(id);
443 
444   if (isLocalVariableType(cvs.kind())) {
445     clang::DeclContext *scope = GetParentDeclContext(id);
446     clang::Decl *scope_decl = clang::Decl::castFromDeclContext(scope);
447     PdbCompilandSymId scope_id(id.modi, m_decl_to_status[scope_decl].uid);
448     return GetOrCreateVariableDecl(scope_id, id);
449   }
450 
451   switch (cvs.kind()) {
452   case S_GPROC32:
453   case S_LPROC32:
454     return GetOrCreateFunctionDecl(id);
455   case S_GDATA32:
456   case S_LDATA32:
457   case S_GTHREAD32:
458   case S_CONSTANT:
459     // global variable
460     return nullptr;
461   case S_BLOCK32:
462     return GetOrCreateBlockDecl(id);
463   default:
464     return nullptr;
465   }
466 }
467 
468 llvm::Optional<CompilerDecl> PdbAstBuilder::GetOrCreateDeclForUid(PdbSymUid uid) {
469   if (clang::Decl *result = TryGetDecl(uid))
470     return ToCompilerDecl(*result);
471 
472   clang::Decl *result = nullptr;
473   switch (uid.kind()) {
474   case PdbSymUidKind::CompilandSym:
475     result = GetOrCreateSymbolForId(uid.asCompilandSym());
476     break;
477   case PdbSymUidKind::Type: {
478     clang::QualType qt = GetOrCreateType(uid.asTypeSym());
479     if (auto *tag = qt->getAsTagDecl()) {
480       result = tag;
481       break;
482     }
483     return llvm::None;
484   }
485   default:
486     return llvm::None;
487   }
488   m_uid_to_decl[toOpaqueUid(uid)] = result;
489   return ToCompilerDecl(*result);
490 }
491 
492 clang::DeclContext *PdbAstBuilder::GetOrCreateDeclContextForUid(PdbSymUid uid) {
493   if (uid.kind() == PdbSymUidKind::CompilandSym) {
494     if (uid.asCompilandSym().offset == 0)
495       return FromCompilerDeclContext(GetTranslationUnitDecl());
496   }
497   auto option = GetOrCreateDeclForUid(uid);
498   if (!option)
499     return nullptr;
500   clang::Decl *decl = FromCompilerDecl(option.getValue());
501   if (!decl)
502     return nullptr;
503 
504   return clang::Decl::castToDeclContext(decl);
505 }
506 
507 std::pair<clang::DeclContext *, std::string>
508 PdbAstBuilder::CreateDeclInfoForUndecoratedName(llvm::StringRef name) {
509   MSVCUndecoratedNameParser parser(name);
510   llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers();
511 
512   auto context = FromCompilerDeclContext(GetTranslationUnitDecl());
513 
514   llvm::StringRef uname = specs.back().GetBaseName();
515   specs = specs.drop_back();
516   if (specs.empty())
517     return {context, name};
518 
519   llvm::StringRef scope_name = specs.back().GetFullName();
520 
521   // It might be a class name, try that first.
522   std::vector<TypeIndex> types = m_index.tpi().findRecordsByName(scope_name);
523   while (!types.empty()) {
524     clang::QualType qt = GetOrCreateType(types.back());
525     clang::TagDecl *tag = qt->getAsTagDecl();
526     if (tag)
527       return {clang::TagDecl::castToDeclContext(tag), uname};
528     types.pop_back();
529   }
530 
531   // If that fails, treat it as a series of namespaces.
532   for (const MSVCUndecoratedNameSpecifier &spec : specs) {
533     std::string ns_name = spec.GetBaseName().str();
534     context = GetOrCreateNamespaceDecl(ns_name.c_str(), *context);
535   }
536   return {context, uname};
537 }
538 
539 clang::DeclContext *
540 PdbAstBuilder::GetParentDeclContextForSymbol(const CVSymbol &sym) {
541   if (!SymbolHasAddress(sym))
542     return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first;
543   SegmentOffset addr = GetSegmentAndOffset(sym);
544   llvm::Optional<PublicSym32> pub =
545       FindPublicSym(addr, m_index.symrecords(), m_index.publics());
546   if (!pub)
547     return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first;
548 
549   llvm::ms_demangle::Demangler demangler;
550   StringView name{pub->Name.begin(), pub->Name.size()};
551   llvm::ms_demangle::SymbolNode *node = demangler.parse(name);
552   if (!node)
553     return FromCompilerDeclContext(GetTranslationUnitDecl());
554   llvm::ArrayRef<llvm::ms_demangle::Node *> name_components{
555       node->Name->Components->Nodes, node->Name->Components->Count - 1};
556 
557   if (!name_components.empty()) {
558     // Render the current list of scope nodes as a fully qualified name, and
559     // look it up in the debug info as a type name.  If we find something,
560     // this is a type (which may itself be prefixed by a namespace).  If we
561     // don't, this is a list of namespaces.
562     std::string qname = RenderScopeList(name_components);
563     std::vector<TypeIndex> matches = m_index.tpi().findRecordsByName(qname);
564     while (!matches.empty()) {
565       clang::QualType qt = GetOrCreateType(matches.back());
566       clang::TagDecl *tag = qt->getAsTagDecl();
567       if (tag)
568         return clang::TagDecl::castToDeclContext(tag);
569       matches.pop_back();
570     }
571   }
572 
573   // It's not a type.  It must be a series of namespaces.
574   auto context = FromCompilerDeclContext(GetTranslationUnitDecl());
575   while (!name_components.empty()) {
576     std::string ns = name_components.front()->toString();
577     context = GetOrCreateNamespaceDecl(ns.c_str(), *context);
578     name_components = name_components.drop_front();
579   }
580   return context;
581 }
582 
583 clang::DeclContext *PdbAstBuilder::GetParentDeclContext(PdbSymUid uid) {
584   // We must do this *without* calling GetOrCreate on the current uid, as
585   // that would be an infinite recursion.
586   switch (uid.kind()) {
587   case PdbSymUidKind::CompilandSym: {
588     llvm::Optional<PdbCompilandSymId> scope =
589         FindSymbolScope(m_index, uid.asCompilandSym());
590     if (scope)
591       return GetOrCreateDeclContextForUid(*scope);
592 
593     CVSymbol sym = m_index.ReadSymbolRecord(uid.asCompilandSym());
594     return GetParentDeclContextForSymbol(sym);
595   }
596   case PdbSymUidKind::Type: {
597     // It could be a namespace, class, or global.  We don't support nested
598     // functions yet.  Anyway, we just need to consult the parent type map.
599     PdbTypeSymId type_id = uid.asTypeSym();
600     auto iter = m_parent_types.find(type_id.index);
601     if (iter == m_parent_types.end())
602       return FromCompilerDeclContext(GetTranslationUnitDecl());
603     return GetOrCreateDeclContextForUid(PdbTypeSymId(iter->second));
604   }
605   case PdbSymUidKind::FieldListMember:
606     // In this case the parent DeclContext is the one for the class that this
607     // member is inside of.
608     break;
609   case PdbSymUidKind::GlobalSym: {
610     // If this refers to a compiland symbol, just recurse in with that symbol.
611     // The only other possibilities are S_CONSTANT and S_UDT, in which case we
612     // need to parse the undecorated name to figure out the scope, then look
613     // that up in the TPI stream.  If it's found, it's a type, othewrise it's
614     // a series of namespaces.
615     // FIXME: do this.
616     CVSymbol global = m_index.ReadSymbolRecord(uid.asGlobalSym());
617     switch (global.kind()) {
618     case SymbolKind::S_GDATA32:
619     case SymbolKind::S_LDATA32:
620       return GetParentDeclContextForSymbol(global);
621     case SymbolKind::S_PROCREF:
622     case SymbolKind::S_LPROCREF: {
623       ProcRefSym ref{global.kind()};
624       llvm::cantFail(
625           SymbolDeserializer::deserializeAs<ProcRefSym>(global, ref));
626       PdbCompilandSymId cu_sym_id{ref.modi(), ref.SymOffset};
627       return GetParentDeclContext(cu_sym_id);
628     }
629     case SymbolKind::S_CONSTANT:
630     case SymbolKind::S_UDT:
631       return CreateDeclInfoForUndecoratedName(getSymbolName(global)).first;
632     default:
633       break;
634     }
635     break;
636   }
637   default:
638     break;
639   }
640   return FromCompilerDeclContext(GetTranslationUnitDecl());
641 }
642 
643 bool PdbAstBuilder::CompleteType(clang::QualType qt) {
644   clang::TagDecl *tag = qt->getAsTagDecl();
645   if (!tag)
646     return false;
647 
648   return CompleteTagDecl(*tag);
649 }
650 
651 bool PdbAstBuilder::CompleteTagDecl(clang::TagDecl &tag) {
652   // If this is not in our map, it's an error.
653   auto status_iter = m_decl_to_status.find(&tag);
654   lldbassert(status_iter != m_decl_to_status.end());
655 
656   // If it's already complete, just return.
657   DeclStatus &status = status_iter->second;
658   if (status.resolved)
659     return true;
660 
661   PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym();
662 
663   lldbassert(IsTagRecord(type_id, m_index.tpi()));
664 
665   clang::QualType tag_qt = m_clang.getASTContext()->getTypeDeclType(&tag);
666   ClangASTContext::SetHasExternalStorage(tag_qt.getAsOpaquePtr(), false);
667 
668   TypeIndex tag_ti = type_id.index;
669   CVType cvt = m_index.tpi().getType(tag_ti);
670   if (cvt.kind() == LF_MODIFIER)
671     tag_ti = LookThroughModifierRecord(cvt);
672 
673   PdbTypeSymId best_ti = GetBestPossibleDecl(tag_ti, m_index.tpi());
674   cvt = m_index.tpi().getType(best_ti.index);
675   lldbassert(IsTagRecord(cvt));
676 
677   if (IsForwardRefUdt(cvt)) {
678     // If we can't find a full decl for this forward ref anywhere in the debug
679     // info, then we have no way to complete it.
680     return false;
681   }
682 
683   TypeIndex field_list_ti = GetFieldListIndex(cvt);
684   CVType field_list_cvt = m_index.tpi().getType(field_list_ti);
685   if (field_list_cvt.kind() != LF_FIELDLIST)
686     return false;
687 
688   // Visit all members of this class, then perform any finalization necessary
689   // to complete the class.
690   CompilerType ct = ToCompilerType(tag_qt);
691   UdtRecordCompleter completer(best_ti, ct, tag, *this, m_index.tpi());
692   auto error =
693       llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer);
694   completer.complete();
695 
696   status.resolved = true;
697   if (!error)
698     return true;
699 
700   llvm::consumeError(std::move(error));
701   return false;
702 }
703 
704 clang::QualType PdbAstBuilder::CreateSimpleType(TypeIndex ti) {
705   if (ti == TypeIndex::NullptrT())
706     return GetBasicType(lldb::eBasicTypeNullPtr);
707 
708   if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
709     clang::QualType direct_type = GetOrCreateType(ti.makeDirect());
710     return m_clang.getASTContext()->getPointerType(direct_type);
711   }
712 
713   if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
714     return {};
715 
716   lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind());
717   if (bt == lldb::eBasicTypeInvalid)
718     return {};
719 
720   return GetBasicType(bt);
721 }
722 
723 clang::QualType PdbAstBuilder::CreatePointerType(const PointerRecord &pointer) {
724   clang::QualType pointee_type = GetOrCreateType(pointer.ReferentType);
725 
726   // This can happen for pointers to LF_VTSHAPE records, which we shouldn't
727   // create in the AST.
728   if (pointee_type.isNull())
729     return {};
730 
731   if (pointer.isPointerToMember()) {
732     MemberPointerInfo mpi = pointer.getMemberInfo();
733     clang::QualType class_type = GetOrCreateType(mpi.ContainingType);
734 
735     return m_clang.getASTContext()->getMemberPointerType(
736         pointee_type, class_type.getTypePtr());
737   }
738 
739   clang::QualType pointer_type;
740   if (pointer.getMode() == PointerMode::LValueReference)
741     pointer_type =
742         m_clang.getASTContext()->getLValueReferenceType(pointee_type);
743   else if (pointer.getMode() == PointerMode::RValueReference)
744     pointer_type =
745         m_clang.getASTContext()->getRValueReferenceType(pointee_type);
746   else
747     pointer_type = m_clang.getASTContext()->getPointerType(pointee_type);
748 
749   if ((pointer.getOptions() & PointerOptions::Const) != PointerOptions::None)
750     pointer_type.addConst();
751 
752   if ((pointer.getOptions() & PointerOptions::Volatile) != PointerOptions::None)
753     pointer_type.addVolatile();
754 
755   if ((pointer.getOptions() & PointerOptions::Restrict) != PointerOptions::None)
756     pointer_type.addRestrict();
757 
758   return pointer_type;
759 }
760 
761 clang::QualType
762 PdbAstBuilder::CreateModifierType(const ModifierRecord &modifier) {
763   clang::QualType unmodified_type = GetOrCreateType(modifier.ModifiedType);
764   if (unmodified_type.isNull())
765     return {};
766 
767   if ((modifier.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
768     unmodified_type.addConst();
769   if ((modifier.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
770     unmodified_type.addVolatile();
771 
772   return unmodified_type;
773 }
774 
775 clang::QualType PdbAstBuilder::CreateRecordType(PdbTypeSymId id,
776                                                 const TagRecord &record) {
777   clang::DeclContext *context = nullptr;
778   std::string uname;
779   std::tie(context, uname) = CreateDeclInfoForType(record, id.index);
780   clang::TagTypeKind ttk = TranslateUdtKind(record);
781   lldb::AccessType access =
782       (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic;
783 
784   ClangASTMetadata metadata;
785   metadata.SetUserID(toOpaqueUid(id));
786   metadata.SetIsDynamicCXXType(false);
787 
788   CompilerType ct =
789       m_clang.CreateRecordType(context, access, uname.c_str(), ttk,
790                                lldb::eLanguageTypeC_plus_plus, &metadata);
791 
792   lldbassert(ct.IsValid());
793 
794   ClangASTContext::StartTagDeclarationDefinition(ct);
795 
796   // Even if it's possible, don't complete it at this point. Just mark it
797   // forward resolved, and if/when LLDB needs the full definition, it can
798   // ask us.
799   clang::QualType result =
800       clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType());
801 
802   ClangASTContext::SetHasExternalStorage(result.getAsOpaquePtr(), true);
803   return result;
804 }
805 
806 clang::Decl *PdbAstBuilder::TryGetDecl(PdbSymUid uid) const {
807   auto iter = m_uid_to_decl.find(toOpaqueUid(uid));
808   if (iter != m_uid_to_decl.end())
809     return iter->second;
810   return nullptr;
811 }
812 
813 clang::NamespaceDecl *
814 PdbAstBuilder::GetOrCreateNamespaceDecl(const char *name,
815                                         clang::DeclContext &context) {
816   return m_clang.GetUniqueNamespaceDeclaration(
817       IsAnonymousNamespaceName(name) ? nullptr : name, &context);
818 }
819 
820 clang::BlockDecl *
821 PdbAstBuilder::GetOrCreateBlockDecl(PdbCompilandSymId block_id) {
822   if (clang::Decl *decl = TryGetDecl(block_id))
823     return llvm::dyn_cast<clang::BlockDecl>(decl);
824 
825   clang::DeclContext *scope = GetParentDeclContext(block_id);
826 
827   clang::BlockDecl *block_decl = m_clang.CreateBlockDeclaration(scope);
828   m_uid_to_decl.insert({toOpaqueUid(block_id), block_decl});
829 
830   DeclStatus status;
831   status.resolved = true;
832   status.uid = toOpaqueUid(block_id);
833   m_decl_to_status.insert({block_decl, status});
834 
835   return block_decl;
836 }
837 
838 clang::VarDecl *PdbAstBuilder::CreateVariableDecl(PdbSymUid uid, CVSymbol sym,
839                                                   clang::DeclContext &scope) {
840   VariableInfo var_info = GetVariableNameInfo(sym);
841   clang::QualType qt = GetOrCreateType(var_info.type);
842 
843   clang::VarDecl *var_decl = m_clang.CreateVariableDeclaration(
844       &scope, var_info.name.str().c_str(), qt);
845 
846   m_uid_to_decl[toOpaqueUid(uid)] = var_decl;
847   DeclStatus status;
848   status.resolved = true;
849   status.uid = toOpaqueUid(uid);
850   m_decl_to_status.insert({var_decl, status});
851   return var_decl;
852 }
853 
854 clang::VarDecl *
855 PdbAstBuilder::GetOrCreateVariableDecl(PdbCompilandSymId scope_id,
856                                        PdbCompilandSymId var_id) {
857   if (clang::Decl *decl = TryGetDecl(var_id))
858     return llvm::dyn_cast<clang::VarDecl>(decl);
859 
860   clang::DeclContext *scope = GetOrCreateDeclContextForUid(scope_id);
861 
862   CVSymbol sym = m_index.ReadSymbolRecord(var_id);
863   return CreateVariableDecl(PdbSymUid(var_id), sym, *scope);
864 }
865 
866 clang::VarDecl *PdbAstBuilder::GetOrCreateVariableDecl(PdbGlobalSymId var_id) {
867   if (clang::Decl *decl = TryGetDecl(var_id))
868     return llvm::dyn_cast<clang::VarDecl>(decl);
869 
870   CVSymbol sym = m_index.ReadSymbolRecord(var_id);
871   auto context = FromCompilerDeclContext(GetTranslationUnitDecl());
872   return CreateVariableDecl(PdbSymUid(var_id), sym, *context);
873 }
874 
875 clang::TypedefNameDecl *
876 PdbAstBuilder::GetOrCreateTypedefDecl(PdbGlobalSymId id) {
877   if (clang::Decl *decl = TryGetDecl(id))
878     return llvm::dyn_cast<clang::TypedefNameDecl>(decl);
879 
880   CVSymbol sym = m_index.ReadSymbolRecord(id);
881   lldbassert(sym.kind() == S_UDT);
882   UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
883 
884   clang::DeclContext *scope = GetParentDeclContext(id);
885 
886   PdbTypeSymId real_type_id{udt.Type, false};
887   clang::QualType qt = GetOrCreateType(real_type_id);
888 
889   std::string uname = DropNameScope(udt.Name);
890 
891   CompilerType ct = m_clang.CreateTypedefType(ToCompilerType(qt), uname.c_str(),
892                                               ToCompilerDeclContext(*scope));
893   clang::TypedefNameDecl *tnd = m_clang.GetAsTypedefDecl(ct);
894   DeclStatus status;
895   status.resolved = true;
896   status.uid = toOpaqueUid(id);
897   m_decl_to_status.insert({tnd, status});
898   return tnd;
899 }
900 
901 clang::QualType PdbAstBuilder::GetBasicType(lldb::BasicType type) {
902   CompilerType ct = m_clang.GetBasicType(type);
903   return clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType());
904 }
905 
906 clang::QualType PdbAstBuilder::CreateType(PdbTypeSymId type) {
907   if (type.index.isSimple())
908     return CreateSimpleType(type.index);
909 
910   CVType cvt = m_index.tpi().getType(type.index);
911 
912   if (cvt.kind() == LF_MODIFIER) {
913     ModifierRecord modifier;
914     llvm::cantFail(
915         TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
916     return CreateModifierType(modifier);
917   }
918 
919   if (cvt.kind() == LF_POINTER) {
920     PointerRecord pointer;
921     llvm::cantFail(
922         TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
923     return CreatePointerType(pointer);
924   }
925 
926   if (IsTagRecord(cvt)) {
927     CVTagRecord tag = CVTagRecord::create(cvt);
928     if (tag.kind() == CVTagRecord::Union)
929       return CreateRecordType(type.index, tag.asUnion());
930     if (tag.kind() == CVTagRecord::Enum)
931       return CreateEnumType(type.index, tag.asEnum());
932     return CreateRecordType(type.index, tag.asClass());
933   }
934 
935   if (cvt.kind() == LF_ARRAY) {
936     ArrayRecord ar;
937     llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
938     return CreateArrayType(ar);
939   }
940 
941   if (cvt.kind() == LF_PROCEDURE) {
942     ProcedureRecord pr;
943     llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
944     return CreateFunctionType(pr.ArgumentList, pr.ReturnType, pr.CallConv);
945   }
946 
947   if (cvt.kind() == LF_MFUNCTION) {
948     MemberFunctionRecord mfr;
949     llvm::cantFail(
950         TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr));
951     return CreateFunctionType(mfr.ArgumentList, mfr.ReturnType, mfr.CallConv);
952   }
953 
954   return {};
955 }
956 
957 clang::QualType PdbAstBuilder::GetOrCreateType(PdbTypeSymId type) {
958   lldb::user_id_t uid = toOpaqueUid(type);
959   auto iter = m_uid_to_type.find(uid);
960   if (iter != m_uid_to_type.end())
961     return iter->second;
962 
963   PdbTypeSymId best_type = GetBestPossibleDecl(type, m_index.tpi());
964 
965   clang::QualType qt;
966   if (best_type.index != type.index) {
967     // This is a forward decl.  Call GetOrCreate on the full decl, then map the
968     // forward decl id to the full decl QualType.
969     clang::QualType qt = GetOrCreateType(best_type);
970     m_uid_to_type[toOpaqueUid(type)] = qt;
971     return qt;
972   }
973 
974   // This is either a full decl, or a forward decl with no matching full decl
975   // in the debug info.
976   qt = CreateType(type);
977   m_uid_to_type[toOpaqueUid(type)] = qt;
978   if (IsTagRecord(type, m_index.tpi())) {
979     clang::TagDecl *tag = qt->getAsTagDecl();
980     lldbassert(m_decl_to_status.count(tag) == 0);
981 
982     DeclStatus &status = m_decl_to_status[tag];
983     status.uid = uid;
984     status.resolved = false;
985   }
986   return qt;
987 }
988 
989 clang::FunctionDecl *
990 PdbAstBuilder::GetOrCreateFunctionDecl(PdbCompilandSymId func_id) {
991   if (clang::Decl *decl = TryGetDecl(func_id))
992     return llvm::dyn_cast<clang::FunctionDecl>(decl);
993 
994   clang::DeclContext *parent = GetParentDeclContext(PdbSymUid(func_id));
995   std::string context_name;
996   if (clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(parent)) {
997     context_name = ns->getQualifiedNameAsString();
998   } else if (clang::TagDecl *tag = llvm::dyn_cast<clang::TagDecl>(parent)) {
999     context_name = tag->getQualifiedNameAsString();
1000   }
1001 
1002   CVSymbol cvs = m_index.ReadSymbolRecord(func_id);
1003   ProcSym proc(static_cast<SymbolRecordKind>(cvs.kind()));
1004   llvm::cantFail(SymbolDeserializer::deserializeAs<ProcSym>(cvs, proc));
1005 
1006   PdbTypeSymId type_id(proc.FunctionType);
1007   clang::QualType qt = GetOrCreateType(type_id);
1008   if (qt.isNull())
1009     return nullptr;
1010 
1011   clang::StorageClass storage = clang::SC_None;
1012   if (proc.Kind == SymbolRecordKind::ProcSym)
1013     storage = clang::SC_Static;
1014 
1015   const clang::FunctionProtoType *func_type =
1016       llvm::dyn_cast<clang::FunctionProtoType>(qt);
1017 
1018   CompilerType func_ct = ToCompilerType(qt);
1019 
1020   llvm::StringRef proc_name = proc.Name;
1021   proc_name.consume_front(context_name);
1022   proc_name.consume_front("::");
1023 
1024   clang::FunctionDecl *function_decl = m_clang.CreateFunctionDeclaration(
1025       parent, proc_name.str().c_str(), func_ct, storage, false);
1026 
1027   lldbassert(m_uid_to_decl.count(toOpaqueUid(func_id)) == 0);
1028   m_uid_to_decl[toOpaqueUid(func_id)] = function_decl;
1029   DeclStatus status;
1030   status.resolved = true;
1031   status.uid = toOpaqueUid(func_id);
1032   m_decl_to_status.insert({function_decl, status});
1033 
1034   CreateFunctionParameters(func_id, *function_decl, func_type->getNumParams());
1035 
1036   return function_decl;
1037 }
1038 
1039 void PdbAstBuilder::CreateFunctionParameters(PdbCompilandSymId func_id,
1040                                              clang::FunctionDecl &function_decl,
1041                                              uint32_t param_count) {
1042   CompilandIndexItem *cii = m_index.compilands().GetCompiland(func_id.modi);
1043   CVSymbolArray scope =
1044       cii->m_debug_stream.getSymbolArrayForScope(func_id.offset);
1045 
1046   auto begin = scope.begin();
1047   auto end = scope.end();
1048   std::vector<clang::ParmVarDecl *> params;
1049   while (begin != end && param_count > 0) {
1050     uint32_t record_offset = begin.offset();
1051     CVSymbol sym = *begin++;
1052 
1053     TypeIndex param_type;
1054     llvm::StringRef param_name;
1055     switch (sym.kind()) {
1056     case S_REGREL32: {
1057       RegRelativeSym reg(SymbolRecordKind::RegRelativeSym);
1058       cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg));
1059       param_type = reg.Type;
1060       param_name = reg.Name;
1061       break;
1062     }
1063     case S_REGISTER: {
1064       RegisterSym reg(SymbolRecordKind::RegisterSym);
1065       cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg));
1066       param_type = reg.Index;
1067       param_name = reg.Name;
1068       break;
1069     }
1070     case S_LOCAL: {
1071       LocalSym local(SymbolRecordKind::LocalSym);
1072       cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local));
1073       if ((local.Flags & LocalSymFlags::IsParameter) == LocalSymFlags::None)
1074         continue;
1075       param_type = local.Type;
1076       param_name = local.Name;
1077       break;
1078     }
1079     case S_BLOCK32:
1080       // All parameters should come before the first block.  If that isn't the
1081       // case, then perhaps this is bad debug info that doesn't contain
1082       // information about all parameters.
1083       return;
1084     default:
1085       continue;
1086     }
1087 
1088     PdbCompilandSymId param_uid(func_id.modi, record_offset);
1089     clang::QualType qt = GetOrCreateType(param_type);
1090 
1091     CompilerType param_type_ct(&m_clang, qt.getAsOpaquePtr());
1092     clang::ParmVarDecl *param = m_clang.CreateParameterDeclaration(
1093         &function_decl, param_name.str().c_str(), param_type_ct,
1094         clang::SC_None);
1095     lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0);
1096 
1097     m_uid_to_decl[toOpaqueUid(param_uid)] = param;
1098     params.push_back(param);
1099     --param_count;
1100   }
1101 
1102   if (!params.empty())
1103     m_clang.SetFunctionParameters(&function_decl, params.data(), params.size());
1104 }
1105 
1106 clang::QualType PdbAstBuilder::CreateEnumType(PdbTypeSymId id,
1107                                               const EnumRecord &er) {
1108   clang::DeclContext *decl_context = nullptr;
1109   std::string uname;
1110   std::tie(decl_context, uname) = CreateDeclInfoForType(er, id.index);
1111   clang::QualType underlying_type = GetOrCreateType(er.UnderlyingType);
1112 
1113   Declaration declaration;
1114   CompilerType enum_ct = m_clang.CreateEnumerationType(
1115       uname.c_str(), decl_context, declaration, ToCompilerType(underlying_type),
1116       er.isScoped());
1117 
1118   ClangASTContext::StartTagDeclarationDefinition(enum_ct);
1119   ClangASTContext::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true);
1120 
1121   return clang::QualType::getFromOpaquePtr(enum_ct.GetOpaqueQualType());
1122 }
1123 
1124 clang::QualType PdbAstBuilder::CreateArrayType(const ArrayRecord &ar) {
1125   clang::QualType element_type = GetOrCreateType(ar.ElementType);
1126 
1127   uint64_t element_count =
1128       ar.Size / GetSizeOfType({ar.ElementType}, m_index.tpi());
1129 
1130   CompilerType array_ct = m_clang.CreateArrayType(ToCompilerType(element_type),
1131                                                   element_count, false);
1132   return clang::QualType::getFromOpaquePtr(array_ct.GetOpaqueQualType());
1133 }
1134 
1135 clang::QualType PdbAstBuilder::CreateFunctionType(
1136     TypeIndex args_type_idx, TypeIndex return_type_idx,
1137     llvm::codeview::CallingConvention calling_convention) {
1138   TpiStream &stream = m_index.tpi();
1139   CVType args_cvt = stream.getType(args_type_idx);
1140   ArgListRecord args;
1141   llvm::cantFail(
1142       TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args));
1143 
1144   llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices);
1145   bool is_variadic = IsCVarArgsFunction(arg_indices);
1146   if (is_variadic)
1147     arg_indices = arg_indices.drop_back();
1148 
1149   std::vector<CompilerType> arg_types;
1150   arg_types.reserve(arg_indices.size());
1151 
1152   for (TypeIndex arg_index : arg_indices) {
1153     clang::QualType arg_type = GetOrCreateType(arg_index);
1154     arg_types.push_back(ToCompilerType(arg_type));
1155   }
1156 
1157   clang::QualType return_type = GetOrCreateType(return_type_idx);
1158 
1159   llvm::Optional<clang::CallingConv> cc =
1160       TranslateCallingConvention(calling_convention);
1161   if (!cc)
1162     return {};
1163 
1164   CompilerType return_ct = ToCompilerType(return_type);
1165   CompilerType func_sig_ast_type = m_clang.CreateFunctionType(
1166       return_ct, arg_types.data(), arg_types.size(), is_variadic, 0, *cc);
1167 
1168   return clang::QualType::getFromOpaquePtr(
1169       func_sig_ast_type.GetOpaqueQualType());
1170 }
1171 
1172 static bool isTagDecl(clang::DeclContext &context) {
1173   return !!llvm::dyn_cast<clang::TagDecl>(&context);
1174 }
1175 
1176 static bool isFunctionDecl(clang::DeclContext &context) {
1177   return !!llvm::dyn_cast<clang::FunctionDecl>(&context);
1178 }
1179 
1180 static bool isBlockDecl(clang::DeclContext &context) {
1181   return !!llvm::dyn_cast<clang::BlockDecl>(&context);
1182 }
1183 
1184 void PdbAstBuilder::ParseAllNamespacesPlusChildrenOf(
1185     llvm::Optional<llvm::StringRef> parent) {
1186   TypeIndex ti{m_index.tpi().TypeIndexBegin()};
1187   for (const CVType &cvt : m_index.tpi().typeArray()) {
1188     PdbTypeSymId tid{ti};
1189     ++ti;
1190 
1191     if (!IsTagRecord(cvt))
1192       continue;
1193 
1194     CVTagRecord tag = CVTagRecord::create(cvt);
1195 
1196     if (!parent.hasValue()) {
1197       clang::QualType qt = GetOrCreateType(tid);
1198       CompleteType(qt);
1199       continue;
1200     }
1201 
1202     // Call CreateDeclInfoForType unconditionally so that the namespace info
1203     // gets created.  But only call CreateRecordType if the namespace name
1204     // matches.
1205     clang::DeclContext *context = nullptr;
1206     std::string uname;
1207     std::tie(context, uname) = CreateDeclInfoForType(tag.asTag(), tid.index);
1208     if (!context->isNamespace())
1209       continue;
1210 
1211     clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(context);
1212     std::string actual_ns = ns->getQualifiedNameAsString();
1213     if (llvm::StringRef(actual_ns).startswith(*parent)) {
1214       clang::QualType qt = GetOrCreateType(tid);
1215       CompleteType(qt);
1216       continue;
1217     }
1218   }
1219 
1220   uint32_t module_count = m_index.dbi().modules().getModuleCount();
1221   for (uint16_t modi = 0; modi < module_count; ++modi) {
1222     CompilandIndexItem &cii = m_index.compilands().GetOrCreateCompiland(modi);
1223     const CVSymbolArray &symbols = cii.m_debug_stream.getSymbolArray();
1224     auto iter = symbols.begin();
1225     while (iter != symbols.end()) {
1226       PdbCompilandSymId sym_id{modi, iter.offset()};
1227 
1228       switch (iter->kind()) {
1229       case S_GPROC32:
1230       case S_LPROC32:
1231         GetOrCreateFunctionDecl(sym_id);
1232         iter = symbols.at(getScopeEndOffset(*iter));
1233         break;
1234       case S_GDATA32:
1235       case S_GTHREAD32:
1236       case S_LDATA32:
1237       case S_LTHREAD32:
1238         GetOrCreateVariableDecl(PdbCompilandSymId(modi, 0), sym_id);
1239         ++iter;
1240         break;
1241       default:
1242         ++iter;
1243         continue;
1244       }
1245     }
1246   }
1247 }
1248 
1249 static CVSymbolArray skipFunctionParameters(clang::Decl &decl,
1250                                             const CVSymbolArray &symbols) {
1251   clang::FunctionDecl *func_decl = llvm::dyn_cast<clang::FunctionDecl>(&decl);
1252   if (!func_decl)
1253     return symbols;
1254   unsigned int params = func_decl->getNumParams();
1255   if (params == 0)
1256     return symbols;
1257 
1258   CVSymbolArray result = symbols;
1259 
1260   while (!result.empty()) {
1261     if (params == 0)
1262       return result;
1263 
1264     CVSymbol sym = *result.begin();
1265     result.drop_front();
1266 
1267     if (!isLocalVariableType(sym.kind()))
1268       continue;
1269 
1270     --params;
1271   }
1272   return result;
1273 }
1274 
1275 void PdbAstBuilder::ParseBlockChildren(PdbCompilandSymId block_id) {
1276   CVSymbol sym = m_index.ReadSymbolRecord(block_id);
1277   lldbassert(sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32 ||
1278              sym.kind() == S_BLOCK32);
1279   CompilandIndexItem &cii =
1280       m_index.compilands().GetOrCreateCompiland(block_id.modi);
1281   CVSymbolArray symbols =
1282       cii.m_debug_stream.getSymbolArrayForScope(block_id.offset);
1283 
1284   // Function parameters should already have been created when the function was
1285   // parsed.
1286   if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32)
1287     symbols =
1288         skipFunctionParameters(*m_uid_to_decl[toOpaqueUid(block_id)], symbols);
1289 
1290   auto begin = symbols.begin();
1291   while (begin != symbols.end()) {
1292     PdbCompilandSymId child_sym_id(block_id.modi, begin.offset());
1293     GetOrCreateSymbolForId(child_sym_id);
1294     if (begin->kind() == S_BLOCK32) {
1295       ParseBlockChildren(child_sym_id);
1296       begin = symbols.at(getScopeEndOffset(*begin));
1297     }
1298     ++begin;
1299   }
1300 }
1301 
1302 void PdbAstBuilder::ParseDeclsForSimpleContext(clang::DeclContext &context) {
1303 
1304   clang::Decl *decl = clang::Decl::castFromDeclContext(&context);
1305   lldbassert(decl);
1306 
1307   auto iter = m_decl_to_status.find(decl);
1308   lldbassert(iter != m_decl_to_status.end());
1309 
1310   if (auto *tag = llvm::dyn_cast<clang::TagDecl>(&context)) {
1311     CompleteTagDecl(*tag);
1312     return;
1313   }
1314 
1315   if (isFunctionDecl(context) || isBlockDecl(context)) {
1316     PdbCompilandSymId block_id = PdbSymUid(iter->second.uid).asCompilandSym();
1317     ParseBlockChildren(block_id);
1318   }
1319 }
1320 
1321 void PdbAstBuilder::ParseDeclsForContext(clang::DeclContext &context) {
1322   // Namespaces aren't explicitly represented in the debug info, and the only
1323   // way to parse them is to parse all type info, demangling every single type
1324   // and trying to reconstruct the DeclContext hierarchy this way.  Since this
1325   // is an expensive operation, we have to special case it so that we do other
1326   // work (such as parsing the items that appear within the namespaces) at the
1327   // same time.
1328   if (context.isTranslationUnit()) {
1329     ParseAllNamespacesPlusChildrenOf(llvm::None);
1330     return;
1331   }
1332 
1333   if (context.isNamespace()) {
1334     clang::NamespaceDecl &ns = *llvm::dyn_cast<clang::NamespaceDecl>(&context);
1335     std::string qname = ns.getQualifiedNameAsString();
1336     ParseAllNamespacesPlusChildrenOf(llvm::StringRef{qname});
1337     return;
1338   }
1339 
1340   if (isTagDecl(context) || isFunctionDecl(context) || isBlockDecl(context)) {
1341     ParseDeclsForSimpleContext(context);
1342     return;
1343   }
1344 }
1345 
1346 CompilerDecl PdbAstBuilder::ToCompilerDecl(clang::Decl &decl) {
1347   return {&m_clang, &decl};
1348 }
1349 
1350 CompilerType PdbAstBuilder::ToCompilerType(clang::QualType qt) {
1351   return {&m_clang, qt.getAsOpaquePtr()};
1352 }
1353 
1354 CompilerDeclContext
1355 PdbAstBuilder::ToCompilerDeclContext(clang::DeclContext &context) {
1356   return {&m_clang, &context};
1357 }
1358 
1359 clang::Decl * PdbAstBuilder::FromCompilerDecl(CompilerDecl decl) {
1360   return static_cast<clang::Decl *>(decl.GetOpaqueDecl());
1361 }
1362 
1363 clang::DeclContext *
1364 PdbAstBuilder::FromCompilerDeclContext(CompilerDeclContext context) {
1365   return static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext());
1366 }
1367 
1368 void PdbAstBuilder::Dump(Stream &stream) { m_clang.Dump(stream); }
1369