1 #include "PdbAstBuilder.h"
2 
3 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
4 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
5 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
6 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
7 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
8 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
9 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
10 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
11 #include "llvm/Demangle/MicrosoftDemangle.h"
12 
13 #include "lldb/Core/Module.h"
14 #include "lldb/Symbol/ClangASTContext.h"
15 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
16 #include "lldb/Symbol/ClangUtil.h"
17 #include "lldb/Symbol/ObjectFile.h"
18 #include "lldb/Utility/LLDBAssert.h"
19 
20 #include "PdbUtil.h"
21 #include "UdtRecordCompleter.h"
22 
23 using namespace lldb_private;
24 using namespace lldb_private::npdb;
25 using namespace llvm::codeview;
26 using namespace llvm::pdb;
27 
28 static llvm::Optional<PdbCompilandSymId> FindSymbolScope(PdbIndex &index,
29                                                          PdbCompilandSymId id) {
30   CVSymbol sym = index.ReadSymbolRecord(id);
31   if (symbolOpensScope(sym.kind())) {
32     // If this exact symbol opens a scope, we can just directly access its
33     // parent.
34     id.offset = getScopeParentOffset(sym);
35     // Global symbols have parent offset of 0.  Return llvm::None to indicate
36     // this.
37     if (id.offset == 0)
38       return llvm::None;
39     return id;
40   }
41 
42   // Otherwise we need to start at the beginning and iterate forward until we
43   // reach (or pass) this particular symbol
44   CompilandIndexItem &cii = index.compilands().GetOrCreateCompiland(id.modi);
45   const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
46 
47   auto begin = syms.begin();
48   auto end = syms.at(id.offset);
49   std::vector<PdbCompilandSymId> scope_stack;
50 
51   while (begin != end) {
52     if (id.offset == begin.offset()) {
53       // We have a match!  Return the top of the stack
54       if (scope_stack.empty())
55         return llvm::None;
56       return scope_stack.back();
57     }
58     if (begin.offset() > id.offset) {
59       // We passed it.  We couldn't even find this symbol record.
60       lldbassert(false && "Invalid compiland symbol id!");
61       return llvm::None;
62     }
63 
64     // We haven't found the symbol yet.  Check if we need to open or close the
65     // scope stack.
66     if (symbolOpensScope(begin->kind())) {
67       // We can use the end offset of the scope to determine whether or not
68       // we can just outright skip this entire scope.
69       uint32_t scope_end = getScopeEndOffset(*begin);
70       if (scope_end < id.modi) {
71         begin = syms.at(scope_end);
72       } else {
73         // The symbol we're looking for is somewhere in this scope.
74         scope_stack.emplace_back(id.modi, begin.offset());
75       }
76     } else if (symbolEndsScope(begin->kind())) {
77       scope_stack.pop_back();
78     }
79     ++begin;
80   }
81 
82   return llvm::None;
83 }
84 
85 static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) {
86   switch (cr.Kind) {
87   case TypeRecordKind::Class:
88     return clang::TTK_Class;
89   case TypeRecordKind::Struct:
90     return clang::TTK_Struct;
91   case TypeRecordKind::Union:
92     return clang::TTK_Union;
93   case TypeRecordKind::Interface:
94     return clang::TTK_Interface;
95   case TypeRecordKind::Enum:
96     return clang::TTK_Enum;
97   default:
98     lldbassert(false && "Invalid tag record kind!");
99     return clang::TTK_Struct;
100   }
101 }
102 
103 static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) {
104   if (args.empty())
105     return false;
106   return args.back() == TypeIndex::None();
107 }
108 
109 static bool
110 AnyScopesHaveTemplateParams(llvm::ArrayRef<llvm::ms_demangle::Node *> scopes) {
111   for (llvm::ms_demangle::Node *n : scopes) {
112     auto *idn = static_cast<llvm::ms_demangle::IdentifierNode *>(n);
113     if (idn->TemplateParams)
114       return true;
115   }
116   return false;
117 }
118 
119 static ClangASTContext &GetClangASTContext(ObjectFile &obj) {
120   TypeSystem *ts =
121       obj.GetModule()->GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
122   lldbassert(ts);
123   return static_cast<ClangASTContext &>(*ts);
124 }
125 
126 static llvm::Optional<clang::CallingConv>
127 TranslateCallingConvention(llvm::codeview::CallingConvention conv) {
128   using CC = llvm::codeview::CallingConvention;
129   switch (conv) {
130 
131   case CC::NearC:
132   case CC::FarC:
133     return clang::CallingConv::CC_C;
134   case CC::NearPascal:
135   case CC::FarPascal:
136     return clang::CallingConv::CC_X86Pascal;
137   case CC::NearFast:
138   case CC::FarFast:
139     return clang::CallingConv::CC_X86FastCall;
140   case CC::NearStdCall:
141   case CC::FarStdCall:
142     return clang::CallingConv::CC_X86StdCall;
143   case CC::ThisCall:
144     return clang::CallingConv::CC_X86ThisCall;
145   case CC::NearVector:
146     return clang::CallingConv::CC_X86VectorCall;
147   default:
148     return llvm::None;
149   }
150 }
151 
152 static llvm::Optional<CVTagRecord>
153 GetNestedTagRecord(const NestedTypeRecord &Record, const CVTagRecord &parent,
154                    TpiStream &tpi) {
155   // An LF_NESTTYPE is essentially a nested typedef / using declaration, but it
156   // is also used to indicate the primary definition of a nested class.  That is
157   // to say, if you have:
158   // struct A {
159   //   struct B {};
160   //   using C = B;
161   // };
162   // Then in the debug info, this will appear as:
163   // LF_STRUCTURE `A::B` [type index = N]
164   // LF_STRUCTURE `A`
165   //   LF_NESTTYPE [name = `B`, index = N]
166   //   LF_NESTTYPE [name = `C`, index = N]
167   // In order to accurately reconstruct the decl context hierarchy, we need to
168   // know which ones are actual definitions and which ones are just aliases.
169 
170   // If it's a simple type, then this is something like `using foo = int`.
171   if (Record.Type.isSimple())
172     return llvm::None;
173 
174   CVType cvt = tpi.getType(Record.Type);
175 
176   if (!IsTagRecord(cvt))
177     return llvm::None;
178 
179   // If it's an inner definition, then treat whatever name we have here as a
180   // single component of a mangled name.  So we can inject it into the parent's
181   // mangled name to see if it matches.
182   CVTagRecord child = CVTagRecord::create(cvt);
183   std::string qname = parent.asTag().getUniqueName();
184   if (qname.size() < 4 || child.asTag().getUniqueName().size() < 4)
185     return llvm::None;
186 
187   // qname[3] is the tag type identifier (struct, class, union, etc).  Since the
188   // inner tag type is not necessarily the same as the outer tag type, re-write
189   // it to match the inner tag type.
190   qname[3] = child.asTag().getUniqueName()[3];
191   std::string piece;
192   if (qname[3] == 'W')
193     piece = "4";
194   piece += Record.Name;
195   piece.push_back('@');
196   qname.insert(4, std::move(piece));
197   if (qname != child.asTag().UniqueName)
198     return llvm::None;
199 
200   return std::move(child);
201 }
202 
203 PdbAstBuilder::PdbAstBuilder(ObjectFile &obj, PdbIndex &index)
204     : m_index(index), m_clang(GetClangASTContext(obj)) {
205   BuildParentMap();
206 }
207 
208 clang::DeclContext &PdbAstBuilder::GetTranslationUnitDecl() {
209   return *m_clang.GetTranslationUnitDecl();
210 }
211 
212 std::pair<clang::DeclContext *, std::string>
213 PdbAstBuilder::CreateDeclInfoForType(const TagRecord &record, TypeIndex ti) {
214   // FIXME: Move this to GetDeclContextContainingUID.
215 
216   llvm::ms_demangle::Demangler demangler;
217   StringView sv(record.UniqueName.begin(), record.UniqueName.size());
218   llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
219   llvm::ms_demangle::IdentifierNode *idn =
220       ttn->QualifiedName->getUnqualifiedIdentifier();
221   std::string uname = idn->toString();
222 
223   llvm::ms_demangle::NodeArrayNode *name_components =
224       ttn->QualifiedName->Components;
225   llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes,
226                                                    name_components->Count - 1);
227 
228   clang::DeclContext *context = m_clang.GetTranslationUnitDecl();
229 
230   // If this type doesn't have a parent type in the debug info, then the best we
231   // can do is to say that it's either a series of namespaces (if the scope is
232   // non-empty), or the translation unit (if the scope is empty).
233   auto parent_iter = m_parent_types.find(ti);
234   if (parent_iter == m_parent_types.end()) {
235     if (scopes.empty())
236       return {context, uname};
237 
238     // If there is no parent in the debug info, but some of the scopes have
239     // template params, then this is a case of bad debug info.  See, for
240     // example, llvm.org/pr39607.  We don't want to create an ambiguity between
241     // a NamespaceDecl and a CXXRecordDecl, so instead we create a class at
242     // global scope with the fully qualified name.
243     if (AnyScopesHaveTemplateParams(scopes))
244       return {context, record.Name};
245 
246     for (llvm::ms_demangle::Node *scope : scopes) {
247       auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope);
248       std::string str = nii->toString();
249       context = m_clang.GetUniqueNamespaceDeclaration(str.c_str(), context);
250     }
251     return {context, uname};
252   }
253 
254   // Otherwise, all we need to do is get the parent type of this type and
255   // recurse into our lazy type creation / AST reconstruction logic to get an
256   // LLDB TypeSP for the parent.  This will cause the AST to automatically get
257   // the right DeclContext created for any parent.
258   clang::QualType parent_qt = GetOrCreateType(parent_iter->second);
259 
260   context = clang::TagDecl::castToDeclContext(parent_qt->getAsTagDecl());
261   return {context, uname};
262 }
263 
264 void PdbAstBuilder::BuildParentMap() {
265   LazyRandomTypeCollection &types = m_index.tpi().typeCollection();
266 
267   for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
268     CVType type = types.getType(*ti);
269     if (!IsTagRecord(type))
270       continue;
271 
272     CVTagRecord tag = CVTagRecord::create(type);
273     // We're looking for LF_NESTTYPE records in the field list, so ignore
274     // forward references (no field list), and anything without a nested class
275     // (since there won't be any LF_NESTTYPE records).
276     if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass())
277       continue;
278 
279     struct ProcessTpiStream : public TypeVisitorCallbacks {
280       ProcessTpiStream(PdbIndex &index, TypeIndex parent,
281                        const CVTagRecord &parent_cvt,
282                        llvm::DenseMap<TypeIndex, TypeIndex> &parents)
283           : index(index), parents(parents), parent(parent),
284             parent_cvt(parent_cvt) {}
285 
286       PdbIndex &index;
287       llvm::DenseMap<TypeIndex, TypeIndex> &parents;
288       TypeIndex parent;
289       const CVTagRecord &parent_cvt;
290 
291       llvm::Error visitKnownMember(CVMemberRecord &CVR,
292                                    NestedTypeRecord &Record) override {
293         llvm::Optional<CVTagRecord> tag =
294             GetNestedTagRecord(Record, parent_cvt, index.tpi());
295         if (!tag)
296           return llvm::ErrorSuccess();
297 
298         parents[Record.Type] = parent;
299         if (!tag->asTag().isForwardRef())
300           return llvm::ErrorSuccess();
301 
302         llvm::Expected<TypeIndex> full_decl =
303             index.tpi().findFullDeclForForwardRef(Record.Type);
304         if (!full_decl) {
305           llvm::consumeError(full_decl.takeError());
306           return llvm::ErrorSuccess();
307         }
308         parents[*full_decl] = parent;
309         return llvm::ErrorSuccess();
310       }
311     };
312 
313     CVType field_list = m_index.tpi().getType(tag.asTag().FieldList);
314     ProcessTpiStream process(m_index, *ti, tag, m_parent_types);
315     llvm::Error error = visitMemberRecordStream(field_list.data(), process);
316     if (error)
317       llvm::consumeError(std::move(error));
318   }
319 }
320 
321 clang::Decl *PdbAstBuilder::GetOrCreateSymbolForId(PdbCompilandSymId id) {
322   CVSymbol cvs = m_index.ReadSymbolRecord(id);
323 
324   switch (cvs.kind()) {
325   case S_GPROC32:
326   case S_LPROC32:
327     return GetOrCreateFunctionDecl(id);
328   case S_GDATA32:
329   case S_LDATA32:
330   case S_GTHREAD32:
331   case S_CONSTANT:
332     // global variable
333     return nullptr;
334   case S_BLOCK32:
335     return GetOrCreateBlockDecl(id);
336   case S_REGISTER:
337   case S_REGREL32:
338   case S_LOCAL: {
339     clang::DeclContext *scope = GetParentDeclContext(id);
340     clang::Decl *scope_decl = clang::Decl::castFromDeclContext(scope);
341     PdbCompilandSymId scope_id(id.modi, m_decl_to_status[scope_decl].uid);
342     return GetOrCreateLocalVariableDecl(scope_id, id);
343   }
344   default:
345     return nullptr;
346   }
347 }
348 
349 clang::Decl *PdbAstBuilder::GetOrCreateDeclForUid(PdbSymUid uid) {
350   if (clang::Decl *result = TryGetDecl(uid))
351     return result;
352 
353   clang::Decl *result = nullptr;
354   switch (uid.kind()) {
355   case PdbSymUidKind::CompilandSym:
356     result = GetOrCreateSymbolForId(uid.asCompilandSym());
357     break;
358   case PdbSymUidKind::Type: {
359     clang::QualType qt = GetOrCreateType(uid.asTypeSym());
360     if (auto *tag = qt->getAsTagDecl()) {
361       result = tag;
362       break;
363     }
364     return nullptr;
365   }
366   default:
367     return nullptr;
368   }
369   m_uid_to_decl[toOpaqueUid(uid)] = result;
370   return result;
371 }
372 
373 clang::DeclContext *PdbAstBuilder::GetOrCreateDeclContextForUid(PdbSymUid uid) {
374   clang::Decl *decl = GetOrCreateDeclForUid(uid);
375   if (!decl)
376     return nullptr;
377 
378   return clang::Decl::castToDeclContext(decl);
379 }
380 
381 clang::DeclContext *PdbAstBuilder::GetParentDeclContext(PdbSymUid uid) {
382   // We must do this *without* calling GetOrCreate on the current uid, as
383   // that would be an infinite recursion.
384   switch (uid.kind()) {
385   case PdbSymUidKind::CompilandSym: {
386     llvm::Optional<PdbCompilandSymId> scope =
387         FindSymbolScope(m_index, uid.asCompilandSym());
388     if (!scope)
389       return &GetTranslationUnitDecl();
390     return GetOrCreateDeclContextForUid(*scope);
391   }
392   case PdbSymUidKind::Type:
393     // It could be a namespace, class, or global.  We don't support nested
394     // functions yet.  Anyway, we just need to consult the parent type map.
395     break;
396   case PdbSymUidKind::FieldListMember:
397     // In this case the parent DeclContext is the one for the class that this
398     // member is inside of.
399     break;
400   default:
401     break;
402   }
403   return &GetTranslationUnitDecl();
404 }
405 
406 bool PdbAstBuilder::CompleteType(clang::QualType qt) {
407   clang::TagDecl *tag = qt->getAsTagDecl();
408   if (!tag)
409     return false;
410 
411   return CompleteTagDecl(*tag);
412 }
413 
414 bool PdbAstBuilder::CompleteTagDecl(clang::TagDecl &tag) {
415   // If this is not in our map, it's an error.
416   auto status_iter = m_decl_to_status.find(&tag);
417   lldbassert(status_iter != m_decl_to_status.end());
418 
419   // If it's already complete, just return.
420   DeclStatus &status = status_iter->second;
421   if (status.resolved)
422     return true;
423 
424   PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym();
425 
426   lldbassert(IsTagRecord(type_id, m_index.tpi()));
427 
428   clang::QualType tag_qt = m_clang.getASTContext()->getTypeDeclType(&tag);
429   ClangASTContext::SetHasExternalStorage(tag_qt.getAsOpaquePtr(), false);
430 
431   TypeIndex tag_ti = type_id.index;
432   CVType cvt = m_index.tpi().getType(tag_ti);
433   if (cvt.kind() == LF_MODIFIER)
434     tag_ti = LookThroughModifierRecord(cvt);
435 
436   PdbTypeSymId best_ti = GetBestPossibleDecl(tag_ti, m_index.tpi());
437   cvt = m_index.tpi().getType(best_ti.index);
438   lldbassert(IsTagRecord(cvt));
439 
440   if (IsForwardRefUdt(cvt)) {
441     // If we can't find a full decl for this forward ref anywhere in the debug
442     // info, then we have no way to complete it.
443     return false;
444   }
445 
446   TypeIndex field_list_ti = GetFieldListIndex(cvt);
447   CVType field_list_cvt = m_index.tpi().getType(field_list_ti);
448   if (field_list_cvt.kind() != LF_FIELDLIST)
449     return false;
450 
451   // Visit all members of this class, then perform any finalization necessary
452   // to complete the class.
453   CompilerType ct = ToCompilerType(tag_qt);
454   UdtRecordCompleter completer(best_ti, ct, tag, *this, m_index.tpi());
455   auto error =
456       llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer);
457   completer.complete();
458 
459   status.resolved = true;
460   if (!error)
461     return true;
462 
463   llvm::consumeError(std::move(error));
464   return false;
465 }
466 
467 clang::QualType PdbAstBuilder::CreateSimpleType(TypeIndex ti) {
468   if (ti == TypeIndex::NullptrT())
469     return GetBasicType(lldb::eBasicTypeNullPtr);
470 
471   if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
472     clang::QualType direct_type = GetOrCreateType(ti.makeDirect());
473     return m_clang.getASTContext()->getPointerType(direct_type);
474   }
475 
476   if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
477     return {};
478 
479   lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind());
480   if (bt == lldb::eBasicTypeInvalid)
481     return {};
482 
483   return GetBasicType(bt);
484 }
485 
486 clang::QualType PdbAstBuilder::CreatePointerType(const PointerRecord &pointer) {
487   clang::QualType pointee_type = GetOrCreateType(pointer.ReferentType);
488 
489   if (pointer.isPointerToMember()) {
490     MemberPointerInfo mpi = pointer.getMemberInfo();
491     clang::QualType class_type = GetOrCreateType(mpi.ContainingType);
492 
493     return m_clang.getASTContext()->getMemberPointerType(
494         pointee_type, class_type.getTypePtr());
495   }
496 
497   clang::QualType pointer_type;
498   if (pointer.getMode() == PointerMode::LValueReference)
499     pointer_type =
500         m_clang.getASTContext()->getLValueReferenceType(pointee_type);
501   else if (pointer.getMode() == PointerMode::RValueReference)
502     pointer_type =
503         m_clang.getASTContext()->getRValueReferenceType(pointee_type);
504   else
505     pointer_type = m_clang.getASTContext()->getPointerType(pointee_type);
506 
507   if ((pointer.getOptions() & PointerOptions::Const) != PointerOptions::None)
508     pointer_type.addConst();
509 
510   if ((pointer.getOptions() & PointerOptions::Volatile) != PointerOptions::None)
511     pointer_type.addVolatile();
512 
513   if ((pointer.getOptions() & PointerOptions::Restrict) != PointerOptions::None)
514     pointer_type.addRestrict();
515 
516   return pointer_type;
517 }
518 
519 clang::QualType
520 PdbAstBuilder::CreateModifierType(const ModifierRecord &modifier) {
521 
522   clang::QualType unmodified_type = GetOrCreateType(modifier.ModifiedType);
523 
524   if ((modifier.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
525     unmodified_type.addConst();
526   if ((modifier.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
527     unmodified_type.addVolatile();
528 
529   return unmodified_type;
530 }
531 
532 clang::QualType PdbAstBuilder::CreateRecordType(PdbTypeSymId id,
533                                                 const TagRecord &record) {
534   clang::DeclContext *decl_context = nullptr;
535   std::string uname;
536   std::tie(decl_context, uname) = CreateDeclInfoForType(record, id.index);
537 
538   clang::TagTypeKind ttk = TranslateUdtKind(record);
539   lldb::AccessType access =
540       (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic;
541 
542   ClangASTMetadata metadata;
543   metadata.SetUserID(toOpaqueUid(id));
544   metadata.SetIsDynamicCXXType(false);
545 
546   CompilerType ct =
547       m_clang.CreateRecordType(decl_context, access, uname.c_str(), ttk,
548                                lldb::eLanguageTypeC_plus_plus, &metadata);
549 
550   lldbassert(ct.IsValid());
551 
552   ClangASTContext::StartTagDeclarationDefinition(ct);
553 
554   // Even if it's possible, don't complete it at this point. Just mark it
555   // forward resolved, and if/when LLDB needs the full definition, it can
556   // ask us.
557   clang::QualType result =
558       clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType());
559 
560   ClangASTContext::SetHasExternalStorage(result.getAsOpaquePtr(), true);
561   return result;
562 }
563 
564 clang::Decl *PdbAstBuilder::TryGetDecl(PdbSymUid uid) const {
565   auto iter = m_uid_to_decl.find(toOpaqueUid(uid));
566   if (iter != m_uid_to_decl.end())
567     return iter->second;
568   return nullptr;
569 }
570 
571 clang::NamespaceDecl *
572 PdbAstBuilder::GetOrCreateNamespaceDecl(llvm::StringRef name,
573                                         clang::DeclContext &context) {
574   return m_clang.GetUniqueNamespaceDeclaration(name.str().c_str(), &context);
575 }
576 
577 clang::BlockDecl *
578 PdbAstBuilder::GetOrCreateBlockDecl(PdbCompilandSymId block_id) {
579   if (clang::Decl *decl = TryGetDecl(block_id))
580     return llvm::dyn_cast<clang::BlockDecl>(decl);
581 
582   clang::DeclContext *scope = GetParentDeclContext(block_id);
583 
584   clang::BlockDecl *block_decl = m_clang.CreateBlockDeclaration(scope);
585   m_uid_to_decl.insert({toOpaqueUid(block_id), block_decl});
586   return block_decl;
587 }
588 
589 clang::VarDecl *
590 PdbAstBuilder::GetOrCreateLocalVariableDecl(PdbCompilandSymId scope_id,
591                                             PdbCompilandSymId var_id) {
592   if (clang::Decl *decl = TryGetDecl(var_id))
593     return llvm::dyn_cast<clang::VarDecl>(decl);
594 
595   clang::DeclContext *scope = GetOrCreateDeclContextForUid(scope_id);
596 
597   CVSymbol var = m_index.ReadSymbolRecord(var_id);
598   VariableInfo var_info = GetVariableNameInfo(var);
599   clang::QualType qt = GetOrCreateType(var_info.type);
600 
601   clang::VarDecl *var_decl =
602       m_clang.CreateVariableDeclaration(scope, var_info.name.str().c_str(), qt);
603 
604   m_uid_to_decl[toOpaqueUid(var_id)] = var_decl;
605   return var_decl;
606 }
607 
608 clang::QualType PdbAstBuilder::GetBasicType(lldb::BasicType type) {
609   CompilerType ct = m_clang.GetBasicType(type);
610   return clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType());
611 }
612 
613 clang::QualType PdbAstBuilder::CreateType(PdbTypeSymId type) {
614   if (type.index.isSimple())
615     return CreateSimpleType(type.index);
616 
617   CVType cvt = m_index.tpi().getType(type.index);
618 
619   if (cvt.kind() == LF_MODIFIER) {
620     ModifierRecord modifier;
621     llvm::cantFail(
622         TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
623     return CreateModifierType(modifier);
624   }
625 
626   if (cvt.kind() == LF_POINTER) {
627     PointerRecord pointer;
628     llvm::cantFail(
629         TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
630     return CreatePointerType(pointer);
631   }
632 
633   if (IsTagRecord(cvt)) {
634     CVTagRecord tag = CVTagRecord::create(cvt);
635     if (tag.kind() == CVTagRecord::Union)
636       return CreateRecordType(type.index, tag.asUnion());
637     if (tag.kind() == CVTagRecord::Enum)
638       return CreateEnumType(type.index, tag.asEnum());
639     return CreateRecordType(type.index, tag.asClass());
640   }
641 
642   if (cvt.kind() == LF_ARRAY) {
643     ArrayRecord ar;
644     llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
645     return CreateArrayType(ar);
646   }
647 
648   if (cvt.kind() == LF_PROCEDURE) {
649     ProcedureRecord pr;
650     llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
651     return CreateProcedureType(pr);
652   }
653 
654   return {};
655 }
656 
657 clang::QualType PdbAstBuilder::GetOrCreateType(PdbTypeSymId type) {
658   lldb::user_id_t uid = toOpaqueUid(type);
659   auto iter = m_uid_to_type.find(uid);
660   if (iter != m_uid_to_type.end())
661     return iter->second;
662 
663   PdbTypeSymId best_type = GetBestPossibleDecl(type, m_index.tpi());
664 
665   clang::QualType qt;
666   if (best_type.index != type.index) {
667     // This is a forward decl.  Call GetOrCreate on the full decl, then map the
668     // forward decl id to the full decl QualType.
669     clang::QualType qt = GetOrCreateType(best_type);
670     m_uid_to_type[toOpaqueUid(type)] = qt;
671     return qt;
672   }
673 
674   // This is either a full decl, or a forward decl with no matching full decl
675   // in the debug info.
676   qt = CreateType(type);
677   m_uid_to_type[toOpaqueUid(type)] = qt;
678   if (IsTagRecord(type, m_index.tpi())) {
679     clang::TagDecl *tag = qt->getAsTagDecl();
680     lldbassert(m_decl_to_status.count(tag) == 0);
681 
682     DeclStatus &status = m_decl_to_status[tag];
683     status.uid = uid;
684     status.resolved = false;
685   }
686   return qt;
687 }
688 
689 clang::FunctionDecl *
690 PdbAstBuilder::GetOrCreateFunctionDecl(PdbCompilandSymId func_id) {
691   if (clang::Decl *decl = TryGetDecl(func_id))
692     return llvm::dyn_cast<clang::FunctionDecl>(decl);
693 
694   clang::DeclContext *parent = GetParentDeclContext(PdbSymUid(func_id));
695 
696   CVSymbol cvs = m_index.ReadSymbolRecord(func_id);
697   ProcSym proc(static_cast<SymbolRecordKind>(cvs.kind()));
698   llvm::cantFail(SymbolDeserializer::deserializeAs<ProcSym>(cvs, proc));
699 
700   PdbTypeSymId type_id(proc.FunctionType);
701   clang::QualType qt = GetOrCreateType(type_id);
702 
703   clang::StorageClass storage = clang::SC_None;
704   if (proc.Kind == SymbolRecordKind::ProcSym)
705     storage = clang::SC_Static;
706 
707   const clang::FunctionProtoType *func_type =
708       llvm::dyn_cast<clang::FunctionProtoType>(qt);
709 
710   CompilerType func_ct = ToCompilerType(qt);
711 
712   clang::FunctionDecl *function_decl = m_clang.CreateFunctionDeclaration(
713       parent, proc.Name.str().c_str(), func_ct, storage, false);
714 
715   lldbassert(m_uid_to_decl.count(toOpaqueUid(func_id)) == 0);
716   m_uid_to_decl[toOpaqueUid(func_id)] = function_decl;
717 
718   CreateFunctionParameters(func_id, *function_decl, func_type->getNumParams());
719 
720   return function_decl;
721 }
722 
723 void PdbAstBuilder::CreateFunctionParameters(PdbCompilandSymId func_id,
724                                              clang::FunctionDecl &function_decl,
725                                              uint32_t param_count) {
726   CompilandIndexItem *cii = m_index.compilands().GetCompiland(func_id.modi);
727   CVSymbolArray scope =
728       cii->m_debug_stream.getSymbolArrayForScope(func_id.offset);
729 
730   auto begin = scope.begin();
731   auto end = scope.end();
732   std::vector<clang::ParmVarDecl *> params;
733   while (begin != end && param_count > 0) {
734     uint32_t record_offset = begin.offset();
735     CVSymbol sym = *begin++;
736 
737     TypeIndex param_type;
738     llvm::StringRef param_name;
739     switch (sym.kind()) {
740     case S_REGREL32: {
741       RegRelativeSym reg(SymbolRecordKind::RegRelativeSym);
742       cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg));
743       param_type = reg.Type;
744       param_name = reg.Name;
745       break;
746     }
747     case S_REGISTER: {
748       RegisterSym reg(SymbolRecordKind::RegisterSym);
749       cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg));
750       param_type = reg.Index;
751       param_name = reg.Name;
752       break;
753     }
754     case S_LOCAL: {
755       LocalSym local(SymbolRecordKind::LocalSym);
756       cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local));
757       if ((local.Flags & LocalSymFlags::IsParameter) == LocalSymFlags::None)
758         continue;
759       param_type = local.Type;
760       param_name = local.Name;
761       break;
762     }
763     case S_BLOCK32:
764       // All parameters should come before the first block.  If that isn't the
765       // case, then perhaps this is bad debug info that doesn't contain
766       // information about all parameters.
767       return;
768     default:
769       continue;
770     }
771 
772     PdbCompilandSymId param_uid(func_id.modi, record_offset);
773     clang::QualType qt = GetOrCreateType(param_type);
774 
775     CompilerType param_type_ct(&m_clang, qt.getAsOpaquePtr());
776     clang::ParmVarDecl *param = m_clang.CreateParameterDeclaration(
777         &function_decl, param_name.str().c_str(), param_type_ct,
778         clang::SC_None);
779     lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0);
780 
781     m_uid_to_decl[toOpaqueUid(param_uid)] = param;
782     params.push_back(param);
783     --param_count;
784   }
785 
786   if (!params.empty())
787     m_clang.SetFunctionParameters(&function_decl, params.data(), params.size());
788 }
789 
790 clang::QualType PdbAstBuilder::CreateEnumType(PdbTypeSymId id,
791                                               const EnumRecord &er) {
792   clang::DeclContext *decl_context = nullptr;
793   std::string uname;
794   std::tie(decl_context, uname) = CreateDeclInfoForType(er, id.index);
795   clang::QualType underlying_type = GetOrCreateType(er.UnderlyingType);
796 
797   Declaration declaration;
798   CompilerType enum_ct = m_clang.CreateEnumerationType(
799       uname.c_str(), decl_context, declaration, ToCompilerType(underlying_type),
800       er.isScoped());
801 
802   ClangASTContext::StartTagDeclarationDefinition(enum_ct);
803   ClangASTContext::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true);
804 
805   return clang::QualType::getFromOpaquePtr(enum_ct.GetOpaqueQualType());
806 }
807 
808 clang::QualType PdbAstBuilder::CreateArrayType(const ArrayRecord &ar) {
809   clang::QualType element_type = GetOrCreateType(ar.ElementType);
810 
811   uint64_t element_count =
812       ar.Size / GetSizeOfType({ar.ElementType}, m_index.tpi());
813 
814   CompilerType array_ct = m_clang.CreateArrayType(ToCompilerType(element_type),
815                                                   element_count, false);
816   return clang::QualType::getFromOpaquePtr(array_ct.GetOpaqueQualType());
817 }
818 
819 clang::QualType
820 PdbAstBuilder::CreateProcedureType(const ProcedureRecord &proc) {
821   TpiStream &stream = m_index.tpi();
822   CVType args_cvt = stream.getType(proc.ArgumentList);
823   ArgListRecord args;
824   llvm::cantFail(
825       TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args));
826 
827   llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices);
828   bool is_variadic = IsCVarArgsFunction(arg_indices);
829   if (is_variadic)
830     arg_indices = arg_indices.drop_back();
831 
832   std::vector<CompilerType> arg_types;
833   arg_types.reserve(arg_indices.size());
834 
835   for (TypeIndex arg_index : arg_indices) {
836     clang::QualType arg_type = GetOrCreateType(arg_index);
837     arg_types.push_back(ToCompilerType(arg_type));
838   }
839 
840   clang::QualType return_type = GetOrCreateType(proc.ReturnType);
841 
842   llvm::Optional<clang::CallingConv> cc =
843       TranslateCallingConvention(proc.CallConv);
844   if (!cc)
845     return {};
846 
847   CompilerType return_ct = ToCompilerType(return_type);
848   CompilerType func_sig_ast_type = m_clang.CreateFunctionType(
849       return_ct, arg_types.data(), arg_types.size(), is_variadic, 0, *cc);
850 
851   return clang::QualType::getFromOpaquePtr(
852       func_sig_ast_type.GetOpaqueQualType());
853 }
854 
855 CompilerDecl PdbAstBuilder::ToCompilerDecl(clang::Decl &decl) {
856   return {&m_clang, &decl};
857 }
858 
859 CompilerType PdbAstBuilder::ToCompilerType(clang::QualType qt) {
860   return {&m_clang, qt.getAsOpaquePtr()};
861 }
862 
863 CompilerDeclContext
864 PdbAstBuilder::ToCompilerDeclContext(clang::DeclContext &context) {
865   return {&m_clang, &context};
866 }
867 
868 void PdbAstBuilder::Dump(Stream &stream) { m_clang.Dump(stream); }
869