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