xref: /llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp (revision 5f5cdf40382f06a8c417c42ec591f97aa76eeb67)
1 //===-- TypeSystemClang.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "TypeSystemClang.h"
10 
11 #include "clang/AST/DeclBase.h"
12 #include "clang/AST/ExprCXX.h"
13 #include "llvm/Support/Casting.h"
14 #include "llvm/Support/FormatAdapters.h"
15 #include "llvm/Support/FormatVariadic.h"
16 
17 #include <mutex>
18 #include <memory>
19 #include <string>
20 #include <vector>
21 
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/ASTImporter.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/CXXInheritance.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/Mangle.h"
29 #include "clang/AST/RecordLayout.h"
30 #include "clang/AST/Type.h"
31 #include "clang/AST/VTableBuilder.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/Diagnostic.h"
34 #include "clang/Basic/FileManager.h"
35 #include "clang/Basic/FileSystemOptions.h"
36 #include "clang/Basic/LangStandard.h"
37 #include "clang/Basic/SourceManager.h"
38 #include "clang/Basic/TargetInfo.h"
39 #include "clang/Basic/TargetOptions.h"
40 #include "clang/Frontend/FrontendOptions.h"
41 #include "clang/Lex/HeaderSearch.h"
42 #include "clang/Lex/HeaderSearchOptions.h"
43 #include "clang/Lex/ModuleMap.h"
44 #include "clang/Sema/Sema.h"
45 
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/Threading.h"
48 
49 #include "Plugins/ExpressionParser/Clang/ClangASTImporter.h"
50 #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
51 #include "Plugins/ExpressionParser/Clang/ClangExternalASTSourceCallbacks.h"
52 #include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h"
53 #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
54 #include "Plugins/ExpressionParser/Clang/ClangUserExpression.h"
55 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
56 #include "Plugins/ExpressionParser/Clang/ClangUtilityFunction.h"
57 #include "lldb/Core/Debugger.h"
58 #include "lldb/Core/DumpDataExtractor.h"
59 #include "lldb/Core/Module.h"
60 #include "lldb/Core/PluginManager.h"
61 #include "lldb/Core/UniqueCStringMap.h"
62 #include "lldb/Host/StreamFile.h"
63 #include "lldb/Symbol/ObjectFile.h"
64 #include "lldb/Symbol/SymbolFile.h"
65 #include "lldb/Target/ExecutionContext.h"
66 #include "lldb/Target/Language.h"
67 #include "lldb/Target/Process.h"
68 #include "lldb/Target/Target.h"
69 #include "lldb/Utility/ArchSpec.h"
70 #include "lldb/Utility/DataExtractor.h"
71 #include "lldb/Utility/Flags.h"
72 #include "lldb/Utility/LLDBAssert.h"
73 #include "lldb/Utility/LLDBLog.h"
74 #include "lldb/Utility/RegularExpression.h"
75 #include "lldb/Utility/Scalar.h"
76 #include "lldb/Utility/ThreadSafeDenseMap.h"
77 
78 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
79 #include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h"
80 #include "Plugins/SymbolFile/PDB/PDBASTParser.h"
81 #include "Plugins/SymbolFile/NativePDB/PdbAstBuilder.h"
82 
83 #include <cstdio>
84 
85 #include <mutex>
86 #include <optional>
87 
88 using namespace lldb;
89 using namespace lldb_private;
90 using namespace lldb_private::dwarf;
91 using namespace lldb_private::plugin::dwarf;
92 using namespace clang;
93 using llvm::StringSwitch;
94 
95 LLDB_PLUGIN_DEFINE(TypeSystemClang)
96 
97 namespace {
98 static void VerifyDecl(clang::Decl *decl) {
99   assert(decl && "VerifyDecl called with nullptr?");
100 #ifndef NDEBUG
101   // We don't care about the actual access value here but only want to trigger
102   // that Clang calls its internal Decl::AccessDeclContextCheck validation.
103   decl->getAccess();
104 #endif
105 }
106 
107 static inline bool
108 TypeSystemClangSupportsLanguage(lldb::LanguageType language) {
109   return language == eLanguageTypeUnknown || // Clang is the default type system
110          lldb_private::Language::LanguageIsC(language) ||
111          lldb_private::Language::LanguageIsCPlusPlus(language) ||
112          lldb_private::Language::LanguageIsObjC(language) ||
113          lldb_private::Language::LanguageIsPascal(language) ||
114          // Use Clang for Rust until there is a proper language plugin for it
115          language == eLanguageTypeRust ||
116          // Use Clang for D until there is a proper language plugin for it
117          language == eLanguageTypeD ||
118          // Open Dylan compiler debug info is designed to be Clang-compatible
119          language == eLanguageTypeDylan;
120 }
121 
122 // Checks whether m1 is an overload of m2 (as opposed to an override). This is
123 // called by addOverridesForMethod to distinguish overrides (which share a
124 // vtable entry) from overloads (which require distinct entries).
125 bool isOverload(clang::CXXMethodDecl *m1, clang::CXXMethodDecl *m2) {
126   // FIXME: This should detect covariant return types, but currently doesn't.
127   lldbassert(&m1->getASTContext() == &m2->getASTContext() &&
128              "Methods should have the same AST context");
129   clang::ASTContext &context = m1->getASTContext();
130 
131   const auto *m1Type = llvm::cast<clang::FunctionProtoType>(
132       context.getCanonicalType(m1->getType()));
133 
134   const auto *m2Type = llvm::cast<clang::FunctionProtoType>(
135       context.getCanonicalType(m2->getType()));
136 
137   auto compareArgTypes = [&context](const clang::QualType &m1p,
138                                     const clang::QualType &m2p) {
139     return context.hasSameType(m1p.getUnqualifiedType(),
140                                m2p.getUnqualifiedType());
141   };
142 
143   // FIXME: In C++14 and later, we can just pass m2Type->param_type_end()
144   //        as a fourth parameter to std::equal().
145   return (m1->getNumParams() != m2->getNumParams()) ||
146          !std::equal(m1Type->param_type_begin(), m1Type->param_type_end(),
147                      m2Type->param_type_begin(), compareArgTypes);
148 }
149 
150 // If decl is a virtual method, walk the base classes looking for methods that
151 // decl overrides. This table of overridden methods is used by IRGen to
152 // determine the vtable layout for decl's parent class.
153 void addOverridesForMethod(clang::CXXMethodDecl *decl) {
154   if (!decl->isVirtual())
155     return;
156 
157   clang::CXXBasePaths paths;
158   llvm::SmallVector<clang::NamedDecl *, 4> decls;
159 
160   auto find_overridden_methods =
161       [&decls, decl](const clang::CXXBaseSpecifier *specifier,
162                      clang::CXXBasePath &path) {
163         if (auto *base_record = llvm::dyn_cast<clang::CXXRecordDecl>(
164                 specifier->getType()->castAs<clang::RecordType>()->getDecl())) {
165 
166           clang::DeclarationName name = decl->getDeclName();
167 
168           // If this is a destructor, check whether the base class destructor is
169           // virtual.
170           if (name.getNameKind() == clang::DeclarationName::CXXDestructorName)
171             if (auto *baseDtorDecl = base_record->getDestructor()) {
172               if (baseDtorDecl->isVirtual()) {
173                 decls.push_back(baseDtorDecl);
174                 return true;
175               } else
176                 return false;
177             }
178 
179           // Otherwise, search for name in the base class.
180           for (path.Decls = base_record->lookup(name).begin();
181                path.Decls != path.Decls.end(); ++path.Decls) {
182             if (auto *method_decl =
183                     llvm::dyn_cast<clang::CXXMethodDecl>(*path.Decls))
184               if (method_decl->isVirtual() && !isOverload(decl, method_decl)) {
185                 decls.push_back(method_decl);
186                 return true;
187               }
188           }
189         }
190 
191         return false;
192       };
193 
194   if (decl->getParent()->lookupInBases(find_overridden_methods, paths)) {
195     for (auto *overridden_decl : decls)
196       decl->addOverriddenMethod(
197           llvm::cast<clang::CXXMethodDecl>(overridden_decl));
198   }
199 }
200 }
201 
202 static lldb::addr_t GetVTableAddress(Process &process,
203                                      VTableContextBase &vtable_ctx,
204                                      ValueObject &valobj,
205                                      const ASTRecordLayout &record_layout) {
206   // Retrieve type info
207   CompilerType pointee_type;
208   CompilerType this_type(valobj.GetCompilerType());
209   uint32_t type_info = this_type.GetTypeInfo(&pointee_type);
210   if (!type_info)
211     return LLDB_INVALID_ADDRESS;
212 
213   // Check if it's a pointer or reference
214   bool ptr_or_ref = false;
215   if (type_info & (eTypeIsPointer | eTypeIsReference)) {
216     ptr_or_ref = true;
217     type_info = pointee_type.GetTypeInfo();
218   }
219 
220   // We process only C++ classes
221   const uint32_t cpp_class = eTypeIsClass | eTypeIsCPlusPlus;
222   if ((type_info & cpp_class) != cpp_class)
223     return LLDB_INVALID_ADDRESS;
224 
225   // Calculate offset to VTable pointer
226   lldb::offset_t vbtable_ptr_offset =
227       vtable_ctx.isMicrosoft() ? record_layout.getVBPtrOffset().getQuantity()
228                                : 0;
229 
230   if (ptr_or_ref) {
231     // We have a pointer / ref to object, so read
232     // VTable pointer from process memory
233 
234     if (valobj.GetAddressTypeOfChildren() != eAddressTypeLoad)
235       return LLDB_INVALID_ADDRESS;
236 
237     auto vbtable_ptr_addr = valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
238     if (vbtable_ptr_addr == LLDB_INVALID_ADDRESS)
239       return LLDB_INVALID_ADDRESS;
240 
241     vbtable_ptr_addr += vbtable_ptr_offset;
242 
243     Status err;
244     return process.ReadPointerFromMemory(vbtable_ptr_addr, err);
245   }
246 
247   // We have an object already read from process memory,
248   // so just extract VTable pointer from it
249 
250   DataExtractor data;
251   Status err;
252   auto size = valobj.GetData(data, err);
253   if (err.Fail() || vbtable_ptr_offset + data.GetAddressByteSize() > size)
254     return LLDB_INVALID_ADDRESS;
255 
256   return data.GetAddress(&vbtable_ptr_offset);
257 }
258 
259 static int64_t ReadVBaseOffsetFromVTable(Process &process,
260                                          VTableContextBase &vtable_ctx,
261                                          lldb::addr_t vtable_ptr,
262                                          const CXXRecordDecl *cxx_record_decl,
263                                          const CXXRecordDecl *base_class_decl) {
264   if (vtable_ctx.isMicrosoft()) {
265     clang::MicrosoftVTableContext &msoft_vtable_ctx =
266         static_cast<clang::MicrosoftVTableContext &>(vtable_ctx);
267 
268     // Get the index into the virtual base table. The
269     // index is the index in uint32_t from vbtable_ptr
270     const unsigned vbtable_index =
271         msoft_vtable_ctx.getVBTableIndex(cxx_record_decl, base_class_decl);
272     const lldb::addr_t base_offset_addr = vtable_ptr + vbtable_index * 4;
273     Status err;
274     return process.ReadSignedIntegerFromMemory(base_offset_addr, 4, INT64_MAX,
275                                                err);
276   }
277 
278   clang::ItaniumVTableContext &itanium_vtable_ctx =
279       static_cast<clang::ItaniumVTableContext &>(vtable_ctx);
280 
281   clang::CharUnits base_offset_offset =
282       itanium_vtable_ctx.getVirtualBaseOffsetOffset(cxx_record_decl,
283                                                     base_class_decl);
284   const lldb::addr_t base_offset_addr =
285       vtable_ptr + base_offset_offset.getQuantity();
286   const uint32_t base_offset_size = process.GetAddressByteSize();
287   Status err;
288   return process.ReadSignedIntegerFromMemory(base_offset_addr, base_offset_size,
289                                              INT64_MAX, err);
290 }
291 
292 static bool GetVBaseBitOffset(VTableContextBase &vtable_ctx,
293                               ValueObject &valobj,
294                               const ASTRecordLayout &record_layout,
295                               const CXXRecordDecl *cxx_record_decl,
296                               const CXXRecordDecl *base_class_decl,
297                               int32_t &bit_offset) {
298   ExecutionContext exe_ctx(valobj.GetExecutionContextRef());
299   Process *process = exe_ctx.GetProcessPtr();
300   if (!process)
301     return false;
302 
303   lldb::addr_t vtable_ptr =
304       GetVTableAddress(*process, vtable_ctx, valobj, record_layout);
305   if (vtable_ptr == LLDB_INVALID_ADDRESS)
306     return false;
307 
308   auto base_offset = ReadVBaseOffsetFromVTable(
309       *process, vtable_ctx, vtable_ptr, cxx_record_decl, base_class_decl);
310   if (base_offset == INT64_MAX)
311     return false;
312 
313   bit_offset = base_offset * 8;
314 
315   return true;
316 }
317 
318 typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, TypeSystemClang *>
319     ClangASTMap;
320 
321 static ClangASTMap &GetASTMap() {
322   static ClangASTMap *g_map_ptr = nullptr;
323   static llvm::once_flag g_once_flag;
324   llvm::call_once(g_once_flag, []() {
325     g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins
326   });
327   return *g_map_ptr;
328 }
329 
330 TypePayloadClang::TypePayloadClang(OptionalClangModuleID owning_module,
331                                    bool is_complete_objc_class)
332     : m_payload(owning_module.GetValue()) {
333   SetIsCompleteObjCClass(is_complete_objc_class);
334 }
335 
336 void TypePayloadClang::SetOwningModule(OptionalClangModuleID id) {
337   assert(id.GetValue() < ObjCClassBit);
338   bool is_complete = IsCompleteObjCClass();
339   m_payload = id.GetValue();
340   SetIsCompleteObjCClass(is_complete);
341 }
342 
343 static void SetMemberOwningModule(clang::Decl *member,
344                                   const clang::Decl *parent) {
345   if (!member || !parent)
346     return;
347 
348   OptionalClangModuleID id(parent->getOwningModuleID());
349   if (!id.HasValue())
350     return;
351 
352   member->setFromASTFile();
353   member->setOwningModuleID(id.GetValue());
354   member->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible);
355   if (llvm::isa<clang::NamedDecl>(member))
356     if (auto *dc = llvm::dyn_cast<clang::DeclContext>(parent)) {
357       dc->setHasExternalVisibleStorage(true);
358       // This triggers ExternalASTSource::FindExternalVisibleDeclsByName() to be
359       // called when searching for members.
360       dc->setHasExternalLexicalStorage(true);
361     }
362 }
363 
364 char TypeSystemClang::ID;
365 
366 bool TypeSystemClang::IsOperator(llvm::StringRef name,
367                                  clang::OverloadedOperatorKind &op_kind) {
368   // All operators have to start with "operator".
369   if (!name.consume_front("operator"))
370     return false;
371 
372   // Remember if there was a space after "operator". This is necessary to
373   // check for collisions with strangely named functions like "operatorint()".
374   bool space_after_operator = name.consume_front(" ");
375 
376   op_kind = StringSwitch<clang::OverloadedOperatorKind>(name)
377                 .Case("+", clang::OO_Plus)
378                 .Case("+=", clang::OO_PlusEqual)
379                 .Case("++", clang::OO_PlusPlus)
380                 .Case("-", clang::OO_Minus)
381                 .Case("-=", clang::OO_MinusEqual)
382                 .Case("--", clang::OO_MinusMinus)
383                 .Case("->", clang::OO_Arrow)
384                 .Case("->*", clang::OO_ArrowStar)
385                 .Case("*", clang::OO_Star)
386                 .Case("*=", clang::OO_StarEqual)
387                 .Case("/", clang::OO_Slash)
388                 .Case("/=", clang::OO_SlashEqual)
389                 .Case("%", clang::OO_Percent)
390                 .Case("%=", clang::OO_PercentEqual)
391                 .Case("^", clang::OO_Caret)
392                 .Case("^=", clang::OO_CaretEqual)
393                 .Case("&", clang::OO_Amp)
394                 .Case("&=", clang::OO_AmpEqual)
395                 .Case("&&", clang::OO_AmpAmp)
396                 .Case("|", clang::OO_Pipe)
397                 .Case("|=", clang::OO_PipeEqual)
398                 .Case("||", clang::OO_PipePipe)
399                 .Case("~", clang::OO_Tilde)
400                 .Case("!", clang::OO_Exclaim)
401                 .Case("!=", clang::OO_ExclaimEqual)
402                 .Case("=", clang::OO_Equal)
403                 .Case("==", clang::OO_EqualEqual)
404                 .Case("<", clang::OO_Less)
405                 .Case("<=>", clang::OO_Spaceship)
406                 .Case("<<", clang::OO_LessLess)
407                 .Case("<<=", clang::OO_LessLessEqual)
408                 .Case("<=", clang::OO_LessEqual)
409                 .Case(">", clang::OO_Greater)
410                 .Case(">>", clang::OO_GreaterGreater)
411                 .Case(">>=", clang::OO_GreaterGreaterEqual)
412                 .Case(">=", clang::OO_GreaterEqual)
413                 .Case("()", clang::OO_Call)
414                 .Case("[]", clang::OO_Subscript)
415                 .Case(",", clang::OO_Comma)
416                 .Default(clang::NUM_OVERLOADED_OPERATORS);
417 
418   // We found a fitting operator, so we can exit now.
419   if (op_kind != clang::NUM_OVERLOADED_OPERATORS)
420     return true;
421 
422   // After the "operator " or "operator" part is something unknown. This means
423   // it's either one of the named operators (new/delete), a conversion operator
424   // (e.g. operator bool) or a function which name starts with "operator"
425   // (e.g. void operatorbool).
426 
427   // If it's a function that starts with operator it can't have a space after
428   // "operator" because identifiers can't contain spaces.
429   // E.g. "operator int" (conversion operator)
430   //  vs. "operatorint" (function with colliding name).
431   if (!space_after_operator)
432     return false; // not an operator.
433 
434   // Now the operator is either one of the named operators or a conversion
435   // operator.
436   op_kind = StringSwitch<clang::OverloadedOperatorKind>(name)
437                 .Case("new", clang::OO_New)
438                 .Case("new[]", clang::OO_Array_New)
439                 .Case("delete", clang::OO_Delete)
440                 .Case("delete[]", clang::OO_Array_Delete)
441                 // conversion operators hit this case.
442                 .Default(clang::NUM_OVERLOADED_OPERATORS);
443 
444   return true;
445 }
446 
447 clang::AccessSpecifier
448 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(AccessType access) {
449   switch (access) {
450   default:
451     break;
452   case eAccessNone:
453     return AS_none;
454   case eAccessPublic:
455     return AS_public;
456   case eAccessPrivate:
457     return AS_private;
458   case eAccessProtected:
459     return AS_protected;
460   }
461   return AS_none;
462 }
463 
464 static void ParseLangArgs(LangOptions &Opts, ArchSpec arch) {
465   // FIXME: Cleanup per-file based stuff.
466 
467   std::vector<std::string> Includes;
468   LangOptions::setLangDefaults(Opts, clang::Language::ObjCXX, arch.GetTriple(),
469                                Includes, clang::LangStandard::lang_gnucxx98);
470 
471   Opts.setValueVisibilityMode(DefaultVisibility);
472 
473   // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs is
474   // specified, or -std is set to a conforming mode.
475   Opts.Trigraphs = !Opts.GNUMode;
476   Opts.CharIsSigned = arch.CharIsSignedByDefault();
477   Opts.OptimizeSize = 0;
478 
479   // FIXME: Eliminate this dependency.
480   //    unsigned Opt =
481   //    Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
482   //    Opts.Optimize = Opt != 0;
483   unsigned Opt = 0;
484 
485   // This is the __NO_INLINE__ define, which just depends on things like the
486   // optimization level and -fno-inline, not actually whether the backend has
487   // inlining enabled.
488   //
489   // FIXME: This is affected by other options (-fno-inline).
490   Opts.NoInlineDefine = !Opt;
491 
492   // This is needed to allocate the extra space for the owning module
493   // on each decl.
494   Opts.ModulesLocalVisibility = 1;
495 }
496 
497 TypeSystemClang::TypeSystemClang(llvm::StringRef name,
498                                  llvm::Triple target_triple) {
499   m_display_name = name.str();
500   if (!target_triple.str().empty())
501     SetTargetTriple(target_triple.str());
502   // The caller didn't pass an ASTContext so create a new one for this
503   // TypeSystemClang.
504   CreateASTContext();
505 
506   LogCreation();
507 }
508 
509 TypeSystemClang::TypeSystemClang(llvm::StringRef name,
510                                  ASTContext &existing_ctxt) {
511   m_display_name = name.str();
512   SetTargetTriple(existing_ctxt.getTargetInfo().getTriple().str());
513 
514   m_ast_up.reset(&existing_ctxt);
515   GetASTMap().Insert(&existing_ctxt, this);
516 
517   LogCreation();
518 }
519 
520 // Destructor
521 TypeSystemClang::~TypeSystemClang() { Finalize(); }
522 
523 lldb::TypeSystemSP TypeSystemClang::CreateInstance(lldb::LanguageType language,
524                                                    lldb_private::Module *module,
525                                                    Target *target) {
526   if (!TypeSystemClangSupportsLanguage(language))
527     return lldb::TypeSystemSP();
528   ArchSpec arch;
529   if (module)
530     arch = module->GetArchitecture();
531   else if (target)
532     arch = target->GetArchitecture();
533 
534   if (!arch.IsValid())
535     return lldb::TypeSystemSP();
536 
537   llvm::Triple triple = arch.GetTriple();
538   // LLVM wants this to be set to iOS or MacOSX; if we're working on
539   // a bare-boards type image, change the triple for llvm's benefit.
540   if (triple.getVendor() == llvm::Triple::Apple &&
541       triple.getOS() == llvm::Triple::UnknownOS) {
542     if (triple.getArch() == llvm::Triple::arm ||
543         triple.getArch() == llvm::Triple::aarch64 ||
544         triple.getArch() == llvm::Triple::aarch64_32 ||
545         triple.getArch() == llvm::Triple::thumb) {
546       triple.setOS(llvm::Triple::IOS);
547     } else {
548       triple.setOS(llvm::Triple::MacOSX);
549     }
550   }
551 
552   if (module) {
553     std::string ast_name =
554         "ASTContext for '" + module->GetFileSpec().GetPath() + "'";
555     return std::make_shared<TypeSystemClang>(ast_name, triple);
556   } else if (target && target->IsValid())
557     return std::make_shared<ScratchTypeSystemClang>(*target, triple);
558   return lldb::TypeSystemSP();
559 }
560 
561 LanguageSet TypeSystemClang::GetSupportedLanguagesForTypes() {
562   LanguageSet languages;
563   languages.Insert(lldb::eLanguageTypeC89);
564   languages.Insert(lldb::eLanguageTypeC);
565   languages.Insert(lldb::eLanguageTypeC11);
566   languages.Insert(lldb::eLanguageTypeC_plus_plus);
567   languages.Insert(lldb::eLanguageTypeC99);
568   languages.Insert(lldb::eLanguageTypeObjC);
569   languages.Insert(lldb::eLanguageTypeObjC_plus_plus);
570   languages.Insert(lldb::eLanguageTypeC_plus_plus_03);
571   languages.Insert(lldb::eLanguageTypeC_plus_plus_11);
572   languages.Insert(lldb::eLanguageTypeC11);
573   languages.Insert(lldb::eLanguageTypeC_plus_plus_14);
574   languages.Insert(lldb::eLanguageTypeC_plus_plus_17);
575   languages.Insert(lldb::eLanguageTypeC_plus_plus_20);
576   return languages;
577 }
578 
579 LanguageSet TypeSystemClang::GetSupportedLanguagesForExpressions() {
580   LanguageSet languages;
581   languages.Insert(lldb::eLanguageTypeC_plus_plus);
582   languages.Insert(lldb::eLanguageTypeObjC_plus_plus);
583   languages.Insert(lldb::eLanguageTypeC_plus_plus_03);
584   languages.Insert(lldb::eLanguageTypeC_plus_plus_11);
585   languages.Insert(lldb::eLanguageTypeC_plus_plus_14);
586   languages.Insert(lldb::eLanguageTypeC_plus_plus_17);
587   languages.Insert(lldb::eLanguageTypeC_plus_plus_20);
588   return languages;
589 }
590 
591 void TypeSystemClang::Initialize() {
592   PluginManager::RegisterPlugin(
593       GetPluginNameStatic(), "clang base AST context plug-in", CreateInstance,
594       GetSupportedLanguagesForTypes(), GetSupportedLanguagesForExpressions());
595 }
596 
597 void TypeSystemClang::Terminate() {
598   PluginManager::UnregisterPlugin(CreateInstance);
599 }
600 
601 void TypeSystemClang::Finalize() {
602   assert(m_ast_up);
603   GetASTMap().Erase(m_ast_up.get());
604   if (!m_ast_owned)
605     m_ast_up.release();
606 
607   m_builtins_up.reset();
608   m_selector_table_up.reset();
609   m_identifier_table_up.reset();
610   m_target_info_up.reset();
611   m_target_options_rp.reset();
612   m_diagnostics_engine_up.reset();
613   m_source_manager_up.reset();
614   m_language_options_up.reset();
615 }
616 
617 void TypeSystemClang::setSema(Sema *s) {
618   // Ensure that the new sema actually belongs to our ASTContext.
619   assert(s == nullptr || &s->getASTContext() == m_ast_up.get());
620   m_sema = s;
621 }
622 
623 const char *TypeSystemClang::GetTargetTriple() {
624   return m_target_triple.c_str();
625 }
626 
627 void TypeSystemClang::SetTargetTriple(llvm::StringRef target_triple) {
628   m_target_triple = target_triple.str();
629 }
630 
631 void TypeSystemClang::SetExternalSource(
632     llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) {
633   ASTContext &ast = getASTContext();
634   ast.getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
635   ast.setExternalSource(ast_source_up);
636 }
637 
638 ASTContext &TypeSystemClang::getASTContext() const {
639   assert(m_ast_up);
640   return *m_ast_up;
641 }
642 
643 class NullDiagnosticConsumer : public DiagnosticConsumer {
644 public:
645   NullDiagnosticConsumer() { m_log = GetLog(LLDBLog::Expressions); }
646 
647   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
648                         const clang::Diagnostic &info) override {
649     if (m_log) {
650       llvm::SmallVector<char, 32> diag_str(10);
651       info.FormatDiagnostic(diag_str);
652       diag_str.push_back('\0');
653       LLDB_LOGF(m_log, "Compiler diagnostic: %s\n", diag_str.data());
654     }
655   }
656 
657   DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
658     return new NullDiagnosticConsumer();
659   }
660 
661 private:
662   Log *m_log;
663 };
664 
665 void TypeSystemClang::CreateASTContext() {
666   assert(!m_ast_up);
667   m_ast_owned = true;
668 
669   m_language_options_up = std::make_unique<LangOptions>();
670   ParseLangArgs(*m_language_options_up, ArchSpec(GetTargetTriple()));
671 
672   m_identifier_table_up =
673       std::make_unique<IdentifierTable>(*m_language_options_up, nullptr);
674   m_builtins_up = std::make_unique<Builtin::Context>();
675 
676   m_selector_table_up = std::make_unique<SelectorTable>();
677 
678   clang::FileSystemOptions file_system_options;
679   m_file_manager_up = std::make_unique<clang::FileManager>(
680       file_system_options, FileSystem::Instance().GetVirtualFileSystem());
681 
682   llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
683   m_diagnostics_engine_up =
684       std::make_unique<DiagnosticsEngine>(diag_id_sp, new DiagnosticOptions());
685 
686   m_source_manager_up = std::make_unique<clang::SourceManager>(
687       *m_diagnostics_engine_up, *m_file_manager_up);
688   m_ast_up = std::make_unique<ASTContext>(
689       *m_language_options_up, *m_source_manager_up, *m_identifier_table_up,
690       *m_selector_table_up, *m_builtins_up, TU_Complete);
691 
692   m_diagnostic_consumer_up = std::make_unique<NullDiagnosticConsumer>();
693   m_ast_up->getDiagnostics().setClient(m_diagnostic_consumer_up.get(), false);
694 
695   // This can be NULL if we don't know anything about the architecture or if
696   // the target for an architecture isn't enabled in the llvm/clang that we
697   // built
698   TargetInfo *target_info = getTargetInfo();
699   if (target_info)
700     m_ast_up->InitBuiltinTypes(*target_info);
701   else {
702     std::string err =
703         llvm::formatv(
704             "Failed to initialize builtin ASTContext types for target '{0}'. "
705             "Printing variables may behave unexpectedly.",
706             m_target_triple)
707             .str();
708 
709     LLDB_LOG(GetLog(LLDBLog::Expressions), err.c_str());
710 
711     static std::once_flag s_uninitialized_target_warning;
712     Debugger::ReportWarning(std::move(err), /*debugger_id=*/std::nullopt,
713                             &s_uninitialized_target_warning);
714   }
715 
716   GetASTMap().Insert(m_ast_up.get(), this);
717 
718   llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_up(
719       new ClangExternalASTSourceCallbacks(*this));
720   SetExternalSource(ast_source_up);
721 }
722 
723 TypeSystemClang *TypeSystemClang::GetASTContext(clang::ASTContext *ast) {
724   TypeSystemClang *clang_ast = GetASTMap().Lookup(ast);
725   return clang_ast;
726 }
727 
728 clang::MangleContext *TypeSystemClang::getMangleContext() {
729   if (m_mangle_ctx_up == nullptr)
730     m_mangle_ctx_up.reset(getASTContext().createMangleContext());
731   return m_mangle_ctx_up.get();
732 }
733 
734 std::shared_ptr<clang::TargetOptions> &TypeSystemClang::getTargetOptions() {
735   if (m_target_options_rp == nullptr && !m_target_triple.empty()) {
736     m_target_options_rp = std::make_shared<clang::TargetOptions>();
737     if (m_target_options_rp != nullptr)
738       m_target_options_rp->Triple = m_target_triple;
739   }
740   return m_target_options_rp;
741 }
742 
743 TargetInfo *TypeSystemClang::getTargetInfo() {
744   // target_triple should be something like "x86_64-apple-macosx"
745   if (m_target_info_up == nullptr && !m_target_triple.empty())
746     m_target_info_up.reset(TargetInfo::CreateTargetInfo(
747         getASTContext().getDiagnostics(), getTargetOptions()));
748   return m_target_info_up.get();
749 }
750 
751 #pragma mark Basic Types
752 
753 static inline bool QualTypeMatchesBitSize(const uint64_t bit_size,
754                                           ASTContext &ast, QualType qual_type) {
755   uint64_t qual_type_bit_size = ast.getTypeSize(qual_type);
756   return qual_type_bit_size == bit_size;
757 }
758 
759 CompilerType
760 TypeSystemClang::GetBuiltinTypeForEncodingAndBitSize(Encoding encoding,
761                                                      size_t bit_size) {
762   ASTContext &ast = getASTContext();
763 
764   if (!ast.VoidPtrTy)
765     return {};
766 
767   switch (encoding) {
768   case eEncodingInvalid:
769     if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy))
770       return GetType(ast.VoidPtrTy);
771     break;
772 
773   case eEncodingUint:
774     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
775       return GetType(ast.UnsignedCharTy);
776     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
777       return GetType(ast.UnsignedShortTy);
778     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
779       return GetType(ast.UnsignedIntTy);
780     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
781       return GetType(ast.UnsignedLongTy);
782     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
783       return GetType(ast.UnsignedLongLongTy);
784     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
785       return GetType(ast.UnsignedInt128Ty);
786     break;
787 
788   case eEncodingSint:
789     if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
790       return GetType(ast.SignedCharTy);
791     if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
792       return GetType(ast.ShortTy);
793     if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
794       return GetType(ast.IntTy);
795     if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
796       return GetType(ast.LongTy);
797     if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
798       return GetType(ast.LongLongTy);
799     if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
800       return GetType(ast.Int128Ty);
801     break;
802 
803   case eEncodingIEEE754:
804     if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
805       return GetType(ast.FloatTy);
806     if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
807       return GetType(ast.DoubleTy);
808     if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
809       return GetType(ast.LongDoubleTy);
810     if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy))
811       return GetType(ast.HalfTy);
812     break;
813 
814   case eEncodingVector:
815     // Sanity check that bit_size is a multiple of 8's.
816     if (bit_size && !(bit_size & 0x7u))
817       return GetType(ast.getExtVectorType(ast.UnsignedCharTy, bit_size / 8));
818     break;
819   }
820 
821   return CompilerType();
822 }
823 
824 lldb::BasicType TypeSystemClang::GetBasicTypeEnumeration(llvm::StringRef name) {
825   static const llvm::StringMap<lldb::BasicType> g_type_map = {
826       // "void"
827       {"void", eBasicTypeVoid},
828 
829       // "char"
830       {"char", eBasicTypeChar},
831       {"signed char", eBasicTypeSignedChar},
832       {"unsigned char", eBasicTypeUnsignedChar},
833       {"wchar_t", eBasicTypeWChar},
834       {"signed wchar_t", eBasicTypeSignedWChar},
835       {"unsigned wchar_t", eBasicTypeUnsignedWChar},
836 
837       // "short"
838       {"short", eBasicTypeShort},
839       {"short int", eBasicTypeShort},
840       {"unsigned short", eBasicTypeUnsignedShort},
841       {"unsigned short int", eBasicTypeUnsignedShort},
842 
843       // "int"
844       {"int", eBasicTypeInt},
845       {"signed int", eBasicTypeInt},
846       {"unsigned int", eBasicTypeUnsignedInt},
847       {"unsigned", eBasicTypeUnsignedInt},
848 
849       // "long"
850       {"long", eBasicTypeLong},
851       {"long int", eBasicTypeLong},
852       {"unsigned long", eBasicTypeUnsignedLong},
853       {"unsigned long int", eBasicTypeUnsignedLong},
854 
855       // "long long"
856       {"long long", eBasicTypeLongLong},
857       {"long long int", eBasicTypeLongLong},
858       {"unsigned long long", eBasicTypeUnsignedLongLong},
859       {"unsigned long long int", eBasicTypeUnsignedLongLong},
860 
861       // "int128"
862       {"__int128_t", eBasicTypeInt128},
863       {"__uint128_t", eBasicTypeUnsignedInt128},
864 
865       // "bool"
866       {"bool", eBasicTypeBool},
867       {"_Bool", eBasicTypeBool},
868 
869       // Miscellaneous
870       {"float", eBasicTypeFloat},
871       {"double", eBasicTypeDouble},
872       {"long double", eBasicTypeLongDouble},
873       {"id", eBasicTypeObjCID},
874       {"SEL", eBasicTypeObjCSel},
875       {"nullptr", eBasicTypeNullPtr},
876   };
877 
878   auto iter = g_type_map.find(name);
879   if (iter == g_type_map.end())
880     return eBasicTypeInvalid;
881 
882   return iter->second;
883 }
884 
885 uint32_t TypeSystemClang::GetPointerByteSize() {
886   if (m_pointer_byte_size == 0)
887     if (auto size = GetBasicType(lldb::eBasicTypeVoid)
888                         .GetPointerType()
889                         .GetByteSize(nullptr))
890       m_pointer_byte_size = *size;
891   return m_pointer_byte_size;
892 }
893 
894 CompilerType TypeSystemClang::GetBasicType(lldb::BasicType basic_type) {
895   clang::ASTContext &ast = getASTContext();
896 
897   lldb::opaque_compiler_type_t clang_type =
898       GetOpaqueCompilerType(&ast, basic_type);
899 
900   if (clang_type)
901     return CompilerType(weak_from_this(), clang_type);
902   return CompilerType();
903 }
904 
905 CompilerType TypeSystemClang::GetBuiltinTypeForDWARFEncodingAndBitSize(
906     llvm::StringRef type_name, uint32_t dw_ate, uint32_t bit_size) {
907   ASTContext &ast = getASTContext();
908 
909   if (!ast.VoidPtrTy)
910     return {};
911 
912   switch (dw_ate) {
913   default:
914     break;
915 
916   case DW_ATE_address:
917     if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy))
918       return GetType(ast.VoidPtrTy);
919     break;
920 
921   case DW_ATE_boolean:
922     if (QualTypeMatchesBitSize(bit_size, ast, ast.BoolTy))
923       return GetType(ast.BoolTy);
924     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
925       return GetType(ast.UnsignedCharTy);
926     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
927       return GetType(ast.UnsignedShortTy);
928     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
929       return GetType(ast.UnsignedIntTy);
930     break;
931 
932   case DW_ATE_lo_user:
933     // This has been seen to mean DW_AT_complex_integer
934     if (type_name.contains("complex")) {
935       CompilerType complex_int_clang_type =
936           GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed,
937                                                    bit_size / 2);
938       return GetType(
939           ast.getComplexType(ClangUtil::GetQualType(complex_int_clang_type)));
940     }
941     break;
942 
943   case DW_ATE_complex_float: {
944     CanQualType FloatComplexTy = ast.getComplexType(ast.FloatTy);
945     if (QualTypeMatchesBitSize(bit_size, ast, FloatComplexTy))
946       return GetType(FloatComplexTy);
947 
948     CanQualType DoubleComplexTy = ast.getComplexType(ast.DoubleTy);
949     if (QualTypeMatchesBitSize(bit_size, ast, DoubleComplexTy))
950       return GetType(DoubleComplexTy);
951 
952     CanQualType LongDoubleComplexTy = ast.getComplexType(ast.LongDoubleTy);
953     if (QualTypeMatchesBitSize(bit_size, ast, LongDoubleComplexTy))
954       return GetType(LongDoubleComplexTy);
955 
956     CompilerType complex_float_clang_type =
957         GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float,
958                                                  bit_size / 2);
959     return GetType(
960         ast.getComplexType(ClangUtil::GetQualType(complex_float_clang_type)));
961   }
962 
963   case DW_ATE_float:
964     if (type_name == "float" &&
965         QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
966       return GetType(ast.FloatTy);
967     if (type_name == "double" &&
968         QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
969       return GetType(ast.DoubleTy);
970     if (type_name == "long double" &&
971         QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
972       return GetType(ast.LongDoubleTy);
973     // Fall back to not requiring a name match
974     if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
975       return GetType(ast.FloatTy);
976     if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
977       return GetType(ast.DoubleTy);
978     if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
979       return GetType(ast.LongDoubleTy);
980     if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy))
981       return GetType(ast.HalfTy);
982     break;
983 
984   case DW_ATE_signed:
985     if (!type_name.empty()) {
986       if (type_name == "wchar_t" &&
987           QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy) &&
988           (getTargetInfo() &&
989            TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
990         return GetType(ast.WCharTy);
991       if (type_name == "void" &&
992           QualTypeMatchesBitSize(bit_size, ast, ast.VoidTy))
993         return GetType(ast.VoidTy);
994       if (type_name.contains("long long") &&
995           QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
996         return GetType(ast.LongLongTy);
997       if (type_name.contains("long") &&
998           QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
999         return GetType(ast.LongTy);
1000       if (type_name.contains("short") &&
1001           QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
1002         return GetType(ast.ShortTy);
1003       if (type_name.contains("char")) {
1004         if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1005           return GetType(ast.CharTy);
1006         if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
1007           return GetType(ast.SignedCharTy);
1008       }
1009       if (type_name.contains("int")) {
1010         if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
1011           return GetType(ast.IntTy);
1012         if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
1013           return GetType(ast.Int128Ty);
1014       }
1015     }
1016     // We weren't able to match up a type name, just search by size
1017     if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1018       return GetType(ast.CharTy);
1019     if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
1020       return GetType(ast.ShortTy);
1021     if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
1022       return GetType(ast.IntTy);
1023     if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
1024       return GetType(ast.LongTy);
1025     if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
1026       return GetType(ast.LongLongTy);
1027     if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
1028       return GetType(ast.Int128Ty);
1029     break;
1030 
1031   case DW_ATE_signed_char:
1032     if (type_name == "char") {
1033       if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1034         return GetType(ast.CharTy);
1035     }
1036     if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
1037       return GetType(ast.SignedCharTy);
1038     break;
1039 
1040   case DW_ATE_unsigned:
1041     if (!type_name.empty()) {
1042       if (type_name == "wchar_t") {
1043         if (QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy)) {
1044           if (!(getTargetInfo() &&
1045                 TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1046             return GetType(ast.WCharTy);
1047         }
1048       }
1049       if (type_name.contains("long long")) {
1050         if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
1051           return GetType(ast.UnsignedLongLongTy);
1052       } else if (type_name.contains("long")) {
1053         if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
1054           return GetType(ast.UnsignedLongTy);
1055       } else if (type_name.contains("short")) {
1056         if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1057           return GetType(ast.UnsignedShortTy);
1058       } else if (type_name.contains("char")) {
1059         if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1060           return GetType(ast.UnsignedCharTy);
1061       } else if (type_name.contains("int")) {
1062         if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
1063           return GetType(ast.UnsignedIntTy);
1064         if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
1065           return GetType(ast.UnsignedInt128Ty);
1066       }
1067     }
1068     // We weren't able to match up a type name, just search by size
1069     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1070       return GetType(ast.UnsignedCharTy);
1071     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1072       return GetType(ast.UnsignedShortTy);
1073     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
1074       return GetType(ast.UnsignedIntTy);
1075     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
1076       return GetType(ast.UnsignedLongTy);
1077     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
1078       return GetType(ast.UnsignedLongLongTy);
1079     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
1080       return GetType(ast.UnsignedInt128Ty);
1081     break;
1082 
1083   case DW_ATE_unsigned_char:
1084     if (type_name == "char") {
1085       if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1086         return GetType(ast.CharTy);
1087     }
1088     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1089       return GetType(ast.UnsignedCharTy);
1090     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1091       return GetType(ast.UnsignedShortTy);
1092     break;
1093 
1094   case DW_ATE_imaginary_float:
1095     break;
1096 
1097   case DW_ATE_UTF:
1098     switch (bit_size) {
1099     case 8:
1100       return GetType(ast.Char8Ty);
1101     case 16:
1102       return GetType(ast.Char16Ty);
1103     case 32:
1104       return GetType(ast.Char32Ty);
1105     default:
1106       if (!type_name.empty()) {
1107         if (type_name == "char16_t")
1108           return GetType(ast.Char16Ty);
1109         if (type_name == "char32_t")
1110           return GetType(ast.Char32Ty);
1111         if (type_name == "char8_t")
1112           return GetType(ast.Char8Ty);
1113       }
1114     }
1115     break;
1116   }
1117 
1118   Log *log = GetLog(LLDBLog::Types);
1119   LLDB_LOG(log,
1120            "error: need to add support for DW_TAG_base_type '{0}' "
1121            "encoded with DW_ATE = {1:x}, bit_size = {2}",
1122            type_name, dw_ate, bit_size);
1123   return CompilerType();
1124 }
1125 
1126 CompilerType TypeSystemClang::GetCStringType(bool is_const) {
1127   ASTContext &ast = getASTContext();
1128   QualType char_type(ast.CharTy);
1129 
1130   if (is_const)
1131     char_type.addConst();
1132 
1133   return GetType(ast.getPointerType(char_type));
1134 }
1135 
1136 bool TypeSystemClang::AreTypesSame(CompilerType type1, CompilerType type2,
1137                                    bool ignore_qualifiers) {
1138   auto ast = type1.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();
1139   if (!ast || type1.GetTypeSystem() != type2.GetTypeSystem())
1140     return false;
1141 
1142   if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
1143     return true;
1144 
1145   QualType type1_qual = ClangUtil::GetQualType(type1);
1146   QualType type2_qual = ClangUtil::GetQualType(type2);
1147 
1148   if (ignore_qualifiers) {
1149     type1_qual = type1_qual.getUnqualifiedType();
1150     type2_qual = type2_qual.getUnqualifiedType();
1151   }
1152 
1153   return ast->getASTContext().hasSameType(type1_qual, type2_qual);
1154 }
1155 
1156 CompilerType TypeSystemClang::GetTypeForDecl(void *opaque_decl) {
1157   if (!opaque_decl)
1158     return CompilerType();
1159 
1160   clang::Decl *decl = static_cast<clang::Decl *>(opaque_decl);
1161   if (auto *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl))
1162     return GetTypeForDecl(named_decl);
1163   return CompilerType();
1164 }
1165 
1166 CompilerDeclContext TypeSystemClang::CreateDeclContext(DeclContext *ctx) {
1167   // Check that the DeclContext actually belongs to this ASTContext.
1168   assert(&ctx->getParentASTContext() == &getASTContext());
1169   return CompilerDeclContext(this, ctx);
1170 }
1171 
1172 CompilerType TypeSystemClang::GetTypeForDecl(clang::NamedDecl *decl) {
1173   if (clang::ObjCInterfaceDecl *interface_decl =
1174       llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
1175     return GetTypeForDecl(interface_decl);
1176   if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
1177     return GetTypeForDecl(tag_decl);
1178   if (clang::ValueDecl *value_decl = llvm::dyn_cast<clang::ValueDecl>(decl))
1179     return GetTypeForDecl(value_decl);
1180   return CompilerType();
1181 }
1182 
1183 CompilerType TypeSystemClang::GetTypeForDecl(TagDecl *decl) {
1184   return GetType(getASTContext().getTagDeclType(decl));
1185 }
1186 
1187 CompilerType TypeSystemClang::GetTypeForDecl(ObjCInterfaceDecl *decl) {
1188   return GetType(getASTContext().getObjCInterfaceType(decl));
1189 }
1190 
1191 CompilerType TypeSystemClang::GetTypeForDecl(clang::ValueDecl *value_decl) {
1192   return GetType(value_decl->getType());
1193 }
1194 
1195 #pragma mark Structure, Unions, Classes
1196 
1197 void TypeSystemClang::SetOwningModule(clang::Decl *decl,
1198                                       OptionalClangModuleID owning_module) {
1199   if (!decl || !owning_module.HasValue())
1200     return;
1201 
1202   decl->setFromASTFile();
1203   decl->setOwningModuleID(owning_module.GetValue());
1204   decl->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible);
1205 }
1206 
1207 OptionalClangModuleID
1208 TypeSystemClang::GetOrCreateClangModule(llvm::StringRef name,
1209                                         OptionalClangModuleID parent,
1210                                         bool is_framework, bool is_explicit) {
1211   // Get the external AST source which holds the modules.
1212   auto *ast_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1213       getASTContext().getExternalSource());
1214   assert(ast_source && "external ast source was lost");
1215   if (!ast_source)
1216     return {};
1217 
1218   // Lazily initialize the module map.
1219   if (!m_header_search_up) {
1220     auto HSOpts = std::make_shared<clang::HeaderSearchOptions>();
1221     m_header_search_up = std::make_unique<clang::HeaderSearch>(
1222         HSOpts, *m_source_manager_up, *m_diagnostics_engine_up,
1223         *m_language_options_up, m_target_info_up.get());
1224     m_module_map_up = std::make_unique<clang::ModuleMap>(
1225         *m_source_manager_up, *m_diagnostics_engine_up, *m_language_options_up,
1226         m_target_info_up.get(), *m_header_search_up);
1227   }
1228 
1229   // Get or create the module context.
1230   bool created;
1231   clang::Module *module;
1232   auto parent_desc = ast_source->getSourceDescriptor(parent.GetValue());
1233   std::tie(module, created) = m_module_map_up->findOrCreateModule(
1234       name, parent_desc ? parent_desc->getModuleOrNull() : nullptr,
1235       is_framework, is_explicit);
1236   if (!created)
1237     return ast_source->GetIDForModule(module);
1238 
1239   return ast_source->RegisterModule(module);
1240 }
1241 
1242 CompilerType TypeSystemClang::CreateRecordType(
1243     clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1244     AccessType access_type, llvm::StringRef name, int kind,
1245     LanguageType language, std::optional<ClangASTMetadata> metadata,
1246     bool exports_symbols) {
1247   ASTContext &ast = getASTContext();
1248 
1249   if (decl_ctx == nullptr)
1250     decl_ctx = ast.getTranslationUnitDecl();
1251 
1252   if (language == eLanguageTypeObjC ||
1253       language == eLanguageTypeObjC_plus_plus) {
1254     bool isInternal = false;
1255     return CreateObjCClass(name, decl_ctx, owning_module, isInternal, metadata);
1256   }
1257 
1258   // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1259   // we will need to update this code. I was told to currently always use the
1260   // CXXRecordDecl class since we often don't know from debug information if
1261   // something is struct or a class, so we default to always use the more
1262   // complete definition just in case.
1263 
1264   bool has_name = !name.empty();
1265   CXXRecordDecl *decl = CXXRecordDecl::CreateDeserialized(ast, GlobalDeclID());
1266   decl->setTagKind(static_cast<TagDecl::TagKind>(kind));
1267   decl->setDeclContext(decl_ctx);
1268   if (has_name)
1269     decl->setDeclName(&ast.Idents.get(name));
1270   SetOwningModule(decl, owning_module);
1271 
1272   if (!has_name) {
1273     // In C++ a lambda is also represented as an unnamed class. This is
1274     // different from an *anonymous class* that the user wrote:
1275     //
1276     // struct A {
1277     //  // anonymous class (GNU/MSVC extension)
1278     //  struct {
1279     //    int x;
1280     //  };
1281     //  // unnamed class within a class
1282     //  struct {
1283     //    int y;
1284     //  } B;
1285     // };
1286     //
1287     // void f() {
1288     //    // unammed class outside of a class
1289     //    struct {
1290     //      int z;
1291     //    } C;
1292     // }
1293     //
1294     // Anonymous classes is a GNU/MSVC extension that clang supports. It
1295     // requires the anonymous class be embedded within a class. So the new
1296     // heuristic verifies this condition.
1297     if (isa<CXXRecordDecl>(decl_ctx) && exports_symbols)
1298       decl->setAnonymousStructOrUnion(true);
1299   }
1300 
1301   if (metadata)
1302     SetMetadata(decl, *metadata);
1303 
1304   if (access_type != eAccessNone)
1305     decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type));
1306 
1307   if (decl_ctx)
1308     decl_ctx->addDecl(decl);
1309 
1310   return GetType(ast.getTagDeclType(decl));
1311 }
1312 
1313 namespace {
1314 /// Returns true iff the given TemplateArgument should be represented as an
1315 /// NonTypeTemplateParmDecl in the AST.
1316 bool IsValueParam(const clang::TemplateArgument &argument) {
1317   return argument.getKind() == TemplateArgument::Integral;
1318 }
1319 
1320 void AddAccessSpecifierDecl(clang::CXXRecordDecl *cxx_record_decl,
1321                             ASTContext &ct,
1322                             clang::AccessSpecifier previous_access,
1323                             clang::AccessSpecifier access_specifier) {
1324   if (!cxx_record_decl->isClass() && !cxx_record_decl->isStruct())
1325     return;
1326   if (previous_access != access_specifier) {
1327     // For struct, don't add AS_public if it's the first AccessSpecDecl.
1328     // For class, don't add AS_private if it's the first AccessSpecDecl.
1329     if ((cxx_record_decl->isStruct() &&
1330          previous_access == clang::AccessSpecifier::AS_none &&
1331          access_specifier == clang::AccessSpecifier::AS_public) ||
1332         (cxx_record_decl->isClass() &&
1333          previous_access == clang::AccessSpecifier::AS_none &&
1334          access_specifier == clang::AccessSpecifier::AS_private)) {
1335       return;
1336     }
1337     cxx_record_decl->addDecl(
1338         AccessSpecDecl::Create(ct, access_specifier, cxx_record_decl,
1339                                SourceLocation(), SourceLocation()));
1340   }
1341 }
1342 } // namespace
1343 
1344 static TemplateParameterList *CreateTemplateParameterList(
1345     ASTContext &ast,
1346     const TypeSystemClang::TemplateParameterInfos &template_param_infos,
1347     llvm::SmallVector<NamedDecl *, 8> &template_param_decls) {
1348   const bool parameter_pack = false;
1349   const bool is_typename = false;
1350   const unsigned depth = 0;
1351   const size_t num_template_params = template_param_infos.Size();
1352   DeclContext *const decl_context =
1353       ast.getTranslationUnitDecl(); // Is this the right decl context?,
1354 
1355   auto const &args = template_param_infos.GetArgs();
1356   auto const &names = template_param_infos.GetNames();
1357   for (size_t i = 0; i < num_template_params; ++i) {
1358     const char *name = names[i];
1359 
1360     IdentifierInfo *identifier_info = nullptr;
1361     if (name && name[0])
1362       identifier_info = &ast.Idents.get(name);
1363     TemplateArgument const &targ = args[i];
1364     if (IsValueParam(targ)) {
1365       QualType template_param_type = targ.getIntegralType();
1366       template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1367           ast, decl_context, SourceLocation(), SourceLocation(), depth, i,
1368           identifier_info, template_param_type, parameter_pack,
1369           ast.getTrivialTypeSourceInfo(template_param_type)));
1370     } else {
1371       template_param_decls.push_back(TemplateTypeParmDecl::Create(
1372           ast, decl_context, SourceLocation(), SourceLocation(), depth, i,
1373           identifier_info, is_typename, parameter_pack));
1374     }
1375   }
1376 
1377   if (template_param_infos.hasParameterPack()) {
1378     IdentifierInfo *identifier_info = nullptr;
1379     if (template_param_infos.HasPackName())
1380       identifier_info = &ast.Idents.get(template_param_infos.GetPackName());
1381     const bool parameter_pack_true = true;
1382 
1383     if (!template_param_infos.GetParameterPack().IsEmpty() &&
1384         IsValueParam(template_param_infos.GetParameterPack().Front())) {
1385       QualType template_param_type =
1386           template_param_infos.GetParameterPack().Front().getIntegralType();
1387       template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1388           ast, decl_context, SourceLocation(), SourceLocation(), depth,
1389           num_template_params, identifier_info, template_param_type,
1390           parameter_pack_true,
1391           ast.getTrivialTypeSourceInfo(template_param_type)));
1392     } else {
1393       template_param_decls.push_back(TemplateTypeParmDecl::Create(
1394           ast, decl_context, SourceLocation(), SourceLocation(), depth,
1395           num_template_params, identifier_info, is_typename,
1396           parameter_pack_true));
1397     }
1398   }
1399   clang::Expr *const requires_clause = nullptr; // TODO: Concepts
1400   TemplateParameterList *template_param_list = TemplateParameterList::Create(
1401       ast, SourceLocation(), SourceLocation(), template_param_decls,
1402       SourceLocation(), requires_clause);
1403   return template_param_list;
1404 }
1405 
1406 clang::FunctionTemplateDecl *TypeSystemClang::CreateFunctionTemplateDecl(
1407     clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1408     clang::FunctionDecl *func_decl,
1409     const TemplateParameterInfos &template_param_infos) {
1410   //    /// Create a function template node.
1411   ASTContext &ast = getASTContext();
1412 
1413   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1414   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1415       ast, template_param_infos, template_param_decls);
1416   FunctionTemplateDecl *func_tmpl_decl =
1417       FunctionTemplateDecl::CreateDeserialized(ast, GlobalDeclID());
1418   func_tmpl_decl->setDeclContext(decl_ctx);
1419   func_tmpl_decl->setLocation(func_decl->getLocation());
1420   func_tmpl_decl->setDeclName(func_decl->getDeclName());
1421   func_tmpl_decl->setTemplateParameters(template_param_list);
1422   func_tmpl_decl->init(func_decl);
1423   SetOwningModule(func_tmpl_decl, owning_module);
1424 
1425   for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1426        i < template_param_decl_count; ++i) {
1427     // TODO: verify which decl context we should put template_param_decls into..
1428     template_param_decls[i]->setDeclContext(func_decl);
1429   }
1430   // Function templates inside a record need to have an access specifier.
1431   // It doesn't matter what access specifier we give the template as LLDB
1432   // anyway allows accessing everything inside a record.
1433   if (decl_ctx->isRecord())
1434     func_tmpl_decl->setAccess(clang::AccessSpecifier::AS_public);
1435 
1436   return func_tmpl_decl;
1437 }
1438 
1439 void TypeSystemClang::CreateFunctionTemplateSpecializationInfo(
1440     FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl,
1441     const TemplateParameterInfos &infos) {
1442   TemplateArgumentList *template_args_ptr = TemplateArgumentList::CreateCopy(
1443       func_decl->getASTContext(), infos.GetArgs());
1444 
1445   func_decl->setFunctionTemplateSpecialization(func_tmpl_decl,
1446                                                template_args_ptr, nullptr);
1447 }
1448 
1449 /// Returns true if the given template parameter can represent the given value.
1450 /// For example, `typename T` can represent `int` but not integral values such
1451 /// as `int I = 3`.
1452 static bool TemplateParameterAllowsValue(NamedDecl *param,
1453                                          const TemplateArgument &value) {
1454   if (llvm::isa<TemplateTypeParmDecl>(param)) {
1455     // Compare the argument kind, i.e. ensure that <typename> != <int>.
1456     if (value.getKind() != TemplateArgument::Type)
1457       return false;
1458   } else if (auto *type_param =
1459                  llvm::dyn_cast<NonTypeTemplateParmDecl>(param)) {
1460     // Compare the argument kind, i.e. ensure that <typename> != <int>.
1461     if (!IsValueParam(value))
1462       return false;
1463     // Compare the integral type, i.e. ensure that <int> != <char>.
1464     if (type_param->getType() != value.getIntegralType())
1465       return false;
1466   } else {
1467     // There is no way to create other parameter decls at the moment, so we
1468     // can't reach this case during normal LLDB usage. Log that this happened
1469     // and assert.
1470     Log *log = GetLog(LLDBLog::Expressions);
1471     LLDB_LOG(log,
1472              "Don't know how to compare template parameter to passed"
1473              " value. Decl kind of parameter is: {0}",
1474              param->getDeclKindName());
1475     lldbassert(false && "Can't compare this TemplateParmDecl subclass");
1476     // In release builds just fall back to marking the parameter as not
1477     // accepting the value so that we don't try to fit an instantiation to a
1478     // template that doesn't fit. E.g., avoid that `S<1>` is being connected to
1479     // `template<typename T> struct S;`.
1480     return false;
1481   }
1482   return true;
1483 }
1484 
1485 /// Returns true if the given class template declaration could produce an
1486 /// instantiation with the specified values.
1487 /// For example, `<typename T>` allows the arguments `float`, but not for
1488 /// example `bool, float` or `3` (as an integer parameter value).
1489 static bool ClassTemplateAllowsToInstantiationArgs(
1490     ClassTemplateDecl *class_template_decl,
1491     const TypeSystemClang::TemplateParameterInfos &instantiation_values) {
1492 
1493   TemplateParameterList &params = *class_template_decl->getTemplateParameters();
1494 
1495   // Save some work by iterating only once over the found parameters and
1496   // calculate the information related to parameter packs.
1497 
1498   // Contains the first pack parameter (or non if there are none).
1499   std::optional<NamedDecl *> pack_parameter;
1500   // Contains the number of non-pack parameters.
1501   size_t non_pack_params = params.size();
1502   for (size_t i = 0; i < params.size(); ++i) {
1503     NamedDecl *param = params.getParam(i);
1504     if (param->isParameterPack()) {
1505       pack_parameter = param;
1506       non_pack_params = i;
1507       break;
1508     }
1509   }
1510 
1511   // The found template needs to have compatible non-pack template arguments.
1512   // E.g., ensure that <typename, typename> != <typename>.
1513   // The pack parameters are compared later.
1514   if (non_pack_params != instantiation_values.Size())
1515     return false;
1516 
1517   // Ensure that <typename...> != <typename>.
1518   if (pack_parameter.has_value() != instantiation_values.hasParameterPack())
1519     return false;
1520 
1521   // Compare the first pack parameter that was found with the first pack
1522   // parameter value. The special case of having an empty parameter pack value
1523   // always fits to a pack parameter.
1524   // E.g., ensure that <int...> != <typename...>.
1525   if (pack_parameter && !instantiation_values.GetParameterPack().IsEmpty() &&
1526       !TemplateParameterAllowsValue(
1527           *pack_parameter, instantiation_values.GetParameterPack().Front()))
1528     return false;
1529 
1530   // Compare all the non-pack parameters now.
1531   // E.g., ensure that <int> != <long>.
1532   for (const auto pair :
1533        llvm::zip_first(instantiation_values.GetArgs(), params)) {
1534     const TemplateArgument &passed_arg = std::get<0>(pair);
1535     NamedDecl *found_param = std::get<1>(pair);
1536     if (!TemplateParameterAllowsValue(found_param, passed_arg))
1537       return false;
1538   }
1539 
1540   return class_template_decl;
1541 }
1542 
1543 ClassTemplateDecl *TypeSystemClang::CreateClassTemplateDecl(
1544     DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1545     lldb::AccessType access_type, llvm::StringRef class_name, int kind,
1546     const TemplateParameterInfos &template_param_infos) {
1547   ASTContext &ast = getASTContext();
1548 
1549   ClassTemplateDecl *class_template_decl = nullptr;
1550   if (decl_ctx == nullptr)
1551     decl_ctx = ast.getTranslationUnitDecl();
1552 
1553   IdentifierInfo &identifier_info = ast.Idents.get(class_name);
1554   DeclarationName decl_name(&identifier_info);
1555 
1556   // Search the AST for an existing ClassTemplateDecl that could be reused.
1557   clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1558   for (NamedDecl *decl : result) {
1559     class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1560     if (!class_template_decl)
1561       continue;
1562     // The class template has to be able to represents the instantiation
1563     // values we received. Without this we might end up putting an instantiation
1564     // with arguments such as <int, int> to a template such as:
1565     //     template<typename T> struct S;
1566     // Connecting the instantiation to an incompatible template could cause
1567     // problems later on.
1568     if (!ClassTemplateAllowsToInstantiationArgs(class_template_decl,
1569                                                 template_param_infos))
1570       continue;
1571     return class_template_decl;
1572   }
1573 
1574   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1575 
1576   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1577       ast, template_param_infos, template_param_decls);
1578 
1579   CXXRecordDecl *template_cxx_decl =
1580       CXXRecordDecl::CreateDeserialized(ast, GlobalDeclID());
1581   template_cxx_decl->setTagKind(static_cast<TagDecl::TagKind>(kind));
1582   // What decl context do we use here? TU? The actual decl context?
1583   template_cxx_decl->setDeclContext(decl_ctx);
1584   template_cxx_decl->setDeclName(decl_name);
1585   SetOwningModule(template_cxx_decl, owning_module);
1586 
1587   for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1588        i < template_param_decl_count; ++i) {
1589     template_param_decls[i]->setDeclContext(template_cxx_decl);
1590   }
1591 
1592   // With templated classes, we say that a class is templated with
1593   // specializations, but that the bare class has no functions.
1594   // template_cxx_decl->startDefinition();
1595   // template_cxx_decl->completeDefinition();
1596 
1597   class_template_decl =
1598       ClassTemplateDecl::CreateDeserialized(ast, GlobalDeclID());
1599   // What decl context do we use here? TU? The actual decl context?
1600   class_template_decl->setDeclContext(decl_ctx);
1601   class_template_decl->setDeclName(decl_name);
1602   class_template_decl->setTemplateParameters(template_param_list);
1603   class_template_decl->init(template_cxx_decl);
1604   template_cxx_decl->setDescribedClassTemplate(class_template_decl);
1605   SetOwningModule(class_template_decl, owning_module);
1606 
1607   if (access_type != eAccessNone)
1608     class_template_decl->setAccess(
1609         ConvertAccessTypeToAccessSpecifier(access_type));
1610 
1611   decl_ctx->addDecl(class_template_decl);
1612 
1613   VerifyDecl(class_template_decl);
1614 
1615   return class_template_decl;
1616 }
1617 
1618 TemplateTemplateParmDecl *
1619 TypeSystemClang::CreateTemplateTemplateParmDecl(const char *template_name) {
1620   ASTContext &ast = getASTContext();
1621 
1622   auto *decl_ctx = ast.getTranslationUnitDecl();
1623 
1624   IdentifierInfo &identifier_info = ast.Idents.get(template_name);
1625   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1626 
1627   TypeSystemClang::TemplateParameterInfos template_param_infos;
1628   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1629       ast, template_param_infos, template_param_decls);
1630 
1631   // LLDB needs to create those decls only to be able to display a
1632   // type that includes a template template argument. Only the name matters for
1633   // this purpose, so we use dummy values for the other characteristics of the
1634   // type.
1635   return TemplateTemplateParmDecl::Create(ast, decl_ctx, SourceLocation(),
1636                                           /*Depth=*/0, /*Position=*/0,
1637                                           /*IsParameterPack=*/false,
1638                                           &identifier_info, /*Typename=*/false,
1639                                           template_param_list);
1640 }
1641 
1642 ClassTemplateSpecializationDecl *
1643 TypeSystemClang::CreateClassTemplateSpecializationDecl(
1644     DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1645     ClassTemplateDecl *class_template_decl, int kind,
1646     const TemplateParameterInfos &template_param_infos) {
1647   ASTContext &ast = getASTContext();
1648   llvm::SmallVector<clang::TemplateArgument, 2> args(
1649       template_param_infos.Size() +
1650       (template_param_infos.hasParameterPack() ? 1 : 0));
1651 
1652   auto const &orig_args = template_param_infos.GetArgs();
1653   std::copy(orig_args.begin(), orig_args.end(), args.begin());
1654   if (template_param_infos.hasParameterPack()) {
1655     args[args.size() - 1] = TemplateArgument::CreatePackCopy(
1656         ast, template_param_infos.GetParameterPackArgs());
1657   }
1658   ClassTemplateSpecializationDecl *class_template_specialization_decl =
1659       ClassTemplateSpecializationDecl::CreateDeserialized(ast, GlobalDeclID());
1660   class_template_specialization_decl->setTagKind(
1661       static_cast<TagDecl::TagKind>(kind));
1662   class_template_specialization_decl->setDeclContext(decl_ctx);
1663   class_template_specialization_decl->setInstantiationOf(class_template_decl);
1664   class_template_specialization_decl->setTemplateArgs(
1665       TemplateArgumentList::CreateCopy(ast, args));
1666   ast.getTypeDeclType(class_template_specialization_decl, nullptr);
1667   class_template_specialization_decl->setDeclName(
1668       class_template_decl->getDeclName());
1669   SetOwningModule(class_template_specialization_decl, owning_module);
1670   decl_ctx->addDecl(class_template_specialization_decl);
1671 
1672   class_template_specialization_decl->setSpecializationKind(
1673       TSK_ExplicitSpecialization);
1674 
1675   return class_template_specialization_decl;
1676 }
1677 
1678 CompilerType TypeSystemClang::CreateClassTemplateSpecializationType(
1679     ClassTemplateSpecializationDecl *class_template_specialization_decl) {
1680   if (class_template_specialization_decl) {
1681     ASTContext &ast = getASTContext();
1682     return GetType(ast.getTagDeclType(class_template_specialization_decl));
1683   }
1684   return CompilerType();
1685 }
1686 
1687 static inline bool check_op_param(bool is_method,
1688                                   clang::OverloadedOperatorKind op_kind,
1689                                   bool unary, bool binary,
1690                                   uint32_t num_params) {
1691   // Special-case call since it can take any number of operands
1692   if (op_kind == OO_Call)
1693     return true;
1694 
1695   // The parameter count doesn't include "this"
1696   if (is_method)
1697     ++num_params;
1698   if (num_params == 1)
1699     return unary;
1700   if (num_params == 2)
1701     return binary;
1702   else
1703     return false;
1704 }
1705 
1706 bool TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
1707     bool is_method, clang::OverloadedOperatorKind op_kind,
1708     uint32_t num_params) {
1709   switch (op_kind) {
1710   default:
1711     break;
1712   // C++ standard allows any number of arguments to new/delete
1713   case OO_New:
1714   case OO_Array_New:
1715   case OO_Delete:
1716   case OO_Array_Delete:
1717     return true;
1718   }
1719 
1720 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
1721   case OO_##Name:                                                              \
1722     return check_op_param(is_method, op_kind, Unary, Binary, num_params);
1723   switch (op_kind) {
1724 #include "clang/Basic/OperatorKinds.def"
1725   default:
1726     break;
1727   }
1728   return false;
1729 }
1730 
1731 clang::AccessSpecifier
1732 TypeSystemClang::UnifyAccessSpecifiers(clang::AccessSpecifier lhs,
1733                                        clang::AccessSpecifier rhs) {
1734   // Make the access equal to the stricter of the field and the nested field's
1735   // access
1736   if (lhs == AS_none || rhs == AS_none)
1737     return AS_none;
1738   if (lhs == AS_private || rhs == AS_private)
1739     return AS_private;
1740   if (lhs == AS_protected || rhs == AS_protected)
1741     return AS_protected;
1742   return AS_public;
1743 }
1744 
1745 bool TypeSystemClang::FieldIsBitfield(FieldDecl *field,
1746                                       uint32_t &bitfield_bit_size) {
1747   ASTContext &ast = getASTContext();
1748   if (field == nullptr)
1749     return false;
1750 
1751   if (field->isBitField()) {
1752     Expr *bit_width_expr = field->getBitWidth();
1753     if (bit_width_expr) {
1754       if (std::optional<llvm::APSInt> bit_width_apsint =
1755               bit_width_expr->getIntegerConstantExpr(ast)) {
1756         bitfield_bit_size = bit_width_apsint->getLimitedValue(UINT32_MAX);
1757         return true;
1758       }
1759     }
1760   }
1761   return false;
1762 }
1763 
1764 bool TypeSystemClang::RecordHasFields(const RecordDecl *record_decl) {
1765   if (record_decl == nullptr)
1766     return false;
1767 
1768   if (!record_decl->field_empty())
1769     return true;
1770 
1771   // No fields, lets check this is a CXX record and check the base classes
1772   const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1773   if (cxx_record_decl) {
1774     CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1775     for (base_class = cxx_record_decl->bases_begin(),
1776         base_class_end = cxx_record_decl->bases_end();
1777          base_class != base_class_end; ++base_class) {
1778       const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(
1779           base_class->getType()->getAs<RecordType>()->getDecl());
1780       if (RecordHasFields(base_class_decl))
1781         return true;
1782     }
1783   }
1784 
1785   // We always want forcefully completed types to show up so we can print a
1786   // message in the summary that indicates that the type is incomplete.
1787   // This will help users know when they are running into issues with
1788   // -flimit-debug-info instead of just seeing nothing if this is a base class
1789   // (since we were hiding empty base classes), or nothing when you turn open
1790   // an valiable whose type was incomplete.
1791   if (std::optional<ClangASTMetadata> meta_data = GetMetadata(record_decl);
1792       meta_data && meta_data->IsForcefullyCompleted())
1793     return true;
1794 
1795   return false;
1796 }
1797 
1798 #pragma mark Objective-C Classes
1799 
1800 CompilerType TypeSystemClang::CreateObjCClass(
1801     llvm::StringRef name, clang::DeclContext *decl_ctx,
1802     OptionalClangModuleID owning_module, bool isInternal,
1803     std::optional<ClangASTMetadata> metadata) {
1804   ASTContext &ast = getASTContext();
1805   assert(!name.empty());
1806   if (!decl_ctx)
1807     decl_ctx = ast.getTranslationUnitDecl();
1808 
1809   ObjCInterfaceDecl *decl =
1810       ObjCInterfaceDecl::CreateDeserialized(ast, GlobalDeclID());
1811   decl->setDeclContext(decl_ctx);
1812   decl->setDeclName(&ast.Idents.get(name));
1813   decl->setImplicit(isInternal);
1814   SetOwningModule(decl, owning_module);
1815 
1816   if (metadata)
1817     SetMetadata(decl, *metadata);
1818 
1819   return GetType(ast.getObjCInterfaceType(decl));
1820 }
1821 
1822 bool TypeSystemClang::BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) {
1823   return !TypeSystemClang::RecordHasFields(b->getType()->getAsCXXRecordDecl());
1824 }
1825 
1826 uint32_t
1827 TypeSystemClang::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl,
1828                                    bool omit_empty_base_classes) {
1829   uint32_t num_bases = 0;
1830   if (cxx_record_decl) {
1831     if (omit_empty_base_classes) {
1832       CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1833       for (base_class = cxx_record_decl->bases_begin(),
1834           base_class_end = cxx_record_decl->bases_end();
1835            base_class != base_class_end; ++base_class) {
1836         // Skip empty base classes
1837         if (BaseSpecifierIsEmpty(base_class))
1838           continue;
1839         ++num_bases;
1840       }
1841     } else
1842       num_bases = cxx_record_decl->getNumBases();
1843   }
1844   return num_bases;
1845 }
1846 
1847 #pragma mark Namespace Declarations
1848 
1849 NamespaceDecl *TypeSystemClang::GetUniqueNamespaceDeclaration(
1850     const char *name, clang::DeclContext *decl_ctx,
1851     OptionalClangModuleID owning_module, bool is_inline) {
1852   NamespaceDecl *namespace_decl = nullptr;
1853   ASTContext &ast = getASTContext();
1854   TranslationUnitDecl *translation_unit_decl = ast.getTranslationUnitDecl();
1855   if (!decl_ctx)
1856     decl_ctx = translation_unit_decl;
1857 
1858   if (name) {
1859     IdentifierInfo &identifier_info = ast.Idents.get(name);
1860     DeclarationName decl_name(&identifier_info);
1861     clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1862     for (NamedDecl *decl : result) {
1863       namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
1864       if (namespace_decl)
1865         return namespace_decl;
1866     }
1867 
1868     namespace_decl = NamespaceDecl::Create(ast, decl_ctx, is_inline,
1869                                            SourceLocation(), SourceLocation(),
1870                                            &identifier_info, nullptr, false);
1871 
1872     decl_ctx->addDecl(namespace_decl);
1873   } else {
1874     if (decl_ctx == translation_unit_decl) {
1875       namespace_decl = translation_unit_decl->getAnonymousNamespace();
1876       if (namespace_decl)
1877         return namespace_decl;
1878 
1879       namespace_decl =
1880           NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(),
1881                                 SourceLocation(), nullptr, nullptr, false);
1882       translation_unit_decl->setAnonymousNamespace(namespace_decl);
1883       translation_unit_decl->addDecl(namespace_decl);
1884       assert(namespace_decl == translation_unit_decl->getAnonymousNamespace());
1885     } else {
1886       NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
1887       if (parent_namespace_decl) {
1888         namespace_decl = parent_namespace_decl->getAnonymousNamespace();
1889         if (namespace_decl)
1890           return namespace_decl;
1891         namespace_decl =
1892             NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(),
1893                                   SourceLocation(), nullptr, nullptr, false);
1894         parent_namespace_decl->setAnonymousNamespace(namespace_decl);
1895         parent_namespace_decl->addDecl(namespace_decl);
1896         assert(namespace_decl ==
1897                parent_namespace_decl->getAnonymousNamespace());
1898       } else {
1899         assert(false && "GetUniqueNamespaceDeclaration called with no name and "
1900                         "no namespace as decl_ctx");
1901       }
1902     }
1903   }
1904   // Note: namespaces can span multiple modules, so perhaps this isn't a good
1905   // idea.
1906   SetOwningModule(namespace_decl, owning_module);
1907 
1908   VerifyDecl(namespace_decl);
1909   return namespace_decl;
1910 }
1911 
1912 clang::BlockDecl *
1913 TypeSystemClang::CreateBlockDeclaration(clang::DeclContext *ctx,
1914                                         OptionalClangModuleID owning_module) {
1915   if (ctx) {
1916     clang::BlockDecl *decl =
1917         clang::BlockDecl::CreateDeserialized(getASTContext(), GlobalDeclID());
1918     decl->setDeclContext(ctx);
1919     ctx->addDecl(decl);
1920     SetOwningModule(decl, owning_module);
1921     return decl;
1922   }
1923   return nullptr;
1924 }
1925 
1926 clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left,
1927                                         clang::DeclContext *right,
1928                                         clang::DeclContext *root) {
1929   if (root == nullptr)
1930     return nullptr;
1931 
1932   std::set<clang::DeclContext *> path_left;
1933   for (clang::DeclContext *d = left; d != nullptr; d = d->getParent())
1934     path_left.insert(d);
1935 
1936   for (clang::DeclContext *d = right; d != nullptr; d = d->getParent())
1937     if (path_left.find(d) != path_left.end())
1938       return d;
1939 
1940   return nullptr;
1941 }
1942 
1943 clang::UsingDirectiveDecl *TypeSystemClang::CreateUsingDirectiveDeclaration(
1944     clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1945     clang::NamespaceDecl *ns_decl) {
1946   if (decl_ctx && ns_decl) {
1947     auto *translation_unit = getASTContext().getTranslationUnitDecl();
1948     clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create(
1949           getASTContext(), decl_ctx, clang::SourceLocation(),
1950           clang::SourceLocation(), clang::NestedNameSpecifierLoc(),
1951           clang::SourceLocation(), ns_decl,
1952           FindLCABetweenDecls(decl_ctx, ns_decl,
1953                               translation_unit));
1954       decl_ctx->addDecl(using_decl);
1955       SetOwningModule(using_decl, owning_module);
1956       return using_decl;
1957   }
1958   return nullptr;
1959 }
1960 
1961 clang::UsingDecl *
1962 TypeSystemClang::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
1963                                         OptionalClangModuleID owning_module,
1964                                         clang::NamedDecl *target) {
1965   if (current_decl_ctx && target) {
1966     clang::UsingDecl *using_decl = clang::UsingDecl::Create(
1967         getASTContext(), current_decl_ctx, clang::SourceLocation(),
1968         clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false);
1969     SetOwningModule(using_decl, owning_module);
1970     clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create(
1971         getASTContext(), current_decl_ctx, clang::SourceLocation(),
1972         target->getDeclName(), using_decl, target);
1973     SetOwningModule(shadow_decl, owning_module);
1974     using_decl->addShadowDecl(shadow_decl);
1975     current_decl_ctx->addDecl(using_decl);
1976     return using_decl;
1977   }
1978   return nullptr;
1979 }
1980 
1981 clang::VarDecl *TypeSystemClang::CreateVariableDeclaration(
1982     clang::DeclContext *decl_context, OptionalClangModuleID owning_module,
1983     const char *name, clang::QualType type) {
1984   if (decl_context) {
1985     clang::VarDecl *var_decl =
1986         clang::VarDecl::CreateDeserialized(getASTContext(), GlobalDeclID());
1987     var_decl->setDeclContext(decl_context);
1988     if (name && name[0])
1989       var_decl->setDeclName(&getASTContext().Idents.getOwn(name));
1990     var_decl->setType(type);
1991     SetOwningModule(var_decl, owning_module);
1992     var_decl->setAccess(clang::AS_public);
1993     decl_context->addDecl(var_decl);
1994     return var_decl;
1995   }
1996   return nullptr;
1997 }
1998 
1999 lldb::opaque_compiler_type_t
2000 TypeSystemClang::GetOpaqueCompilerType(clang::ASTContext *ast,
2001                                        lldb::BasicType basic_type) {
2002   switch (basic_type) {
2003   case eBasicTypeVoid:
2004     return ast->VoidTy.getAsOpaquePtr();
2005   case eBasicTypeChar:
2006     return ast->CharTy.getAsOpaquePtr();
2007   case eBasicTypeSignedChar:
2008     return ast->SignedCharTy.getAsOpaquePtr();
2009   case eBasicTypeUnsignedChar:
2010     return ast->UnsignedCharTy.getAsOpaquePtr();
2011   case eBasicTypeWChar:
2012     return ast->getWCharType().getAsOpaquePtr();
2013   case eBasicTypeSignedWChar:
2014     return ast->getSignedWCharType().getAsOpaquePtr();
2015   case eBasicTypeUnsignedWChar:
2016     return ast->getUnsignedWCharType().getAsOpaquePtr();
2017   case eBasicTypeChar8:
2018     return ast->Char8Ty.getAsOpaquePtr();
2019   case eBasicTypeChar16:
2020     return ast->Char16Ty.getAsOpaquePtr();
2021   case eBasicTypeChar32:
2022     return ast->Char32Ty.getAsOpaquePtr();
2023   case eBasicTypeShort:
2024     return ast->ShortTy.getAsOpaquePtr();
2025   case eBasicTypeUnsignedShort:
2026     return ast->UnsignedShortTy.getAsOpaquePtr();
2027   case eBasicTypeInt:
2028     return ast->IntTy.getAsOpaquePtr();
2029   case eBasicTypeUnsignedInt:
2030     return ast->UnsignedIntTy.getAsOpaquePtr();
2031   case eBasicTypeLong:
2032     return ast->LongTy.getAsOpaquePtr();
2033   case eBasicTypeUnsignedLong:
2034     return ast->UnsignedLongTy.getAsOpaquePtr();
2035   case eBasicTypeLongLong:
2036     return ast->LongLongTy.getAsOpaquePtr();
2037   case eBasicTypeUnsignedLongLong:
2038     return ast->UnsignedLongLongTy.getAsOpaquePtr();
2039   case eBasicTypeInt128:
2040     return ast->Int128Ty.getAsOpaquePtr();
2041   case eBasicTypeUnsignedInt128:
2042     return ast->UnsignedInt128Ty.getAsOpaquePtr();
2043   case eBasicTypeBool:
2044     return ast->BoolTy.getAsOpaquePtr();
2045   case eBasicTypeHalf:
2046     return ast->HalfTy.getAsOpaquePtr();
2047   case eBasicTypeFloat:
2048     return ast->FloatTy.getAsOpaquePtr();
2049   case eBasicTypeDouble:
2050     return ast->DoubleTy.getAsOpaquePtr();
2051   case eBasicTypeLongDouble:
2052     return ast->LongDoubleTy.getAsOpaquePtr();
2053   case eBasicTypeFloatComplex:
2054     return ast->getComplexType(ast->FloatTy).getAsOpaquePtr();
2055   case eBasicTypeDoubleComplex:
2056     return ast->getComplexType(ast->DoubleTy).getAsOpaquePtr();
2057   case eBasicTypeLongDoubleComplex:
2058     return ast->getComplexType(ast->LongDoubleTy).getAsOpaquePtr();
2059   case eBasicTypeObjCID:
2060     return ast->getObjCIdType().getAsOpaquePtr();
2061   case eBasicTypeObjCClass:
2062     return ast->getObjCClassType().getAsOpaquePtr();
2063   case eBasicTypeObjCSel:
2064     return ast->getObjCSelType().getAsOpaquePtr();
2065   case eBasicTypeNullPtr:
2066     return ast->NullPtrTy.getAsOpaquePtr();
2067   default:
2068     return nullptr;
2069   }
2070 }
2071 
2072 #pragma mark Function Types
2073 
2074 clang::DeclarationName
2075 TypeSystemClang::GetDeclarationName(llvm::StringRef name,
2076                                     const CompilerType &function_clang_type) {
2077   clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
2078   if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS)
2079     return DeclarationName(&getASTContext().Idents.get(
2080         name)); // Not operator, but a regular function.
2081 
2082   // Check the number of operator parameters. Sometimes we have seen bad DWARF
2083   // that doesn't correctly describe operators and if we try to create a method
2084   // and add it to the class, clang will assert and crash, so we need to make
2085   // sure things are acceptable.
2086   clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type));
2087   const clang::FunctionProtoType *function_type =
2088       llvm::dyn_cast<clang::FunctionProtoType>(method_qual_type.getTypePtr());
2089   if (function_type == nullptr)
2090     return clang::DeclarationName();
2091 
2092   const bool is_method = false;
2093   const unsigned int num_params = function_type->getNumParams();
2094   if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
2095           is_method, op_kind, num_params))
2096     return clang::DeclarationName();
2097 
2098   return getASTContext().DeclarationNames.getCXXOperatorName(op_kind);
2099 }
2100 
2101 PrintingPolicy TypeSystemClang::GetTypePrintingPolicy() {
2102   clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy());
2103   printing_policy.SuppressTagKeyword = true;
2104   // Inline namespaces are important for some type formatters (e.g., libc++
2105   // and libstdc++ are differentiated by their inline namespaces).
2106   printing_policy.SuppressInlineNamespace = false;
2107   printing_policy.SuppressUnwrittenScope = false;
2108   // Default arguments are also always important for type formatters. Otherwise
2109   // we would need to always specify two type names for the setups where we do
2110   // know the default arguments and where we don't know default arguments.
2111   //
2112   // For example, without this we would need to have formatters for both:
2113   //   std::basic_string<char>
2114   // and
2115   //   std::basic_string<char, std::char_traits<char>, std::allocator<char> >
2116   // to support setups where LLDB was able to reconstruct default arguments
2117   // (and we then would have suppressed them from the type name) and also setups
2118   // where LLDB wasn't able to reconstruct the default arguments.
2119   printing_policy.SuppressDefaultTemplateArgs = false;
2120   return printing_policy;
2121 }
2122 
2123 std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl,
2124                                                 bool qualified) {
2125   clang::PrintingPolicy printing_policy = GetTypePrintingPolicy();
2126   std::string result;
2127   llvm::raw_string_ostream os(result);
2128   named_decl->getNameForDiagnostic(os, printing_policy, qualified);
2129   return result;
2130 }
2131 
2132 FunctionDecl *TypeSystemClang::CreateFunctionDeclaration(
2133     clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2134     llvm::StringRef name, const CompilerType &function_clang_type,
2135     clang::StorageClass storage, bool is_inline) {
2136   FunctionDecl *func_decl = nullptr;
2137   ASTContext &ast = getASTContext();
2138   if (!decl_ctx)
2139     decl_ctx = ast.getTranslationUnitDecl();
2140 
2141   const bool hasWrittenPrototype = true;
2142   const bool isConstexprSpecified = false;
2143 
2144   clang::DeclarationName declarationName =
2145       GetDeclarationName(name, function_clang_type);
2146   func_decl = FunctionDecl::CreateDeserialized(ast, GlobalDeclID());
2147   func_decl->setDeclContext(decl_ctx);
2148   func_decl->setDeclName(declarationName);
2149   func_decl->setType(ClangUtil::GetQualType(function_clang_type));
2150   func_decl->setStorageClass(storage);
2151   func_decl->setInlineSpecified(is_inline);
2152   func_decl->setHasWrittenPrototype(hasWrittenPrototype);
2153   func_decl->setConstexprKind(isConstexprSpecified
2154                                   ? ConstexprSpecKind::Constexpr
2155                                   : ConstexprSpecKind::Unspecified);
2156   SetOwningModule(func_decl, owning_module);
2157   decl_ctx->addDecl(func_decl);
2158 
2159   VerifyDecl(func_decl);
2160 
2161   return func_decl;
2162 }
2163 
2164 CompilerType TypeSystemClang::CreateFunctionType(
2165     const CompilerType &result_type, const CompilerType *args,
2166     unsigned num_args, bool is_variadic, unsigned type_quals,
2167     clang::CallingConv cc, clang::RefQualifierKind ref_qual) {
2168   if (!result_type || !ClangUtil::IsClangType(result_type))
2169     return CompilerType(); // invalid return type
2170 
2171   std::vector<QualType> qual_type_args;
2172   if (num_args > 0 && args == nullptr)
2173     return CompilerType(); // invalid argument array passed in
2174 
2175   // Verify that all arguments are valid and the right type
2176   for (unsigned i = 0; i < num_args; ++i) {
2177     if (args[i]) {
2178       // Make sure we have a clang type in args[i] and not a type from another
2179       // language whose name might match
2180       const bool is_clang_type = ClangUtil::IsClangType(args[i]);
2181       lldbassert(is_clang_type);
2182       if (is_clang_type)
2183         qual_type_args.push_back(ClangUtil::GetQualType(args[i]));
2184       else
2185         return CompilerType(); //  invalid argument type (must be a clang type)
2186     } else
2187       return CompilerType(); // invalid argument type (empty)
2188   }
2189 
2190   // TODO: Detect calling convention in DWARF?
2191   FunctionProtoType::ExtProtoInfo proto_info;
2192   proto_info.ExtInfo = cc;
2193   proto_info.Variadic = is_variadic;
2194   proto_info.ExceptionSpec = EST_None;
2195   proto_info.TypeQuals = clang::Qualifiers::fromFastMask(type_quals);
2196   proto_info.RefQualifier = ref_qual;
2197 
2198   return GetType(getASTContext().getFunctionType(
2199       ClangUtil::GetQualType(result_type), qual_type_args, proto_info));
2200 }
2201 
2202 ParmVarDecl *TypeSystemClang::CreateParameterDeclaration(
2203     clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2204     const char *name, const CompilerType &param_type, int storage,
2205     bool add_decl) {
2206   ASTContext &ast = getASTContext();
2207   auto *decl = ParmVarDecl::CreateDeserialized(ast, GlobalDeclID());
2208   decl->setDeclContext(decl_ctx);
2209   if (name && name[0])
2210     decl->setDeclName(&ast.Idents.get(name));
2211   decl->setType(ClangUtil::GetQualType(param_type));
2212   decl->setStorageClass(static_cast<clang::StorageClass>(storage));
2213   SetOwningModule(decl, owning_module);
2214   if (add_decl)
2215     decl_ctx->addDecl(decl);
2216 
2217   return decl;
2218 }
2219 
2220 CompilerType
2221 TypeSystemClang::CreateBlockPointerType(const CompilerType &function_type) {
2222   QualType block_type = m_ast_up->getBlockPointerType(
2223       clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType()));
2224 
2225   return GetType(block_type);
2226 }
2227 
2228 #pragma mark Array Types
2229 
2230 CompilerType
2231 TypeSystemClang::CreateArrayType(const CompilerType &element_type,
2232                                  std::optional<size_t> element_count,
2233                                  bool is_vector) {
2234   if (!element_type.IsValid())
2235     return {};
2236 
2237   ASTContext &ast = getASTContext();
2238 
2239   // Unknown number of elements; this is an incomplete array
2240   // (e.g., variable length array with non-constant bounds, or
2241   // a flexible array member).
2242   if (!element_count)
2243     return GetType(
2244         ast.getIncompleteArrayType(ClangUtil::GetQualType(element_type),
2245                                    clang::ArraySizeModifier::Normal, 0));
2246 
2247   if (is_vector)
2248     return GetType(ast.getExtVectorType(ClangUtil::GetQualType(element_type),
2249                                         *element_count));
2250 
2251   llvm::APInt ap_element_count(64, *element_count);
2252   return GetType(ast.getConstantArrayType(ClangUtil::GetQualType(element_type),
2253                                           ap_element_count, nullptr,
2254                                           clang::ArraySizeModifier::Normal, 0));
2255 }
2256 
2257 CompilerType TypeSystemClang::CreateStructForIdentifier(
2258     llvm::StringRef type_name,
2259     const std::initializer_list<std::pair<const char *, CompilerType>>
2260         &type_fields,
2261     bool packed) {
2262   CompilerType type;
2263   if (!type_name.empty() &&
2264       (type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name))
2265           .IsValid()) {
2266     lldbassert(0 && "Trying to create a type for an existing name");
2267     return type;
2268   }
2269 
2270   type = CreateRecordType(
2271       nullptr, OptionalClangModuleID(), lldb::eAccessPublic, type_name,
2272       llvm::to_underlying(clang::TagTypeKind::Struct), lldb::eLanguageTypeC);
2273   StartTagDeclarationDefinition(type);
2274   for (const auto &field : type_fields)
2275     AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic,
2276                          0);
2277   if (packed)
2278     SetIsPacked(type);
2279   CompleteTagDeclarationDefinition(type);
2280   return type;
2281 }
2282 
2283 CompilerType TypeSystemClang::GetOrCreateStructForIdentifier(
2284     llvm::StringRef type_name,
2285     const std::initializer_list<std::pair<const char *, CompilerType>>
2286         &type_fields,
2287     bool packed) {
2288   CompilerType type;
2289   if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid())
2290     return type;
2291 
2292   return CreateStructForIdentifier(type_name, type_fields, packed);
2293 }
2294 
2295 #pragma mark Enumeration Types
2296 
2297 CompilerType TypeSystemClang::CreateEnumerationType(
2298     llvm::StringRef name, clang::DeclContext *decl_ctx,
2299     OptionalClangModuleID owning_module, const Declaration &decl,
2300     const CompilerType &integer_clang_type, bool is_scoped) {
2301   // TODO: Do something intelligent with the Declaration object passed in
2302   // like maybe filling in the SourceLocation with it...
2303   ASTContext &ast = getASTContext();
2304 
2305   // TODO: ask about these...
2306   //    const bool IsFixed = false;
2307   EnumDecl *enum_decl = EnumDecl::CreateDeserialized(ast, GlobalDeclID());
2308   enum_decl->setDeclContext(decl_ctx);
2309   if (!name.empty())
2310     enum_decl->setDeclName(&ast.Idents.get(name));
2311   enum_decl->setScoped(is_scoped);
2312   enum_decl->setScopedUsingClassTag(is_scoped);
2313   enum_decl->setFixed(false);
2314   SetOwningModule(enum_decl, owning_module);
2315   if (decl_ctx)
2316     decl_ctx->addDecl(enum_decl);
2317 
2318   // TODO: check if we should be setting the promotion type too?
2319   enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type));
2320 
2321   enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
2322 
2323   return GetType(ast.getTagDeclType(enum_decl));
2324 }
2325 
2326 CompilerType TypeSystemClang::GetIntTypeFromBitSize(size_t bit_size,
2327                                                     bool is_signed) {
2328   clang::ASTContext &ast = getASTContext();
2329 
2330   if (!ast.VoidPtrTy)
2331     return {};
2332 
2333   if (is_signed) {
2334     if (bit_size == ast.getTypeSize(ast.SignedCharTy))
2335       return GetType(ast.SignedCharTy);
2336 
2337     if (bit_size == ast.getTypeSize(ast.ShortTy))
2338       return GetType(ast.ShortTy);
2339 
2340     if (bit_size == ast.getTypeSize(ast.IntTy))
2341       return GetType(ast.IntTy);
2342 
2343     if (bit_size == ast.getTypeSize(ast.LongTy))
2344       return GetType(ast.LongTy);
2345 
2346     if (bit_size == ast.getTypeSize(ast.LongLongTy))
2347       return GetType(ast.LongLongTy);
2348 
2349     if (bit_size == ast.getTypeSize(ast.Int128Ty))
2350       return GetType(ast.Int128Ty);
2351   } else {
2352     if (bit_size == ast.getTypeSize(ast.UnsignedCharTy))
2353       return GetType(ast.UnsignedCharTy);
2354 
2355     if (bit_size == ast.getTypeSize(ast.UnsignedShortTy))
2356       return GetType(ast.UnsignedShortTy);
2357 
2358     if (bit_size == ast.getTypeSize(ast.UnsignedIntTy))
2359       return GetType(ast.UnsignedIntTy);
2360 
2361     if (bit_size == ast.getTypeSize(ast.UnsignedLongTy))
2362       return GetType(ast.UnsignedLongTy);
2363 
2364     if (bit_size == ast.getTypeSize(ast.UnsignedLongLongTy))
2365       return GetType(ast.UnsignedLongLongTy);
2366 
2367     if (bit_size == ast.getTypeSize(ast.UnsignedInt128Ty))
2368       return GetType(ast.UnsignedInt128Ty);
2369   }
2370   return CompilerType();
2371 }
2372 
2373 CompilerType TypeSystemClang::GetPointerSizedIntType(bool is_signed) {
2374   if (!getASTContext().VoidPtrTy)
2375     return {};
2376 
2377   return GetIntTypeFromBitSize(
2378       getASTContext().getTypeSize(getASTContext().VoidPtrTy), is_signed);
2379 }
2380 
2381 void TypeSystemClang::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) {
2382   if (decl_ctx) {
2383     DumpDeclContextHiearchy(decl_ctx->getParent());
2384 
2385     clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl_ctx);
2386     if (named_decl) {
2387       printf("%20s: %s\n", decl_ctx->getDeclKindName(),
2388              named_decl->getDeclName().getAsString().c_str());
2389     } else {
2390       printf("%20s\n", decl_ctx->getDeclKindName());
2391     }
2392   }
2393 }
2394 
2395 void TypeSystemClang::DumpDeclHiearchy(clang::Decl *decl) {
2396   if (decl == nullptr)
2397     return;
2398   DumpDeclContextHiearchy(decl->getDeclContext());
2399 
2400   clang::RecordDecl *record_decl = llvm::dyn_cast<clang::RecordDecl>(decl);
2401   if (record_decl) {
2402     printf("%20s: %s%s\n", decl->getDeclKindName(),
2403            record_decl->getDeclName().getAsString().c_str(),
2404            record_decl->isInjectedClassName() ? " (injected class name)" : "");
2405 
2406   } else {
2407     clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl);
2408     if (named_decl) {
2409       printf("%20s: %s\n", decl->getDeclKindName(),
2410              named_decl->getDeclName().getAsString().c_str());
2411     } else {
2412       printf("%20s\n", decl->getDeclKindName());
2413     }
2414   }
2415 }
2416 
2417 bool TypeSystemClang::GetCompleteDecl(clang::ASTContext *ast,
2418                                       clang::Decl *decl) {
2419   if (!decl)
2420     return false;
2421 
2422   ExternalASTSource *ast_source = ast->getExternalSource();
2423 
2424   if (!ast_source)
2425     return false;
2426 
2427   if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) {
2428     if (tag_decl->isCompleteDefinition())
2429       return true;
2430 
2431     if (!tag_decl->hasExternalLexicalStorage())
2432       return false;
2433 
2434     ast_source->CompleteType(tag_decl);
2435 
2436     return !tag_decl->getTypeForDecl()->isIncompleteType();
2437   } else if (clang::ObjCInterfaceDecl *objc_interface_decl =
2438                  llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) {
2439     if (objc_interface_decl->getDefinition())
2440       return true;
2441 
2442     if (!objc_interface_decl->hasExternalLexicalStorage())
2443       return false;
2444 
2445     ast_source->CompleteType(objc_interface_decl);
2446 
2447     return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
2448   } else {
2449     return false;
2450   }
2451 }
2452 
2453 void TypeSystemClang::SetMetadataAsUserID(const clang::Decl *decl,
2454                                           user_id_t user_id) {
2455   ClangASTMetadata meta_data;
2456   meta_data.SetUserID(user_id);
2457   SetMetadata(decl, meta_data);
2458 }
2459 
2460 void TypeSystemClang::SetMetadataAsUserID(const clang::Type *type,
2461                                           user_id_t user_id) {
2462   ClangASTMetadata meta_data;
2463   meta_data.SetUserID(user_id);
2464   SetMetadata(type, meta_data);
2465 }
2466 
2467 void TypeSystemClang::SetMetadata(const clang::Decl *object,
2468                                   ClangASTMetadata metadata) {
2469   m_decl_metadata[object] = metadata;
2470 }
2471 
2472 void TypeSystemClang::SetMetadata(const clang::Type *object,
2473                                   ClangASTMetadata metadata) {
2474   m_type_metadata[object] = metadata;
2475 }
2476 
2477 std::optional<ClangASTMetadata>
2478 TypeSystemClang::GetMetadata(const clang::Decl *object) {
2479   auto It = m_decl_metadata.find(object);
2480   if (It != m_decl_metadata.end())
2481     return It->second;
2482 
2483   return std::nullopt;
2484 }
2485 
2486 std::optional<ClangASTMetadata>
2487 TypeSystemClang::GetMetadata(const clang::Type *object) {
2488   auto It = m_type_metadata.find(object);
2489   if (It != m_type_metadata.end())
2490     return It->second;
2491 
2492   return std::nullopt;
2493 }
2494 
2495 void TypeSystemClang::SetCXXRecordDeclAccess(const clang::CXXRecordDecl *object,
2496                                              clang::AccessSpecifier access) {
2497   if (access == clang::AccessSpecifier::AS_none)
2498     m_cxx_record_decl_access.erase(object);
2499   else
2500     m_cxx_record_decl_access[object] = access;
2501 }
2502 
2503 clang::AccessSpecifier
2504 TypeSystemClang::GetCXXRecordDeclAccess(const clang::CXXRecordDecl *object) {
2505   auto It = m_cxx_record_decl_access.find(object);
2506   if (It != m_cxx_record_decl_access.end())
2507     return It->second;
2508   return clang::AccessSpecifier::AS_none;
2509 }
2510 
2511 clang::DeclContext *
2512 TypeSystemClang::GetDeclContextForType(const CompilerType &type) {
2513   return GetDeclContextForType(ClangUtil::GetQualType(type));
2514 }
2515 
2516 CompilerDeclContext
2517 TypeSystemClang::GetCompilerDeclContextForType(const CompilerType &type) {
2518   if (auto *decl_context = GetDeclContextForType(type))
2519     return CreateDeclContext(decl_context);
2520   return CompilerDeclContext();
2521 }
2522 
2523 /// Aggressively desugar the provided type, skipping past various kinds of
2524 /// syntactic sugar and other constructs one typically wants to ignore.
2525 /// The \p mask argument allows one to skip certain kinds of simplifications,
2526 /// when one wishes to handle a certain kind of type directly.
2527 static QualType
2528 RemoveWrappingTypes(QualType type, ArrayRef<clang::Type::TypeClass> mask = {}) {
2529   while (true) {
2530     if (find(mask, type->getTypeClass()) != mask.end())
2531       return type;
2532     switch (type->getTypeClass()) {
2533     // This is not fully correct as _Atomic is more than sugar, but it is
2534     // sufficient for the purposes we care about.
2535     case clang::Type::Atomic:
2536       type = cast<clang::AtomicType>(type)->getValueType();
2537       break;
2538     case clang::Type::Auto:
2539     case clang::Type::Decltype:
2540     case clang::Type::Elaborated:
2541     case clang::Type::Paren:
2542     case clang::Type::SubstTemplateTypeParm:
2543     case clang::Type::TemplateSpecialization:
2544     case clang::Type::Typedef:
2545     case clang::Type::TypeOf:
2546     case clang::Type::TypeOfExpr:
2547     case clang::Type::Using:
2548       type = type->getLocallyUnqualifiedSingleStepDesugaredType();
2549       break;
2550     default:
2551       return type;
2552     }
2553   }
2554 }
2555 
2556 clang::DeclContext *
2557 TypeSystemClang::GetDeclContextForType(clang::QualType type) {
2558   if (type.isNull())
2559     return nullptr;
2560 
2561   clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType());
2562   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2563   switch (type_class) {
2564   case clang::Type::ObjCInterface:
2565     return llvm::cast<clang::ObjCObjectType>(qual_type.getTypePtr())
2566         ->getInterface();
2567   case clang::Type::ObjCObjectPointer:
2568     return GetDeclContextForType(
2569         llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
2570             ->getPointeeType());
2571   case clang::Type::Record:
2572     return llvm::cast<clang::RecordType>(qual_type)->getDecl();
2573   case clang::Type::Enum:
2574     return llvm::cast<clang::EnumType>(qual_type)->getDecl();
2575   default:
2576     break;
2577   }
2578   // No DeclContext in this type...
2579   return nullptr;
2580 }
2581 
2582 /// Returns the clang::RecordType of the specified \ref qual_type. This
2583 /// function will try to complete the type if necessary (and allowed
2584 /// by the specified \ref allow_completion). If we fail to return a *complete*
2585 /// type, returns nullptr.
2586 static const clang::RecordType *GetCompleteRecordType(clang::ASTContext *ast,
2587                                                       clang::QualType qual_type,
2588                                                       bool allow_completion) {
2589   assert(qual_type->isRecordType());
2590 
2591   const auto *tag_type = llvm::cast<clang::RecordType>(qual_type.getTypePtr());
2592 
2593   clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2594 
2595   // RecordType with no way of completing it, return the plain
2596   // TagType.
2597   if (!cxx_record_decl || !cxx_record_decl->hasExternalLexicalStorage())
2598     return tag_type;
2599 
2600   const bool is_complete = cxx_record_decl->isCompleteDefinition();
2601   const bool fields_loaded =
2602       cxx_record_decl->hasLoadedFieldsFromExternalStorage();
2603 
2604   // Already completed this type, nothing to be done.
2605   if (is_complete && fields_loaded)
2606     return tag_type;
2607 
2608   if (!allow_completion)
2609     return nullptr;
2610 
2611   // Call the field_begin() accessor to for it to use the external source
2612   // to load the fields...
2613   //
2614   // TODO: if we need to complete the type but have no external source,
2615   // shouldn't we error out instead?
2616   clang::ExternalASTSource *external_ast_source = ast->getExternalSource();
2617   if (external_ast_source) {
2618     external_ast_source->CompleteType(cxx_record_decl);
2619     if (cxx_record_decl->isCompleteDefinition()) {
2620       cxx_record_decl->field_begin();
2621       cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
2622     }
2623   }
2624 
2625   return tag_type;
2626 }
2627 
2628 /// Returns the clang::EnumType of the specified \ref qual_type. This
2629 /// function will try to complete the type if necessary (and allowed
2630 /// by the specified \ref allow_completion). If we fail to return a *complete*
2631 /// type, returns nullptr.
2632 static const clang::EnumType *GetCompleteEnumType(clang::ASTContext *ast,
2633                                                   clang::QualType qual_type,
2634                                                   bool allow_completion) {
2635   assert(qual_type->isEnumeralType());
2636   assert(ast);
2637 
2638   const clang::EnumType *enum_type =
2639       llvm::cast<clang::EnumType>(qual_type.getTypePtr());
2640 
2641   auto *tag_decl = enum_type->getAsTagDecl();
2642   assert(tag_decl);
2643 
2644   // Already completed, nothing to be done.
2645   if (tag_decl->getDefinition())
2646     return enum_type;
2647 
2648   if (!allow_completion)
2649     return nullptr;
2650 
2651   // No definition but can't complete it, error out.
2652   if (!tag_decl->hasExternalLexicalStorage())
2653     return nullptr;
2654 
2655   // We can't complete the type without an external source.
2656   clang::ExternalASTSource *external_ast_source = ast->getExternalSource();
2657   if (!external_ast_source)
2658     return nullptr;
2659 
2660   external_ast_source->CompleteType(tag_decl);
2661   return enum_type;
2662 }
2663 
2664 /// Returns the clang::ObjCObjectType of the specified \ref qual_type. This
2665 /// function will try to complete the type if necessary (and allowed
2666 /// by the specified \ref allow_completion). If we fail to return a *complete*
2667 /// type, returns nullptr.
2668 static const clang::ObjCObjectType *
2669 GetCompleteObjCObjectType(clang::ASTContext *ast, QualType qual_type,
2670                           bool allow_completion) {
2671   assert(qual_type->isObjCObjectType());
2672   assert(ast);
2673 
2674   const clang::ObjCObjectType *objc_class_type =
2675       llvm::cast<clang::ObjCObjectType>(qual_type);
2676 
2677   clang::ObjCInterfaceDecl *class_interface_decl =
2678       objc_class_type->getInterface();
2679   // We currently can't complete objective C types through the newly added
2680   // ASTContext because it only supports TagDecl objects right now...
2681   if (!class_interface_decl)
2682     return objc_class_type;
2683 
2684   // Already complete, nothing to be done.
2685   if (class_interface_decl->getDefinition())
2686     return objc_class_type;
2687 
2688   if (!allow_completion)
2689     return nullptr;
2690 
2691   // No definition but can't complete it, error out.
2692   if (!class_interface_decl->hasExternalLexicalStorage())
2693     return nullptr;
2694 
2695   // We can't complete the type without an external source.
2696   clang::ExternalASTSource *external_ast_source = ast->getExternalSource();
2697   if (!external_ast_source)
2698     return nullptr;
2699 
2700   external_ast_source->CompleteType(class_interface_decl);
2701   return objc_class_type;
2702 }
2703 
2704 static bool GetCompleteQualType(clang::ASTContext *ast,
2705                                 clang::QualType qual_type,
2706                                 bool allow_completion = true) {
2707   qual_type = RemoveWrappingTypes(qual_type);
2708   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2709   switch (type_class) {
2710   case clang::Type::ConstantArray:
2711   case clang::Type::IncompleteArray:
2712   case clang::Type::VariableArray: {
2713     const clang::ArrayType *array_type =
2714         llvm::dyn_cast<clang::ArrayType>(qual_type.getTypePtr());
2715 
2716     if (array_type)
2717       return GetCompleteQualType(ast, array_type->getElementType(),
2718                                  allow_completion);
2719   } break;
2720   case clang::Type::Record: {
2721     if (const auto *RT =
2722             GetCompleteRecordType(ast, qual_type, allow_completion))
2723       return !RT->isIncompleteType();
2724 
2725     return false;
2726   } break;
2727 
2728   case clang::Type::Enum: {
2729     if (const auto *ET = GetCompleteEnumType(ast, qual_type, allow_completion))
2730       return !ET->isIncompleteType();
2731 
2732     return false;
2733   } break;
2734   case clang::Type::ObjCObject:
2735   case clang::Type::ObjCInterface: {
2736     if (const auto *OT =
2737             GetCompleteObjCObjectType(ast, qual_type, allow_completion))
2738       return !OT->isIncompleteType();
2739 
2740     return false;
2741   } break;
2742 
2743   case clang::Type::Attributed:
2744     return GetCompleteQualType(
2745         ast, llvm::cast<clang::AttributedType>(qual_type)->getModifiedType(),
2746         allow_completion);
2747 
2748   case clang::Type::MemberPointer:
2749     // MS C++ ABI requires type of the class to be complete of which the pointee
2750     // is a member.
2751     if (ast->getTargetInfo().getCXXABI().isMicrosoft()) {
2752       auto *MPT = qual_type.getTypePtr()->castAs<clang::MemberPointerType>();
2753       if (MPT->getClass()->isRecordType())
2754         GetCompleteRecordType(ast, clang::QualType(MPT->getClass(), 0),
2755                               allow_completion);
2756 
2757       return !qual_type.getTypePtr()->isIncompleteType();
2758     }
2759     break;
2760 
2761   default:
2762     break;
2763   }
2764 
2765   return true;
2766 }
2767 
2768 static clang::ObjCIvarDecl::AccessControl
2769 ConvertAccessTypeToObjCIvarAccessControl(AccessType access) {
2770   switch (access) {
2771   case eAccessNone:
2772     return clang::ObjCIvarDecl::None;
2773   case eAccessPublic:
2774     return clang::ObjCIvarDecl::Public;
2775   case eAccessPrivate:
2776     return clang::ObjCIvarDecl::Private;
2777   case eAccessProtected:
2778     return clang::ObjCIvarDecl::Protected;
2779   case eAccessPackage:
2780     return clang::ObjCIvarDecl::Package;
2781   }
2782   return clang::ObjCIvarDecl::None;
2783 }
2784 
2785 // Tests
2786 
2787 #ifndef NDEBUG
2788 bool TypeSystemClang::Verify(lldb::opaque_compiler_type_t type) {
2789   return !type || llvm::isa<clang::Type>(GetQualType(type).getTypePtr());
2790 }
2791 #endif
2792 
2793 bool TypeSystemClang::IsAggregateType(lldb::opaque_compiler_type_t type) {
2794   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2795 
2796   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2797   switch (type_class) {
2798   case clang::Type::IncompleteArray:
2799   case clang::Type::VariableArray:
2800   case clang::Type::ConstantArray:
2801   case clang::Type::ExtVector:
2802   case clang::Type::Vector:
2803   case clang::Type::Record:
2804   case clang::Type::ObjCObject:
2805   case clang::Type::ObjCInterface:
2806     return true;
2807   default:
2808     break;
2809   }
2810   // The clang type does have a value
2811   return false;
2812 }
2813 
2814 bool TypeSystemClang::IsAnonymousType(lldb::opaque_compiler_type_t type) {
2815   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2816 
2817   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2818   switch (type_class) {
2819   case clang::Type::Record: {
2820     if (const clang::RecordType *record_type =
2821             llvm::dyn_cast_or_null<clang::RecordType>(
2822                 qual_type.getTypePtrOrNull())) {
2823       if (const clang::RecordDecl *record_decl = record_type->getDecl()) {
2824         return record_decl->isAnonymousStructOrUnion();
2825       }
2826     }
2827     break;
2828   }
2829   default:
2830     break;
2831   }
2832   // The clang type does have a value
2833   return false;
2834 }
2835 
2836 bool TypeSystemClang::IsArrayType(lldb::opaque_compiler_type_t type,
2837                                   CompilerType *element_type_ptr,
2838                                   uint64_t *size, bool *is_incomplete) {
2839   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2840 
2841   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2842   switch (type_class) {
2843   default:
2844     break;
2845 
2846   case clang::Type::ConstantArray:
2847     if (element_type_ptr)
2848       element_type_ptr->SetCompilerType(
2849           weak_from_this(), llvm::cast<clang::ConstantArrayType>(qual_type)
2850                                 ->getElementType()
2851                                 .getAsOpaquePtr());
2852     if (size)
2853       *size = llvm::cast<clang::ConstantArrayType>(qual_type)
2854                   ->getSize()
2855                   .getLimitedValue(ULLONG_MAX);
2856     if (is_incomplete)
2857       *is_incomplete = false;
2858     return true;
2859 
2860   case clang::Type::IncompleteArray:
2861     if (element_type_ptr)
2862       element_type_ptr->SetCompilerType(
2863           weak_from_this(), llvm::cast<clang::IncompleteArrayType>(qual_type)
2864                                 ->getElementType()
2865                                 .getAsOpaquePtr());
2866     if (size)
2867       *size = 0;
2868     if (is_incomplete)
2869       *is_incomplete = true;
2870     return true;
2871 
2872   case clang::Type::VariableArray:
2873     if (element_type_ptr)
2874       element_type_ptr->SetCompilerType(
2875           weak_from_this(), llvm::cast<clang::VariableArrayType>(qual_type)
2876                                 ->getElementType()
2877                                 .getAsOpaquePtr());
2878     if (size)
2879       *size = 0;
2880     if (is_incomplete)
2881       *is_incomplete = false;
2882     return true;
2883 
2884   case clang::Type::DependentSizedArray:
2885     if (element_type_ptr)
2886       element_type_ptr->SetCompilerType(
2887           weak_from_this(),
2888           llvm::cast<clang::DependentSizedArrayType>(qual_type)
2889               ->getElementType()
2890               .getAsOpaquePtr());
2891     if (size)
2892       *size = 0;
2893     if (is_incomplete)
2894       *is_incomplete = false;
2895     return true;
2896   }
2897   if (element_type_ptr)
2898     element_type_ptr->Clear();
2899   if (size)
2900     *size = 0;
2901   if (is_incomplete)
2902     *is_incomplete = false;
2903   return false;
2904 }
2905 
2906 bool TypeSystemClang::IsVectorType(lldb::opaque_compiler_type_t type,
2907                                    CompilerType *element_type, uint64_t *size) {
2908   clang::QualType qual_type(GetCanonicalQualType(type));
2909 
2910   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2911   switch (type_class) {
2912   case clang::Type::Vector: {
2913     const clang::VectorType *vector_type =
2914         qual_type->getAs<clang::VectorType>();
2915     if (vector_type) {
2916       if (size)
2917         *size = vector_type->getNumElements();
2918       if (element_type)
2919         *element_type = GetType(vector_type->getElementType());
2920     }
2921     return true;
2922   } break;
2923   case clang::Type::ExtVector: {
2924     const clang::ExtVectorType *ext_vector_type =
2925         qual_type->getAs<clang::ExtVectorType>();
2926     if (ext_vector_type) {
2927       if (size)
2928         *size = ext_vector_type->getNumElements();
2929       if (element_type)
2930         *element_type =
2931             CompilerType(weak_from_this(),
2932                          ext_vector_type->getElementType().getAsOpaquePtr());
2933     }
2934     return true;
2935   }
2936   default:
2937     break;
2938   }
2939   return false;
2940 }
2941 
2942 bool TypeSystemClang::IsRuntimeGeneratedType(
2943     lldb::opaque_compiler_type_t type) {
2944   clang::DeclContext *decl_ctx = GetDeclContextForType(GetQualType(type));
2945   if (!decl_ctx)
2946     return false;
2947 
2948   if (!llvm::isa<clang::ObjCInterfaceDecl>(decl_ctx))
2949     return false;
2950 
2951   clang::ObjCInterfaceDecl *result_iface_decl =
2952       llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl_ctx);
2953 
2954   std::optional<ClangASTMetadata> ast_metadata = GetMetadata(result_iface_decl);
2955   if (!ast_metadata)
2956     return false;
2957 
2958   return (ast_metadata->GetISAPtr() != 0);
2959 }
2960 
2961 bool TypeSystemClang::IsCharType(lldb::opaque_compiler_type_t type) {
2962   return GetQualType(type).getUnqualifiedType()->isCharType();
2963 }
2964 
2965 bool TypeSystemClang::IsCompleteType(lldb::opaque_compiler_type_t type) {
2966   // If the type hasn't been lazily completed yet, complete it now so that we
2967   // can give the caller an accurate answer whether the type actually has a
2968   // definition. Without completing the type now we would just tell the user
2969   // the current (internal) completeness state of the type and most users don't
2970   // care (or even know) about this behavior.
2971   const bool allow_completion = true;
2972   return GetCompleteQualType(&getASTContext(), GetQualType(type),
2973                              allow_completion);
2974 }
2975 
2976 bool TypeSystemClang::IsConst(lldb::opaque_compiler_type_t type) {
2977   return GetQualType(type).isConstQualified();
2978 }
2979 
2980 bool TypeSystemClang::IsCStringType(lldb::opaque_compiler_type_t type,
2981                                     uint32_t &length) {
2982   CompilerType pointee_or_element_clang_type;
2983   length = 0;
2984   Flags type_flags(GetTypeInfo(type, &pointee_or_element_clang_type));
2985 
2986   if (!pointee_or_element_clang_type.IsValid())
2987     return false;
2988 
2989   if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer)) {
2990     if (pointee_or_element_clang_type.IsCharType()) {
2991       if (type_flags.Test(eTypeIsArray)) {
2992         // We know the size of the array and it could be a C string since it is
2993         // an array of characters
2994         length = llvm::cast<clang::ConstantArrayType>(
2995                      GetCanonicalQualType(type).getTypePtr())
2996                      ->getSize()
2997                      .getLimitedValue();
2998       }
2999       return true;
3000     }
3001   }
3002   return false;
3003 }
3004 
3005 unsigned TypeSystemClang::GetPtrAuthKey(lldb::opaque_compiler_type_t type) {
3006   if (type) {
3007     clang::QualType qual_type(GetCanonicalQualType(type));
3008     if (auto pointer_auth = qual_type.getPointerAuth())
3009       return pointer_auth.getKey();
3010   }
3011   return 0;
3012 }
3013 
3014 unsigned
3015 TypeSystemClang::GetPtrAuthDiscriminator(lldb::opaque_compiler_type_t type) {
3016   if (type) {
3017     clang::QualType qual_type(GetCanonicalQualType(type));
3018     if (auto pointer_auth = qual_type.getPointerAuth())
3019       return pointer_auth.getExtraDiscriminator();
3020   }
3021   return 0;
3022 }
3023 
3024 bool TypeSystemClang::GetPtrAuthAddressDiversity(
3025     lldb::opaque_compiler_type_t type) {
3026   if (type) {
3027     clang::QualType qual_type(GetCanonicalQualType(type));
3028     if (auto pointer_auth = qual_type.getPointerAuth())
3029       return pointer_auth.isAddressDiscriminated();
3030   }
3031   return false;
3032 }
3033 
3034 bool TypeSystemClang::IsFunctionType(lldb::opaque_compiler_type_t type) {
3035   auto isFunctionType = [&](clang::QualType qual_type) {
3036     return qual_type->isFunctionType();
3037   };
3038 
3039   return IsTypeImpl(type, isFunctionType);
3040 }
3041 
3042 // Used to detect "Homogeneous Floating-point Aggregates"
3043 uint32_t
3044 TypeSystemClang::IsHomogeneousAggregate(lldb::opaque_compiler_type_t type,
3045                                         CompilerType *base_type_ptr) {
3046   if (!type)
3047     return 0;
3048 
3049   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
3050   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3051   switch (type_class) {
3052   case clang::Type::Record:
3053     if (GetCompleteType(type)) {
3054       const clang::CXXRecordDecl *cxx_record_decl =
3055           qual_type->getAsCXXRecordDecl();
3056       if (cxx_record_decl) {
3057         if (cxx_record_decl->getNumBases() || cxx_record_decl->isDynamicClass())
3058           return 0;
3059       }
3060       const clang::RecordType *record_type =
3061           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3062       if (record_type) {
3063         const clang::RecordDecl *record_decl = record_type->getDecl();
3064         if (record_decl) {
3065           // We are looking for a structure that contains only floating point
3066           // types
3067           clang::RecordDecl::field_iterator field_pos,
3068               field_end = record_decl->field_end();
3069           uint32_t num_fields = 0;
3070           bool is_hva = false;
3071           bool is_hfa = false;
3072           clang::QualType base_qual_type;
3073           uint64_t base_bitwidth = 0;
3074           for (field_pos = record_decl->field_begin(); field_pos != field_end;
3075                ++field_pos) {
3076             clang::QualType field_qual_type = field_pos->getType();
3077             uint64_t field_bitwidth = getASTContext().getTypeSize(qual_type);
3078             if (field_qual_type->isFloatingType()) {
3079               if (field_qual_type->isComplexType())
3080                 return 0;
3081               else {
3082                 if (num_fields == 0)
3083                   base_qual_type = field_qual_type;
3084                 else {
3085                   if (is_hva)
3086                     return 0;
3087                   is_hfa = true;
3088                   if (field_qual_type.getTypePtr() !=
3089                       base_qual_type.getTypePtr())
3090                     return 0;
3091                 }
3092               }
3093             } else if (field_qual_type->isVectorType() ||
3094                        field_qual_type->isExtVectorType()) {
3095               if (num_fields == 0) {
3096                 base_qual_type = field_qual_type;
3097                 base_bitwidth = field_bitwidth;
3098               } else {
3099                 if (is_hfa)
3100                   return 0;
3101                 is_hva = true;
3102                 if (base_bitwidth != field_bitwidth)
3103                   return 0;
3104                 if (field_qual_type.getTypePtr() != base_qual_type.getTypePtr())
3105                   return 0;
3106               }
3107             } else
3108               return 0;
3109             ++num_fields;
3110           }
3111           if (base_type_ptr)
3112             *base_type_ptr =
3113                 CompilerType(weak_from_this(), base_qual_type.getAsOpaquePtr());
3114           return num_fields;
3115         }
3116       }
3117     }
3118     break;
3119 
3120   default:
3121     break;
3122   }
3123   return 0;
3124 }
3125 
3126 size_t TypeSystemClang::GetNumberOfFunctionArguments(
3127     lldb::opaque_compiler_type_t type) {
3128   if (type) {
3129     clang::QualType qual_type(GetCanonicalQualType(type));
3130     const clang::FunctionProtoType *func =
3131         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3132     if (func)
3133       return func->getNumParams();
3134   }
3135   return 0;
3136 }
3137 
3138 CompilerType
3139 TypeSystemClang::GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,
3140                                             const size_t index) {
3141   if (type) {
3142     clang::QualType qual_type(GetQualType(type));
3143     const clang::FunctionProtoType *func =
3144         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3145     if (func) {
3146       if (index < func->getNumParams())
3147         return CompilerType(weak_from_this(), func->getParamType(index).getAsOpaquePtr());
3148     }
3149   }
3150   return CompilerType();
3151 }
3152 
3153 bool TypeSystemClang::IsTypeImpl(
3154     lldb::opaque_compiler_type_t type,
3155     llvm::function_ref<bool(clang::QualType)> predicate) const {
3156   if (type) {
3157     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3158 
3159     if (predicate(qual_type))
3160       return true;
3161 
3162     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3163     switch (type_class) {
3164     default:
3165       break;
3166 
3167     case clang::Type::LValueReference:
3168     case clang::Type::RValueReference: {
3169       const clang::ReferenceType *reference_type =
3170           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3171       if (reference_type)
3172         return IsTypeImpl(reference_type->getPointeeType().getAsOpaquePtr(), predicate);
3173     } break;
3174     }
3175   }
3176   return false;
3177 }
3178 
3179 bool TypeSystemClang::IsMemberFunctionPointerType(
3180     lldb::opaque_compiler_type_t type) {
3181   auto isMemberFunctionPointerType = [](clang::QualType qual_type) {
3182     return qual_type->isMemberFunctionPointerType();
3183   };
3184 
3185   return IsTypeImpl(type, isMemberFunctionPointerType);
3186 }
3187 
3188 bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
3189   auto isFunctionPointerType = [](clang::QualType qual_type) {
3190     return qual_type->isFunctionPointerType();
3191   };
3192 
3193   return IsTypeImpl(type, isFunctionPointerType);
3194 }
3195 
3196 bool TypeSystemClang::IsBlockPointerType(
3197     lldb::opaque_compiler_type_t type,
3198     CompilerType *function_pointer_type_ptr) {
3199   auto isBlockPointerType = [&](clang::QualType qual_type) {
3200     if (qual_type->isBlockPointerType()) {
3201       if (function_pointer_type_ptr) {
3202         const clang::BlockPointerType *block_pointer_type =
3203             qual_type->castAs<clang::BlockPointerType>();
3204         QualType pointee_type = block_pointer_type->getPointeeType();
3205         QualType function_pointer_type = m_ast_up->getPointerType(pointee_type);
3206         *function_pointer_type_ptr = CompilerType(
3207             weak_from_this(), function_pointer_type.getAsOpaquePtr());
3208       }
3209       return true;
3210     }
3211 
3212     return false;
3213   };
3214 
3215   return IsTypeImpl(type, isBlockPointerType);
3216 }
3217 
3218 bool TypeSystemClang::IsIntegerType(lldb::opaque_compiler_type_t type,
3219                                     bool &is_signed) {
3220   if (!type)
3221     return false;
3222 
3223   clang::QualType qual_type(GetCanonicalQualType(type));
3224   const clang::BuiltinType *builtin_type =
3225       llvm::dyn_cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3226 
3227   if (builtin_type) {
3228     if (builtin_type->isInteger()) {
3229       is_signed = builtin_type->isSignedInteger();
3230       return true;
3231     }
3232   }
3233 
3234   return false;
3235 }
3236 
3237 bool TypeSystemClang::IsEnumerationType(lldb::opaque_compiler_type_t type,
3238                                         bool &is_signed) {
3239   if (type) {
3240     const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3241         GetCanonicalQualType(type)->getCanonicalTypeInternal());
3242 
3243     if (enum_type) {
3244       IsIntegerType(enum_type->getDecl()->getIntegerType().getAsOpaquePtr(),
3245                     is_signed);
3246       return true;
3247     }
3248   }
3249 
3250   return false;
3251 }
3252 
3253 bool TypeSystemClang::IsScopedEnumerationType(
3254     lldb::opaque_compiler_type_t type) {
3255   if (type) {
3256     const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3257         GetCanonicalQualType(type)->getCanonicalTypeInternal());
3258 
3259     if (enum_type) {
3260       return enum_type->isScopedEnumeralType();
3261     }
3262   }
3263 
3264   return false;
3265 }
3266 
3267 bool TypeSystemClang::IsPointerType(lldb::opaque_compiler_type_t type,
3268                                     CompilerType *pointee_type) {
3269   if (type) {
3270     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3271     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3272     switch (type_class) {
3273     case clang::Type::Builtin:
3274       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3275       default:
3276         break;
3277       case clang::BuiltinType::ObjCId:
3278       case clang::BuiltinType::ObjCClass:
3279         return true;
3280       }
3281       return false;
3282     case clang::Type::ObjCObjectPointer:
3283       if (pointee_type)
3284         pointee_type->SetCompilerType(
3285             weak_from_this(),
3286             llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3287                 ->getPointeeType()
3288                 .getAsOpaquePtr());
3289       return true;
3290     case clang::Type::BlockPointer:
3291       if (pointee_type)
3292         pointee_type->SetCompilerType(
3293             weak_from_this(), llvm::cast<clang::BlockPointerType>(qual_type)
3294                                   ->getPointeeType()
3295                                   .getAsOpaquePtr());
3296       return true;
3297     case clang::Type::Pointer:
3298       if (pointee_type)
3299         pointee_type->SetCompilerType(weak_from_this(),
3300                                       llvm::cast<clang::PointerType>(qual_type)
3301                                           ->getPointeeType()
3302                                           .getAsOpaquePtr());
3303       return true;
3304     case clang::Type::MemberPointer:
3305       if (pointee_type)
3306         pointee_type->SetCompilerType(
3307             weak_from_this(), llvm::cast<clang::MemberPointerType>(qual_type)
3308                                   ->getPointeeType()
3309                                   .getAsOpaquePtr());
3310       return true;
3311     default:
3312       break;
3313     }
3314   }
3315   if (pointee_type)
3316     pointee_type->Clear();
3317   return false;
3318 }
3319 
3320 bool TypeSystemClang::IsPointerOrReferenceType(
3321     lldb::opaque_compiler_type_t type, CompilerType *pointee_type) {
3322   if (type) {
3323     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3324     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3325     switch (type_class) {
3326     case clang::Type::Builtin:
3327       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3328       default:
3329         break;
3330       case clang::BuiltinType::ObjCId:
3331       case clang::BuiltinType::ObjCClass:
3332         return true;
3333       }
3334       return false;
3335     case clang::Type::ObjCObjectPointer:
3336       if (pointee_type)
3337         pointee_type->SetCompilerType(
3338             weak_from_this(),
3339             llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3340                 ->getPointeeType()
3341                 .getAsOpaquePtr());
3342       return true;
3343     case clang::Type::BlockPointer:
3344       if (pointee_type)
3345         pointee_type->SetCompilerType(
3346             weak_from_this(), llvm::cast<clang::BlockPointerType>(qual_type)
3347                                   ->getPointeeType()
3348                                   .getAsOpaquePtr());
3349       return true;
3350     case clang::Type::Pointer:
3351       if (pointee_type)
3352         pointee_type->SetCompilerType(weak_from_this(),
3353                                       llvm::cast<clang::PointerType>(qual_type)
3354                                           ->getPointeeType()
3355                                           .getAsOpaquePtr());
3356       return true;
3357     case clang::Type::MemberPointer:
3358       if (pointee_type)
3359         pointee_type->SetCompilerType(
3360             weak_from_this(), llvm::cast<clang::MemberPointerType>(qual_type)
3361                                   ->getPointeeType()
3362                                   .getAsOpaquePtr());
3363       return true;
3364     case clang::Type::LValueReference:
3365       if (pointee_type)
3366         pointee_type->SetCompilerType(
3367             weak_from_this(), llvm::cast<clang::LValueReferenceType>(qual_type)
3368                                   ->desugar()
3369                                   .getAsOpaquePtr());
3370       return true;
3371     case clang::Type::RValueReference:
3372       if (pointee_type)
3373         pointee_type->SetCompilerType(
3374             weak_from_this(), llvm::cast<clang::RValueReferenceType>(qual_type)
3375                                   ->desugar()
3376                                   .getAsOpaquePtr());
3377       return true;
3378     default:
3379       break;
3380     }
3381   }
3382   if (pointee_type)
3383     pointee_type->Clear();
3384   return false;
3385 }
3386 
3387 bool TypeSystemClang::IsReferenceType(lldb::opaque_compiler_type_t type,
3388                                       CompilerType *pointee_type,
3389                                       bool *is_rvalue) {
3390   if (type) {
3391     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3392     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3393 
3394     switch (type_class) {
3395     case clang::Type::LValueReference:
3396       if (pointee_type)
3397         pointee_type->SetCompilerType(
3398             weak_from_this(), llvm::cast<clang::LValueReferenceType>(qual_type)
3399                                   ->desugar()
3400                                   .getAsOpaquePtr());
3401       if (is_rvalue)
3402         *is_rvalue = false;
3403       return true;
3404     case clang::Type::RValueReference:
3405       if (pointee_type)
3406         pointee_type->SetCompilerType(
3407             weak_from_this(), llvm::cast<clang::RValueReferenceType>(qual_type)
3408                                   ->desugar()
3409                                   .getAsOpaquePtr());
3410       if (is_rvalue)
3411         *is_rvalue = true;
3412       return true;
3413 
3414     default:
3415       break;
3416     }
3417   }
3418   if (pointee_type)
3419     pointee_type->Clear();
3420   return false;
3421 }
3422 
3423 bool TypeSystemClang::IsFloatingPointType(lldb::opaque_compiler_type_t type,
3424                                           uint32_t &count, bool &is_complex) {
3425   if (type) {
3426     clang::QualType qual_type(GetCanonicalQualType(type));
3427 
3428     if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(
3429             qual_type->getCanonicalTypeInternal())) {
3430       clang::BuiltinType::Kind kind = BT->getKind();
3431       if (kind >= clang::BuiltinType::Float &&
3432           kind <= clang::BuiltinType::LongDouble) {
3433         count = 1;
3434         is_complex = false;
3435         return true;
3436       }
3437     } else if (const clang::ComplexType *CT =
3438                    llvm::dyn_cast<clang::ComplexType>(
3439                        qual_type->getCanonicalTypeInternal())) {
3440       if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count,
3441                               is_complex)) {
3442         count = 2;
3443         is_complex = true;
3444         return true;
3445       }
3446     } else if (const clang::VectorType *VT = llvm::dyn_cast<clang::VectorType>(
3447                    qual_type->getCanonicalTypeInternal())) {
3448       if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count,
3449                               is_complex)) {
3450         count = VT->getNumElements();
3451         is_complex = false;
3452         return true;
3453       }
3454     }
3455   }
3456   count = 0;
3457   is_complex = false;
3458   return false;
3459 }
3460 
3461 bool TypeSystemClang::IsDefined(lldb::opaque_compiler_type_t type) {
3462   if (!type)
3463     return false;
3464 
3465   clang::QualType qual_type(GetQualType(type));
3466   const clang::TagType *tag_type =
3467       llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
3468   if (tag_type) {
3469     clang::TagDecl *tag_decl = tag_type->getDecl();
3470     if (tag_decl)
3471       return tag_decl->isCompleteDefinition();
3472     return false;
3473   } else {
3474     const clang::ObjCObjectType *objc_class_type =
3475         llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
3476     if (objc_class_type) {
3477       clang::ObjCInterfaceDecl *class_interface_decl =
3478           objc_class_type->getInterface();
3479       if (class_interface_decl)
3480         return class_interface_decl->getDefinition() != nullptr;
3481       return false;
3482     }
3483   }
3484   return true;
3485 }
3486 
3487 bool TypeSystemClang::IsObjCClassType(const CompilerType &type) {
3488   if (ClangUtil::IsClangType(type)) {
3489     clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3490 
3491     const clang::ObjCObjectPointerType *obj_pointer_type =
3492         llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3493 
3494     if (obj_pointer_type)
3495       return obj_pointer_type->isObjCClassType();
3496   }
3497   return false;
3498 }
3499 
3500 bool TypeSystemClang::IsObjCObjectOrInterfaceType(const CompilerType &type) {
3501   if (ClangUtil::IsClangType(type))
3502     return ClangUtil::GetCanonicalQualType(type)->isObjCObjectOrInterfaceType();
3503   return false;
3504 }
3505 
3506 bool TypeSystemClang::IsClassType(lldb::opaque_compiler_type_t type) {
3507   if (!type)
3508     return false;
3509   clang::QualType qual_type(GetCanonicalQualType(type));
3510   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3511   return (type_class == clang::Type::Record);
3512 }
3513 
3514 bool TypeSystemClang::IsEnumType(lldb::opaque_compiler_type_t type) {
3515   if (!type)
3516     return false;
3517   clang::QualType qual_type(GetCanonicalQualType(type));
3518   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3519   return (type_class == clang::Type::Enum);
3520 }
3521 
3522 bool TypeSystemClang::IsPolymorphicClass(lldb::opaque_compiler_type_t type) {
3523   if (type) {
3524     clang::QualType qual_type(GetCanonicalQualType(type));
3525     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3526     switch (type_class) {
3527     case clang::Type::Record:
3528       if (GetCompleteType(type)) {
3529         const clang::RecordType *record_type =
3530             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3531         const clang::RecordDecl *record_decl = record_type->getDecl();
3532         if (record_decl) {
3533           const clang::CXXRecordDecl *cxx_record_decl =
3534               llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
3535           if (cxx_record_decl) {
3536             // We can't just call is isPolymorphic() here because that just
3537             // means the current class has virtual functions, it doesn't check
3538             // if any inherited classes have virtual functions. The doc string
3539             // in SBType::IsPolymorphicClass() says it is looking for both
3540             // if the class has virtual methods or if any bases do, so this
3541             // should be more correct.
3542             return cxx_record_decl->isDynamicClass();
3543           }
3544         }
3545       }
3546       break;
3547 
3548     default:
3549       break;
3550     }
3551   }
3552   return false;
3553 }
3554 
3555 bool TypeSystemClang::IsPossibleDynamicType(lldb::opaque_compiler_type_t type,
3556                                             CompilerType *dynamic_pointee_type,
3557                                             bool check_cplusplus,
3558                                             bool check_objc) {
3559   clang::QualType pointee_qual_type;
3560   if (type) {
3561     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3562     bool success = false;
3563     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3564     switch (type_class) {
3565     case clang::Type::Builtin:
3566       if (check_objc &&
3567           llvm::cast<clang::BuiltinType>(qual_type)->getKind() ==
3568               clang::BuiltinType::ObjCId) {
3569         if (dynamic_pointee_type)
3570           dynamic_pointee_type->SetCompilerType(weak_from_this(), type);
3571         return true;
3572       }
3573       break;
3574 
3575     case clang::Type::ObjCObjectPointer:
3576       if (check_objc) {
3577         if (const auto *objc_pointee_type =
3578                 qual_type->getPointeeType().getTypePtrOrNull()) {
3579           if (const auto *objc_object_type =
3580                   llvm::dyn_cast_or_null<clang::ObjCObjectType>(
3581                       objc_pointee_type)) {
3582             if (objc_object_type->isObjCClass())
3583               return false;
3584           }
3585         }
3586         if (dynamic_pointee_type)
3587           dynamic_pointee_type->SetCompilerType(
3588               weak_from_this(),
3589               llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3590                   ->getPointeeType()
3591                   .getAsOpaquePtr());
3592         return true;
3593       }
3594       break;
3595 
3596     case clang::Type::Pointer:
3597       pointee_qual_type =
3598           llvm::cast<clang::PointerType>(qual_type)->getPointeeType();
3599       success = true;
3600       break;
3601 
3602     case clang::Type::LValueReference:
3603     case clang::Type::RValueReference:
3604       pointee_qual_type =
3605           llvm::cast<clang::ReferenceType>(qual_type)->getPointeeType();
3606       success = true;
3607       break;
3608 
3609     default:
3610       break;
3611     }
3612 
3613     if (success) {
3614       // Check to make sure what we are pointing too is a possible dynamic C++
3615       // type We currently accept any "void *" (in case we have a class that
3616       // has been watered down to an opaque pointer) and virtual C++ classes.
3617       const clang::Type::TypeClass pointee_type_class =
3618           pointee_qual_type.getCanonicalType()->getTypeClass();
3619       switch (pointee_type_class) {
3620       case clang::Type::Builtin:
3621         switch (llvm::cast<clang::BuiltinType>(pointee_qual_type)->getKind()) {
3622         case clang::BuiltinType::UnknownAny:
3623         case clang::BuiltinType::Void:
3624           if (dynamic_pointee_type)
3625             dynamic_pointee_type->SetCompilerType(
3626                 weak_from_this(), pointee_qual_type.getAsOpaquePtr());
3627           return true;
3628         default:
3629           break;
3630         }
3631         break;
3632 
3633       case clang::Type::Record:
3634         if (check_cplusplus) {
3635           clang::CXXRecordDecl *cxx_record_decl =
3636               pointee_qual_type->getAsCXXRecordDecl();
3637           if (cxx_record_decl) {
3638             bool is_complete = cxx_record_decl->isCompleteDefinition();
3639 
3640             if (is_complete)
3641               success = cxx_record_decl->isDynamicClass();
3642             else {
3643               if (std::optional<ClangASTMetadata> metadata =
3644                       GetMetadata(cxx_record_decl))
3645                 success = metadata->GetIsDynamicCXXType();
3646               else {
3647                 is_complete = GetType(pointee_qual_type).GetCompleteType();
3648                 if (is_complete)
3649                   success = cxx_record_decl->isDynamicClass();
3650                 else
3651                   success = false;
3652               }
3653             }
3654 
3655             if (success) {
3656               if (dynamic_pointee_type)
3657                 dynamic_pointee_type->SetCompilerType(
3658                     weak_from_this(), pointee_qual_type.getAsOpaquePtr());
3659               return true;
3660             }
3661           }
3662         }
3663         break;
3664 
3665       case clang::Type::ObjCObject:
3666       case clang::Type::ObjCInterface:
3667         if (check_objc) {
3668           if (dynamic_pointee_type)
3669             dynamic_pointee_type->SetCompilerType(
3670                 weak_from_this(), pointee_qual_type.getAsOpaquePtr());
3671           return true;
3672         }
3673         break;
3674 
3675       default:
3676         break;
3677       }
3678     }
3679   }
3680   if (dynamic_pointee_type)
3681     dynamic_pointee_type->Clear();
3682   return false;
3683 }
3684 
3685 bool TypeSystemClang::IsScalarType(lldb::opaque_compiler_type_t type) {
3686   if (!type)
3687     return false;
3688 
3689   return (GetTypeInfo(type, nullptr) & eTypeIsScalar) != 0;
3690 }
3691 
3692 bool TypeSystemClang::IsTypedefType(lldb::opaque_compiler_type_t type) {
3693   if (!type)
3694     return false;
3695   return RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef})
3696              ->getTypeClass() == clang::Type::Typedef;
3697 }
3698 
3699 bool TypeSystemClang::IsVoidType(lldb::opaque_compiler_type_t type) {
3700   if (!type)
3701     return false;
3702   return GetCanonicalQualType(type)->isVoidType();
3703 }
3704 
3705 bool TypeSystemClang::CanPassInRegisters(const CompilerType &type) {
3706   if (auto *record_decl =
3707       TypeSystemClang::GetAsRecordDecl(type)) {
3708     return record_decl->canPassInRegisters();
3709   }
3710   return false;
3711 }
3712 
3713 bool TypeSystemClang::SupportsLanguage(lldb::LanguageType language) {
3714   return TypeSystemClangSupportsLanguage(language);
3715 }
3716 
3717 std::optional<std::string>
3718 TypeSystemClang::GetCXXClassName(const CompilerType &type) {
3719   if (!type)
3720     return std::nullopt;
3721 
3722   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3723   if (qual_type.isNull())
3724     return std::nullopt;
3725 
3726   clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3727   if (!cxx_record_decl)
3728     return std::nullopt;
3729 
3730   return std::string(cxx_record_decl->getIdentifier()->getNameStart());
3731 }
3732 
3733 bool TypeSystemClang::IsCXXClassType(const CompilerType &type) {
3734   if (!type)
3735     return false;
3736 
3737   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3738   return !qual_type.isNull() && qual_type->getAsCXXRecordDecl() != nullptr;
3739 }
3740 
3741 bool TypeSystemClang::IsBeingDefined(lldb::opaque_compiler_type_t type) {
3742   if (!type)
3743     return false;
3744   clang::QualType qual_type(GetCanonicalQualType(type));
3745   const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type);
3746   if (tag_type)
3747     return tag_type->isBeingDefined();
3748   return false;
3749 }
3750 
3751 bool TypeSystemClang::IsObjCObjectPointerType(const CompilerType &type,
3752                                               CompilerType *class_type_ptr) {
3753   if (!ClangUtil::IsClangType(type))
3754     return false;
3755 
3756   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3757 
3758   if (!qual_type.isNull() && qual_type->isObjCObjectPointerType()) {
3759     if (class_type_ptr) {
3760       if (!qual_type->isObjCClassType() && !qual_type->isObjCIdType()) {
3761         const clang::ObjCObjectPointerType *obj_pointer_type =
3762             llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3763         if (obj_pointer_type == nullptr)
3764           class_type_ptr->Clear();
3765         else
3766           class_type_ptr->SetCompilerType(
3767               type.GetTypeSystem(),
3768               clang::QualType(obj_pointer_type->getInterfaceType(), 0)
3769                   .getAsOpaquePtr());
3770       }
3771     }
3772     return true;
3773   }
3774   if (class_type_ptr)
3775     class_type_ptr->Clear();
3776   return false;
3777 }
3778 
3779 // Type Completion
3780 
3781 bool TypeSystemClang::GetCompleteType(lldb::opaque_compiler_type_t type) {
3782   if (!type)
3783     return false;
3784   const bool allow_completion = true;
3785   return GetCompleteQualType(&getASTContext(), GetQualType(type),
3786                              allow_completion);
3787 }
3788 
3789 ConstString TypeSystemClang::GetTypeName(lldb::opaque_compiler_type_t type,
3790                                          bool base_only) {
3791   if (!type)
3792     return ConstString();
3793 
3794   clang::QualType qual_type(GetQualType(type));
3795 
3796   // Remove certain type sugar from the name. Sugar such as elaborated types
3797   // or template types which only serve to improve diagnostics shouldn't
3798   // act as their own types from the user's perspective (e.g., formatter
3799   // shouldn't format a variable differently depending on how the ser has
3800   // specified the type. '::Type' and 'Type' should behave the same).
3801   // Typedefs and atomic derived types are not removed as they are actually
3802   // useful for identifiying specific types.
3803   qual_type = RemoveWrappingTypes(qual_type,
3804                                   {clang::Type::Typedef, clang::Type::Atomic});
3805 
3806   // For a typedef just return the qualified name.
3807   if (const auto *typedef_type = qual_type->getAs<clang::TypedefType>()) {
3808     const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
3809     return ConstString(GetTypeNameForDecl(typedef_decl));
3810   }
3811 
3812   // For consistency, this follows the same code path that clang uses to emit
3813   // debug info. This also handles when we don't want any scopes preceding the
3814   // name.
3815   if (auto *named_decl = qual_type->getAsTagDecl())
3816     return ConstString(GetTypeNameForDecl(named_decl, !base_only));
3817 
3818   return ConstString(qual_type.getAsString(GetTypePrintingPolicy()));
3819 }
3820 
3821 ConstString
3822 TypeSystemClang::GetDisplayTypeName(lldb::opaque_compiler_type_t type) {
3823   if (!type)
3824     return ConstString();
3825 
3826   clang::QualType qual_type(GetQualType(type));
3827   clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy());
3828   printing_policy.SuppressTagKeyword = true;
3829   printing_policy.SuppressScope = false;
3830   printing_policy.SuppressUnwrittenScope = true;
3831   printing_policy.SuppressInlineNamespace = true;
3832   return ConstString(qual_type.getAsString(printing_policy));
3833 }
3834 
3835 uint32_t
3836 TypeSystemClang::GetTypeInfo(lldb::opaque_compiler_type_t type,
3837                              CompilerType *pointee_or_element_clang_type) {
3838   if (!type)
3839     return 0;
3840 
3841   if (pointee_or_element_clang_type)
3842     pointee_or_element_clang_type->Clear();
3843 
3844   clang::QualType qual_type =
3845       RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
3846 
3847   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3848   switch (type_class) {
3849   case clang::Type::Attributed:
3850     return GetTypeInfo(qual_type->castAs<clang::AttributedType>()
3851                            ->getModifiedType()
3852                            .getAsOpaquePtr(),
3853                        pointee_or_element_clang_type);
3854   case clang::Type::Builtin: {
3855     const clang::BuiltinType *builtin_type =
3856         llvm::cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3857 
3858     uint32_t builtin_type_flags = eTypeIsBuiltIn | eTypeHasValue;
3859     switch (builtin_type->getKind()) {
3860     case clang::BuiltinType::ObjCId:
3861     case clang::BuiltinType::ObjCClass:
3862       if (pointee_or_element_clang_type)
3863         pointee_or_element_clang_type->SetCompilerType(
3864             weak_from_this(),
3865             getASTContext().ObjCBuiltinClassTy.getAsOpaquePtr());
3866       builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3867       break;
3868 
3869     case clang::BuiltinType::ObjCSel:
3870       if (pointee_or_element_clang_type)
3871         pointee_or_element_clang_type->SetCompilerType(
3872             weak_from_this(), getASTContext().CharTy.getAsOpaquePtr());
3873       builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3874       break;
3875 
3876     case clang::BuiltinType::Bool:
3877     case clang::BuiltinType::Char_U:
3878     case clang::BuiltinType::UChar:
3879     case clang::BuiltinType::WChar_U:
3880     case clang::BuiltinType::Char16:
3881     case clang::BuiltinType::Char32:
3882     case clang::BuiltinType::UShort:
3883     case clang::BuiltinType::UInt:
3884     case clang::BuiltinType::ULong:
3885     case clang::BuiltinType::ULongLong:
3886     case clang::BuiltinType::UInt128:
3887     case clang::BuiltinType::Char_S:
3888     case clang::BuiltinType::SChar:
3889     case clang::BuiltinType::WChar_S:
3890     case clang::BuiltinType::Short:
3891     case clang::BuiltinType::Int:
3892     case clang::BuiltinType::Long:
3893     case clang::BuiltinType::LongLong:
3894     case clang::BuiltinType::Int128:
3895     case clang::BuiltinType::Float:
3896     case clang::BuiltinType::Double:
3897     case clang::BuiltinType::LongDouble:
3898       builtin_type_flags |= eTypeIsScalar;
3899       if (builtin_type->isInteger()) {
3900         builtin_type_flags |= eTypeIsInteger;
3901         if (builtin_type->isSignedInteger())
3902           builtin_type_flags |= eTypeIsSigned;
3903       } else if (builtin_type->isFloatingPoint())
3904         builtin_type_flags |= eTypeIsFloat;
3905       break;
3906     default:
3907       break;
3908     }
3909     return builtin_type_flags;
3910   }
3911 
3912   case clang::Type::BlockPointer:
3913     if (pointee_or_element_clang_type)
3914       pointee_or_element_clang_type->SetCompilerType(
3915           weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr());
3916     return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
3917 
3918   case clang::Type::Complex: {
3919     uint32_t complex_type_flags =
3920         eTypeIsBuiltIn | eTypeHasValue | eTypeIsComplex;
3921     const clang::ComplexType *complex_type = llvm::dyn_cast<clang::ComplexType>(
3922         qual_type->getCanonicalTypeInternal());
3923     if (complex_type) {
3924       clang::QualType complex_element_type(complex_type->getElementType());
3925       if (complex_element_type->isIntegerType())
3926         complex_type_flags |= eTypeIsFloat;
3927       else if (complex_element_type->isFloatingType())
3928         complex_type_flags |= eTypeIsInteger;
3929     }
3930     return complex_type_flags;
3931   } break;
3932 
3933   case clang::Type::ConstantArray:
3934   case clang::Type::DependentSizedArray:
3935   case clang::Type::IncompleteArray:
3936   case clang::Type::VariableArray:
3937     if (pointee_or_element_clang_type)
3938       pointee_or_element_clang_type->SetCompilerType(
3939           weak_from_this(), llvm::cast<clang::ArrayType>(qual_type.getTypePtr())
3940                                 ->getElementType()
3941                                 .getAsOpaquePtr());
3942     return eTypeHasChildren | eTypeIsArray;
3943 
3944   case clang::Type::DependentName:
3945     return 0;
3946   case clang::Type::DependentSizedExtVector:
3947     return eTypeHasChildren | eTypeIsVector;
3948   case clang::Type::DependentTemplateSpecialization:
3949     return eTypeIsTemplate;
3950 
3951   case clang::Type::Enum:
3952     if (pointee_or_element_clang_type)
3953       pointee_or_element_clang_type->SetCompilerType(
3954           weak_from_this(), llvm::cast<clang::EnumType>(qual_type)
3955                                 ->getDecl()
3956                                 ->getIntegerType()
3957                                 .getAsOpaquePtr());
3958     return eTypeIsEnumeration | eTypeHasValue;
3959 
3960   case clang::Type::FunctionProto:
3961     return eTypeIsFuncPrototype | eTypeHasValue;
3962   case clang::Type::FunctionNoProto:
3963     return eTypeIsFuncPrototype | eTypeHasValue;
3964   case clang::Type::InjectedClassName:
3965     return 0;
3966 
3967   case clang::Type::LValueReference:
3968   case clang::Type::RValueReference:
3969     if (pointee_or_element_clang_type)
3970       pointee_or_element_clang_type->SetCompilerType(
3971           weak_from_this(),
3972           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr())
3973               ->getPointeeType()
3974               .getAsOpaquePtr());
3975     return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
3976 
3977   case clang::Type::MemberPointer:
3978     return eTypeIsPointer | eTypeIsMember | eTypeHasValue;
3979 
3980   case clang::Type::ObjCObjectPointer:
3981     if (pointee_or_element_clang_type)
3982       pointee_or_element_clang_type->SetCompilerType(
3983           weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr());
3984     return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer |
3985            eTypeHasValue;
3986 
3987   case clang::Type::ObjCObject:
3988     return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3989   case clang::Type::ObjCInterface:
3990     return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3991 
3992   case clang::Type::Pointer:
3993     if (pointee_or_element_clang_type)
3994       pointee_or_element_clang_type->SetCompilerType(
3995           weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr());
3996     return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
3997 
3998   case clang::Type::Record:
3999     if (qual_type->getAsCXXRecordDecl())
4000       return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
4001     else
4002       return eTypeHasChildren | eTypeIsStructUnion;
4003     break;
4004   case clang::Type::SubstTemplateTypeParm:
4005     return eTypeIsTemplate;
4006   case clang::Type::TemplateTypeParm:
4007     return eTypeIsTemplate;
4008   case clang::Type::TemplateSpecialization:
4009     return eTypeIsTemplate;
4010 
4011   case clang::Type::Typedef:
4012     return eTypeIsTypedef | GetType(llvm::cast<clang::TypedefType>(qual_type)
4013                                         ->getDecl()
4014                                         ->getUnderlyingType())
4015                                 .GetTypeInfo(pointee_or_element_clang_type);
4016   case clang::Type::UnresolvedUsing:
4017     return 0;
4018 
4019   case clang::Type::ExtVector:
4020   case clang::Type::Vector: {
4021     uint32_t vector_type_flags = eTypeHasChildren | eTypeIsVector;
4022     const clang::VectorType *vector_type = llvm::dyn_cast<clang::VectorType>(
4023         qual_type->getCanonicalTypeInternal());
4024     if (vector_type) {
4025       if (vector_type->isIntegerType())
4026         vector_type_flags |= eTypeIsFloat;
4027       else if (vector_type->isFloatingType())
4028         vector_type_flags |= eTypeIsInteger;
4029     }
4030     return vector_type_flags;
4031   }
4032   default:
4033     return 0;
4034   }
4035   return 0;
4036 }
4037 
4038 lldb::LanguageType
4039 TypeSystemClang::GetMinimumLanguage(lldb::opaque_compiler_type_t type) {
4040   if (!type)
4041     return lldb::eLanguageTypeC;
4042 
4043   // If the type is a reference, then resolve it to what it refers to first:
4044   clang::QualType qual_type(GetCanonicalQualType(type).getNonReferenceType());
4045   if (qual_type->isAnyPointerType()) {
4046     if (qual_type->isObjCObjectPointerType())
4047       return lldb::eLanguageTypeObjC;
4048     if (qual_type->getPointeeCXXRecordDecl())
4049       return lldb::eLanguageTypeC_plus_plus;
4050 
4051     clang::QualType pointee_type(qual_type->getPointeeType());
4052     if (pointee_type->getPointeeCXXRecordDecl())
4053       return lldb::eLanguageTypeC_plus_plus;
4054     if (pointee_type->isObjCObjectOrInterfaceType())
4055       return lldb::eLanguageTypeObjC;
4056     if (pointee_type->isObjCClassType())
4057       return lldb::eLanguageTypeObjC;
4058     if (pointee_type.getTypePtr() ==
4059         getASTContext().ObjCBuiltinIdTy.getTypePtr())
4060       return lldb::eLanguageTypeObjC;
4061   } else {
4062     if (qual_type->isObjCObjectOrInterfaceType())
4063       return lldb::eLanguageTypeObjC;
4064     if (qual_type->getAsCXXRecordDecl())
4065       return lldb::eLanguageTypeC_plus_plus;
4066     switch (qual_type->getTypeClass()) {
4067     default:
4068       break;
4069     case clang::Type::Builtin:
4070       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4071       default:
4072       case clang::BuiltinType::Void:
4073       case clang::BuiltinType::Bool:
4074       case clang::BuiltinType::Char_U:
4075       case clang::BuiltinType::UChar:
4076       case clang::BuiltinType::WChar_U:
4077       case clang::BuiltinType::Char16:
4078       case clang::BuiltinType::Char32:
4079       case clang::BuiltinType::UShort:
4080       case clang::BuiltinType::UInt:
4081       case clang::BuiltinType::ULong:
4082       case clang::BuiltinType::ULongLong:
4083       case clang::BuiltinType::UInt128:
4084       case clang::BuiltinType::Char_S:
4085       case clang::BuiltinType::SChar:
4086       case clang::BuiltinType::WChar_S:
4087       case clang::BuiltinType::Short:
4088       case clang::BuiltinType::Int:
4089       case clang::BuiltinType::Long:
4090       case clang::BuiltinType::LongLong:
4091       case clang::BuiltinType::Int128:
4092       case clang::BuiltinType::Float:
4093       case clang::BuiltinType::Double:
4094       case clang::BuiltinType::LongDouble:
4095         break;
4096 
4097       case clang::BuiltinType::NullPtr:
4098         return eLanguageTypeC_plus_plus;
4099 
4100       case clang::BuiltinType::ObjCId:
4101       case clang::BuiltinType::ObjCClass:
4102       case clang::BuiltinType::ObjCSel:
4103         return eLanguageTypeObjC;
4104 
4105       case clang::BuiltinType::Dependent:
4106       case clang::BuiltinType::Overload:
4107       case clang::BuiltinType::BoundMember:
4108       case clang::BuiltinType::UnknownAny:
4109         break;
4110       }
4111       break;
4112     case clang::Type::Typedef:
4113       return GetType(llvm::cast<clang::TypedefType>(qual_type)
4114                          ->getDecl()
4115                          ->getUnderlyingType())
4116           .GetMinimumLanguage();
4117     }
4118   }
4119   return lldb::eLanguageTypeC;
4120 }
4121 
4122 lldb::TypeClass
4123 TypeSystemClang::GetTypeClass(lldb::opaque_compiler_type_t type) {
4124   if (!type)
4125     return lldb::eTypeClassInvalid;
4126 
4127   clang::QualType qual_type =
4128       RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
4129 
4130   switch (qual_type->getTypeClass()) {
4131   case clang::Type::Atomic:
4132   case clang::Type::Auto:
4133   case clang::Type::CountAttributed:
4134   case clang::Type::Decltype:
4135   case clang::Type::Elaborated:
4136   case clang::Type::Paren:
4137   case clang::Type::TypeOf:
4138   case clang::Type::TypeOfExpr:
4139   case clang::Type::Using:
4140     llvm_unreachable("Handled in RemoveWrappingTypes!");
4141   case clang::Type::UnaryTransform:
4142     break;
4143   case clang::Type::FunctionNoProto:
4144     return lldb::eTypeClassFunction;
4145   case clang::Type::FunctionProto:
4146     return lldb::eTypeClassFunction;
4147   case clang::Type::IncompleteArray:
4148     return lldb::eTypeClassArray;
4149   case clang::Type::VariableArray:
4150     return lldb::eTypeClassArray;
4151   case clang::Type::ConstantArray:
4152     return lldb::eTypeClassArray;
4153   case clang::Type::DependentSizedArray:
4154     return lldb::eTypeClassArray;
4155   case clang::Type::ArrayParameter:
4156     return lldb::eTypeClassArray;
4157   case clang::Type::DependentSizedExtVector:
4158     return lldb::eTypeClassVector;
4159   case clang::Type::DependentVector:
4160     return lldb::eTypeClassVector;
4161   case clang::Type::ExtVector:
4162     return lldb::eTypeClassVector;
4163   case clang::Type::Vector:
4164     return lldb::eTypeClassVector;
4165   case clang::Type::Builtin:
4166   // Ext-Int is just an integer type.
4167   case clang::Type::BitInt:
4168   case clang::Type::DependentBitInt:
4169     return lldb::eTypeClassBuiltin;
4170   case clang::Type::ObjCObjectPointer:
4171     return lldb::eTypeClassObjCObjectPointer;
4172   case clang::Type::BlockPointer:
4173     return lldb::eTypeClassBlockPointer;
4174   case clang::Type::Pointer:
4175     return lldb::eTypeClassPointer;
4176   case clang::Type::LValueReference:
4177     return lldb::eTypeClassReference;
4178   case clang::Type::RValueReference:
4179     return lldb::eTypeClassReference;
4180   case clang::Type::MemberPointer:
4181     return lldb::eTypeClassMemberPointer;
4182   case clang::Type::Complex:
4183     if (qual_type->isComplexType())
4184       return lldb::eTypeClassComplexFloat;
4185     else
4186       return lldb::eTypeClassComplexInteger;
4187   case clang::Type::ObjCObject:
4188     return lldb::eTypeClassObjCObject;
4189   case clang::Type::ObjCInterface:
4190     return lldb::eTypeClassObjCInterface;
4191   case clang::Type::Record: {
4192     const clang::RecordType *record_type =
4193         llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4194     const clang::RecordDecl *record_decl = record_type->getDecl();
4195     if (record_decl->isUnion())
4196       return lldb::eTypeClassUnion;
4197     else if (record_decl->isStruct())
4198       return lldb::eTypeClassStruct;
4199     else
4200       return lldb::eTypeClassClass;
4201   } break;
4202   case clang::Type::Enum:
4203     return lldb::eTypeClassEnumeration;
4204   case clang::Type::Typedef:
4205     return lldb::eTypeClassTypedef;
4206   case clang::Type::UnresolvedUsing:
4207     break;
4208 
4209   case clang::Type::Attributed:
4210   case clang::Type::BTFTagAttributed:
4211     break;
4212   case clang::Type::TemplateTypeParm:
4213     break;
4214   case clang::Type::SubstTemplateTypeParm:
4215     break;
4216   case clang::Type::SubstTemplateTypeParmPack:
4217     break;
4218   case clang::Type::InjectedClassName:
4219     break;
4220   case clang::Type::DependentName:
4221     break;
4222   case clang::Type::DependentTemplateSpecialization:
4223     break;
4224   case clang::Type::PackExpansion:
4225     break;
4226 
4227   case clang::Type::TemplateSpecialization:
4228     break;
4229   case clang::Type::DeducedTemplateSpecialization:
4230     break;
4231   case clang::Type::Pipe:
4232     break;
4233 
4234   // pointer type decayed from an array or function type.
4235   case clang::Type::Decayed:
4236     break;
4237   case clang::Type::Adjusted:
4238     break;
4239   case clang::Type::ObjCTypeParam:
4240     break;
4241 
4242   case clang::Type::DependentAddressSpace:
4243     break;
4244   case clang::Type::MacroQualified:
4245     break;
4246 
4247   // Matrix types that we're not sure how to display at the moment.
4248   case clang::Type::ConstantMatrix:
4249   case clang::Type::DependentSizedMatrix:
4250     break;
4251 
4252   // We don't handle pack indexing yet
4253   case clang::Type::PackIndexing:
4254     break;
4255 
4256   case clang::Type::HLSLAttributedResource:
4257     break;
4258   }
4259   // We don't know hot to display this type...
4260   return lldb::eTypeClassOther;
4261 }
4262 
4263 unsigned TypeSystemClang::GetTypeQualifiers(lldb::opaque_compiler_type_t type) {
4264   if (type)
4265     return GetQualType(type).getQualifiers().getCVRQualifiers();
4266   return 0;
4267 }
4268 
4269 // Creating related types
4270 
4271 CompilerType
4272 TypeSystemClang::GetArrayElementType(lldb::opaque_compiler_type_t type,
4273                                      ExecutionContextScope *exe_scope) {
4274   if (type) {
4275     clang::QualType qual_type(GetQualType(type));
4276 
4277     const clang::Type *array_eletype =
4278         qual_type.getTypePtr()->getArrayElementTypeNoTypeQual();
4279 
4280     if (!array_eletype)
4281       return CompilerType();
4282 
4283     return GetType(clang::QualType(array_eletype, 0));
4284   }
4285   return CompilerType();
4286 }
4287 
4288 CompilerType TypeSystemClang::GetArrayType(lldb::opaque_compiler_type_t type,
4289                                            uint64_t size) {
4290   if (type) {
4291     clang::QualType qual_type(GetCanonicalQualType(type));
4292     clang::ASTContext &ast_ctx = getASTContext();
4293     if (size != 0)
4294       return GetType(ast_ctx.getConstantArrayType(
4295           qual_type, llvm::APInt(64, size), nullptr,
4296           clang::ArraySizeModifier::Normal, 0));
4297     else
4298       return GetType(ast_ctx.getIncompleteArrayType(
4299           qual_type, clang::ArraySizeModifier::Normal, 0));
4300   }
4301 
4302   return CompilerType();
4303 }
4304 
4305 CompilerType
4306 TypeSystemClang::GetCanonicalType(lldb::opaque_compiler_type_t type) {
4307   if (type)
4308     return GetType(GetCanonicalQualType(type));
4309   return CompilerType();
4310 }
4311 
4312 static clang::QualType GetFullyUnqualifiedType_Impl(clang::ASTContext *ast,
4313                                                     clang::QualType qual_type) {
4314   if (qual_type->isPointerType())
4315     qual_type = ast->getPointerType(
4316         GetFullyUnqualifiedType_Impl(ast, qual_type->getPointeeType()));
4317   else if (const ConstantArrayType *arr =
4318                ast->getAsConstantArrayType(qual_type)) {
4319     qual_type = ast->getConstantArrayType(
4320         GetFullyUnqualifiedType_Impl(ast, arr->getElementType()),
4321         arr->getSize(), arr->getSizeExpr(), arr->getSizeModifier(),
4322         arr->getIndexTypeQualifiers().getAsOpaqueValue());
4323   } else
4324     qual_type = qual_type.getUnqualifiedType();
4325   qual_type.removeLocalConst();
4326   qual_type.removeLocalRestrict();
4327   qual_type.removeLocalVolatile();
4328   return qual_type;
4329 }
4330 
4331 CompilerType
4332 TypeSystemClang::GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) {
4333   if (type)
4334     return GetType(
4335         GetFullyUnqualifiedType_Impl(&getASTContext(), GetQualType(type)));
4336   return CompilerType();
4337 }
4338 
4339 CompilerType
4340 TypeSystemClang::GetEnumerationIntegerType(lldb::opaque_compiler_type_t type) {
4341   if (type)
4342     return GetEnumerationIntegerType(GetType(GetCanonicalQualType(type)));
4343   return CompilerType();
4344 }
4345 
4346 int TypeSystemClang::GetFunctionArgumentCount(
4347     lldb::opaque_compiler_type_t type) {
4348   if (type) {
4349     const clang::FunctionProtoType *func =
4350         llvm::dyn_cast<clang::FunctionProtoType>(GetCanonicalQualType(type));
4351     if (func)
4352       return func->getNumParams();
4353   }
4354   return -1;
4355 }
4356 
4357 CompilerType TypeSystemClang::GetFunctionArgumentTypeAtIndex(
4358     lldb::opaque_compiler_type_t type, size_t idx) {
4359   if (type) {
4360     const clang::FunctionProtoType *func =
4361         llvm::dyn_cast<clang::FunctionProtoType>(GetQualType(type));
4362     if (func) {
4363       const uint32_t num_args = func->getNumParams();
4364       if (idx < num_args)
4365         return GetType(func->getParamType(idx));
4366     }
4367   }
4368   return CompilerType();
4369 }
4370 
4371 CompilerType
4372 TypeSystemClang::GetFunctionReturnType(lldb::opaque_compiler_type_t type) {
4373   if (type) {
4374     clang::QualType qual_type(GetQualType(type));
4375     const clang::FunctionProtoType *func =
4376         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
4377     if (func)
4378       return GetType(func->getReturnType());
4379   }
4380   return CompilerType();
4381 }
4382 
4383 size_t
4384 TypeSystemClang::GetNumMemberFunctions(lldb::opaque_compiler_type_t type) {
4385   size_t num_functions = 0;
4386   if (type) {
4387     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4388     switch (qual_type->getTypeClass()) {
4389     case clang::Type::Record:
4390       if (GetCompleteQualType(&getASTContext(), qual_type)) {
4391         const clang::RecordType *record_type =
4392             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4393         const clang::RecordDecl *record_decl = record_type->getDecl();
4394         assert(record_decl);
4395         const clang::CXXRecordDecl *cxx_record_decl =
4396             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4397         if (cxx_record_decl)
4398           num_functions = std::distance(cxx_record_decl->method_begin(),
4399                                         cxx_record_decl->method_end());
4400       }
4401       break;
4402 
4403     case clang::Type::ObjCObjectPointer: {
4404       const clang::ObjCObjectPointerType *objc_class_type =
4405           qual_type->castAs<clang::ObjCObjectPointerType>();
4406       const clang::ObjCInterfaceType *objc_interface_type =
4407           objc_class_type->getInterfaceType();
4408       if (objc_interface_type &&
4409           GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4410               const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4411         clang::ObjCInterfaceDecl *class_interface_decl =
4412             objc_interface_type->getDecl();
4413         if (class_interface_decl) {
4414           num_functions = std::distance(class_interface_decl->meth_begin(),
4415                                         class_interface_decl->meth_end());
4416         }
4417       }
4418       break;
4419     }
4420 
4421     case clang::Type::ObjCObject:
4422     case clang::Type::ObjCInterface:
4423       if (GetCompleteType(type)) {
4424         const clang::ObjCObjectType *objc_class_type =
4425             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4426         if (objc_class_type) {
4427           clang::ObjCInterfaceDecl *class_interface_decl =
4428               objc_class_type->getInterface();
4429           if (class_interface_decl)
4430             num_functions = std::distance(class_interface_decl->meth_begin(),
4431                                           class_interface_decl->meth_end());
4432         }
4433       }
4434       break;
4435 
4436     default:
4437       break;
4438     }
4439   }
4440   return num_functions;
4441 }
4442 
4443 TypeMemberFunctionImpl
4444 TypeSystemClang::GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type,
4445                                           size_t idx) {
4446   std::string name;
4447   MemberFunctionKind kind(MemberFunctionKind::eMemberFunctionKindUnknown);
4448   CompilerType clang_type;
4449   CompilerDecl clang_decl;
4450   if (type) {
4451     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4452     switch (qual_type->getTypeClass()) {
4453     case clang::Type::Record:
4454       if (GetCompleteQualType(&getASTContext(), qual_type)) {
4455         const clang::RecordType *record_type =
4456             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4457         const clang::RecordDecl *record_decl = record_type->getDecl();
4458         assert(record_decl);
4459         const clang::CXXRecordDecl *cxx_record_decl =
4460             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4461         if (cxx_record_decl) {
4462           auto method_iter = cxx_record_decl->method_begin();
4463           auto method_end = cxx_record_decl->method_end();
4464           if (idx <
4465               static_cast<size_t>(std::distance(method_iter, method_end))) {
4466             std::advance(method_iter, idx);
4467             clang::CXXMethodDecl *cxx_method_decl =
4468                 method_iter->getCanonicalDecl();
4469             if (cxx_method_decl) {
4470               name = cxx_method_decl->getDeclName().getAsString();
4471               if (cxx_method_decl->isStatic())
4472                 kind = lldb::eMemberFunctionKindStaticMethod;
4473               else if (llvm::isa<clang::CXXConstructorDecl>(cxx_method_decl))
4474                 kind = lldb::eMemberFunctionKindConstructor;
4475               else if (llvm::isa<clang::CXXDestructorDecl>(cxx_method_decl))
4476                 kind = lldb::eMemberFunctionKindDestructor;
4477               else
4478                 kind = lldb::eMemberFunctionKindInstanceMethod;
4479               clang_type = GetType(cxx_method_decl->getType());
4480               clang_decl = GetCompilerDecl(cxx_method_decl);
4481             }
4482           }
4483         }
4484       }
4485       break;
4486 
4487     case clang::Type::ObjCObjectPointer: {
4488       const clang::ObjCObjectPointerType *objc_class_type =
4489           qual_type->castAs<clang::ObjCObjectPointerType>();
4490       const clang::ObjCInterfaceType *objc_interface_type =
4491           objc_class_type->getInterfaceType();
4492       if (objc_interface_type &&
4493           GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4494               const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4495         clang::ObjCInterfaceDecl *class_interface_decl =
4496             objc_interface_type->getDecl();
4497         if (class_interface_decl) {
4498           auto method_iter = class_interface_decl->meth_begin();
4499           auto method_end = class_interface_decl->meth_end();
4500           if (idx <
4501               static_cast<size_t>(std::distance(method_iter, method_end))) {
4502             std::advance(method_iter, idx);
4503             clang::ObjCMethodDecl *objc_method_decl =
4504                 method_iter->getCanonicalDecl();
4505             if (objc_method_decl) {
4506               clang_decl = GetCompilerDecl(objc_method_decl);
4507               name = objc_method_decl->getSelector().getAsString();
4508               if (objc_method_decl->isClassMethod())
4509                 kind = lldb::eMemberFunctionKindStaticMethod;
4510               else
4511                 kind = lldb::eMemberFunctionKindInstanceMethod;
4512             }
4513           }
4514         }
4515       }
4516       break;
4517     }
4518 
4519     case clang::Type::ObjCObject:
4520     case clang::Type::ObjCInterface:
4521       if (GetCompleteType(type)) {
4522         const clang::ObjCObjectType *objc_class_type =
4523             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4524         if (objc_class_type) {
4525           clang::ObjCInterfaceDecl *class_interface_decl =
4526               objc_class_type->getInterface();
4527           if (class_interface_decl) {
4528             auto method_iter = class_interface_decl->meth_begin();
4529             auto method_end = class_interface_decl->meth_end();
4530             if (idx <
4531                 static_cast<size_t>(std::distance(method_iter, method_end))) {
4532               std::advance(method_iter, idx);
4533               clang::ObjCMethodDecl *objc_method_decl =
4534                   method_iter->getCanonicalDecl();
4535               if (objc_method_decl) {
4536                 clang_decl = GetCompilerDecl(objc_method_decl);
4537                 name = objc_method_decl->getSelector().getAsString();
4538                 if (objc_method_decl->isClassMethod())
4539                   kind = lldb::eMemberFunctionKindStaticMethod;
4540                 else
4541                   kind = lldb::eMemberFunctionKindInstanceMethod;
4542               }
4543             }
4544           }
4545         }
4546       }
4547       break;
4548 
4549     default:
4550       break;
4551     }
4552   }
4553 
4554   if (kind == eMemberFunctionKindUnknown)
4555     return TypeMemberFunctionImpl();
4556   else
4557     return TypeMemberFunctionImpl(clang_type, clang_decl, name, kind);
4558 }
4559 
4560 CompilerType
4561 TypeSystemClang::GetNonReferenceType(lldb::opaque_compiler_type_t type) {
4562   if (type)
4563     return GetType(GetQualType(type).getNonReferenceType());
4564   return CompilerType();
4565 }
4566 
4567 CompilerType
4568 TypeSystemClang::GetPointeeType(lldb::opaque_compiler_type_t type) {
4569   if (type) {
4570     clang::QualType qual_type(GetQualType(type));
4571     return GetType(qual_type.getTypePtr()->getPointeeType());
4572   }
4573   return CompilerType();
4574 }
4575 
4576 CompilerType
4577 TypeSystemClang::GetPointerType(lldb::opaque_compiler_type_t type) {
4578   if (type) {
4579     clang::QualType qual_type(GetQualType(type));
4580 
4581     switch (qual_type.getDesugaredType(getASTContext())->getTypeClass()) {
4582     case clang::Type::ObjCObject:
4583     case clang::Type::ObjCInterface:
4584       return GetType(getASTContext().getObjCObjectPointerType(qual_type));
4585 
4586     default:
4587       return GetType(getASTContext().getPointerType(qual_type));
4588     }
4589   }
4590   return CompilerType();
4591 }
4592 
4593 CompilerType
4594 TypeSystemClang::GetLValueReferenceType(lldb::opaque_compiler_type_t type) {
4595   if (type)
4596     return GetType(getASTContext().getLValueReferenceType(GetQualType(type)));
4597   else
4598     return CompilerType();
4599 }
4600 
4601 CompilerType
4602 TypeSystemClang::GetRValueReferenceType(lldb::opaque_compiler_type_t type) {
4603   if (type)
4604     return GetType(getASTContext().getRValueReferenceType(GetQualType(type)));
4605   else
4606     return CompilerType();
4607 }
4608 
4609 CompilerType TypeSystemClang::GetAtomicType(lldb::opaque_compiler_type_t type) {
4610   if (!type)
4611     return CompilerType();
4612   return GetType(getASTContext().getAtomicType(GetQualType(type)));
4613 }
4614 
4615 CompilerType
4616 TypeSystemClang::AddConstModifier(lldb::opaque_compiler_type_t type) {
4617   if (type) {
4618     clang::QualType result(GetQualType(type));
4619     result.addConst();
4620     return GetType(result);
4621   }
4622   return CompilerType();
4623 }
4624 
4625 CompilerType
4626 TypeSystemClang::AddPtrAuthModifier(lldb::opaque_compiler_type_t type,
4627                                     uint32_t payload) {
4628   if (type) {
4629     clang::ASTContext &clang_ast = getASTContext();
4630     auto pauth = PointerAuthQualifier::fromOpaqueValue(payload);
4631     clang::QualType result =
4632         clang_ast.getPointerAuthType(GetQualType(type), pauth);
4633     return GetType(result);
4634   }
4635   return CompilerType();
4636 }
4637 
4638 CompilerType
4639 TypeSystemClang::AddVolatileModifier(lldb::opaque_compiler_type_t type) {
4640   if (type) {
4641     clang::QualType result(GetQualType(type));
4642     result.addVolatile();
4643     return GetType(result);
4644   }
4645   return CompilerType();
4646 }
4647 
4648 CompilerType
4649 TypeSystemClang::AddRestrictModifier(lldb::opaque_compiler_type_t type) {
4650   if (type) {
4651     clang::QualType result(GetQualType(type));
4652     result.addRestrict();
4653     return GetType(result);
4654   }
4655   return CompilerType();
4656 }
4657 
4658 CompilerType TypeSystemClang::CreateTypedef(
4659     lldb::opaque_compiler_type_t type, const char *typedef_name,
4660     const CompilerDeclContext &compiler_decl_ctx, uint32_t payload) {
4661   if (type && typedef_name && typedef_name[0]) {
4662     clang::ASTContext &clang_ast = getASTContext();
4663     clang::QualType qual_type(GetQualType(type));
4664 
4665     clang::DeclContext *decl_ctx =
4666         TypeSystemClang::DeclContextGetAsDeclContext(compiler_decl_ctx);
4667     if (!decl_ctx)
4668       decl_ctx = getASTContext().getTranslationUnitDecl();
4669 
4670     clang::TypedefDecl *decl =
4671         clang::TypedefDecl::CreateDeserialized(clang_ast, GlobalDeclID());
4672     decl->setDeclContext(decl_ctx);
4673     decl->setDeclName(&clang_ast.Idents.get(typedef_name));
4674     decl->setTypeSourceInfo(clang_ast.getTrivialTypeSourceInfo(qual_type));
4675     decl_ctx->addDecl(decl);
4676     SetOwningModule(decl, TypePayloadClang(payload).GetOwningModule());
4677 
4678     clang::TagDecl *tdecl = nullptr;
4679     if (!qual_type.isNull()) {
4680       if (const clang::RecordType *rt = qual_type->getAs<clang::RecordType>())
4681         tdecl = rt->getDecl();
4682       if (const clang::EnumType *et = qual_type->getAs<clang::EnumType>())
4683         tdecl = et->getDecl();
4684     }
4685 
4686     // Check whether this declaration is an anonymous struct, union, or enum,
4687     // hidden behind a typedef. If so, we try to check whether we have a
4688     // typedef tag to attach to the original record declaration
4689     if (tdecl && !tdecl->getIdentifier() && !tdecl->getTypedefNameForAnonDecl())
4690       tdecl->setTypedefNameForAnonDecl(decl);
4691 
4692     decl->setAccess(clang::AS_public); // TODO respect proper access specifier
4693 
4694     // Get a uniqued clang::QualType for the typedef decl type
4695     return GetType(clang_ast.getTypedefType(decl));
4696   }
4697   return CompilerType();
4698 }
4699 
4700 CompilerType
4701 TypeSystemClang::GetTypedefedType(lldb::opaque_compiler_type_t type) {
4702   if (type) {
4703     const clang::TypedefType *typedef_type = llvm::dyn_cast<clang::TypedefType>(
4704         RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}));
4705     if (typedef_type)
4706       return GetType(typedef_type->getDecl()->getUnderlyingType());
4707   }
4708   return CompilerType();
4709 }
4710 
4711 // Create related types using the current type's AST
4712 
4713 CompilerType TypeSystemClang::GetBasicTypeFromAST(lldb::BasicType basic_type) {
4714   return TypeSystemClang::GetBasicType(basic_type);
4715 }
4716 
4717 CompilerType TypeSystemClang::CreateGenericFunctionPrototype() {
4718   clang::ASTContext &ast = getASTContext();
4719   const FunctionType::ExtInfo generic_ext_info(
4720     /*noReturn=*/false,
4721     /*hasRegParm=*/false,
4722     /*regParm=*/0,
4723     CallingConv::CC_C,
4724     /*producesResult=*/false,
4725     /*noCallerSavedRegs=*/false,
4726     /*NoCfCheck=*/false,
4727     /*cmseNSCall=*/false);
4728   QualType func_type = ast.getFunctionNoProtoType(ast.VoidTy, generic_ext_info);
4729   return GetType(func_type);
4730 }
4731 // Exploring the type
4732 
4733 const llvm::fltSemantics &
4734 TypeSystemClang::GetFloatTypeSemantics(size_t byte_size) {
4735   clang::ASTContext &ast = getASTContext();
4736   const size_t bit_size = byte_size * 8;
4737   if (bit_size == ast.getTypeSize(ast.FloatTy))
4738     return ast.getFloatTypeSemantics(ast.FloatTy);
4739   else if (bit_size == ast.getTypeSize(ast.DoubleTy))
4740     return ast.getFloatTypeSemantics(ast.DoubleTy);
4741   else if (bit_size == ast.getTypeSize(ast.LongDoubleTy) ||
4742            bit_size == llvm::APFloat::semanticsSizeInBits(
4743                            ast.getFloatTypeSemantics(ast.LongDoubleTy)))
4744     return ast.getFloatTypeSemantics(ast.LongDoubleTy);
4745   else if (bit_size == ast.getTypeSize(ast.HalfTy))
4746     return ast.getFloatTypeSemantics(ast.HalfTy);
4747   return llvm::APFloatBase::Bogus();
4748 }
4749 
4750 std::optional<uint64_t>
4751 TypeSystemClang::GetObjCBitSize(QualType qual_type,
4752                                 ExecutionContextScope *exe_scope) {
4753   assert(qual_type->isObjCObjectOrInterfaceType());
4754   ExecutionContext exe_ctx(exe_scope);
4755   if (Process *process = exe_ctx.GetProcessPtr()) {
4756     if (ObjCLanguageRuntime *objc_runtime =
4757             ObjCLanguageRuntime::Get(*process)) {
4758       if (std::optional<uint64_t> bit_size =
4759               objc_runtime->GetTypeBitSize(GetType(qual_type)))
4760         return *bit_size;
4761     }
4762   } else {
4763     static bool g_printed = false;
4764     if (!g_printed) {
4765       StreamString s;
4766       DumpTypeDescription(qual_type.getAsOpaquePtr(), s);
4767 
4768       llvm::outs() << "warning: trying to determine the size of type ";
4769       llvm::outs() << s.GetString() << "\n";
4770       llvm::outs() << "without a valid ExecutionContext. this is not "
4771                       "reliable. please file a bug against LLDB.\n";
4772       llvm::outs() << "backtrace:\n";
4773       llvm::sys::PrintStackTrace(llvm::outs());
4774       llvm::outs() << "\n";
4775       g_printed = true;
4776     }
4777   }
4778 
4779   return getASTContext().getTypeSize(qual_type) +
4780          getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy);
4781 }
4782 
4783 std::optional<uint64_t>
4784 TypeSystemClang::GetBitSize(lldb::opaque_compiler_type_t type,
4785                             ExecutionContextScope *exe_scope) {
4786   if (!GetCompleteType(type))
4787     return std::nullopt;
4788 
4789   clang::QualType qual_type(GetCanonicalQualType(type));
4790   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4791   switch (type_class) {
4792   case clang::Type::ConstantArray:
4793   case clang::Type::FunctionProto:
4794   case clang::Type::Record:
4795     return getASTContext().getTypeSize(qual_type);
4796   case clang::Type::ObjCInterface:
4797   case clang::Type::ObjCObject:
4798     return GetObjCBitSize(qual_type, exe_scope);
4799   case clang::Type::IncompleteArray: {
4800     const uint64_t bit_size = getASTContext().getTypeSize(qual_type);
4801     if (bit_size == 0)
4802       return getASTContext().getTypeSize(
4803           qual_type->getArrayElementTypeNoTypeQual()
4804               ->getCanonicalTypeUnqualified());
4805 
4806     return bit_size;
4807   }
4808   default:
4809     if (const uint64_t bit_size = getASTContext().getTypeSize(qual_type))
4810       return bit_size;
4811   }
4812 
4813   return std::nullopt;
4814 }
4815 
4816 std::optional<size_t>
4817 TypeSystemClang::GetTypeBitAlign(lldb::opaque_compiler_type_t type,
4818                                  ExecutionContextScope *exe_scope) {
4819   if (GetCompleteType(type))
4820     return getASTContext().getTypeAlign(GetQualType(type));
4821   return {};
4822 }
4823 
4824 lldb::Encoding TypeSystemClang::GetEncoding(lldb::opaque_compiler_type_t type,
4825                                             uint64_t &count) {
4826   if (!type)
4827     return lldb::eEncodingInvalid;
4828 
4829   count = 1;
4830   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4831 
4832   switch (qual_type->getTypeClass()) {
4833   case clang::Type::Atomic:
4834   case clang::Type::Auto:
4835   case clang::Type::CountAttributed:
4836   case clang::Type::Decltype:
4837   case clang::Type::Elaborated:
4838   case clang::Type::Paren:
4839   case clang::Type::Typedef:
4840   case clang::Type::TypeOf:
4841   case clang::Type::TypeOfExpr:
4842   case clang::Type::Using:
4843     llvm_unreachable("Handled in RemoveWrappingTypes!");
4844 
4845   case clang::Type::UnaryTransform:
4846     break;
4847 
4848   case clang::Type::FunctionNoProto:
4849   case clang::Type::FunctionProto:
4850     return lldb::eEncodingUint;
4851 
4852   case clang::Type::IncompleteArray:
4853   case clang::Type::VariableArray:
4854   case clang::Type::ArrayParameter:
4855     break;
4856 
4857   case clang::Type::ConstantArray:
4858     break;
4859 
4860   case clang::Type::DependentVector:
4861   case clang::Type::ExtVector:
4862   case clang::Type::Vector:
4863     // TODO: Set this to more than one???
4864     break;
4865 
4866   case clang::Type::BitInt:
4867   case clang::Type::DependentBitInt:
4868     return qual_type->isUnsignedIntegerType() ? lldb::eEncodingUint
4869                                               : lldb::eEncodingSint;
4870 
4871   case clang::Type::Builtin:
4872     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4873     case clang::BuiltinType::Void:
4874       break;
4875 
4876     case clang::BuiltinType::Char_S:
4877     case clang::BuiltinType::SChar:
4878     case clang::BuiltinType::WChar_S:
4879     case clang::BuiltinType::Short:
4880     case clang::BuiltinType::Int:
4881     case clang::BuiltinType::Long:
4882     case clang::BuiltinType::LongLong:
4883     case clang::BuiltinType::Int128:
4884       return lldb::eEncodingSint;
4885 
4886     case clang::BuiltinType::Bool:
4887     case clang::BuiltinType::Char_U:
4888     case clang::BuiltinType::UChar:
4889     case clang::BuiltinType::WChar_U:
4890     case clang::BuiltinType::Char8:
4891     case clang::BuiltinType::Char16:
4892     case clang::BuiltinType::Char32:
4893     case clang::BuiltinType::UShort:
4894     case clang::BuiltinType::UInt:
4895     case clang::BuiltinType::ULong:
4896     case clang::BuiltinType::ULongLong:
4897     case clang::BuiltinType::UInt128:
4898       return lldb::eEncodingUint;
4899 
4900     // Fixed point types. Note that they are currently ignored.
4901     case clang::BuiltinType::ShortAccum:
4902     case clang::BuiltinType::Accum:
4903     case clang::BuiltinType::LongAccum:
4904     case clang::BuiltinType::UShortAccum:
4905     case clang::BuiltinType::UAccum:
4906     case clang::BuiltinType::ULongAccum:
4907     case clang::BuiltinType::ShortFract:
4908     case clang::BuiltinType::Fract:
4909     case clang::BuiltinType::LongFract:
4910     case clang::BuiltinType::UShortFract:
4911     case clang::BuiltinType::UFract:
4912     case clang::BuiltinType::ULongFract:
4913     case clang::BuiltinType::SatShortAccum:
4914     case clang::BuiltinType::SatAccum:
4915     case clang::BuiltinType::SatLongAccum:
4916     case clang::BuiltinType::SatUShortAccum:
4917     case clang::BuiltinType::SatUAccum:
4918     case clang::BuiltinType::SatULongAccum:
4919     case clang::BuiltinType::SatShortFract:
4920     case clang::BuiltinType::SatFract:
4921     case clang::BuiltinType::SatLongFract:
4922     case clang::BuiltinType::SatUShortFract:
4923     case clang::BuiltinType::SatUFract:
4924     case clang::BuiltinType::SatULongFract:
4925       break;
4926 
4927     case clang::BuiltinType::Half:
4928     case clang::BuiltinType::Float:
4929     case clang::BuiltinType::Float16:
4930     case clang::BuiltinType::Float128:
4931     case clang::BuiltinType::Double:
4932     case clang::BuiltinType::LongDouble:
4933     case clang::BuiltinType::BFloat16:
4934     case clang::BuiltinType::Ibm128:
4935       return lldb::eEncodingIEEE754;
4936 
4937     case clang::BuiltinType::ObjCClass:
4938     case clang::BuiltinType::ObjCId:
4939     case clang::BuiltinType::ObjCSel:
4940       return lldb::eEncodingUint;
4941 
4942     case clang::BuiltinType::NullPtr:
4943       return lldb::eEncodingUint;
4944 
4945     case clang::BuiltinType::Kind::ARCUnbridgedCast:
4946     case clang::BuiltinType::Kind::BoundMember:
4947     case clang::BuiltinType::Kind::BuiltinFn:
4948     case clang::BuiltinType::Kind::Dependent:
4949     case clang::BuiltinType::Kind::OCLClkEvent:
4950     case clang::BuiltinType::Kind::OCLEvent:
4951     case clang::BuiltinType::Kind::OCLImage1dRO:
4952     case clang::BuiltinType::Kind::OCLImage1dWO:
4953     case clang::BuiltinType::Kind::OCLImage1dRW:
4954     case clang::BuiltinType::Kind::OCLImage1dArrayRO:
4955     case clang::BuiltinType::Kind::OCLImage1dArrayWO:
4956     case clang::BuiltinType::Kind::OCLImage1dArrayRW:
4957     case clang::BuiltinType::Kind::OCLImage1dBufferRO:
4958     case clang::BuiltinType::Kind::OCLImage1dBufferWO:
4959     case clang::BuiltinType::Kind::OCLImage1dBufferRW:
4960     case clang::BuiltinType::Kind::OCLImage2dRO:
4961     case clang::BuiltinType::Kind::OCLImage2dWO:
4962     case clang::BuiltinType::Kind::OCLImage2dRW:
4963     case clang::BuiltinType::Kind::OCLImage2dArrayRO:
4964     case clang::BuiltinType::Kind::OCLImage2dArrayWO:
4965     case clang::BuiltinType::Kind::OCLImage2dArrayRW:
4966     case clang::BuiltinType::Kind::OCLImage2dArrayDepthRO:
4967     case clang::BuiltinType::Kind::OCLImage2dArrayDepthWO:
4968     case clang::BuiltinType::Kind::OCLImage2dArrayDepthRW:
4969     case clang::BuiltinType::Kind::OCLImage2dArrayMSAARO:
4970     case clang::BuiltinType::Kind::OCLImage2dArrayMSAAWO:
4971     case clang::BuiltinType::Kind::OCLImage2dArrayMSAARW:
4972     case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRO:
4973     case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthWO:
4974     case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRW:
4975     case clang::BuiltinType::Kind::OCLImage2dDepthRO:
4976     case clang::BuiltinType::Kind::OCLImage2dDepthWO:
4977     case clang::BuiltinType::Kind::OCLImage2dDepthRW:
4978     case clang::BuiltinType::Kind::OCLImage2dMSAARO:
4979     case clang::BuiltinType::Kind::OCLImage2dMSAAWO:
4980     case clang::BuiltinType::Kind::OCLImage2dMSAARW:
4981     case clang::BuiltinType::Kind::OCLImage2dMSAADepthRO:
4982     case clang::BuiltinType::Kind::OCLImage2dMSAADepthWO:
4983     case clang::BuiltinType::Kind::OCLImage2dMSAADepthRW:
4984     case clang::BuiltinType::Kind::OCLImage3dRO:
4985     case clang::BuiltinType::Kind::OCLImage3dWO:
4986     case clang::BuiltinType::Kind::OCLImage3dRW:
4987     case clang::BuiltinType::Kind::OCLQueue:
4988     case clang::BuiltinType::Kind::OCLReserveID:
4989     case clang::BuiltinType::Kind::OCLSampler:
4990     case clang::BuiltinType::Kind::HLSLResource:
4991     case clang::BuiltinType::Kind::ArraySection:
4992     case clang::BuiltinType::Kind::OMPArrayShaping:
4993     case clang::BuiltinType::Kind::OMPIterator:
4994     case clang::BuiltinType::Kind::Overload:
4995     case clang::BuiltinType::Kind::PseudoObject:
4996     case clang::BuiltinType::Kind::UnknownAny:
4997       break;
4998 
4999     case clang::BuiltinType::OCLIntelSubgroupAVCMcePayload:
5000     case clang::BuiltinType::OCLIntelSubgroupAVCImePayload:
5001     case clang::BuiltinType::OCLIntelSubgroupAVCRefPayload:
5002     case clang::BuiltinType::OCLIntelSubgroupAVCSicPayload:
5003     case clang::BuiltinType::OCLIntelSubgroupAVCMceResult:
5004     case clang::BuiltinType::OCLIntelSubgroupAVCImeResult:
5005     case clang::BuiltinType::OCLIntelSubgroupAVCRefResult:
5006     case clang::BuiltinType::OCLIntelSubgroupAVCSicResult:
5007     case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleReferenceStreamout:
5008     case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualReferenceStreamout:
5009     case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleReferenceStreamin:
5010     case clang::BuiltinType::OCLIntelSubgroupAVCImeDualReferenceStreamin:
5011       break;
5012 
5013     // PowerPC -- Matrix Multiply Assist
5014     case clang::BuiltinType::VectorPair:
5015     case clang::BuiltinType::VectorQuad:
5016       break;
5017 
5018     // ARM -- Scalable Vector Extension
5019 #define SVE_TYPE(Name, Id, SingletonId) case clang::BuiltinType::Id:
5020 #include "clang/Basic/AArch64SVEACLETypes.def"
5021       break;
5022 
5023     // RISC-V V builtin types.
5024 #define RVV_TYPE(Name, Id, SingletonId) case clang::BuiltinType::Id:
5025 #include "clang/Basic/RISCVVTypes.def"
5026       break;
5027 
5028     // WebAssembly builtin types.
5029     case clang::BuiltinType::WasmExternRef:
5030       break;
5031 
5032     case clang::BuiltinType::IncompleteMatrixIdx:
5033       break;
5034 
5035     case clang::BuiltinType::UnresolvedTemplate:
5036       break;
5037 
5038     // AMD GPU builtin types.
5039 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align)                       \
5040   case clang::BuiltinType::Id:
5041 #include "clang/Basic/AMDGPUTypes.def"
5042       break;
5043     }
5044     break;
5045   // All pointer types are represented as unsigned integer encodings. We may
5046   // nee to add a eEncodingPointer if we ever need to know the difference
5047   case clang::Type::ObjCObjectPointer:
5048   case clang::Type::BlockPointer:
5049   case clang::Type::Pointer:
5050   case clang::Type::LValueReference:
5051   case clang::Type::RValueReference:
5052   case clang::Type::MemberPointer:
5053     return lldb::eEncodingUint;
5054   case clang::Type::Complex: {
5055     lldb::Encoding encoding = lldb::eEncodingIEEE754;
5056     if (qual_type->isComplexType())
5057       encoding = lldb::eEncodingIEEE754;
5058     else {
5059       const clang::ComplexType *complex_type =
5060           qual_type->getAsComplexIntegerType();
5061       if (complex_type)
5062         encoding = GetType(complex_type->getElementType()).GetEncoding(count);
5063       else
5064         encoding = lldb::eEncodingSint;
5065     }
5066     count = 2;
5067     return encoding;
5068   }
5069 
5070   case clang::Type::ObjCInterface:
5071     break;
5072   case clang::Type::Record:
5073     break;
5074   case clang::Type::Enum:
5075     return qual_type->isUnsignedIntegerOrEnumerationType()
5076                ? lldb::eEncodingUint
5077                : lldb::eEncodingSint;
5078   case clang::Type::DependentSizedArray:
5079   case clang::Type::DependentSizedExtVector:
5080   case clang::Type::UnresolvedUsing:
5081   case clang::Type::Attributed:
5082   case clang::Type::BTFTagAttributed:
5083   case clang::Type::TemplateTypeParm:
5084   case clang::Type::SubstTemplateTypeParm:
5085   case clang::Type::SubstTemplateTypeParmPack:
5086   case clang::Type::InjectedClassName:
5087   case clang::Type::DependentName:
5088   case clang::Type::DependentTemplateSpecialization:
5089   case clang::Type::PackExpansion:
5090   case clang::Type::ObjCObject:
5091 
5092   case clang::Type::TemplateSpecialization:
5093   case clang::Type::DeducedTemplateSpecialization:
5094   case clang::Type::Adjusted:
5095   case clang::Type::Pipe:
5096     break;
5097 
5098   // pointer type decayed from an array or function type.
5099   case clang::Type::Decayed:
5100     break;
5101   case clang::Type::ObjCTypeParam:
5102     break;
5103 
5104   case clang::Type::DependentAddressSpace:
5105     break;
5106   case clang::Type::MacroQualified:
5107     break;
5108 
5109   case clang::Type::ConstantMatrix:
5110   case clang::Type::DependentSizedMatrix:
5111     break;
5112 
5113   // We don't handle pack indexing yet
5114   case clang::Type::PackIndexing:
5115     break;
5116 
5117   case clang::Type::HLSLAttributedResource:
5118     break;
5119   }
5120   count = 0;
5121   return lldb::eEncodingInvalid;
5122 }
5123 
5124 lldb::Format TypeSystemClang::GetFormat(lldb::opaque_compiler_type_t type) {
5125   if (!type)
5126     return lldb::eFormatDefault;
5127 
5128   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5129 
5130   switch (qual_type->getTypeClass()) {
5131   case clang::Type::Atomic:
5132   case clang::Type::Auto:
5133   case clang::Type::CountAttributed:
5134   case clang::Type::Decltype:
5135   case clang::Type::Elaborated:
5136   case clang::Type::Paren:
5137   case clang::Type::Typedef:
5138   case clang::Type::TypeOf:
5139   case clang::Type::TypeOfExpr:
5140   case clang::Type::Using:
5141     llvm_unreachable("Handled in RemoveWrappingTypes!");
5142   case clang::Type::UnaryTransform:
5143     break;
5144 
5145   case clang::Type::FunctionNoProto:
5146   case clang::Type::FunctionProto:
5147     break;
5148 
5149   case clang::Type::IncompleteArray:
5150   case clang::Type::VariableArray:
5151   case clang::Type::ArrayParameter:
5152     break;
5153 
5154   case clang::Type::ConstantArray:
5155     return lldb::eFormatVoid; // no value
5156 
5157   case clang::Type::DependentVector:
5158   case clang::Type::ExtVector:
5159   case clang::Type::Vector:
5160     break;
5161 
5162   case clang::Type::BitInt:
5163   case clang::Type::DependentBitInt:
5164     return qual_type->isUnsignedIntegerType() ? lldb::eFormatUnsigned
5165                                               : lldb::eFormatDecimal;
5166 
5167   case clang::Type::Builtin:
5168     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5169     case clang::BuiltinType::UnknownAny:
5170     case clang::BuiltinType::Void:
5171     case clang::BuiltinType::BoundMember:
5172       break;
5173 
5174     case clang::BuiltinType::Bool:
5175       return lldb::eFormatBoolean;
5176     case clang::BuiltinType::Char_S:
5177     case clang::BuiltinType::SChar:
5178     case clang::BuiltinType::WChar_S:
5179     case clang::BuiltinType::Char_U:
5180     case clang::BuiltinType::UChar:
5181     case clang::BuiltinType::WChar_U:
5182       return lldb::eFormatChar;
5183     case clang::BuiltinType::Char8:
5184       return lldb::eFormatUnicode8;
5185     case clang::BuiltinType::Char16:
5186       return lldb::eFormatUnicode16;
5187     case clang::BuiltinType::Char32:
5188       return lldb::eFormatUnicode32;
5189     case clang::BuiltinType::UShort:
5190       return lldb::eFormatUnsigned;
5191     case clang::BuiltinType::Short:
5192       return lldb::eFormatDecimal;
5193     case clang::BuiltinType::UInt:
5194       return lldb::eFormatUnsigned;
5195     case clang::BuiltinType::Int:
5196       return lldb::eFormatDecimal;
5197     case clang::BuiltinType::ULong:
5198       return lldb::eFormatUnsigned;
5199     case clang::BuiltinType::Long:
5200       return lldb::eFormatDecimal;
5201     case clang::BuiltinType::ULongLong:
5202       return lldb::eFormatUnsigned;
5203     case clang::BuiltinType::LongLong:
5204       return lldb::eFormatDecimal;
5205     case clang::BuiltinType::UInt128:
5206       return lldb::eFormatUnsigned;
5207     case clang::BuiltinType::Int128:
5208       return lldb::eFormatDecimal;
5209     case clang::BuiltinType::Half:
5210     case clang::BuiltinType::Float:
5211     case clang::BuiltinType::Double:
5212     case clang::BuiltinType::LongDouble:
5213       return lldb::eFormatFloat;
5214     default:
5215       return lldb::eFormatHex;
5216     }
5217     break;
5218   case clang::Type::ObjCObjectPointer:
5219     return lldb::eFormatHex;
5220   case clang::Type::BlockPointer:
5221     return lldb::eFormatHex;
5222   case clang::Type::Pointer:
5223     return lldb::eFormatHex;
5224   case clang::Type::LValueReference:
5225   case clang::Type::RValueReference:
5226     return lldb::eFormatHex;
5227   case clang::Type::MemberPointer:
5228     return lldb::eFormatHex;
5229   case clang::Type::Complex: {
5230     if (qual_type->isComplexType())
5231       return lldb::eFormatComplex;
5232     else
5233       return lldb::eFormatComplexInteger;
5234   }
5235   case clang::Type::ObjCInterface:
5236     break;
5237   case clang::Type::Record:
5238     break;
5239   case clang::Type::Enum:
5240     return lldb::eFormatEnum;
5241   case clang::Type::DependentSizedArray:
5242   case clang::Type::DependentSizedExtVector:
5243   case clang::Type::UnresolvedUsing:
5244   case clang::Type::Attributed:
5245   case clang::Type::BTFTagAttributed:
5246   case clang::Type::TemplateTypeParm:
5247   case clang::Type::SubstTemplateTypeParm:
5248   case clang::Type::SubstTemplateTypeParmPack:
5249   case clang::Type::InjectedClassName:
5250   case clang::Type::DependentName:
5251   case clang::Type::DependentTemplateSpecialization:
5252   case clang::Type::PackExpansion:
5253   case clang::Type::ObjCObject:
5254 
5255   case clang::Type::TemplateSpecialization:
5256   case clang::Type::DeducedTemplateSpecialization:
5257   case clang::Type::Adjusted:
5258   case clang::Type::Pipe:
5259     break;
5260 
5261   // pointer type decayed from an array or function type.
5262   case clang::Type::Decayed:
5263     break;
5264   case clang::Type::ObjCTypeParam:
5265     break;
5266 
5267   case clang::Type::DependentAddressSpace:
5268     break;
5269   case clang::Type::MacroQualified:
5270     break;
5271 
5272   // Matrix types we're not sure how to display yet.
5273   case clang::Type::ConstantMatrix:
5274   case clang::Type::DependentSizedMatrix:
5275     break;
5276 
5277   // We don't handle pack indexing yet
5278   case clang::Type::PackIndexing:
5279     break;
5280 
5281   case clang::Type::HLSLAttributedResource:
5282     break;
5283   }
5284   // We don't know hot to display this type...
5285   return lldb::eFormatBytes;
5286 }
5287 
5288 static bool ObjCDeclHasIVars(clang::ObjCInterfaceDecl *class_interface_decl,
5289                              bool check_superclass) {
5290   while (class_interface_decl) {
5291     if (class_interface_decl->ivar_size() > 0)
5292       return true;
5293 
5294     if (check_superclass)
5295       class_interface_decl = class_interface_decl->getSuperClass();
5296     else
5297       break;
5298   }
5299   return false;
5300 }
5301 
5302 static std::optional<SymbolFile::ArrayInfo>
5303 GetDynamicArrayInfo(TypeSystemClang &ast, SymbolFile *sym_file,
5304                     clang::QualType qual_type,
5305                     const ExecutionContext *exe_ctx) {
5306   if (qual_type->isIncompleteArrayType())
5307     if (std::optional<ClangASTMetadata> metadata =
5308             ast.GetMetadata(qual_type.getTypePtr()))
5309       return sym_file->GetDynamicArrayInfoForUID(metadata->GetUserID(),
5310                                                  exe_ctx);
5311   return std::nullopt;
5312 }
5313 
5314 llvm::Expected<uint32_t>
5315 TypeSystemClang::GetNumChildren(lldb::opaque_compiler_type_t type,
5316                                 bool omit_empty_base_classes,
5317                                 const ExecutionContext *exe_ctx) {
5318   if (!type)
5319     return llvm::createStringError("invalid clang type");
5320 
5321   uint32_t num_children = 0;
5322   clang::QualType qual_type(RemoveWrappingTypes(GetQualType(type)));
5323   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5324   switch (type_class) {
5325   case clang::Type::Builtin:
5326     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5327     case clang::BuiltinType::ObjCId:    // child is Class
5328     case clang::BuiltinType::ObjCClass: // child is Class
5329       num_children = 1;
5330       break;
5331 
5332     default:
5333       break;
5334     }
5335     break;
5336 
5337   case clang::Type::Complex:
5338     return 0;
5339   case clang::Type::Record:
5340     if (GetCompleteQualType(&getASTContext(), qual_type)) {
5341       const clang::RecordType *record_type =
5342           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5343       const clang::RecordDecl *record_decl = record_type->getDecl();
5344       assert(record_decl);
5345       const clang::CXXRecordDecl *cxx_record_decl =
5346           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
5347       if (cxx_record_decl) {
5348         if (omit_empty_base_classes) {
5349           // Check each base classes to see if it or any of its base classes
5350           // contain any fields. This can help limit the noise in variable
5351           // views by not having to show base classes that contain no members.
5352           clang::CXXRecordDecl::base_class_const_iterator base_class,
5353               base_class_end;
5354           for (base_class = cxx_record_decl->bases_begin(),
5355               base_class_end = cxx_record_decl->bases_end();
5356                base_class != base_class_end; ++base_class) {
5357             const clang::CXXRecordDecl *base_class_decl =
5358                 llvm::cast<clang::CXXRecordDecl>(
5359                     base_class->getType()
5360                         ->getAs<clang::RecordType>()
5361                         ->getDecl());
5362 
5363             // Skip empty base classes
5364             if (!TypeSystemClang::RecordHasFields(base_class_decl))
5365               continue;
5366 
5367             num_children++;
5368           }
5369         } else {
5370           // Include all base classes
5371           num_children += cxx_record_decl->getNumBases();
5372         }
5373       }
5374       num_children += std::distance(record_decl->field_begin(),
5375                                record_decl->field_end());
5376     } else
5377       return llvm::createStringError(
5378           "incomplete type \"" + GetDisplayTypeName(type).GetString() + "\"");
5379     break;
5380   case clang::Type::ObjCObject:
5381   case clang::Type::ObjCInterface:
5382     if (GetCompleteQualType(&getASTContext(), qual_type)) {
5383       const clang::ObjCObjectType *objc_class_type =
5384           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5385       assert(objc_class_type);
5386       if (objc_class_type) {
5387         clang::ObjCInterfaceDecl *class_interface_decl =
5388             objc_class_type->getInterface();
5389 
5390         if (class_interface_decl) {
5391 
5392           clang::ObjCInterfaceDecl *superclass_interface_decl =
5393               class_interface_decl->getSuperClass();
5394           if (superclass_interface_decl) {
5395             if (omit_empty_base_classes) {
5396               if (ObjCDeclHasIVars(superclass_interface_decl, true))
5397                 ++num_children;
5398             } else
5399               ++num_children;
5400           }
5401 
5402           num_children += class_interface_decl->ivar_size();
5403         }
5404       }
5405     }
5406     break;
5407 
5408   case clang::Type::LValueReference:
5409   case clang::Type::RValueReference:
5410   case clang::Type::ObjCObjectPointer: {
5411     CompilerType pointee_clang_type(GetPointeeType(type));
5412 
5413     uint32_t num_pointee_children = 0;
5414     if (pointee_clang_type.IsAggregateType()) {
5415       auto num_children_or_err =
5416           pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx);
5417       if (!num_children_or_err)
5418         return num_children_or_err;
5419       num_pointee_children = *num_children_or_err;
5420     }
5421     // If this type points to a simple type, then it has 1 child
5422     if (num_pointee_children == 0)
5423       num_children = 1;
5424     else
5425       num_children = num_pointee_children;
5426   } break;
5427 
5428   case clang::Type::Vector:
5429   case clang::Type::ExtVector:
5430     num_children =
5431         llvm::cast<clang::VectorType>(qual_type.getTypePtr())->getNumElements();
5432     break;
5433 
5434   case clang::Type::ConstantArray:
5435     num_children = llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr())
5436                        ->getSize()
5437                        .getLimitedValue();
5438     break;
5439   case clang::Type::IncompleteArray:
5440     if (auto array_info =
5441             GetDynamicArrayInfo(*this, GetSymbolFile(), qual_type, exe_ctx))
5442       // FIXME: Only 1-dimensional arrays are supported.
5443       num_children = array_info->element_orders.size()
5444                          ? array_info->element_orders.back().value_or(0)
5445                          : 0;
5446     break;
5447 
5448   case clang::Type::Pointer: {
5449     const clang::PointerType *pointer_type =
5450         llvm::cast<clang::PointerType>(qual_type.getTypePtr());
5451     clang::QualType pointee_type(pointer_type->getPointeeType());
5452     CompilerType pointee_clang_type(GetType(pointee_type));
5453     uint32_t num_pointee_children = 0;
5454     if (pointee_clang_type.IsAggregateType()) {
5455       auto num_children_or_err =
5456           pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx);
5457       if (!num_children_or_err)
5458         return num_children_or_err;
5459       num_pointee_children = *num_children_or_err;
5460     }
5461     if (num_pointee_children == 0) {
5462       // We have a pointer to a pointee type that claims it has no children. We
5463       // will want to look at
5464       num_children = GetNumPointeeChildren(pointee_type);
5465     } else
5466       num_children = num_pointee_children;
5467   } break;
5468 
5469   default:
5470     break;
5471   }
5472   return num_children;
5473 }
5474 
5475 CompilerType TypeSystemClang::GetBuiltinTypeByName(ConstString name) {
5476   return GetBasicType(GetBasicTypeEnumeration(name));
5477 }
5478 
5479 lldb::BasicType
5480 TypeSystemClang::GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) {
5481   if (type) {
5482     clang::QualType qual_type(GetQualType(type));
5483     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5484     if (type_class == clang::Type::Builtin) {
5485       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5486       case clang::BuiltinType::Void:
5487         return eBasicTypeVoid;
5488       case clang::BuiltinType::Bool:
5489         return eBasicTypeBool;
5490       case clang::BuiltinType::Char_S:
5491         return eBasicTypeSignedChar;
5492       case clang::BuiltinType::Char_U:
5493         return eBasicTypeUnsignedChar;
5494       case clang::BuiltinType::Char8:
5495         return eBasicTypeChar8;
5496       case clang::BuiltinType::Char16:
5497         return eBasicTypeChar16;
5498       case clang::BuiltinType::Char32:
5499         return eBasicTypeChar32;
5500       case clang::BuiltinType::UChar:
5501         return eBasicTypeUnsignedChar;
5502       case clang::BuiltinType::SChar:
5503         return eBasicTypeSignedChar;
5504       case clang::BuiltinType::WChar_S:
5505         return eBasicTypeSignedWChar;
5506       case clang::BuiltinType::WChar_U:
5507         return eBasicTypeUnsignedWChar;
5508       case clang::BuiltinType::Short:
5509         return eBasicTypeShort;
5510       case clang::BuiltinType::UShort:
5511         return eBasicTypeUnsignedShort;
5512       case clang::BuiltinType::Int:
5513         return eBasicTypeInt;
5514       case clang::BuiltinType::UInt:
5515         return eBasicTypeUnsignedInt;
5516       case clang::BuiltinType::Long:
5517         return eBasicTypeLong;
5518       case clang::BuiltinType::ULong:
5519         return eBasicTypeUnsignedLong;
5520       case clang::BuiltinType::LongLong:
5521         return eBasicTypeLongLong;
5522       case clang::BuiltinType::ULongLong:
5523         return eBasicTypeUnsignedLongLong;
5524       case clang::BuiltinType::Int128:
5525         return eBasicTypeInt128;
5526       case clang::BuiltinType::UInt128:
5527         return eBasicTypeUnsignedInt128;
5528 
5529       case clang::BuiltinType::Half:
5530         return eBasicTypeHalf;
5531       case clang::BuiltinType::Float:
5532         return eBasicTypeFloat;
5533       case clang::BuiltinType::Double:
5534         return eBasicTypeDouble;
5535       case clang::BuiltinType::LongDouble:
5536         return eBasicTypeLongDouble;
5537 
5538       case clang::BuiltinType::NullPtr:
5539         return eBasicTypeNullPtr;
5540       case clang::BuiltinType::ObjCId:
5541         return eBasicTypeObjCID;
5542       case clang::BuiltinType::ObjCClass:
5543         return eBasicTypeObjCClass;
5544       case clang::BuiltinType::ObjCSel:
5545         return eBasicTypeObjCSel;
5546       default:
5547         return eBasicTypeOther;
5548       }
5549     }
5550   }
5551   return eBasicTypeInvalid;
5552 }
5553 
5554 void TypeSystemClang::ForEachEnumerator(
5555     lldb::opaque_compiler_type_t type,
5556     std::function<bool(const CompilerType &integer_type,
5557                        ConstString name,
5558                        const llvm::APSInt &value)> const &callback) {
5559   const clang::EnumType *enum_type =
5560       llvm::dyn_cast<clang::EnumType>(GetCanonicalQualType(type));
5561   if (enum_type) {
5562     const clang::EnumDecl *enum_decl = enum_type->getDecl();
5563     if (enum_decl) {
5564       CompilerType integer_type = GetType(enum_decl->getIntegerType());
5565 
5566       clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
5567       for (enum_pos = enum_decl->enumerator_begin(),
5568           enum_end_pos = enum_decl->enumerator_end();
5569            enum_pos != enum_end_pos; ++enum_pos) {
5570         ConstString name(enum_pos->getNameAsString().c_str());
5571         if (!callback(integer_type, name, enum_pos->getInitVal()))
5572           break;
5573       }
5574     }
5575   }
5576 }
5577 
5578 #pragma mark Aggregate Types
5579 
5580 uint32_t TypeSystemClang::GetNumFields(lldb::opaque_compiler_type_t type) {
5581   if (!type)
5582     return 0;
5583 
5584   uint32_t count = 0;
5585   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
5586   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5587   switch (type_class) {
5588   case clang::Type::Record:
5589     if (GetCompleteType(type)) {
5590       const clang::RecordType *record_type =
5591           llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr());
5592       if (record_type) {
5593         clang::RecordDecl *record_decl = record_type->getDecl();
5594         if (record_decl) {
5595           count = std::distance(record_decl->field_begin(),
5596                                 record_decl->field_end());
5597         }
5598       }
5599     }
5600     break;
5601 
5602   case clang::Type::ObjCObjectPointer: {
5603     const clang::ObjCObjectPointerType *objc_class_type =
5604         qual_type->castAs<clang::ObjCObjectPointerType>();
5605     const clang::ObjCInterfaceType *objc_interface_type =
5606         objc_class_type->getInterfaceType();
5607     if (objc_interface_type &&
5608         GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5609             const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5610       clang::ObjCInterfaceDecl *class_interface_decl =
5611           objc_interface_type->getDecl();
5612       if (class_interface_decl) {
5613         count = class_interface_decl->ivar_size();
5614       }
5615     }
5616     break;
5617   }
5618 
5619   case clang::Type::ObjCObject:
5620   case clang::Type::ObjCInterface:
5621     if (GetCompleteType(type)) {
5622       const clang::ObjCObjectType *objc_class_type =
5623           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5624       if (objc_class_type) {
5625         clang::ObjCInterfaceDecl *class_interface_decl =
5626             objc_class_type->getInterface();
5627 
5628         if (class_interface_decl)
5629           count = class_interface_decl->ivar_size();
5630       }
5631     }
5632     break;
5633 
5634   default:
5635     break;
5636   }
5637   return count;
5638 }
5639 
5640 static lldb::opaque_compiler_type_t
5641 GetObjCFieldAtIndex(clang::ASTContext *ast,
5642                     clang::ObjCInterfaceDecl *class_interface_decl, size_t idx,
5643                     std::string &name, uint64_t *bit_offset_ptr,
5644                     uint32_t *bitfield_bit_size_ptr, bool *is_bitfield_ptr) {
5645   if (class_interface_decl) {
5646     if (idx < (class_interface_decl->ivar_size())) {
5647       clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
5648           ivar_end = class_interface_decl->ivar_end();
5649       uint32_t ivar_idx = 0;
5650 
5651       for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end;
5652            ++ivar_pos, ++ivar_idx) {
5653         if (ivar_idx == idx) {
5654           const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
5655 
5656           clang::QualType ivar_qual_type(ivar_decl->getType());
5657 
5658           name.assign(ivar_decl->getNameAsString());
5659 
5660           if (bit_offset_ptr) {
5661             const clang::ASTRecordLayout &interface_layout =
5662                 ast->getASTObjCInterfaceLayout(class_interface_decl);
5663             *bit_offset_ptr = interface_layout.getFieldOffset(ivar_idx);
5664           }
5665 
5666           const bool is_bitfield = ivar_pos->isBitField();
5667 
5668           if (bitfield_bit_size_ptr) {
5669             *bitfield_bit_size_ptr = 0;
5670 
5671             if (is_bitfield && ast) {
5672               clang::Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
5673               clang::Expr::EvalResult result;
5674               if (bitfield_bit_size_expr &&
5675                   bitfield_bit_size_expr->EvaluateAsInt(result, *ast)) {
5676                 llvm::APSInt bitfield_apsint = result.Val.getInt();
5677                 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5678               }
5679             }
5680           }
5681           if (is_bitfield_ptr)
5682             *is_bitfield_ptr = is_bitfield;
5683 
5684           return ivar_qual_type.getAsOpaquePtr();
5685         }
5686       }
5687     }
5688   }
5689   return nullptr;
5690 }
5691 
5692 CompilerType TypeSystemClang::GetFieldAtIndex(lldb::opaque_compiler_type_t type,
5693                                               size_t idx, std::string &name,
5694                                               uint64_t *bit_offset_ptr,
5695                                               uint32_t *bitfield_bit_size_ptr,
5696                                               bool *is_bitfield_ptr) {
5697   if (!type)
5698     return CompilerType();
5699 
5700   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
5701   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5702   switch (type_class) {
5703   case clang::Type::Record:
5704     if (GetCompleteType(type)) {
5705       const clang::RecordType *record_type =
5706           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5707       const clang::RecordDecl *record_decl = record_type->getDecl();
5708       uint32_t field_idx = 0;
5709       clang::RecordDecl::field_iterator field, field_end;
5710       for (field = record_decl->field_begin(),
5711           field_end = record_decl->field_end();
5712            field != field_end; ++field, ++field_idx) {
5713         if (idx == field_idx) {
5714           // Print the member type if requested
5715           // Print the member name and equal sign
5716           name.assign(field->getNameAsString());
5717 
5718           // Figure out the type byte size (field_type_info.first) and
5719           // alignment (field_type_info.second) from the AST context.
5720           if (bit_offset_ptr) {
5721             const clang::ASTRecordLayout &record_layout =
5722                 getASTContext().getASTRecordLayout(record_decl);
5723             *bit_offset_ptr = record_layout.getFieldOffset(field_idx);
5724           }
5725 
5726           const bool is_bitfield = field->isBitField();
5727 
5728           if (bitfield_bit_size_ptr) {
5729             *bitfield_bit_size_ptr = 0;
5730 
5731             if (is_bitfield) {
5732               clang::Expr *bitfield_bit_size_expr = field->getBitWidth();
5733               clang::Expr::EvalResult result;
5734               if (bitfield_bit_size_expr &&
5735                   bitfield_bit_size_expr->EvaluateAsInt(result,
5736                                                         getASTContext())) {
5737                 llvm::APSInt bitfield_apsint = result.Val.getInt();
5738                 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5739               }
5740             }
5741           }
5742           if (is_bitfield_ptr)
5743             *is_bitfield_ptr = is_bitfield;
5744 
5745           return GetType(field->getType());
5746         }
5747       }
5748     }
5749     break;
5750 
5751   case clang::Type::ObjCObjectPointer: {
5752     const clang::ObjCObjectPointerType *objc_class_type =
5753         qual_type->castAs<clang::ObjCObjectPointerType>();
5754     const clang::ObjCInterfaceType *objc_interface_type =
5755         objc_class_type->getInterfaceType();
5756     if (objc_interface_type &&
5757         GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5758             const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5759       clang::ObjCInterfaceDecl *class_interface_decl =
5760           objc_interface_type->getDecl();
5761       if (class_interface_decl) {
5762         return CompilerType(
5763             weak_from_this(),
5764             GetObjCFieldAtIndex(&getASTContext(), class_interface_decl, idx,
5765                                 name, bit_offset_ptr, bitfield_bit_size_ptr,
5766                                 is_bitfield_ptr));
5767       }
5768     }
5769     break;
5770   }
5771 
5772   case clang::Type::ObjCObject:
5773   case clang::Type::ObjCInterface:
5774     if (GetCompleteType(type)) {
5775       const clang::ObjCObjectType *objc_class_type =
5776           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5777       assert(objc_class_type);
5778       if (objc_class_type) {
5779         clang::ObjCInterfaceDecl *class_interface_decl =
5780             objc_class_type->getInterface();
5781         return CompilerType(
5782             weak_from_this(),
5783             GetObjCFieldAtIndex(&getASTContext(), class_interface_decl, idx,
5784                                 name, bit_offset_ptr, bitfield_bit_size_ptr,
5785                                 is_bitfield_ptr));
5786       }
5787     }
5788     break;
5789 
5790   default:
5791     break;
5792   }
5793   return CompilerType();
5794 }
5795 
5796 uint32_t
5797 TypeSystemClang::GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) {
5798   uint32_t count = 0;
5799   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5800   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5801   switch (type_class) {
5802   case clang::Type::Record:
5803     if (GetCompleteType(type)) {
5804       const clang::CXXRecordDecl *cxx_record_decl =
5805           qual_type->getAsCXXRecordDecl();
5806       if (cxx_record_decl)
5807         count = cxx_record_decl->getNumBases();
5808     }
5809     break;
5810 
5811   case clang::Type::ObjCObjectPointer:
5812     count = GetPointeeType(type).GetNumDirectBaseClasses();
5813     break;
5814 
5815   case clang::Type::ObjCObject:
5816     if (GetCompleteType(type)) {
5817       const clang::ObjCObjectType *objc_class_type =
5818           qual_type->getAsObjCQualifiedInterfaceType();
5819       if (objc_class_type) {
5820         clang::ObjCInterfaceDecl *class_interface_decl =
5821             objc_class_type->getInterface();
5822 
5823         if (class_interface_decl && class_interface_decl->getSuperClass())
5824           count = 1;
5825       }
5826     }
5827     break;
5828   case clang::Type::ObjCInterface:
5829     if (GetCompleteType(type)) {
5830       const clang::ObjCInterfaceType *objc_interface_type =
5831           qual_type->getAs<clang::ObjCInterfaceType>();
5832       if (objc_interface_type) {
5833         clang::ObjCInterfaceDecl *class_interface_decl =
5834             objc_interface_type->getInterface();
5835 
5836         if (class_interface_decl && class_interface_decl->getSuperClass())
5837           count = 1;
5838       }
5839     }
5840     break;
5841 
5842   default:
5843     break;
5844   }
5845   return count;
5846 }
5847 
5848 uint32_t
5849 TypeSystemClang::GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) {
5850   uint32_t count = 0;
5851   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5852   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5853   switch (type_class) {
5854   case clang::Type::Record:
5855     if (GetCompleteType(type)) {
5856       const clang::CXXRecordDecl *cxx_record_decl =
5857           qual_type->getAsCXXRecordDecl();
5858       if (cxx_record_decl)
5859         count = cxx_record_decl->getNumVBases();
5860     }
5861     break;
5862 
5863   default:
5864     break;
5865   }
5866   return count;
5867 }
5868 
5869 CompilerType TypeSystemClang::GetDirectBaseClassAtIndex(
5870     lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
5871   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5872   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5873   switch (type_class) {
5874   case clang::Type::Record:
5875     if (GetCompleteType(type)) {
5876       const clang::CXXRecordDecl *cxx_record_decl =
5877           qual_type->getAsCXXRecordDecl();
5878       if (cxx_record_decl) {
5879         uint32_t curr_idx = 0;
5880         clang::CXXRecordDecl::base_class_const_iterator base_class,
5881             base_class_end;
5882         for (base_class = cxx_record_decl->bases_begin(),
5883             base_class_end = cxx_record_decl->bases_end();
5884              base_class != base_class_end; ++base_class, ++curr_idx) {
5885           if (curr_idx == idx) {
5886             if (bit_offset_ptr) {
5887               const clang::ASTRecordLayout &record_layout =
5888                   getASTContext().getASTRecordLayout(cxx_record_decl);
5889               const clang::CXXRecordDecl *base_class_decl =
5890                   llvm::cast<clang::CXXRecordDecl>(
5891                       base_class->getType()
5892                           ->castAs<clang::RecordType>()
5893                           ->getDecl());
5894               if (base_class->isVirtual())
5895                 *bit_offset_ptr =
5896                     record_layout.getVBaseClassOffset(base_class_decl)
5897                         .getQuantity() *
5898                     8;
5899               else
5900                 *bit_offset_ptr =
5901                     record_layout.getBaseClassOffset(base_class_decl)
5902                         .getQuantity() *
5903                     8;
5904             }
5905             return GetType(base_class->getType());
5906           }
5907         }
5908       }
5909     }
5910     break;
5911 
5912   case clang::Type::ObjCObjectPointer:
5913     return GetPointeeType(type).GetDirectBaseClassAtIndex(idx, bit_offset_ptr);
5914 
5915   case clang::Type::ObjCObject:
5916     if (idx == 0 && GetCompleteType(type)) {
5917       const clang::ObjCObjectType *objc_class_type =
5918           qual_type->getAsObjCQualifiedInterfaceType();
5919       if (objc_class_type) {
5920         clang::ObjCInterfaceDecl *class_interface_decl =
5921             objc_class_type->getInterface();
5922 
5923         if (class_interface_decl) {
5924           clang::ObjCInterfaceDecl *superclass_interface_decl =
5925               class_interface_decl->getSuperClass();
5926           if (superclass_interface_decl) {
5927             if (bit_offset_ptr)
5928               *bit_offset_ptr = 0;
5929             return GetType(getASTContext().getObjCInterfaceType(
5930                 superclass_interface_decl));
5931           }
5932         }
5933       }
5934     }
5935     break;
5936   case clang::Type::ObjCInterface:
5937     if (idx == 0 && GetCompleteType(type)) {
5938       const clang::ObjCObjectType *objc_interface_type =
5939           qual_type->getAs<clang::ObjCInterfaceType>();
5940       if (objc_interface_type) {
5941         clang::ObjCInterfaceDecl *class_interface_decl =
5942             objc_interface_type->getInterface();
5943 
5944         if (class_interface_decl) {
5945           clang::ObjCInterfaceDecl *superclass_interface_decl =
5946               class_interface_decl->getSuperClass();
5947           if (superclass_interface_decl) {
5948             if (bit_offset_ptr)
5949               *bit_offset_ptr = 0;
5950             return GetType(getASTContext().getObjCInterfaceType(
5951                 superclass_interface_decl));
5952           }
5953         }
5954       }
5955     }
5956     break;
5957 
5958   default:
5959     break;
5960   }
5961   return CompilerType();
5962 }
5963 
5964 CompilerType TypeSystemClang::GetVirtualBaseClassAtIndex(
5965     lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
5966   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5967   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5968   switch (type_class) {
5969   case clang::Type::Record:
5970     if (GetCompleteType(type)) {
5971       const clang::CXXRecordDecl *cxx_record_decl =
5972           qual_type->getAsCXXRecordDecl();
5973       if (cxx_record_decl) {
5974         uint32_t curr_idx = 0;
5975         clang::CXXRecordDecl::base_class_const_iterator base_class,
5976             base_class_end;
5977         for (base_class = cxx_record_decl->vbases_begin(),
5978             base_class_end = cxx_record_decl->vbases_end();
5979              base_class != base_class_end; ++base_class, ++curr_idx) {
5980           if (curr_idx == idx) {
5981             if (bit_offset_ptr) {
5982               const clang::ASTRecordLayout &record_layout =
5983                   getASTContext().getASTRecordLayout(cxx_record_decl);
5984               const clang::CXXRecordDecl *base_class_decl =
5985                   llvm::cast<clang::CXXRecordDecl>(
5986                       base_class->getType()
5987                           ->castAs<clang::RecordType>()
5988                           ->getDecl());
5989               *bit_offset_ptr =
5990                   record_layout.getVBaseClassOffset(base_class_decl)
5991                       .getQuantity() *
5992                   8;
5993             }
5994             return GetType(base_class->getType());
5995           }
5996         }
5997       }
5998     }
5999     break;
6000 
6001   default:
6002     break;
6003   }
6004   return CompilerType();
6005 }
6006 
6007 CompilerDecl
6008 TypeSystemClang::GetStaticFieldWithName(lldb::opaque_compiler_type_t type,
6009                                         llvm::StringRef name) {
6010   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6011   switch (qual_type->getTypeClass()) {
6012   case clang::Type::Record: {
6013     if (!GetCompleteType(type))
6014       return CompilerDecl();
6015 
6016     const clang::RecordType *record_type =
6017         llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6018     const clang::RecordDecl *record_decl = record_type->getDecl();
6019 
6020     clang::DeclarationName decl_name(&getASTContext().Idents.get(name));
6021     for (NamedDecl *decl : record_decl->lookup(decl_name)) {
6022       auto *var_decl = dyn_cast<clang::VarDecl>(decl);
6023       if (!var_decl || var_decl->getStorageClass() != clang::SC_Static)
6024         continue;
6025 
6026       return CompilerDecl(this, var_decl);
6027     }
6028     break;
6029   }
6030 
6031   default:
6032     break;
6033   }
6034   return CompilerDecl();
6035 }
6036 
6037 // If a pointer to a pointee type (the clang_type arg) says that it has no
6038 // children, then we either need to trust it, or override it and return a
6039 // different result. For example, an "int *" has one child that is an integer,
6040 // but a function pointer doesn't have any children. Likewise if a Record type
6041 // claims it has no children, then there really is nothing to show.
6042 uint32_t TypeSystemClang::GetNumPointeeChildren(clang::QualType type) {
6043   if (type.isNull())
6044     return 0;
6045 
6046   clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType());
6047   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6048   switch (type_class) {
6049   case clang::Type::Builtin:
6050     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
6051     case clang::BuiltinType::UnknownAny:
6052     case clang::BuiltinType::Void:
6053     case clang::BuiltinType::NullPtr:
6054     case clang::BuiltinType::OCLEvent:
6055     case clang::BuiltinType::OCLImage1dRO:
6056     case clang::BuiltinType::OCLImage1dWO:
6057     case clang::BuiltinType::OCLImage1dRW:
6058     case clang::BuiltinType::OCLImage1dArrayRO:
6059     case clang::BuiltinType::OCLImage1dArrayWO:
6060     case clang::BuiltinType::OCLImage1dArrayRW:
6061     case clang::BuiltinType::OCLImage1dBufferRO:
6062     case clang::BuiltinType::OCLImage1dBufferWO:
6063     case clang::BuiltinType::OCLImage1dBufferRW:
6064     case clang::BuiltinType::OCLImage2dRO:
6065     case clang::BuiltinType::OCLImage2dWO:
6066     case clang::BuiltinType::OCLImage2dRW:
6067     case clang::BuiltinType::OCLImage2dArrayRO:
6068     case clang::BuiltinType::OCLImage2dArrayWO:
6069     case clang::BuiltinType::OCLImage2dArrayRW:
6070     case clang::BuiltinType::OCLImage3dRO:
6071     case clang::BuiltinType::OCLImage3dWO:
6072     case clang::BuiltinType::OCLImage3dRW:
6073     case clang::BuiltinType::OCLSampler:
6074     case clang::BuiltinType::HLSLResource:
6075       return 0;
6076     case clang::BuiltinType::Bool:
6077     case clang::BuiltinType::Char_U:
6078     case clang::BuiltinType::UChar:
6079     case clang::BuiltinType::WChar_U:
6080     case clang::BuiltinType::Char16:
6081     case clang::BuiltinType::Char32:
6082     case clang::BuiltinType::UShort:
6083     case clang::BuiltinType::UInt:
6084     case clang::BuiltinType::ULong:
6085     case clang::BuiltinType::ULongLong:
6086     case clang::BuiltinType::UInt128:
6087     case clang::BuiltinType::Char_S:
6088     case clang::BuiltinType::SChar:
6089     case clang::BuiltinType::WChar_S:
6090     case clang::BuiltinType::Short:
6091     case clang::BuiltinType::Int:
6092     case clang::BuiltinType::Long:
6093     case clang::BuiltinType::LongLong:
6094     case clang::BuiltinType::Int128:
6095     case clang::BuiltinType::Float:
6096     case clang::BuiltinType::Double:
6097     case clang::BuiltinType::LongDouble:
6098     case clang::BuiltinType::Dependent:
6099     case clang::BuiltinType::Overload:
6100     case clang::BuiltinType::ObjCId:
6101     case clang::BuiltinType::ObjCClass:
6102     case clang::BuiltinType::ObjCSel:
6103     case clang::BuiltinType::BoundMember:
6104     case clang::BuiltinType::Half:
6105     case clang::BuiltinType::ARCUnbridgedCast:
6106     case clang::BuiltinType::PseudoObject:
6107     case clang::BuiltinType::BuiltinFn:
6108     case clang::BuiltinType::ArraySection:
6109       return 1;
6110     default:
6111       return 0;
6112     }
6113     break;
6114 
6115   case clang::Type::Complex:
6116     return 1;
6117   case clang::Type::Pointer:
6118     return 1;
6119   case clang::Type::BlockPointer:
6120     return 0; // If block pointers don't have debug info, then no children for
6121               // them
6122   case clang::Type::LValueReference:
6123     return 1;
6124   case clang::Type::RValueReference:
6125     return 1;
6126   case clang::Type::MemberPointer:
6127     return 0;
6128   case clang::Type::ConstantArray:
6129     return 0;
6130   case clang::Type::IncompleteArray:
6131     return 0;
6132   case clang::Type::VariableArray:
6133     return 0;
6134   case clang::Type::DependentSizedArray:
6135     return 0;
6136   case clang::Type::DependentSizedExtVector:
6137     return 0;
6138   case clang::Type::Vector:
6139     return 0;
6140   case clang::Type::ExtVector:
6141     return 0;
6142   case clang::Type::FunctionProto:
6143     return 0; // When we function pointers, they have no children...
6144   case clang::Type::FunctionNoProto:
6145     return 0; // When we function pointers, they have no children...
6146   case clang::Type::UnresolvedUsing:
6147     return 0;
6148   case clang::Type::Record:
6149     return 0;
6150   case clang::Type::Enum:
6151     return 1;
6152   case clang::Type::TemplateTypeParm:
6153     return 1;
6154   case clang::Type::SubstTemplateTypeParm:
6155     return 1;
6156   case clang::Type::TemplateSpecialization:
6157     return 1;
6158   case clang::Type::InjectedClassName:
6159     return 0;
6160   case clang::Type::DependentName:
6161     return 1;
6162   case clang::Type::DependentTemplateSpecialization:
6163     return 1;
6164   case clang::Type::ObjCObject:
6165     return 0;
6166   case clang::Type::ObjCInterface:
6167     return 0;
6168   case clang::Type::ObjCObjectPointer:
6169     return 1;
6170   default:
6171     break;
6172   }
6173   return 0;
6174 }
6175 
6176 llvm::Expected<CompilerType> TypeSystemClang::GetChildCompilerTypeAtIndex(
6177     lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, size_t idx,
6178     bool transparent_pointers, bool omit_empty_base_classes,
6179     bool ignore_array_bounds, std::string &child_name,
6180     uint32_t &child_byte_size, int32_t &child_byte_offset,
6181     uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset,
6182     bool &child_is_base_class, bool &child_is_deref_of_parent,
6183     ValueObject *valobj, uint64_t &language_flags) {
6184   if (!type)
6185     return CompilerType();
6186 
6187   auto get_exe_scope = [&exe_ctx]() {
6188     return exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr;
6189   };
6190 
6191   clang::QualType parent_qual_type(
6192       RemoveWrappingTypes(GetCanonicalQualType(type)));
6193   const clang::Type::TypeClass parent_type_class =
6194       parent_qual_type->getTypeClass();
6195   child_bitfield_bit_size = 0;
6196   child_bitfield_bit_offset = 0;
6197   child_is_base_class = false;
6198   language_flags = 0;
6199 
6200   auto num_children_or_err =
6201       GetNumChildren(type, omit_empty_base_classes, exe_ctx);
6202   if (!num_children_or_err)
6203     return num_children_or_err.takeError();
6204 
6205   const bool idx_is_valid = idx < *num_children_or_err;
6206   int32_t bit_offset;
6207   switch (parent_type_class) {
6208   case clang::Type::Builtin:
6209     if (idx_is_valid) {
6210       switch (llvm::cast<clang::BuiltinType>(parent_qual_type)->getKind()) {
6211       case clang::BuiltinType::ObjCId:
6212       case clang::BuiltinType::ObjCClass:
6213         child_name = "isa";
6214         child_byte_size =
6215             getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy) /
6216             CHAR_BIT;
6217         return GetType(getASTContext().ObjCBuiltinClassTy);
6218 
6219       default:
6220         break;
6221       }
6222     }
6223     break;
6224 
6225   case clang::Type::Record:
6226     if (idx_is_valid && GetCompleteType(type)) {
6227       const clang::RecordType *record_type =
6228           llvm::cast<clang::RecordType>(parent_qual_type.getTypePtr());
6229       const clang::RecordDecl *record_decl = record_type->getDecl();
6230       assert(record_decl);
6231       const clang::ASTRecordLayout &record_layout =
6232           getASTContext().getASTRecordLayout(record_decl);
6233       uint32_t child_idx = 0;
6234 
6235       const clang::CXXRecordDecl *cxx_record_decl =
6236           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6237       if (cxx_record_decl) {
6238         // We might have base classes to print out first
6239         clang::CXXRecordDecl::base_class_const_iterator base_class,
6240             base_class_end;
6241         for (base_class = cxx_record_decl->bases_begin(),
6242             base_class_end = cxx_record_decl->bases_end();
6243              base_class != base_class_end; ++base_class) {
6244           const clang::CXXRecordDecl *base_class_decl = nullptr;
6245 
6246           // Skip empty base classes
6247           if (omit_empty_base_classes) {
6248             base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6249                 base_class->getType()->getAs<clang::RecordType>()->getDecl());
6250             if (!TypeSystemClang::RecordHasFields(base_class_decl))
6251               continue;
6252           }
6253 
6254           if (idx == child_idx) {
6255             if (base_class_decl == nullptr)
6256               base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6257                   base_class->getType()->getAs<clang::RecordType>()->getDecl());
6258 
6259             if (base_class->isVirtual()) {
6260               bool handled = false;
6261               if (valobj) {
6262                 clang::VTableContextBase *vtable_ctx =
6263                     getASTContext().getVTableContext();
6264                 if (vtable_ctx)
6265                   handled = GetVBaseBitOffset(*vtable_ctx, *valobj,
6266                                               record_layout, cxx_record_decl,
6267                                               base_class_decl, bit_offset);
6268               }
6269               if (!handled)
6270                 bit_offset = record_layout.getVBaseClassOffset(base_class_decl)
6271                                  .getQuantity() *
6272                              8;
6273             } else
6274               bit_offset = record_layout.getBaseClassOffset(base_class_decl)
6275                                .getQuantity() *
6276                            8;
6277 
6278             // Base classes should be a multiple of 8 bits in size
6279             child_byte_offset = bit_offset / 8;
6280             CompilerType base_class_clang_type = GetType(base_class->getType());
6281             child_name = base_class_clang_type.GetTypeName().AsCString("");
6282             std::optional<uint64_t> size =
6283                 base_class_clang_type.GetBitSize(get_exe_scope());
6284             if (!size)
6285               return llvm::createStringError("no size info for base class");
6286 
6287             uint64_t base_class_clang_type_bit_size = *size;
6288 
6289             // Base classes bit sizes should be a multiple of 8 bits in size
6290             assert(base_class_clang_type_bit_size % 8 == 0);
6291             child_byte_size = base_class_clang_type_bit_size / 8;
6292             child_is_base_class = true;
6293             return base_class_clang_type;
6294           }
6295           // We don't increment the child index in the for loop since we might
6296           // be skipping empty base classes
6297           ++child_idx;
6298         }
6299       }
6300       // Make sure index is in range...
6301       uint32_t field_idx = 0;
6302       clang::RecordDecl::field_iterator field, field_end;
6303       for (field = record_decl->field_begin(),
6304           field_end = record_decl->field_end();
6305            field != field_end; ++field, ++field_idx, ++child_idx) {
6306         if (idx == child_idx) {
6307           // Print the member type if requested
6308           // Print the member name and equal sign
6309           child_name.assign(field->getNameAsString());
6310 
6311           // Figure out the type byte size (field_type_info.first) and
6312           // alignment (field_type_info.second) from the AST context.
6313           CompilerType field_clang_type = GetType(field->getType());
6314           assert(field_idx < record_layout.getFieldCount());
6315           std::optional<uint64_t> size =
6316               field_clang_type.GetByteSize(get_exe_scope());
6317           if (!size)
6318             return llvm::createStringError("no size info for field");
6319 
6320           child_byte_size = *size;
6321           const uint32_t child_bit_size = child_byte_size * 8;
6322 
6323           // Figure out the field offset within the current struct/union/class
6324           // type
6325           bit_offset = record_layout.getFieldOffset(field_idx);
6326           if (FieldIsBitfield(*field, child_bitfield_bit_size)) {
6327             child_bitfield_bit_offset = bit_offset % child_bit_size;
6328             const uint32_t child_bit_offset =
6329                 bit_offset - child_bitfield_bit_offset;
6330             child_byte_offset = child_bit_offset / 8;
6331           } else {
6332             child_byte_offset = bit_offset / 8;
6333           }
6334 
6335           return field_clang_type;
6336         }
6337       }
6338     }
6339     break;
6340 
6341   case clang::Type::ObjCObject:
6342   case clang::Type::ObjCInterface:
6343     if (idx_is_valid && GetCompleteType(type)) {
6344       const clang::ObjCObjectType *objc_class_type =
6345           llvm::dyn_cast<clang::ObjCObjectType>(parent_qual_type.getTypePtr());
6346       assert(objc_class_type);
6347       if (objc_class_type) {
6348         uint32_t child_idx = 0;
6349         clang::ObjCInterfaceDecl *class_interface_decl =
6350             objc_class_type->getInterface();
6351 
6352         if (class_interface_decl) {
6353 
6354           const clang::ASTRecordLayout &interface_layout =
6355               getASTContext().getASTObjCInterfaceLayout(class_interface_decl);
6356           clang::ObjCInterfaceDecl *superclass_interface_decl =
6357               class_interface_decl->getSuperClass();
6358           if (superclass_interface_decl) {
6359             if (omit_empty_base_classes) {
6360               CompilerType base_class_clang_type =
6361                   GetType(getASTContext().getObjCInterfaceType(
6362                       superclass_interface_decl));
6363               if (llvm::expectedToStdOptional(
6364                       base_class_clang_type.GetNumChildren(
6365                           omit_empty_base_classes, exe_ctx))
6366                       .value_or(0) > 0) {
6367                 if (idx == 0) {
6368                   clang::QualType ivar_qual_type(
6369                       getASTContext().getObjCInterfaceType(
6370                           superclass_interface_decl));
6371 
6372                   child_name.assign(
6373                       superclass_interface_decl->getNameAsString());
6374 
6375                   clang::TypeInfo ivar_type_info =
6376                       getASTContext().getTypeInfo(ivar_qual_type.getTypePtr());
6377 
6378                   child_byte_size = ivar_type_info.Width / 8;
6379                   child_byte_offset = 0;
6380                   child_is_base_class = true;
6381 
6382                   return GetType(ivar_qual_type);
6383                 }
6384 
6385                 ++child_idx;
6386               }
6387             } else
6388               ++child_idx;
6389           }
6390 
6391           const uint32_t superclass_idx = child_idx;
6392 
6393           if (idx < (child_idx + class_interface_decl->ivar_size())) {
6394             clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6395                 ivar_end = class_interface_decl->ivar_end();
6396 
6397             for (ivar_pos = class_interface_decl->ivar_begin();
6398                  ivar_pos != ivar_end; ++ivar_pos) {
6399               if (child_idx == idx) {
6400                 clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6401 
6402                 clang::QualType ivar_qual_type(ivar_decl->getType());
6403 
6404                 child_name.assign(ivar_decl->getNameAsString());
6405 
6406                 clang::TypeInfo ivar_type_info =
6407                     getASTContext().getTypeInfo(ivar_qual_type.getTypePtr());
6408 
6409                 child_byte_size = ivar_type_info.Width / 8;
6410 
6411                 // Figure out the field offset within the current
6412                 // struct/union/class type For ObjC objects, we can't trust the
6413                 // bit offset we get from the Clang AST, since that doesn't
6414                 // account for the space taken up by unbacked properties, or
6415                 // from the changing size of base classes that are newer than
6416                 // this class. So if we have a process around that we can ask
6417                 // about this object, do so.
6418                 child_byte_offset = LLDB_INVALID_IVAR_OFFSET;
6419                 Process *process = nullptr;
6420                 if (exe_ctx)
6421                   process = exe_ctx->GetProcessPtr();
6422                 if (process) {
6423                   ObjCLanguageRuntime *objc_runtime =
6424                       ObjCLanguageRuntime::Get(*process);
6425                   if (objc_runtime != nullptr) {
6426                     CompilerType parent_ast_type = GetType(parent_qual_type);
6427                     child_byte_offset = objc_runtime->GetByteOffsetForIvar(
6428                         parent_ast_type, ivar_decl->getNameAsString().c_str());
6429                   }
6430                 }
6431 
6432                 // Setting this to INT32_MAX to make sure we don't compute it
6433                 // twice...
6434                 bit_offset = INT32_MAX;
6435 
6436                 if (child_byte_offset ==
6437                     static_cast<int32_t>(LLDB_INVALID_IVAR_OFFSET)) {
6438                   bit_offset = interface_layout.getFieldOffset(child_idx -
6439                                                                superclass_idx);
6440                   child_byte_offset = bit_offset / 8;
6441                 }
6442 
6443                 // Note, the ObjC Ivar Byte offset is just that, it doesn't
6444                 // account for the bit offset of a bitfield within its
6445                 // containing object.  So regardless of where we get the byte
6446                 // offset from, we still need to get the bit offset for
6447                 // bitfields from the layout.
6448 
6449                 if (FieldIsBitfield(ivar_decl, child_bitfield_bit_size)) {
6450                   if (bit_offset == INT32_MAX)
6451                     bit_offset = interface_layout.getFieldOffset(
6452                         child_idx - superclass_idx);
6453 
6454                   child_bitfield_bit_offset = bit_offset % 8;
6455                 }
6456                 return GetType(ivar_qual_type);
6457               }
6458               ++child_idx;
6459             }
6460           }
6461         }
6462       }
6463     }
6464     break;
6465 
6466   case clang::Type::ObjCObjectPointer:
6467     if (idx_is_valid) {
6468       CompilerType pointee_clang_type(GetPointeeType(type));
6469 
6470       if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6471         child_is_deref_of_parent = false;
6472         bool tmp_child_is_deref_of_parent = false;
6473         return pointee_clang_type.GetChildCompilerTypeAtIndex(
6474             exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6475             ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6476             child_bitfield_bit_size, child_bitfield_bit_offset,
6477             child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6478             language_flags);
6479       } else {
6480         child_is_deref_of_parent = true;
6481         const char *parent_name =
6482             valobj ? valobj->GetName().GetCString() : nullptr;
6483         if (parent_name) {
6484           child_name.assign(1, '*');
6485           child_name += parent_name;
6486         }
6487 
6488         // We have a pointer to an simple type
6489         if (idx == 0 && pointee_clang_type.GetCompleteType()) {
6490           if (std::optional<uint64_t> size =
6491                   pointee_clang_type.GetByteSize(get_exe_scope())) {
6492             child_byte_size = *size;
6493             child_byte_offset = 0;
6494             return pointee_clang_type;
6495           }
6496         }
6497       }
6498     }
6499     break;
6500 
6501   case clang::Type::Vector:
6502   case clang::Type::ExtVector:
6503     if (idx_is_valid) {
6504       const clang::VectorType *array =
6505           llvm::cast<clang::VectorType>(parent_qual_type.getTypePtr());
6506       if (array) {
6507         CompilerType element_type = GetType(array->getElementType());
6508         if (element_type.GetCompleteType()) {
6509           char element_name[64];
6510           ::snprintf(element_name, sizeof(element_name), "[%" PRIu64 "]",
6511                      static_cast<uint64_t>(idx));
6512           child_name.assign(element_name);
6513           if (std::optional<uint64_t> size =
6514                   element_type.GetByteSize(get_exe_scope())) {
6515             child_byte_size = *size;
6516             child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6517             return element_type;
6518           }
6519         }
6520       }
6521     }
6522     break;
6523 
6524   case clang::Type::ConstantArray:
6525   case clang::Type::IncompleteArray:
6526     if (ignore_array_bounds || idx_is_valid) {
6527       const clang::ArrayType *array = GetQualType(type)->getAsArrayTypeUnsafe();
6528       if (array) {
6529         CompilerType element_type = GetType(array->getElementType());
6530         if (element_type.GetCompleteType()) {
6531           child_name = std::string(llvm::formatv("[{0}]", idx));
6532           if (std::optional<uint64_t> size =
6533                   element_type.GetByteSize(get_exe_scope())) {
6534             child_byte_size = *size;
6535             child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6536             return element_type;
6537           }
6538         }
6539       }
6540     }
6541     break;
6542 
6543   case clang::Type::Pointer: {
6544     CompilerType pointee_clang_type(GetPointeeType(type));
6545 
6546     // Don't dereference "void *" pointers
6547     if (pointee_clang_type.IsVoidType())
6548       return CompilerType();
6549 
6550     if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6551       child_is_deref_of_parent = false;
6552       bool tmp_child_is_deref_of_parent = false;
6553       return pointee_clang_type.GetChildCompilerTypeAtIndex(
6554           exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6555           ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6556           child_bitfield_bit_size, child_bitfield_bit_offset,
6557           child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6558           language_flags);
6559     } else {
6560       child_is_deref_of_parent = true;
6561 
6562       const char *parent_name =
6563           valobj ? valobj->GetName().GetCString() : nullptr;
6564       if (parent_name) {
6565         child_name.assign(1, '*');
6566         child_name += parent_name;
6567       }
6568 
6569       // We have a pointer to an simple type
6570       if (idx == 0) {
6571         if (std::optional<uint64_t> size =
6572                 pointee_clang_type.GetByteSize(get_exe_scope())) {
6573           child_byte_size = *size;
6574           child_byte_offset = 0;
6575           return pointee_clang_type;
6576         }
6577       }
6578     }
6579     break;
6580   }
6581 
6582   case clang::Type::LValueReference:
6583   case clang::Type::RValueReference:
6584     if (idx_is_valid) {
6585       const clang::ReferenceType *reference_type =
6586           llvm::cast<clang::ReferenceType>(
6587               RemoveWrappingTypes(GetQualType(type)).getTypePtr());
6588       CompilerType pointee_clang_type =
6589           GetType(reference_type->getPointeeType());
6590       if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6591         child_is_deref_of_parent = false;
6592         bool tmp_child_is_deref_of_parent = false;
6593         return pointee_clang_type.GetChildCompilerTypeAtIndex(
6594             exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6595             ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6596             child_bitfield_bit_size, child_bitfield_bit_offset,
6597             child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6598             language_flags);
6599       } else {
6600         const char *parent_name =
6601             valobj ? valobj->GetName().GetCString() : nullptr;
6602         if (parent_name) {
6603           child_name.assign(1, '&');
6604           child_name += parent_name;
6605         }
6606 
6607         // We have a pointer to an simple type
6608         if (idx == 0) {
6609           if (std::optional<uint64_t> size =
6610                   pointee_clang_type.GetByteSize(get_exe_scope())) {
6611             child_byte_size = *size;
6612             child_byte_offset = 0;
6613             return pointee_clang_type;
6614           }
6615         }
6616       }
6617     }
6618     break;
6619 
6620   default:
6621     break;
6622   }
6623   return CompilerType();
6624 }
6625 
6626 uint32_t TypeSystemClang::GetIndexForRecordBase(
6627     const clang::RecordDecl *record_decl,
6628     const clang::CXXBaseSpecifier *base_spec,
6629     bool omit_empty_base_classes) {
6630   uint32_t child_idx = 0;
6631 
6632   const clang::CXXRecordDecl *cxx_record_decl =
6633       llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6634 
6635   if (cxx_record_decl) {
6636     clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
6637     for (base_class = cxx_record_decl->bases_begin(),
6638         base_class_end = cxx_record_decl->bases_end();
6639          base_class != base_class_end; ++base_class) {
6640       if (omit_empty_base_classes) {
6641         if (BaseSpecifierIsEmpty(base_class))
6642           continue;
6643       }
6644 
6645       if (base_class == base_spec)
6646         return child_idx;
6647       ++child_idx;
6648     }
6649   }
6650 
6651   return UINT32_MAX;
6652 }
6653 
6654 uint32_t TypeSystemClang::GetIndexForRecordChild(
6655     const clang::RecordDecl *record_decl, clang::NamedDecl *canonical_decl,
6656     bool omit_empty_base_classes) {
6657   uint32_t child_idx = TypeSystemClang::GetNumBaseClasses(
6658       llvm::dyn_cast<clang::CXXRecordDecl>(record_decl),
6659       omit_empty_base_classes);
6660 
6661   clang::RecordDecl::field_iterator field, field_end;
6662   for (field = record_decl->field_begin(), field_end = record_decl->field_end();
6663        field != field_end; ++field, ++child_idx) {
6664     if (field->getCanonicalDecl() == canonical_decl)
6665       return child_idx;
6666   }
6667 
6668   return UINT32_MAX;
6669 }
6670 
6671 // Look for a child member (doesn't include base classes, but it does include
6672 // their members) in the type hierarchy. Returns an index path into
6673 // "clang_type" on how to reach the appropriate member.
6674 //
6675 //    class A
6676 //    {
6677 //    public:
6678 //        int m_a;
6679 //        int m_b;
6680 //    };
6681 //
6682 //    class B
6683 //    {
6684 //    };
6685 //
6686 //    class C :
6687 //        public B,
6688 //        public A
6689 //    {
6690 //    };
6691 //
6692 // If we have a clang type that describes "class C", and we wanted to looked
6693 // "m_b" in it:
6694 //
6695 // With omit_empty_base_classes == false we would get an integer array back
6696 // with: { 1,  1 } The first index 1 is the child index for "class A" within
6697 // class C The second index 1 is the child index for "m_b" within class A
6698 //
6699 // With omit_empty_base_classes == true we would get an integer array back
6700 // with: { 0,  1 } The first index 0 is the child index for "class A" within
6701 // class C (since class B doesn't have any members it doesn't count) The second
6702 // index 1 is the child index for "m_b" within class A
6703 
6704 size_t TypeSystemClang::GetIndexOfChildMemberWithName(
6705     lldb::opaque_compiler_type_t type, llvm::StringRef name,
6706     bool omit_empty_base_classes, std::vector<uint32_t> &child_indexes) {
6707   if (type && !name.empty()) {
6708     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6709     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6710     switch (type_class) {
6711     case clang::Type::Record:
6712       if (GetCompleteType(type)) {
6713         const clang::RecordType *record_type =
6714             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6715         const clang::RecordDecl *record_decl = record_type->getDecl();
6716 
6717         assert(record_decl);
6718         uint32_t child_idx = 0;
6719 
6720         const clang::CXXRecordDecl *cxx_record_decl =
6721             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6722 
6723         // Try and find a field that matches NAME
6724         clang::RecordDecl::field_iterator field, field_end;
6725         for (field = record_decl->field_begin(),
6726             field_end = record_decl->field_end();
6727              field != field_end; ++field, ++child_idx) {
6728           llvm::StringRef field_name = field->getName();
6729           if (field_name.empty()) {
6730             CompilerType field_type = GetType(field->getType());
6731             std::vector<uint32_t> save_indices = child_indexes;
6732             child_indexes.push_back(child_idx);
6733             if (field_type.GetIndexOfChildMemberWithName(
6734                     name, omit_empty_base_classes, child_indexes))
6735               return child_indexes.size();
6736             child_indexes = std::move(save_indices);
6737           } else if (field_name == name) {
6738             // We have to add on the number of base classes to this index!
6739             child_indexes.push_back(
6740                 child_idx + TypeSystemClang::GetNumBaseClasses(
6741                                 cxx_record_decl, omit_empty_base_classes));
6742             return child_indexes.size();
6743           }
6744         }
6745 
6746         if (cxx_record_decl) {
6747           const clang::RecordDecl *parent_record_decl = cxx_record_decl;
6748 
6749           // Didn't find things easily, lets let clang do its thang...
6750           clang::IdentifierInfo &ident_ref = getASTContext().Idents.get(name);
6751           clang::DeclarationName decl_name(&ident_ref);
6752 
6753           clang::CXXBasePaths paths;
6754           if (cxx_record_decl->lookupInBases(
6755                   [decl_name](const clang::CXXBaseSpecifier *specifier,
6756                               clang::CXXBasePath &path) {
6757                     CXXRecordDecl *record =
6758                       specifier->getType()->getAsCXXRecordDecl();
6759                     auto r = record->lookup(decl_name);
6760                     path.Decls = r.begin();
6761                     return !r.empty();
6762                   },
6763                   paths)) {
6764             clang::CXXBasePaths::const_paths_iterator path,
6765                 path_end = paths.end();
6766             for (path = paths.begin(); path != path_end; ++path) {
6767               const size_t num_path_elements = path->size();
6768               for (size_t e = 0; e < num_path_elements; ++e) {
6769                 clang::CXXBasePathElement elem = (*path)[e];
6770 
6771                 child_idx = GetIndexForRecordBase(parent_record_decl, elem.Base,
6772                                                   omit_empty_base_classes);
6773                 if (child_idx == UINT32_MAX) {
6774                   child_indexes.clear();
6775                   return 0;
6776                 } else {
6777                   child_indexes.push_back(child_idx);
6778                   parent_record_decl = llvm::cast<clang::RecordDecl>(
6779                       elem.Base->getType()
6780                           ->castAs<clang::RecordType>()
6781                           ->getDecl());
6782                 }
6783               }
6784               for (clang::DeclContext::lookup_iterator I = path->Decls, E;
6785                    I != E; ++I) {
6786                 child_idx = GetIndexForRecordChild(
6787                     parent_record_decl, *I, omit_empty_base_classes);
6788                 if (child_idx == UINT32_MAX) {
6789                   child_indexes.clear();
6790                   return 0;
6791                 } else {
6792                   child_indexes.push_back(child_idx);
6793                 }
6794               }
6795             }
6796             return child_indexes.size();
6797           }
6798         }
6799       }
6800       break;
6801 
6802     case clang::Type::ObjCObject:
6803     case clang::Type::ObjCInterface:
6804       if (GetCompleteType(type)) {
6805         llvm::StringRef name_sref(name);
6806         const clang::ObjCObjectType *objc_class_type =
6807             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
6808         assert(objc_class_type);
6809         if (objc_class_type) {
6810           uint32_t child_idx = 0;
6811           clang::ObjCInterfaceDecl *class_interface_decl =
6812               objc_class_type->getInterface();
6813 
6814           if (class_interface_decl) {
6815             clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6816                 ivar_end = class_interface_decl->ivar_end();
6817             clang::ObjCInterfaceDecl *superclass_interface_decl =
6818                 class_interface_decl->getSuperClass();
6819 
6820             for (ivar_pos = class_interface_decl->ivar_begin();
6821                  ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
6822               const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6823 
6824               if (ivar_decl->getName() == name_sref) {
6825                 if ((!omit_empty_base_classes && superclass_interface_decl) ||
6826                     (omit_empty_base_classes &&
6827                      ObjCDeclHasIVars(superclass_interface_decl, true)))
6828                   ++child_idx;
6829 
6830                 child_indexes.push_back(child_idx);
6831                 return child_indexes.size();
6832               }
6833             }
6834 
6835             if (superclass_interface_decl) {
6836               // The super class index is always zero for ObjC classes, so we
6837               // push it onto the child indexes in case we find an ivar in our
6838               // superclass...
6839               child_indexes.push_back(0);
6840 
6841               CompilerType superclass_clang_type =
6842                   GetType(getASTContext().getObjCInterfaceType(
6843                       superclass_interface_decl));
6844               if (superclass_clang_type.GetIndexOfChildMemberWithName(
6845                       name, omit_empty_base_classes, child_indexes)) {
6846                 // We did find an ivar in a superclass so just return the
6847                 // results!
6848                 return child_indexes.size();
6849               }
6850 
6851               // We didn't find an ivar matching "name" in our superclass, pop
6852               // the superclass zero index that we pushed on above.
6853               child_indexes.pop_back();
6854             }
6855           }
6856         }
6857       }
6858       break;
6859 
6860     case clang::Type::ObjCObjectPointer: {
6861       CompilerType objc_object_clang_type = GetType(
6862           llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
6863               ->getPointeeType());
6864       return objc_object_clang_type.GetIndexOfChildMemberWithName(
6865           name, omit_empty_base_classes, child_indexes);
6866     } break;
6867 
6868     case clang::Type::ConstantArray: {
6869       //                const clang::ConstantArrayType *array =
6870       //                llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
6871       //                const uint64_t element_count =
6872       //                array->getSize().getLimitedValue();
6873       //
6874       //                if (idx < element_count)
6875       //                {
6876       //                    std::pair<uint64_t, unsigned> field_type_info =
6877       //                    ast->getTypeInfo(array->getElementType());
6878       //
6879       //                    char element_name[32];
6880       //                    ::snprintf (element_name, sizeof (element_name),
6881       //                    "%s[%u]", parent_name ? parent_name : "", idx);
6882       //
6883       //                    child_name.assign(element_name);
6884       //                    assert(field_type_info.first % 8 == 0);
6885       //                    child_byte_size = field_type_info.first / 8;
6886       //                    child_byte_offset = idx * child_byte_size;
6887       //                    return array->getElementType().getAsOpaquePtr();
6888       //                }
6889     } break;
6890 
6891     //        case clang::Type::MemberPointerType:
6892     //            {
6893     //                MemberPointerType *mem_ptr_type =
6894     //                llvm::cast<MemberPointerType>(qual_type.getTypePtr());
6895     //                clang::QualType pointee_type =
6896     //                mem_ptr_type->getPointeeType();
6897     //
6898     //                if (TypeSystemClang::IsAggregateType
6899     //                (pointee_type.getAsOpaquePtr()))
6900     //                {
6901     //                    return GetIndexOfChildWithName (ast,
6902     //                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
6903     //                                                    name);
6904     //                }
6905     //            }
6906     //            break;
6907     //
6908     case clang::Type::LValueReference:
6909     case clang::Type::RValueReference: {
6910       const clang::ReferenceType *reference_type =
6911           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
6912       clang::QualType pointee_type(reference_type->getPointeeType());
6913       CompilerType pointee_clang_type = GetType(pointee_type);
6914 
6915       if (pointee_clang_type.IsAggregateType()) {
6916         return pointee_clang_type.GetIndexOfChildMemberWithName(
6917             name, omit_empty_base_classes, child_indexes);
6918       }
6919     } break;
6920 
6921     case clang::Type::Pointer: {
6922       CompilerType pointee_clang_type(GetPointeeType(type));
6923 
6924       if (pointee_clang_type.IsAggregateType()) {
6925         return pointee_clang_type.GetIndexOfChildMemberWithName(
6926             name, omit_empty_base_classes, child_indexes);
6927       }
6928     } break;
6929 
6930     default:
6931       break;
6932     }
6933   }
6934   return 0;
6935 }
6936 
6937 // Get the index of the child of "clang_type" whose name matches. This function
6938 // doesn't descend into the children, but only looks one level deep and name
6939 // matches can include base class names.
6940 
6941 uint32_t
6942 TypeSystemClang::GetIndexOfChildWithName(lldb::opaque_compiler_type_t type,
6943                                          llvm::StringRef name,
6944                                          bool omit_empty_base_classes) {
6945   if (type && !name.empty()) {
6946     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6947 
6948     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6949 
6950     switch (type_class) {
6951     case clang::Type::Record:
6952       if (GetCompleteType(type)) {
6953         const clang::RecordType *record_type =
6954             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6955         const clang::RecordDecl *record_decl = record_type->getDecl();
6956 
6957         assert(record_decl);
6958         uint32_t child_idx = 0;
6959 
6960         const clang::CXXRecordDecl *cxx_record_decl =
6961             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6962 
6963         if (cxx_record_decl) {
6964           clang::CXXRecordDecl::base_class_const_iterator base_class,
6965               base_class_end;
6966           for (base_class = cxx_record_decl->bases_begin(),
6967               base_class_end = cxx_record_decl->bases_end();
6968                base_class != base_class_end; ++base_class) {
6969             // Skip empty base classes
6970             clang::CXXRecordDecl *base_class_decl =
6971                 llvm::cast<clang::CXXRecordDecl>(
6972                     base_class->getType()
6973                         ->castAs<clang::RecordType>()
6974                         ->getDecl());
6975             if (omit_empty_base_classes &&
6976                 !TypeSystemClang::RecordHasFields(base_class_decl))
6977               continue;
6978 
6979             CompilerType base_class_clang_type = GetType(base_class->getType());
6980             std::string base_class_type_name(
6981                 base_class_clang_type.GetTypeName().AsCString(""));
6982             if (base_class_type_name == name)
6983               return child_idx;
6984             ++child_idx;
6985           }
6986         }
6987 
6988         // Try and find a field that matches NAME
6989         clang::RecordDecl::field_iterator field, field_end;
6990         for (field = record_decl->field_begin(),
6991             field_end = record_decl->field_end();
6992              field != field_end; ++field, ++child_idx) {
6993           if (field->getName() == name)
6994             return child_idx;
6995         }
6996       }
6997       break;
6998 
6999     case clang::Type::ObjCObject:
7000     case clang::Type::ObjCInterface:
7001       if (GetCompleteType(type)) {
7002         const clang::ObjCObjectType *objc_class_type =
7003             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
7004         assert(objc_class_type);
7005         if (objc_class_type) {
7006           uint32_t child_idx = 0;
7007           clang::ObjCInterfaceDecl *class_interface_decl =
7008               objc_class_type->getInterface();
7009 
7010           if (class_interface_decl) {
7011             clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
7012                 ivar_end = class_interface_decl->ivar_end();
7013             clang::ObjCInterfaceDecl *superclass_interface_decl =
7014                 class_interface_decl->getSuperClass();
7015 
7016             for (ivar_pos = class_interface_decl->ivar_begin();
7017                  ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
7018               const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
7019 
7020               if (ivar_decl->getName() == name) {
7021                 if ((!omit_empty_base_classes && superclass_interface_decl) ||
7022                     (omit_empty_base_classes &&
7023                      ObjCDeclHasIVars(superclass_interface_decl, true)))
7024                   ++child_idx;
7025 
7026                 return child_idx;
7027               }
7028             }
7029 
7030             if (superclass_interface_decl) {
7031               if (superclass_interface_decl->getName() == name)
7032                 return 0;
7033             }
7034           }
7035         }
7036       }
7037       break;
7038 
7039     case clang::Type::ObjCObjectPointer: {
7040       CompilerType pointee_clang_type = GetType(
7041           llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
7042               ->getPointeeType());
7043       return pointee_clang_type.GetIndexOfChildWithName(
7044           name, omit_empty_base_classes);
7045     } break;
7046 
7047     case clang::Type::ConstantArray: {
7048       //                const clang::ConstantArrayType *array =
7049       //                llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
7050       //                const uint64_t element_count =
7051       //                array->getSize().getLimitedValue();
7052       //
7053       //                if (idx < element_count)
7054       //                {
7055       //                    std::pair<uint64_t, unsigned> field_type_info =
7056       //                    ast->getTypeInfo(array->getElementType());
7057       //
7058       //                    char element_name[32];
7059       //                    ::snprintf (element_name, sizeof (element_name),
7060       //                    "%s[%u]", parent_name ? parent_name : "", idx);
7061       //
7062       //                    child_name.assign(element_name);
7063       //                    assert(field_type_info.first % 8 == 0);
7064       //                    child_byte_size = field_type_info.first / 8;
7065       //                    child_byte_offset = idx * child_byte_size;
7066       //                    return array->getElementType().getAsOpaquePtr();
7067       //                }
7068     } break;
7069 
7070     //        case clang::Type::MemberPointerType:
7071     //            {
7072     //                MemberPointerType *mem_ptr_type =
7073     //                llvm::cast<MemberPointerType>(qual_type.getTypePtr());
7074     //                clang::QualType pointee_type =
7075     //                mem_ptr_type->getPointeeType();
7076     //
7077     //                if (TypeSystemClang::IsAggregateType
7078     //                (pointee_type.getAsOpaquePtr()))
7079     //                {
7080     //                    return GetIndexOfChildWithName (ast,
7081     //                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
7082     //                                                    name);
7083     //                }
7084     //            }
7085     //            break;
7086     //
7087     case clang::Type::LValueReference:
7088     case clang::Type::RValueReference: {
7089       const clang::ReferenceType *reference_type =
7090           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
7091       CompilerType pointee_type = GetType(reference_type->getPointeeType());
7092 
7093       if (pointee_type.IsAggregateType()) {
7094         return pointee_type.GetIndexOfChildWithName(name,
7095                                                     omit_empty_base_classes);
7096       }
7097     } break;
7098 
7099     case clang::Type::Pointer: {
7100       const clang::PointerType *pointer_type =
7101           llvm::cast<clang::PointerType>(qual_type.getTypePtr());
7102       CompilerType pointee_type = GetType(pointer_type->getPointeeType());
7103 
7104       if (pointee_type.IsAggregateType()) {
7105         return pointee_type.GetIndexOfChildWithName(name,
7106                                                     omit_empty_base_classes);
7107       } else {
7108         //                    if (parent_name)
7109         //                    {
7110         //                        child_name.assign(1, '*');
7111         //                        child_name += parent_name;
7112         //                    }
7113         //
7114         //                    // We have a pointer to an simple type
7115         //                    if (idx == 0)
7116         //                    {
7117         //                        std::pair<uint64_t, unsigned> clang_type_info
7118         //                        = ast->getTypeInfo(pointee_type);
7119         //                        assert(clang_type_info.first % 8 == 0);
7120         //                        child_byte_size = clang_type_info.first / 8;
7121         //                        child_byte_offset = 0;
7122         //                        return pointee_type.getAsOpaquePtr();
7123         //                    }
7124       }
7125     } break;
7126 
7127     default:
7128       break;
7129     }
7130   }
7131   return UINT32_MAX;
7132 }
7133 
7134 CompilerType
7135 TypeSystemClang::GetDirectNestedTypeWithName(lldb::opaque_compiler_type_t type,
7136                                              llvm::StringRef name) {
7137   if (!type || name.empty())
7138     return CompilerType();
7139 
7140   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
7141   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7142 
7143   switch (type_class) {
7144   case clang::Type::Record: {
7145     if (!GetCompleteType(type))
7146       return CompilerType();
7147     const clang::RecordType *record_type =
7148         llvm::cast<clang::RecordType>(qual_type.getTypePtr());
7149     const clang::RecordDecl *record_decl = record_type->getDecl();
7150 
7151     clang::DeclarationName decl_name(&getASTContext().Idents.get(name));
7152     for (NamedDecl *decl : record_decl->lookup(decl_name)) {
7153       if (auto *tag_decl = dyn_cast<clang::TagDecl>(decl))
7154         return GetType(getASTContext().getTagDeclType(tag_decl));
7155       if (auto *typedef_decl = dyn_cast<clang::TypedefNameDecl>(decl))
7156         return GetType(getASTContext().getTypedefType(typedef_decl));
7157     }
7158     break;
7159   }
7160   default:
7161     break;
7162   }
7163   return CompilerType();
7164 }
7165 
7166 bool TypeSystemClang::IsTemplateType(lldb::opaque_compiler_type_t type) {
7167   if (!type)
7168     return false;
7169   CompilerType ct(weak_from_this(), type);
7170   const clang::Type *clang_type = ClangUtil::GetQualType(ct).getTypePtr();
7171   if (auto *cxx_record_decl = dyn_cast<clang::TagType>(clang_type))
7172     return isa<clang::ClassTemplateSpecializationDecl>(
7173         cxx_record_decl->getDecl());
7174   return false;
7175 }
7176 
7177 size_t
7178 TypeSystemClang::GetNumTemplateArguments(lldb::opaque_compiler_type_t type,
7179                                          bool expand_pack) {
7180   if (!type)
7181     return 0;
7182 
7183   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
7184   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7185   switch (type_class) {
7186   case clang::Type::Record:
7187     if (GetCompleteType(type)) {
7188       const clang::CXXRecordDecl *cxx_record_decl =
7189           qual_type->getAsCXXRecordDecl();
7190       if (cxx_record_decl) {
7191         const clang::ClassTemplateSpecializationDecl *template_decl =
7192             llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
7193                 cxx_record_decl);
7194         if (template_decl) {
7195           const auto &template_arg_list = template_decl->getTemplateArgs();
7196           size_t num_args = template_arg_list.size();
7197           assert(num_args && "template specialization without any args");
7198           if (expand_pack && num_args) {
7199             const auto &pack = template_arg_list[num_args - 1];
7200             if (pack.getKind() == clang::TemplateArgument::Pack)
7201               num_args += pack.pack_size() - 1;
7202           }
7203           return num_args;
7204         }
7205       }
7206     }
7207     break;
7208 
7209   default:
7210     break;
7211   }
7212 
7213   return 0;
7214 }
7215 
7216 const clang::ClassTemplateSpecializationDecl *
7217 TypeSystemClang::GetAsTemplateSpecialization(
7218     lldb::opaque_compiler_type_t type) {
7219   if (!type)
7220     return nullptr;
7221 
7222   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
7223   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7224   switch (type_class) {
7225   case clang::Type::Record: {
7226     if (! GetCompleteType(type))
7227       return nullptr;
7228     const clang::CXXRecordDecl *cxx_record_decl =
7229         qual_type->getAsCXXRecordDecl();
7230     if (!cxx_record_decl)
7231       return nullptr;
7232     return llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
7233         cxx_record_decl);
7234   }
7235 
7236   default:
7237     return nullptr;
7238   }
7239 }
7240 
7241 const TemplateArgument *
7242 GetNthTemplateArgument(const clang::ClassTemplateSpecializationDecl *decl,
7243                        size_t idx, bool expand_pack) {
7244   const auto &args = decl->getTemplateArgs();
7245   const size_t args_size = args.size();
7246 
7247   assert(args_size && "template specialization without any args");
7248   if (!args_size)
7249     return nullptr;
7250 
7251   const size_t last_idx = args_size - 1;
7252 
7253   // We're asked for a template argument that can't be a parameter pack, so
7254   // return it without worrying about 'expand_pack'.
7255   if (idx < last_idx)
7256     return &args[idx];
7257 
7258   // We're asked for the last template argument but we don't want/need to
7259   // expand it.
7260   if (!expand_pack || args[last_idx].getKind() != clang::TemplateArgument::Pack)
7261     return idx >= args.size() ? nullptr : &args[idx];
7262 
7263   // Index into the expanded pack.
7264   // Note that 'idx' counts from the beginning of all template arguments
7265   // (including the ones preceding the parameter pack).
7266   const auto &pack = args[last_idx];
7267   const size_t pack_idx = idx - last_idx;
7268   if (pack_idx >= pack.pack_size())
7269     return nullptr;
7270   return &pack.pack_elements()[pack_idx];
7271 }
7272 
7273 lldb::TemplateArgumentKind
7274 TypeSystemClang::GetTemplateArgumentKind(lldb::opaque_compiler_type_t type,
7275                                          size_t arg_idx, bool expand_pack) {
7276   const clang::ClassTemplateSpecializationDecl *template_decl =
7277       GetAsTemplateSpecialization(type);
7278   if (!template_decl)
7279     return eTemplateArgumentKindNull;
7280 
7281   const auto *arg = GetNthTemplateArgument(template_decl, arg_idx, expand_pack);
7282   if (!arg)
7283     return eTemplateArgumentKindNull;
7284 
7285   switch (arg->getKind()) {
7286   case clang::TemplateArgument::Null:
7287     return eTemplateArgumentKindNull;
7288 
7289   case clang::TemplateArgument::NullPtr:
7290     return eTemplateArgumentKindNullPtr;
7291 
7292   case clang::TemplateArgument::Type:
7293     return eTemplateArgumentKindType;
7294 
7295   case clang::TemplateArgument::Declaration:
7296     return eTemplateArgumentKindDeclaration;
7297 
7298   case clang::TemplateArgument::Integral:
7299     return eTemplateArgumentKindIntegral;
7300 
7301   case clang::TemplateArgument::Template:
7302     return eTemplateArgumentKindTemplate;
7303 
7304   case clang::TemplateArgument::TemplateExpansion:
7305     return eTemplateArgumentKindTemplateExpansion;
7306 
7307   case clang::TemplateArgument::Expression:
7308     return eTemplateArgumentKindExpression;
7309 
7310   case clang::TemplateArgument::Pack:
7311     return eTemplateArgumentKindPack;
7312 
7313   case clang::TemplateArgument::StructuralValue:
7314     return eTemplateArgumentKindStructuralValue;
7315   }
7316   llvm_unreachable("Unhandled clang::TemplateArgument::ArgKind");
7317 }
7318 
7319 CompilerType
7320 TypeSystemClang::GetTypeTemplateArgument(lldb::opaque_compiler_type_t type,
7321                                          size_t idx, bool expand_pack) {
7322   const clang::ClassTemplateSpecializationDecl *template_decl =
7323       GetAsTemplateSpecialization(type);
7324   if (!template_decl)
7325     return CompilerType();
7326 
7327   const auto *arg = GetNthTemplateArgument(template_decl, idx, expand_pack);
7328   if (!arg || arg->getKind() != clang::TemplateArgument::Type)
7329     return CompilerType();
7330 
7331   return GetType(arg->getAsType());
7332 }
7333 
7334 std::optional<CompilerType::IntegralTemplateArgument>
7335 TypeSystemClang::GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type,
7336                                              size_t idx, bool expand_pack) {
7337   const clang::ClassTemplateSpecializationDecl *template_decl =
7338       GetAsTemplateSpecialization(type);
7339   if (!template_decl)
7340     return std::nullopt;
7341 
7342   const auto *arg = GetNthTemplateArgument(template_decl, idx, expand_pack);
7343   if (!arg || arg->getKind() != clang::TemplateArgument::Integral)
7344     return std::nullopt;
7345 
7346   return {{arg->getAsIntegral(), GetType(arg->getIntegralType())}};
7347 }
7348 
7349 CompilerType TypeSystemClang::GetTypeForFormatters(void *type) {
7350   if (type)
7351     return ClangUtil::RemoveFastQualifiers(CompilerType(weak_from_this(), type));
7352   return CompilerType();
7353 }
7354 
7355 clang::EnumDecl *TypeSystemClang::GetAsEnumDecl(const CompilerType &type) {
7356   const clang::EnumType *enutype =
7357       llvm::dyn_cast<clang::EnumType>(ClangUtil::GetCanonicalQualType(type));
7358   if (enutype)
7359     return enutype->getDecl();
7360   return nullptr;
7361 }
7362 
7363 clang::RecordDecl *TypeSystemClang::GetAsRecordDecl(const CompilerType &type) {
7364   const clang::RecordType *record_type =
7365       llvm::dyn_cast<clang::RecordType>(ClangUtil::GetCanonicalQualType(type));
7366   if (record_type)
7367     return record_type->getDecl();
7368   return nullptr;
7369 }
7370 
7371 clang::TagDecl *TypeSystemClang::GetAsTagDecl(const CompilerType &type) {
7372   return ClangUtil::GetAsTagDecl(type);
7373 }
7374 
7375 clang::TypedefNameDecl *
7376 TypeSystemClang::GetAsTypedefDecl(const CompilerType &type) {
7377   const clang::TypedefType *typedef_type =
7378       llvm::dyn_cast<clang::TypedefType>(ClangUtil::GetQualType(type));
7379   if (typedef_type)
7380     return typedef_type->getDecl();
7381   return nullptr;
7382 }
7383 
7384 clang::CXXRecordDecl *
7385 TypeSystemClang::GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type) {
7386   return GetCanonicalQualType(type)->getAsCXXRecordDecl();
7387 }
7388 
7389 clang::ObjCInterfaceDecl *
7390 TypeSystemClang::GetAsObjCInterfaceDecl(const CompilerType &type) {
7391   const clang::ObjCObjectType *objc_class_type =
7392       llvm::dyn_cast<clang::ObjCObjectType>(
7393           ClangUtil::GetCanonicalQualType(type));
7394   if (objc_class_type)
7395     return objc_class_type->getInterface();
7396   return nullptr;
7397 }
7398 
7399 clang::FieldDecl *TypeSystemClang::AddFieldToRecordType(
7400     const CompilerType &type, llvm::StringRef name,
7401     const CompilerType &field_clang_type, AccessType access,
7402     uint32_t bitfield_bit_size) {
7403   if (!type.IsValid() || !field_clang_type.IsValid())
7404     return nullptr;
7405   auto ts = type.GetTypeSystem();
7406   auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7407   if (!ast)
7408     return nullptr;
7409   clang::ASTContext &clang_ast = ast->getASTContext();
7410   clang::IdentifierInfo *ident = nullptr;
7411   if (!name.empty())
7412     ident = &clang_ast.Idents.get(name);
7413 
7414   clang::FieldDecl *field = nullptr;
7415 
7416   clang::Expr *bit_width = nullptr;
7417   if (bitfield_bit_size != 0) {
7418     if (clang_ast.IntTy.isNull()) {
7419       LLDB_LOG(
7420           GetLog(LLDBLog::Expressions),
7421           "{0} failed: builtin ASTContext types have not been initialized");
7422       return nullptr;
7423     }
7424 
7425     llvm::APInt bitfield_bit_size_apint(clang_ast.getTypeSize(clang_ast.IntTy),
7426                                         bitfield_bit_size);
7427     bit_width = new (clang_ast)
7428         clang::IntegerLiteral(clang_ast, bitfield_bit_size_apint,
7429                               clang_ast.IntTy, clang::SourceLocation());
7430     bit_width = clang::ConstantExpr::Create(
7431         clang_ast, bit_width, APValue(llvm::APSInt(bitfield_bit_size_apint)));
7432   }
7433 
7434   clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7435   if (record_decl) {
7436     field = clang::FieldDecl::CreateDeserialized(clang_ast, GlobalDeclID());
7437     field->setDeclContext(record_decl);
7438     field->setDeclName(ident);
7439     field->setType(ClangUtil::GetQualType(field_clang_type));
7440     if (bit_width)
7441       field->setBitWidth(bit_width);
7442     SetMemberOwningModule(field, record_decl);
7443 
7444     if (name.empty()) {
7445       // Determine whether this field corresponds to an anonymous struct or
7446       // union.
7447       if (const clang::TagType *TagT =
7448               field->getType()->getAs<clang::TagType>()) {
7449         if (clang::RecordDecl *Rec =
7450                 llvm::dyn_cast<clang::RecordDecl>(TagT->getDecl()))
7451           if (!Rec->getDeclName()) {
7452             Rec->setAnonymousStructOrUnion(true);
7453             field->setImplicit();
7454           }
7455       }
7456     }
7457 
7458     if (field) {
7459       clang::AccessSpecifier access_specifier =
7460           TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access);
7461       field->setAccess(access_specifier);
7462 
7463       if (clang::CXXRecordDecl *cxx_record_decl =
7464               llvm::dyn_cast<CXXRecordDecl>(record_decl)) {
7465         AddAccessSpecifierDecl(cxx_record_decl, ast->getASTContext(),
7466                                ast->GetCXXRecordDeclAccess(cxx_record_decl),
7467                                access_specifier);
7468         ast->SetCXXRecordDeclAccess(cxx_record_decl, access_specifier);
7469       }
7470       record_decl->addDecl(field);
7471 
7472       VerifyDecl(field);
7473     }
7474   } else {
7475     clang::ObjCInterfaceDecl *class_interface_decl =
7476         ast->GetAsObjCInterfaceDecl(type);
7477 
7478     if (class_interface_decl) {
7479       const bool is_synthesized = false;
7480 
7481       field_clang_type.GetCompleteType();
7482 
7483       auto *ivar =
7484           clang::ObjCIvarDecl::CreateDeserialized(clang_ast, GlobalDeclID());
7485       ivar->setDeclContext(class_interface_decl);
7486       ivar->setDeclName(ident);
7487       ivar->setType(ClangUtil::GetQualType(field_clang_type));
7488       ivar->setAccessControl(ConvertAccessTypeToObjCIvarAccessControl(access));
7489       if (bit_width)
7490         ivar->setBitWidth(bit_width);
7491       ivar->setSynthesize(is_synthesized);
7492       field = ivar;
7493       SetMemberOwningModule(field, class_interface_decl);
7494 
7495       if (field) {
7496         class_interface_decl->addDecl(field);
7497 
7498         VerifyDecl(field);
7499       }
7500     }
7501   }
7502   return field;
7503 }
7504 
7505 void TypeSystemClang::BuildIndirectFields(const CompilerType &type) {
7506   if (!type)
7507     return;
7508 
7509   auto ts = type.GetTypeSystem();
7510   auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7511   if (!ast)
7512     return;
7513 
7514   clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7515 
7516   if (!record_decl)
7517     return;
7518 
7519   typedef llvm::SmallVector<clang::IndirectFieldDecl *, 1> IndirectFieldVector;
7520 
7521   IndirectFieldVector indirect_fields;
7522   clang::RecordDecl::field_iterator field_pos;
7523   clang::RecordDecl::field_iterator field_end_pos = record_decl->field_end();
7524   clang::RecordDecl::field_iterator last_field_pos = field_end_pos;
7525   for (field_pos = record_decl->field_begin(); field_pos != field_end_pos;
7526        last_field_pos = field_pos++) {
7527     if (field_pos->isAnonymousStructOrUnion()) {
7528       clang::QualType field_qual_type = field_pos->getType();
7529 
7530       const clang::RecordType *field_record_type =
7531           field_qual_type->getAs<clang::RecordType>();
7532 
7533       if (!field_record_type)
7534         continue;
7535 
7536       clang::RecordDecl *field_record_decl = field_record_type->getDecl();
7537 
7538       if (!field_record_decl)
7539         continue;
7540 
7541       for (clang::RecordDecl::decl_iterator
7542                di = field_record_decl->decls_begin(),
7543                de = field_record_decl->decls_end();
7544            di != de; ++di) {
7545         if (clang::FieldDecl *nested_field_decl =
7546                 llvm::dyn_cast<clang::FieldDecl>(*di)) {
7547           clang::NamedDecl **chain =
7548               new (ast->getASTContext()) clang::NamedDecl *[2];
7549           chain[0] = *field_pos;
7550           chain[1] = nested_field_decl;
7551           clang::IndirectFieldDecl *indirect_field =
7552               clang::IndirectFieldDecl::Create(
7553                   ast->getASTContext(), record_decl, clang::SourceLocation(),
7554                   nested_field_decl->getIdentifier(),
7555                   nested_field_decl->getType(), {chain, 2});
7556           SetMemberOwningModule(indirect_field, record_decl);
7557 
7558           indirect_field->setImplicit();
7559 
7560           indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers(
7561               field_pos->getAccess(), nested_field_decl->getAccess()));
7562 
7563           indirect_fields.push_back(indirect_field);
7564         } else if (clang::IndirectFieldDecl *nested_indirect_field_decl =
7565                        llvm::dyn_cast<clang::IndirectFieldDecl>(*di)) {
7566           size_t nested_chain_size =
7567               nested_indirect_field_decl->getChainingSize();
7568           clang::NamedDecl **chain = new (ast->getASTContext())
7569               clang::NamedDecl *[nested_chain_size + 1];
7570           chain[0] = *field_pos;
7571 
7572           int chain_index = 1;
7573           for (clang::IndirectFieldDecl::chain_iterator
7574                    nci = nested_indirect_field_decl->chain_begin(),
7575                    nce = nested_indirect_field_decl->chain_end();
7576                nci < nce; ++nci) {
7577             chain[chain_index] = *nci;
7578             chain_index++;
7579           }
7580 
7581           clang::IndirectFieldDecl *indirect_field =
7582               clang::IndirectFieldDecl::Create(
7583                   ast->getASTContext(), record_decl, clang::SourceLocation(),
7584                   nested_indirect_field_decl->getIdentifier(),
7585                   nested_indirect_field_decl->getType(),
7586                   {chain, nested_chain_size + 1});
7587           SetMemberOwningModule(indirect_field, record_decl);
7588 
7589           indirect_field->setImplicit();
7590 
7591           indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers(
7592               field_pos->getAccess(), nested_indirect_field_decl->getAccess()));
7593 
7594           indirect_fields.push_back(indirect_field);
7595         }
7596       }
7597     }
7598   }
7599 
7600   // Check the last field to see if it has an incomplete array type as its last
7601   // member and if it does, the tell the record decl about it
7602   if (last_field_pos != field_end_pos) {
7603     if (last_field_pos->getType()->isIncompleteArrayType())
7604       record_decl->hasFlexibleArrayMember();
7605   }
7606 
7607   for (IndirectFieldVector::iterator ifi = indirect_fields.begin(),
7608                                      ife = indirect_fields.end();
7609        ifi < ife; ++ifi) {
7610     record_decl->addDecl(*ifi);
7611   }
7612 }
7613 
7614 void TypeSystemClang::SetIsPacked(const CompilerType &type) {
7615   if (type) {
7616     auto ts = type.GetTypeSystem();
7617     auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7618     if (ast) {
7619       clang::RecordDecl *record_decl = GetAsRecordDecl(type);
7620 
7621       if (!record_decl)
7622         return;
7623 
7624       record_decl->addAttr(
7625           clang::PackedAttr::CreateImplicit(ast->getASTContext()));
7626     }
7627   }
7628 }
7629 
7630 clang::VarDecl *TypeSystemClang::AddVariableToRecordType(
7631     const CompilerType &type, llvm::StringRef name,
7632     const CompilerType &var_type, AccessType access) {
7633   if (!type.IsValid() || !var_type.IsValid())
7634     return nullptr;
7635 
7636   auto ts = type.GetTypeSystem();
7637   auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7638   if (!ast)
7639     return nullptr;
7640 
7641   clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7642   if (!record_decl)
7643     return nullptr;
7644 
7645   clang::VarDecl *var_decl = nullptr;
7646   clang::IdentifierInfo *ident = nullptr;
7647   if (!name.empty())
7648     ident = &ast->getASTContext().Idents.get(name);
7649 
7650   var_decl =
7651       clang::VarDecl::CreateDeserialized(ast->getASTContext(), GlobalDeclID());
7652   var_decl->setDeclContext(record_decl);
7653   var_decl->setDeclName(ident);
7654   var_decl->setType(ClangUtil::GetQualType(var_type));
7655   var_decl->setStorageClass(clang::SC_Static);
7656   SetMemberOwningModule(var_decl, record_decl);
7657   if (!var_decl)
7658     return nullptr;
7659 
7660   var_decl->setAccess(
7661       TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access));
7662   record_decl->addDecl(var_decl);
7663 
7664   VerifyDecl(var_decl);
7665 
7666   return var_decl;
7667 }
7668 
7669 void TypeSystemClang::SetIntegerInitializerForVariable(
7670     VarDecl *var, const llvm::APInt &init_value) {
7671   assert(!var->hasInit() && "variable already initialized");
7672 
7673   clang::ASTContext &ast = var->getASTContext();
7674   QualType qt = var->getType();
7675   assert(qt->isIntegralOrEnumerationType() &&
7676          "only integer or enum types supported");
7677   // If the variable is an enum type, take the underlying integer type as
7678   // the type of the integer literal.
7679   if (const EnumType *enum_type = qt->getAs<EnumType>()) {
7680     const EnumDecl *enum_decl = enum_type->getDecl();
7681     qt = enum_decl->getIntegerType();
7682   }
7683   // Bools are handled separately because the clang AST printer handles bools
7684   // separately from other integral types.
7685   if (qt->isSpecificBuiltinType(BuiltinType::Bool)) {
7686     var->setInit(CXXBoolLiteralExpr::Create(
7687         ast, !init_value.isZero(), qt.getUnqualifiedType(), SourceLocation()));
7688   } else {
7689     var->setInit(IntegerLiteral::Create(
7690         ast, init_value, qt.getUnqualifiedType(), SourceLocation()));
7691   }
7692 }
7693 
7694 void TypeSystemClang::SetFloatingInitializerForVariable(
7695     clang::VarDecl *var, const llvm::APFloat &init_value) {
7696   assert(!var->hasInit() && "variable already initialized");
7697 
7698   clang::ASTContext &ast = var->getASTContext();
7699   QualType qt = var->getType();
7700   assert(qt->isFloatingType() && "only floating point types supported");
7701   var->setInit(FloatingLiteral::Create(
7702       ast, init_value, true, qt.getUnqualifiedType(), SourceLocation()));
7703 }
7704 
7705 llvm::SmallVector<clang::ParmVarDecl *>
7706 TypeSystemClang::CreateParameterDeclarations(
7707     clang::FunctionDecl *func, const clang::FunctionProtoType &prototype,
7708     const llvm::SmallVector<llvm::StringRef> &parameter_names) {
7709   assert(func);
7710   assert(parameter_names.empty() ||
7711          parameter_names.size() == prototype.getNumParams());
7712 
7713   llvm::SmallVector<clang::ParmVarDecl *> params;
7714   for (unsigned param_index = 0; param_index < prototype.getNumParams();
7715        ++param_index) {
7716     llvm::StringRef name =
7717         !parameter_names.empty() ? parameter_names[param_index] : "";
7718 
7719     auto *param =
7720         CreateParameterDeclaration(func, /*owning_module=*/{}, name.data(),
7721                                    GetType(prototype.getParamType(param_index)),
7722                                    clang::SC_None, /*add_decl=*/false);
7723     assert(param);
7724 
7725     params.push_back(param);
7726   }
7727 
7728   return params;
7729 }
7730 
7731 clang::CXXMethodDecl *TypeSystemClang::AddMethodToCXXRecordType(
7732     lldb::opaque_compiler_type_t type, llvm::StringRef name,
7733     const char *mangled_name, const CompilerType &method_clang_type,
7734     lldb::AccessType access, bool is_virtual, bool is_static, bool is_inline,
7735     bool is_explicit, bool is_attr_used, bool is_artificial) {
7736   if (!type || !method_clang_type.IsValid() || name.empty())
7737     return nullptr;
7738 
7739   clang::QualType record_qual_type(GetCanonicalQualType(type));
7740 
7741   clang::CXXRecordDecl *cxx_record_decl =
7742       record_qual_type->getAsCXXRecordDecl();
7743 
7744   if (cxx_record_decl == nullptr)
7745     return nullptr;
7746 
7747   clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
7748 
7749   clang::CXXMethodDecl *cxx_method_decl = nullptr;
7750 
7751   clang::DeclarationName decl_name(&getASTContext().Idents.get(name));
7752 
7753   const clang::FunctionType *function_type =
7754       llvm::dyn_cast<clang::FunctionType>(method_qual_type.getTypePtr());
7755 
7756   if (function_type == nullptr)
7757     return nullptr;
7758 
7759   const clang::FunctionProtoType *method_function_prototype(
7760       llvm::dyn_cast<clang::FunctionProtoType>(function_type));
7761 
7762   if (!method_function_prototype)
7763     return nullptr;
7764 
7765   unsigned int num_params = method_function_prototype->getNumParams();
7766 
7767   clang::CXXDestructorDecl *cxx_dtor_decl(nullptr);
7768   clang::CXXConstructorDecl *cxx_ctor_decl(nullptr);
7769 
7770   if (is_artificial)
7771     return nullptr; // skip everything artificial
7772 
7773   const clang::ExplicitSpecifier explicit_spec(
7774       nullptr /*expr*/, is_explicit ? clang::ExplicitSpecKind::ResolvedTrue
7775                                     : clang::ExplicitSpecKind::ResolvedFalse);
7776 
7777   if (name.starts_with("~")) {
7778     cxx_dtor_decl = clang::CXXDestructorDecl::CreateDeserialized(
7779         getASTContext(), GlobalDeclID());
7780     cxx_dtor_decl->setDeclContext(cxx_record_decl);
7781     cxx_dtor_decl->setDeclName(
7782         getASTContext().DeclarationNames.getCXXDestructorName(
7783             getASTContext().getCanonicalType(record_qual_type)));
7784     cxx_dtor_decl->setType(method_qual_type);
7785     cxx_dtor_decl->setImplicit(is_artificial);
7786     cxx_dtor_decl->setInlineSpecified(is_inline);
7787     cxx_dtor_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7788     cxx_method_decl = cxx_dtor_decl;
7789   } else if (decl_name == cxx_record_decl->getDeclName()) {
7790     cxx_ctor_decl = clang::CXXConstructorDecl::CreateDeserialized(
7791         getASTContext(), GlobalDeclID(), 0);
7792     cxx_ctor_decl->setDeclContext(cxx_record_decl);
7793     cxx_ctor_decl->setDeclName(
7794         getASTContext().DeclarationNames.getCXXConstructorName(
7795             getASTContext().getCanonicalType(record_qual_type)));
7796     cxx_ctor_decl->setType(method_qual_type);
7797     cxx_ctor_decl->setImplicit(is_artificial);
7798     cxx_ctor_decl->setInlineSpecified(is_inline);
7799     cxx_ctor_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7800     cxx_ctor_decl->setNumCtorInitializers(0);
7801     cxx_ctor_decl->setExplicitSpecifier(explicit_spec);
7802     cxx_method_decl = cxx_ctor_decl;
7803   } else {
7804     clang::StorageClass SC = is_static ? clang::SC_Static : clang::SC_None;
7805     clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
7806 
7807     if (IsOperator(name, op_kind)) {
7808       if (op_kind != clang::NUM_OVERLOADED_OPERATORS) {
7809         // Check the number of operator parameters. Sometimes we have seen bad
7810         // DWARF that doesn't correctly describe operators and if we try to
7811         // create a method and add it to the class, clang will assert and
7812         // crash, so we need to make sure things are acceptable.
7813         const bool is_method = true;
7814         if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
7815                 is_method, op_kind, num_params))
7816           return nullptr;
7817         cxx_method_decl = clang::CXXMethodDecl::CreateDeserialized(
7818             getASTContext(), GlobalDeclID());
7819         cxx_method_decl->setDeclContext(cxx_record_decl);
7820         cxx_method_decl->setDeclName(
7821             getASTContext().DeclarationNames.getCXXOperatorName(op_kind));
7822         cxx_method_decl->setType(method_qual_type);
7823         cxx_method_decl->setStorageClass(SC);
7824         cxx_method_decl->setInlineSpecified(is_inline);
7825         cxx_method_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7826       } else if (num_params == 0) {
7827         // Conversion operators don't take params...
7828         auto *cxx_conversion_decl =
7829             clang::CXXConversionDecl::CreateDeserialized(getASTContext(),
7830                                                          GlobalDeclID());
7831         cxx_conversion_decl->setDeclContext(cxx_record_decl);
7832         cxx_conversion_decl->setDeclName(
7833             getASTContext().DeclarationNames.getCXXConversionFunctionName(
7834                 getASTContext().getCanonicalType(
7835                     function_type->getReturnType())));
7836         cxx_conversion_decl->setType(method_qual_type);
7837         cxx_conversion_decl->setInlineSpecified(is_inline);
7838         cxx_conversion_decl->setExplicitSpecifier(explicit_spec);
7839         cxx_conversion_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7840         cxx_method_decl = cxx_conversion_decl;
7841       }
7842     }
7843 
7844     if (cxx_method_decl == nullptr) {
7845       cxx_method_decl = clang::CXXMethodDecl::CreateDeserialized(
7846           getASTContext(), GlobalDeclID());
7847       cxx_method_decl->setDeclContext(cxx_record_decl);
7848       cxx_method_decl->setDeclName(decl_name);
7849       cxx_method_decl->setType(method_qual_type);
7850       cxx_method_decl->setInlineSpecified(is_inline);
7851       cxx_method_decl->setStorageClass(SC);
7852       cxx_method_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7853     }
7854   }
7855   SetMemberOwningModule(cxx_method_decl, cxx_record_decl);
7856 
7857   clang::AccessSpecifier access_specifier =
7858       TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access);
7859 
7860   cxx_method_decl->setAccess(access_specifier);
7861   cxx_method_decl->setVirtualAsWritten(is_virtual);
7862 
7863   if (is_attr_used)
7864     cxx_method_decl->addAttr(clang::UsedAttr::CreateImplicit(getASTContext()));
7865 
7866   if (mangled_name != nullptr) {
7867     cxx_method_decl->addAttr(clang::AsmLabelAttr::CreateImplicit(
7868         getASTContext(), mangled_name, /*literal=*/false));
7869   }
7870 
7871   // Parameters on member function declarations in DWARF generally don't
7872   // have names, so we omit them when creating the ParmVarDecls.
7873   cxx_method_decl->setParams(CreateParameterDeclarations(
7874       cxx_method_decl, *method_function_prototype, /*parameter_names=*/{}));
7875 
7876   AddAccessSpecifierDecl(cxx_record_decl, getASTContext(),
7877                          GetCXXRecordDeclAccess(cxx_record_decl),
7878                          access_specifier);
7879   SetCXXRecordDeclAccess(cxx_record_decl, access_specifier);
7880 
7881   cxx_record_decl->addDecl(cxx_method_decl);
7882 
7883   // Sometimes the debug info will mention a constructor (default/copy/move),
7884   // destructor, or assignment operator (copy/move) but there won't be any
7885   // version of this in the code. So we check if the function was artificially
7886   // generated and if it is trivial and this lets the compiler/backend know
7887   // that it can inline the IR for these when it needs to and we can avoid a
7888   // "missing function" error when running expressions.
7889 
7890   if (is_artificial) {
7891     if (cxx_ctor_decl && ((cxx_ctor_decl->isDefaultConstructor() &&
7892                            cxx_record_decl->hasTrivialDefaultConstructor()) ||
7893                           (cxx_ctor_decl->isCopyConstructor() &&
7894                            cxx_record_decl->hasTrivialCopyConstructor()) ||
7895                           (cxx_ctor_decl->isMoveConstructor() &&
7896                            cxx_record_decl->hasTrivialMoveConstructor()))) {
7897       cxx_ctor_decl->setDefaulted();
7898       cxx_ctor_decl->setTrivial(true);
7899     } else if (cxx_dtor_decl) {
7900       if (cxx_record_decl->hasTrivialDestructor()) {
7901         cxx_dtor_decl->setDefaulted();
7902         cxx_dtor_decl->setTrivial(true);
7903       }
7904     } else if ((cxx_method_decl->isCopyAssignmentOperator() &&
7905                 cxx_record_decl->hasTrivialCopyAssignment()) ||
7906                (cxx_method_decl->isMoveAssignmentOperator() &&
7907                 cxx_record_decl->hasTrivialMoveAssignment())) {
7908       cxx_method_decl->setDefaulted();
7909       cxx_method_decl->setTrivial(true);
7910     }
7911   }
7912 
7913   VerifyDecl(cxx_method_decl);
7914 
7915   return cxx_method_decl;
7916 }
7917 
7918 void TypeSystemClang::AddMethodOverridesForCXXRecordType(
7919     lldb::opaque_compiler_type_t type) {
7920   if (auto *record = GetAsCXXRecordDecl(type))
7921     for (auto *method : record->methods())
7922       addOverridesForMethod(method);
7923 }
7924 
7925 #pragma mark C++ Base Classes
7926 
7927 std::unique_ptr<clang::CXXBaseSpecifier>
7928 TypeSystemClang::CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type,
7929                                           AccessType access, bool is_virtual,
7930                                           bool base_of_class) {
7931   if (!type)
7932     return nullptr;
7933 
7934   return std::make_unique<clang::CXXBaseSpecifier>(
7935       clang::SourceRange(), is_virtual, base_of_class,
7936       TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access),
7937       getASTContext().getTrivialTypeSourceInfo(GetQualType(type)),
7938       clang::SourceLocation());
7939 }
7940 
7941 bool TypeSystemClang::TransferBaseClasses(
7942     lldb::opaque_compiler_type_t type,
7943     std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases) {
7944   if (!type)
7945     return false;
7946   clang::CXXRecordDecl *cxx_record_decl = GetAsCXXRecordDecl(type);
7947   if (!cxx_record_decl)
7948     return false;
7949   std::vector<clang::CXXBaseSpecifier *> raw_bases;
7950   raw_bases.reserve(bases.size());
7951 
7952   // Clang will make a copy of them, so it's ok that we pass pointers that we're
7953   // about to destroy.
7954   for (auto &b : bases)
7955     raw_bases.push_back(b.get());
7956   cxx_record_decl->setBases(raw_bases.data(), raw_bases.size());
7957   return true;
7958 }
7959 
7960 bool TypeSystemClang::SetObjCSuperClass(
7961     const CompilerType &type, const CompilerType &superclass_clang_type) {
7962   auto ts = type.GetTypeSystem();
7963   auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7964   if (!ast)
7965     return false;
7966   clang::ASTContext &clang_ast = ast->getASTContext();
7967 
7968   if (type && superclass_clang_type.IsValid() &&
7969       superclass_clang_type.GetTypeSystem() == type.GetTypeSystem()) {
7970     clang::ObjCInterfaceDecl *class_interface_decl =
7971         GetAsObjCInterfaceDecl(type);
7972     clang::ObjCInterfaceDecl *super_interface_decl =
7973         GetAsObjCInterfaceDecl(superclass_clang_type);
7974     if (class_interface_decl && super_interface_decl) {
7975       class_interface_decl->setSuperClass(clang_ast.getTrivialTypeSourceInfo(
7976           clang_ast.getObjCInterfaceType(super_interface_decl)));
7977       return true;
7978     }
7979   }
7980   return false;
7981 }
7982 
7983 bool TypeSystemClang::AddObjCClassProperty(
7984     const CompilerType &type, const char *property_name,
7985     const CompilerType &property_clang_type, clang::ObjCIvarDecl *ivar_decl,
7986     const char *property_setter_name, const char *property_getter_name,
7987     uint32_t property_attributes, ClangASTMetadata metadata) {
7988   if (!type || !property_clang_type.IsValid() || property_name == nullptr ||
7989       property_name[0] == '\0')
7990     return false;
7991   auto ts = type.GetTypeSystem();
7992   auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7993   if (!ast)
7994     return false;
7995   clang::ASTContext &clang_ast = ast->getASTContext();
7996 
7997   clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
7998   if (!class_interface_decl)
7999     return false;
8000 
8001   CompilerType property_clang_type_to_access;
8002 
8003   if (property_clang_type.IsValid())
8004     property_clang_type_to_access = property_clang_type;
8005   else if (ivar_decl)
8006     property_clang_type_to_access = ast->GetType(ivar_decl->getType());
8007 
8008   if (!class_interface_decl || !property_clang_type_to_access.IsValid())
8009     return false;
8010 
8011   clang::TypeSourceInfo *prop_type_source;
8012   if (ivar_decl)
8013     prop_type_source = clang_ast.getTrivialTypeSourceInfo(ivar_decl->getType());
8014   else
8015     prop_type_source = clang_ast.getTrivialTypeSourceInfo(
8016         ClangUtil::GetQualType(property_clang_type));
8017 
8018   clang::ObjCPropertyDecl *property_decl =
8019       clang::ObjCPropertyDecl::CreateDeserialized(clang_ast, GlobalDeclID());
8020   property_decl->setDeclContext(class_interface_decl);
8021   property_decl->setDeclName(&clang_ast.Idents.get(property_name));
8022   property_decl->setType(ivar_decl
8023                              ? ivar_decl->getType()
8024                              : ClangUtil::GetQualType(property_clang_type),
8025                          prop_type_source);
8026   SetMemberOwningModule(property_decl, class_interface_decl);
8027 
8028   if (!property_decl)
8029     return false;
8030 
8031   ast->SetMetadata(property_decl, metadata);
8032 
8033   class_interface_decl->addDecl(property_decl);
8034 
8035   clang::Selector setter_sel, getter_sel;
8036 
8037   if (property_setter_name) {
8038     std::string property_setter_no_colon(property_setter_name,
8039                                          strlen(property_setter_name) - 1);
8040     const clang::IdentifierInfo *setter_ident =
8041         &clang_ast.Idents.get(property_setter_no_colon);
8042     setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident);
8043   } else if (!(property_attributes & DW_APPLE_PROPERTY_readonly)) {
8044     std::string setter_sel_string("set");
8045     setter_sel_string.push_back(::toupper(property_name[0]));
8046     setter_sel_string.append(&property_name[1]);
8047     const clang::IdentifierInfo *setter_ident =
8048         &clang_ast.Idents.get(setter_sel_string);
8049     setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident);
8050   }
8051   property_decl->setSetterName(setter_sel);
8052   property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_setter);
8053 
8054   if (property_getter_name != nullptr) {
8055     const clang::IdentifierInfo *getter_ident =
8056         &clang_ast.Idents.get(property_getter_name);
8057     getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident);
8058   } else {
8059     const clang::IdentifierInfo *getter_ident =
8060         &clang_ast.Idents.get(property_name);
8061     getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident);
8062   }
8063   property_decl->setGetterName(getter_sel);
8064   property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_getter);
8065 
8066   if (ivar_decl)
8067     property_decl->setPropertyIvarDecl(ivar_decl);
8068 
8069   if (property_attributes & DW_APPLE_PROPERTY_readonly)
8070     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readonly);
8071   if (property_attributes & DW_APPLE_PROPERTY_readwrite)
8072     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readwrite);
8073   if (property_attributes & DW_APPLE_PROPERTY_assign)
8074     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_assign);
8075   if (property_attributes & DW_APPLE_PROPERTY_retain)
8076     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_retain);
8077   if (property_attributes & DW_APPLE_PROPERTY_copy)
8078     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_copy);
8079   if (property_attributes & DW_APPLE_PROPERTY_nonatomic)
8080     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_nonatomic);
8081   if (property_attributes & ObjCPropertyAttribute::kind_nullability)
8082     property_decl->setPropertyAttributes(
8083         ObjCPropertyAttribute::kind_nullability);
8084   if (property_attributes & ObjCPropertyAttribute::kind_null_resettable)
8085     property_decl->setPropertyAttributes(
8086         ObjCPropertyAttribute::kind_null_resettable);
8087   if (property_attributes & ObjCPropertyAttribute::kind_class)
8088     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_class);
8089 
8090   const bool isInstance =
8091       (property_attributes & ObjCPropertyAttribute::kind_class) == 0;
8092 
8093   clang::ObjCMethodDecl *getter = nullptr;
8094   if (!getter_sel.isNull())
8095     getter = isInstance ? class_interface_decl->lookupInstanceMethod(getter_sel)
8096                         : class_interface_decl->lookupClassMethod(getter_sel);
8097   if (!getter_sel.isNull() && !getter) {
8098     const bool isVariadic = false;
8099     const bool isPropertyAccessor = true;
8100     const bool isSynthesizedAccessorStub = false;
8101     const bool isImplicitlyDeclared = true;
8102     const bool isDefined = false;
8103     const clang::ObjCImplementationControl impControl =
8104         clang::ObjCImplementationControl::None;
8105     const bool HasRelatedResultType = false;
8106 
8107     getter =
8108         clang::ObjCMethodDecl::CreateDeserialized(clang_ast, GlobalDeclID());
8109     getter->setDeclName(getter_sel);
8110     getter->setReturnType(ClangUtil::GetQualType(property_clang_type_to_access));
8111     getter->setDeclContext(class_interface_decl);
8112     getter->setInstanceMethod(isInstance);
8113     getter->setVariadic(isVariadic);
8114     getter->setPropertyAccessor(isPropertyAccessor);
8115     getter->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
8116     getter->setImplicit(isImplicitlyDeclared);
8117     getter->setDefined(isDefined);
8118     getter->setDeclImplementation(impControl);
8119     getter->setRelatedResultType(HasRelatedResultType);
8120     SetMemberOwningModule(getter, class_interface_decl);
8121 
8122     if (getter) {
8123       ast->SetMetadata(getter, metadata);
8124 
8125       getter->setMethodParams(clang_ast, llvm::ArrayRef<clang::ParmVarDecl *>(),
8126                               llvm::ArrayRef<clang::SourceLocation>());
8127       class_interface_decl->addDecl(getter);
8128     }
8129   }
8130   if (getter) {
8131     getter->setPropertyAccessor(true);
8132     property_decl->setGetterMethodDecl(getter);
8133   }
8134 
8135   clang::ObjCMethodDecl *setter = nullptr;
8136     setter = isInstance ? class_interface_decl->lookupInstanceMethod(setter_sel)
8137                         : class_interface_decl->lookupClassMethod(setter_sel);
8138   if (!setter_sel.isNull() && !setter) {
8139     clang::QualType result_type = clang_ast.VoidTy;
8140     const bool isVariadic = false;
8141     const bool isPropertyAccessor = true;
8142     const bool isSynthesizedAccessorStub = false;
8143     const bool isImplicitlyDeclared = true;
8144     const bool isDefined = false;
8145     const clang::ObjCImplementationControl impControl =
8146         clang::ObjCImplementationControl::None;
8147     const bool HasRelatedResultType = false;
8148 
8149     setter =
8150         clang::ObjCMethodDecl::CreateDeserialized(clang_ast, GlobalDeclID());
8151     setter->setDeclName(setter_sel);
8152     setter->setReturnType(result_type);
8153     setter->setDeclContext(class_interface_decl);
8154     setter->setInstanceMethod(isInstance);
8155     setter->setVariadic(isVariadic);
8156     setter->setPropertyAccessor(isPropertyAccessor);
8157     setter->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
8158     setter->setImplicit(isImplicitlyDeclared);
8159     setter->setDefined(isDefined);
8160     setter->setDeclImplementation(impControl);
8161     setter->setRelatedResultType(HasRelatedResultType);
8162     SetMemberOwningModule(setter, class_interface_decl);
8163 
8164     if (setter) {
8165       ast->SetMetadata(setter, metadata);
8166 
8167       llvm::SmallVector<clang::ParmVarDecl *, 1> params;
8168       params.push_back(clang::ParmVarDecl::Create(
8169           clang_ast, setter, clang::SourceLocation(), clang::SourceLocation(),
8170           nullptr, // anonymous
8171           ClangUtil::GetQualType(property_clang_type_to_access), nullptr,
8172           clang::SC_Auto, nullptr));
8173 
8174       setter->setMethodParams(clang_ast,
8175                               llvm::ArrayRef<clang::ParmVarDecl *>(params),
8176                               llvm::ArrayRef<clang::SourceLocation>());
8177 
8178       class_interface_decl->addDecl(setter);
8179     }
8180   }
8181   if (setter) {
8182     setter->setPropertyAccessor(true);
8183     property_decl->setSetterMethodDecl(setter);
8184   }
8185 
8186   return true;
8187 }
8188 
8189 bool TypeSystemClang::IsObjCClassTypeAndHasIVars(const CompilerType &type,
8190                                                  bool check_superclass) {
8191   clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
8192   if (class_interface_decl)
8193     return ObjCDeclHasIVars(class_interface_decl, check_superclass);
8194   return false;
8195 }
8196 
8197 clang::ObjCMethodDecl *TypeSystemClang::AddMethodToObjCObjectType(
8198     const CompilerType &type,
8199     const char *name, // the full symbol name as seen in the symbol table
8200                       // (lldb::opaque_compiler_type_t type, "-[NString
8201                       // stringWithCString:]")
8202     const CompilerType &method_clang_type, bool is_artificial, bool is_variadic,
8203     bool is_objc_direct_call) {
8204   if (!type || !method_clang_type.IsValid())
8205     return nullptr;
8206 
8207   clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
8208 
8209   if (class_interface_decl == nullptr)
8210     return nullptr;
8211   auto ts = type.GetTypeSystem();
8212   auto lldb_ast = ts.dyn_cast_or_null<TypeSystemClang>();
8213   if (lldb_ast == nullptr)
8214     return nullptr;
8215   clang::ASTContext &ast = lldb_ast->getASTContext();
8216 
8217   const char *selector_start = ::strchr(name, ' ');
8218   if (selector_start == nullptr)
8219     return nullptr;
8220 
8221   selector_start++;
8222   llvm::SmallVector<const clang::IdentifierInfo *, 12> selector_idents;
8223 
8224   size_t len = 0;
8225   const char *start;
8226 
8227   unsigned num_selectors_with_args = 0;
8228   for (start = selector_start; start && *start != '\0' && *start != ']';
8229        start += len) {
8230     len = ::strcspn(start, ":]");
8231     bool has_arg = (start[len] == ':');
8232     if (has_arg)
8233       ++num_selectors_with_args;
8234     selector_idents.push_back(&ast.Idents.get(llvm::StringRef(start, len)));
8235     if (has_arg)
8236       len += 1;
8237   }
8238 
8239   if (selector_idents.size() == 0)
8240     return nullptr;
8241 
8242   clang::Selector method_selector = ast.Selectors.getSelector(
8243       num_selectors_with_args ? selector_idents.size() : 0,
8244       selector_idents.data());
8245 
8246   clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
8247 
8248   // Populate the method decl with parameter decls
8249   const clang::Type *method_type(method_qual_type.getTypePtr());
8250 
8251   if (method_type == nullptr)
8252     return nullptr;
8253 
8254   const clang::FunctionProtoType *method_function_prototype(
8255       llvm::dyn_cast<clang::FunctionProtoType>(method_type));
8256 
8257   if (!method_function_prototype)
8258     return nullptr;
8259 
8260   const bool isInstance = (name[0] == '-');
8261   const bool isVariadic = is_variadic;
8262   const bool isPropertyAccessor = false;
8263   const bool isSynthesizedAccessorStub = false;
8264   /// Force this to true because we don't have source locations.
8265   const bool isImplicitlyDeclared = true;
8266   const bool isDefined = false;
8267   const clang::ObjCImplementationControl impControl =
8268       clang::ObjCImplementationControl::None;
8269   const bool HasRelatedResultType = false;
8270 
8271   const unsigned num_args = method_function_prototype->getNumParams();
8272 
8273   if (num_args != num_selectors_with_args)
8274     return nullptr; // some debug information is corrupt.  We are not going to
8275                     // deal with it.
8276 
8277   auto *objc_method_decl =
8278       clang::ObjCMethodDecl::CreateDeserialized(ast, GlobalDeclID());
8279   objc_method_decl->setDeclName(method_selector);
8280   objc_method_decl->setReturnType(method_function_prototype->getReturnType());
8281   objc_method_decl->setDeclContext(
8282       lldb_ast->GetDeclContextForType(ClangUtil::GetQualType(type)));
8283   objc_method_decl->setInstanceMethod(isInstance);
8284   objc_method_decl->setVariadic(isVariadic);
8285   objc_method_decl->setPropertyAccessor(isPropertyAccessor);
8286   objc_method_decl->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
8287   objc_method_decl->setImplicit(isImplicitlyDeclared);
8288   objc_method_decl->setDefined(isDefined);
8289   objc_method_decl->setDeclImplementation(impControl);
8290   objc_method_decl->setRelatedResultType(HasRelatedResultType);
8291   SetMemberOwningModule(objc_method_decl, class_interface_decl);
8292 
8293   if (objc_method_decl == nullptr)
8294     return nullptr;
8295 
8296   if (num_args > 0) {
8297     llvm::SmallVector<clang::ParmVarDecl *, 12> params;
8298 
8299     for (unsigned param_index = 0; param_index < num_args; ++param_index) {
8300       params.push_back(clang::ParmVarDecl::Create(
8301           ast, objc_method_decl, clang::SourceLocation(),
8302           clang::SourceLocation(),
8303           nullptr, // anonymous
8304           method_function_prototype->getParamType(param_index), nullptr,
8305           clang::SC_Auto, nullptr));
8306     }
8307 
8308     objc_method_decl->setMethodParams(
8309         ast, llvm::ArrayRef<clang::ParmVarDecl *>(params),
8310         llvm::ArrayRef<clang::SourceLocation>());
8311   }
8312 
8313   if (is_objc_direct_call) {
8314     // Add a the objc_direct attribute to the declaration we generate that
8315     // we generate a direct method call for this ObjCMethodDecl.
8316     objc_method_decl->addAttr(
8317         clang::ObjCDirectAttr::CreateImplicit(ast, SourceLocation()));
8318     // Usually Sema is creating implicit parameters (e.g., self) when it
8319     // parses the method. We don't have a parsing Sema when we build our own
8320     // AST here so we manually need to create these implicit parameters to
8321     // make the direct call code generation happy.
8322     objc_method_decl->createImplicitParams(ast, class_interface_decl);
8323   }
8324 
8325   class_interface_decl->addDecl(objc_method_decl);
8326 
8327   VerifyDecl(objc_method_decl);
8328 
8329   return objc_method_decl;
8330 }
8331 
8332 bool TypeSystemClang::SetHasExternalStorage(lldb::opaque_compiler_type_t type,
8333                                             bool has_extern) {
8334   if (!type)
8335     return false;
8336 
8337   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
8338 
8339   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8340   switch (type_class) {
8341   case clang::Type::Record: {
8342     clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
8343     if (cxx_record_decl) {
8344       cxx_record_decl->setHasExternalLexicalStorage(has_extern);
8345       cxx_record_decl->setHasExternalVisibleStorage(has_extern);
8346       return true;
8347     }
8348   } break;
8349 
8350   case clang::Type::Enum: {
8351     clang::EnumDecl *enum_decl =
8352         llvm::cast<clang::EnumType>(qual_type)->getDecl();
8353     if (enum_decl) {
8354       enum_decl->setHasExternalLexicalStorage(has_extern);
8355       enum_decl->setHasExternalVisibleStorage(has_extern);
8356       return true;
8357     }
8358   } break;
8359 
8360   case clang::Type::ObjCObject:
8361   case clang::Type::ObjCInterface: {
8362     const clang::ObjCObjectType *objc_class_type =
8363         llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
8364     assert(objc_class_type);
8365     if (objc_class_type) {
8366       clang::ObjCInterfaceDecl *class_interface_decl =
8367           objc_class_type->getInterface();
8368 
8369       if (class_interface_decl) {
8370         class_interface_decl->setHasExternalLexicalStorage(has_extern);
8371         class_interface_decl->setHasExternalVisibleStorage(has_extern);
8372         return true;
8373       }
8374     }
8375   } break;
8376 
8377   default:
8378     break;
8379   }
8380   return false;
8381 }
8382 
8383 #pragma mark TagDecl
8384 
8385 bool TypeSystemClang::StartTagDeclarationDefinition(const CompilerType &type) {
8386   clang::QualType qual_type(ClangUtil::GetQualType(type));
8387   if (!qual_type.isNull()) {
8388     const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8389     if (tag_type) {
8390       clang::TagDecl *tag_decl = tag_type->getDecl();
8391       if (tag_decl) {
8392         tag_decl->startDefinition();
8393         return true;
8394       }
8395     }
8396 
8397     const clang::ObjCObjectType *object_type =
8398         qual_type->getAs<clang::ObjCObjectType>();
8399     if (object_type) {
8400       clang::ObjCInterfaceDecl *interface_decl = object_type->getInterface();
8401       if (interface_decl) {
8402         interface_decl->startDefinition();
8403         return true;
8404       }
8405     }
8406   }
8407   return false;
8408 }
8409 
8410 bool TypeSystemClang::CompleteTagDeclarationDefinition(
8411     const CompilerType &type) {
8412   clang::QualType qual_type(ClangUtil::GetQualType(type));
8413   if (qual_type.isNull())
8414     return false;
8415 
8416   auto ts = type.GetTypeSystem();
8417   auto lldb_ast = ts.dyn_cast_or_null<TypeSystemClang>();
8418   if (lldb_ast == nullptr)
8419     return false;
8420 
8421   // Make sure we use the same methodology as
8422   // TypeSystemClang::StartTagDeclarationDefinition() as to how we start/end
8423   // the definition.
8424   const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8425   if (tag_type) {
8426     clang::TagDecl *tag_decl = tag_type->getDecl();
8427 
8428     if (auto *cxx_record_decl = llvm::dyn_cast<CXXRecordDecl>(tag_decl)) {
8429       // If we have a move constructor declared but no copy constructor we
8430       // need to explicitly mark it as deleted. Usually Sema would do this for
8431       // us in Sema::DeclareImplicitCopyConstructor but we don't have a Sema
8432       // when building an AST from debug information.
8433       // See also:
8434       // C++11 [class.copy]p7, p18:
8435       //  If the class definition declares a move constructor or move assignment
8436       //  operator, an implicitly declared copy constructor or copy assignment
8437       //  operator is defined as deleted.
8438       if (cxx_record_decl->hasUserDeclaredMoveConstructor() ||
8439           cxx_record_decl->hasUserDeclaredMoveAssignment()) {
8440         if (cxx_record_decl->needsImplicitCopyConstructor())
8441           cxx_record_decl->setImplicitCopyConstructorIsDeleted();
8442         if (cxx_record_decl->needsImplicitCopyAssignment())
8443           cxx_record_decl->setImplicitCopyAssignmentIsDeleted();
8444       }
8445 
8446       if (!cxx_record_decl->isCompleteDefinition())
8447         cxx_record_decl->completeDefinition();
8448       cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
8449       cxx_record_decl->setHasExternalLexicalStorage(false);
8450       cxx_record_decl->setHasExternalVisibleStorage(false);
8451       lldb_ast->SetCXXRecordDeclAccess(cxx_record_decl,
8452                                        clang::AccessSpecifier::AS_none);
8453       return true;
8454     }
8455   }
8456 
8457   const clang::EnumType *enutype = qual_type->getAs<clang::EnumType>();
8458 
8459   if (!enutype)
8460     return false;
8461   clang::EnumDecl *enum_decl = enutype->getDecl();
8462 
8463   if (enum_decl->isCompleteDefinition())
8464     return true;
8465 
8466   clang::ASTContext &ast = lldb_ast->getASTContext();
8467 
8468   /// TODO This really needs to be fixed.
8469 
8470   QualType integer_type(enum_decl->getIntegerType());
8471   if (!integer_type.isNull()) {
8472     unsigned NumPositiveBits = 1;
8473     unsigned NumNegativeBits = 0;
8474 
8475     clang::QualType promotion_qual_type;
8476     // If the enum integer type is less than an integer in bit width,
8477     // then we must promote it to an integer size.
8478     if (ast.getTypeSize(enum_decl->getIntegerType()) <
8479         ast.getTypeSize(ast.IntTy)) {
8480       if (enum_decl->getIntegerType()->isSignedIntegerType())
8481         promotion_qual_type = ast.IntTy;
8482       else
8483         promotion_qual_type = ast.UnsignedIntTy;
8484     } else
8485       promotion_qual_type = enum_decl->getIntegerType();
8486 
8487     enum_decl->completeDefinition(enum_decl->getIntegerType(),
8488                                   promotion_qual_type, NumPositiveBits,
8489                                   NumNegativeBits);
8490   }
8491   return true;
8492 }
8493 
8494 clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType(
8495     const CompilerType &enum_type, const Declaration &decl, const char *name,
8496     const llvm::APSInt &value) {
8497 
8498   if (!enum_type || ConstString(name).IsEmpty())
8499     return nullptr;
8500 
8501   lldbassert(enum_type.GetTypeSystem().GetSharedPointer().get() ==
8502              static_cast<TypeSystem *>(this));
8503 
8504   lldb::opaque_compiler_type_t enum_opaque_compiler_type =
8505       enum_type.GetOpaqueQualType();
8506 
8507   if (!enum_opaque_compiler_type)
8508     return nullptr;
8509 
8510   clang::QualType enum_qual_type(
8511       GetCanonicalQualType(enum_opaque_compiler_type));
8512 
8513   const clang::Type *clang_type = enum_qual_type.getTypePtr();
8514 
8515   if (!clang_type)
8516     return nullptr;
8517 
8518   const clang::EnumType *enutype = llvm::dyn_cast<clang::EnumType>(clang_type);
8519 
8520   if (!enutype)
8521     return nullptr;
8522 
8523   clang::EnumConstantDecl *enumerator_decl =
8524       clang::EnumConstantDecl::CreateDeserialized(getASTContext(),
8525                                                   GlobalDeclID());
8526   enumerator_decl->setDeclContext(enutype->getDecl());
8527   if (name && name[0])
8528     enumerator_decl->setDeclName(&getASTContext().Idents.get(name));
8529   enumerator_decl->setType(clang::QualType(enutype, 0));
8530   enumerator_decl->setInitVal(getASTContext(), value);
8531   SetMemberOwningModule(enumerator_decl, enutype->getDecl());
8532 
8533   if (!enumerator_decl)
8534     return nullptr;
8535 
8536   enutype->getDecl()->addDecl(enumerator_decl);
8537 
8538   VerifyDecl(enumerator_decl);
8539   return enumerator_decl;
8540 }
8541 
8542 clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType(
8543     const CompilerType &enum_type, const Declaration &decl, const char *name,
8544     int64_t enum_value, uint32_t enum_value_bit_size) {
8545   CompilerType underlying_type = GetEnumerationIntegerType(enum_type);
8546   bool is_signed = false;
8547   underlying_type.IsIntegerType(is_signed);
8548 
8549   llvm::APSInt value(enum_value_bit_size, !is_signed);
8550   value = enum_value;
8551 
8552   return AddEnumerationValueToEnumerationType(enum_type, decl, name, value);
8553 }
8554 
8555 CompilerType TypeSystemClang::GetEnumerationIntegerType(CompilerType type) {
8556   clang::QualType qt(ClangUtil::GetQualType(type));
8557   const clang::Type *clang_type = qt.getTypePtrOrNull();
8558   const auto *enum_type = llvm::dyn_cast_or_null<clang::EnumType>(clang_type);
8559   if (!enum_type)
8560     return CompilerType();
8561 
8562   return GetType(enum_type->getDecl()->getIntegerType());
8563 }
8564 
8565 CompilerType
8566 TypeSystemClang::CreateMemberPointerType(const CompilerType &type,
8567                                          const CompilerType &pointee_type) {
8568   if (type && pointee_type.IsValid() &&
8569       type.GetTypeSystem() == pointee_type.GetTypeSystem()) {
8570     auto ts = type.GetTypeSystem();
8571     auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
8572     if (!ast)
8573       return CompilerType();
8574     return ast->GetType(ast->getASTContext().getMemberPointerType(
8575         ClangUtil::GetQualType(pointee_type),
8576         ClangUtil::GetQualType(type).getTypePtr()));
8577   }
8578   return CompilerType();
8579 }
8580 
8581 // Dumping types
8582 #define DEPTH_INCREMENT 2
8583 
8584 #ifndef NDEBUG
8585 LLVM_DUMP_METHOD void
8586 TypeSystemClang::dump(lldb::opaque_compiler_type_t type) const {
8587   if (!type)
8588     return;
8589   clang::QualType qual_type(GetQualType(type));
8590   qual_type.dump();
8591 }
8592 #endif
8593 
8594 void TypeSystemClang::Dump(llvm::raw_ostream &output) {
8595   GetTranslationUnitDecl()->dump(output);
8596 }
8597 
8598 void TypeSystemClang::DumpFromSymbolFile(Stream &s,
8599                                          llvm::StringRef symbol_name) {
8600   SymbolFile *symfile = GetSymbolFile();
8601 
8602   if (!symfile)
8603     return;
8604 
8605   lldb_private::TypeList type_list;
8606   symfile->GetTypes(nullptr, eTypeClassAny, type_list);
8607   size_t ntypes = type_list.GetSize();
8608 
8609   for (size_t i = 0; i < ntypes; ++i) {
8610     TypeSP type = type_list.GetTypeAtIndex(i);
8611 
8612     if (!symbol_name.empty())
8613       if (symbol_name != type->GetName().GetStringRef())
8614         continue;
8615 
8616     s << type->GetName().AsCString() << "\n";
8617 
8618     CompilerType full_type = type->GetFullCompilerType();
8619     if (clang::TagDecl *tag_decl = GetAsTagDecl(full_type)) {
8620       tag_decl->dump(s.AsRawOstream());
8621       continue;
8622     }
8623     if (clang::TypedefNameDecl *typedef_decl = GetAsTypedefDecl(full_type)) {
8624       typedef_decl->dump(s.AsRawOstream());
8625       continue;
8626     }
8627     if (auto *objc_obj = llvm::dyn_cast<clang::ObjCObjectType>(
8628             ClangUtil::GetQualType(full_type).getTypePtr())) {
8629       if (clang::ObjCInterfaceDecl *interface_decl = objc_obj->getInterface()) {
8630         interface_decl->dump(s.AsRawOstream());
8631         continue;
8632       }
8633     }
8634     GetCanonicalQualType(full_type.GetOpaqueQualType())
8635         .dump(s.AsRawOstream(), getASTContext());
8636   }
8637 }
8638 
8639 static bool DumpEnumValue(const clang::QualType &qual_type, Stream &s,
8640                           const DataExtractor &data, lldb::offset_t byte_offset,
8641                           size_t byte_size, uint32_t bitfield_bit_offset,
8642                           uint32_t bitfield_bit_size) {
8643   const clang::EnumType *enutype =
8644       llvm::cast<clang::EnumType>(qual_type.getTypePtr());
8645   const clang::EnumDecl *enum_decl = enutype->getDecl();
8646   assert(enum_decl);
8647   lldb::offset_t offset = byte_offset;
8648   bool qual_type_is_signed = qual_type->isSignedIntegerOrEnumerationType();
8649   const uint64_t enum_svalue =
8650       qual_type_is_signed
8651           ? data.GetMaxS64Bitfield(&offset, byte_size, bitfield_bit_size,
8652                                    bitfield_bit_offset)
8653           : data.GetMaxU64Bitfield(&offset, byte_size, bitfield_bit_size,
8654                                    bitfield_bit_offset);
8655   bool can_be_bitfield = true;
8656   uint64_t covered_bits = 0;
8657   int num_enumerators = 0;
8658 
8659   // Try to find an exact match for the value.
8660   // At the same time, we're applying a heuristic to determine whether we want
8661   // to print this enum as a bitfield. We're likely dealing with a bitfield if
8662   // every enumerator is either a one bit value or a superset of the previous
8663   // enumerators. Also 0 doesn't make sense when the enumerators are used as
8664   // flags.
8665   clang::EnumDecl::enumerator_range enumerators = enum_decl->enumerators();
8666   if (enumerators.empty())
8667     can_be_bitfield = false;
8668   else {
8669     for (auto *enumerator : enumerators) {
8670       llvm::APSInt init_val = enumerator->getInitVal();
8671       uint64_t val = qual_type_is_signed ? init_val.getSExtValue()
8672                                          : init_val.getZExtValue();
8673       if (qual_type_is_signed)
8674         val = llvm::SignExtend64(val, 8 * byte_size);
8675       if (llvm::popcount(val) != 1 && (val & ~covered_bits) != 0)
8676         can_be_bitfield = false;
8677       covered_bits |= val;
8678       ++num_enumerators;
8679       if (val == enum_svalue) {
8680         // Found an exact match, that's all we need to do.
8681         s.PutCString(enumerator->getNameAsString());
8682         return true;
8683       }
8684     }
8685   }
8686 
8687   // Unsigned values make more sense for flags.
8688   offset = byte_offset;
8689   const uint64_t enum_uvalue = data.GetMaxU64Bitfield(
8690       &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
8691 
8692   // No exact match, but we don't think this is a bitfield. Print the value as
8693   // decimal.
8694   if (!can_be_bitfield) {
8695     if (qual_type_is_signed)
8696       s.Printf("%" PRIi64, enum_svalue);
8697     else
8698       s.Printf("%" PRIu64, enum_uvalue);
8699     return true;
8700   }
8701 
8702   if (!enum_uvalue) {
8703     // This is a bitfield enum, but the value is 0 so we know it won't match
8704     // with any of the enumerators.
8705     s.Printf("0x%" PRIx64, enum_uvalue);
8706     return true;
8707   }
8708 
8709   uint64_t remaining_value = enum_uvalue;
8710   std::vector<std::pair<uint64_t, llvm::StringRef>> values;
8711   values.reserve(num_enumerators);
8712   for (auto *enumerator : enum_decl->enumerators())
8713     if (auto val = enumerator->getInitVal().getZExtValue())
8714       values.emplace_back(val, enumerator->getName());
8715 
8716   // Sort in reverse order of the number of the population count,  so that in
8717   // `enum {A, B, ALL = A|B }` we visit ALL first. Use a stable sort so that
8718   // A | C where A is declared before C is displayed in this order.
8719   std::stable_sort(values.begin(), values.end(),
8720                    [](const auto &a, const auto &b) {
8721                      return llvm::popcount(a.first) > llvm::popcount(b.first);
8722                    });
8723 
8724   for (const auto &val : values) {
8725     if ((remaining_value & val.first) != val.first)
8726       continue;
8727     remaining_value &= ~val.first;
8728     s.PutCString(val.second);
8729     if (remaining_value)
8730       s.PutCString(" | ");
8731   }
8732 
8733   // If there is a remainder that is not covered by the value, print it as
8734   // hex.
8735   if (remaining_value)
8736     s.Printf("0x%" PRIx64, remaining_value);
8737 
8738   return true;
8739 }
8740 
8741 bool TypeSystemClang::DumpTypeValue(
8742     lldb::opaque_compiler_type_t type, Stream &s, lldb::Format format,
8743     const lldb_private::DataExtractor &data, lldb::offset_t byte_offset,
8744     size_t byte_size, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
8745     ExecutionContextScope *exe_scope) {
8746   if (!type)
8747     return false;
8748   if (IsAggregateType(type)) {
8749     return false;
8750   } else {
8751     clang::QualType qual_type(GetQualType(type));
8752 
8753     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8754 
8755     if (type_class == clang::Type::Elaborated) {
8756       qual_type = llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType();
8757       return DumpTypeValue(qual_type.getAsOpaquePtr(), s, format, data, byte_offset, byte_size,
8758                            bitfield_bit_size, bitfield_bit_offset, exe_scope);
8759     }
8760 
8761     switch (type_class) {
8762     case clang::Type::Typedef: {
8763       clang::QualType typedef_qual_type =
8764           llvm::cast<clang::TypedefType>(qual_type)
8765               ->getDecl()
8766               ->getUnderlyingType();
8767       CompilerType typedef_clang_type = GetType(typedef_qual_type);
8768       if (format == eFormatDefault)
8769         format = typedef_clang_type.GetFormat();
8770       clang::TypeInfo typedef_type_info =
8771           getASTContext().getTypeInfo(typedef_qual_type);
8772       uint64_t typedef_byte_size = typedef_type_info.Width / 8;
8773 
8774       return typedef_clang_type.DumpTypeValue(
8775           &s,
8776           format,            // The format with which to display the element
8777           data,              // Data buffer containing all bytes for this type
8778           byte_offset,       // Offset into "data" where to grab value from
8779           typedef_byte_size, // Size of this type in bytes
8780           bitfield_bit_size, // Size in bits of a bitfield value, if zero don't
8781                              // treat as a bitfield
8782           bitfield_bit_offset, // Offset in bits of a bitfield value if
8783                                // bitfield_bit_size != 0
8784           exe_scope);
8785     } break;
8786 
8787     case clang::Type::Enum:
8788       // If our format is enum or default, show the enumeration value as its
8789       // enumeration string value, else just display it as requested.
8790       if ((format == eFormatEnum || format == eFormatDefault) &&
8791           GetCompleteType(type))
8792         return DumpEnumValue(qual_type, s, data, byte_offset, byte_size,
8793                              bitfield_bit_offset, bitfield_bit_size);
8794       // format was not enum, just fall through and dump the value as
8795       // requested....
8796       [[fallthrough]];
8797 
8798     default:
8799       // We are down to a scalar type that we just need to display.
8800       {
8801         uint32_t item_count = 1;
8802         // A few formats, we might need to modify our size and count for
8803         // depending
8804         // on how we are trying to display the value...
8805         switch (format) {
8806         default:
8807         case eFormatBoolean:
8808         case eFormatBinary:
8809         case eFormatComplex:
8810         case eFormatCString: // NULL terminated C strings
8811         case eFormatDecimal:
8812         case eFormatEnum:
8813         case eFormatHex:
8814         case eFormatHexUppercase:
8815         case eFormatFloat:
8816         case eFormatOctal:
8817         case eFormatOSType:
8818         case eFormatUnsigned:
8819         case eFormatPointer:
8820         case eFormatVectorOfChar:
8821         case eFormatVectorOfSInt8:
8822         case eFormatVectorOfUInt8:
8823         case eFormatVectorOfSInt16:
8824         case eFormatVectorOfUInt16:
8825         case eFormatVectorOfSInt32:
8826         case eFormatVectorOfUInt32:
8827         case eFormatVectorOfSInt64:
8828         case eFormatVectorOfUInt64:
8829         case eFormatVectorOfFloat32:
8830         case eFormatVectorOfFloat64:
8831         case eFormatVectorOfUInt128:
8832           break;
8833 
8834         case eFormatChar:
8835         case eFormatCharPrintable:
8836         case eFormatCharArray:
8837         case eFormatBytes:
8838         case eFormatUnicode8:
8839         case eFormatBytesWithASCII:
8840           item_count = byte_size;
8841           byte_size = 1;
8842           break;
8843 
8844         case eFormatUnicode16:
8845           item_count = byte_size / 2;
8846           byte_size = 2;
8847           break;
8848 
8849         case eFormatUnicode32:
8850           item_count = byte_size / 4;
8851           byte_size = 4;
8852           break;
8853         }
8854         return DumpDataExtractor(data, &s, byte_offset, format, byte_size,
8855                                  item_count, UINT32_MAX, LLDB_INVALID_ADDRESS,
8856                                  bitfield_bit_size, bitfield_bit_offset,
8857                                  exe_scope);
8858       }
8859       break;
8860     }
8861   }
8862   return false;
8863 }
8864 
8865 void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type,
8866                                           lldb::DescriptionLevel level) {
8867   StreamFile s(stdout, false);
8868   DumpTypeDescription(type, s, level);
8869 
8870   CompilerType ct(weak_from_this(), type);
8871   const clang::Type *clang_type = ClangUtil::GetQualType(ct).getTypePtr();
8872   if (std::optional<ClangASTMetadata> metadata = GetMetadata(clang_type)) {
8873     metadata->Dump(&s);
8874   }
8875 }
8876 
8877 void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type,
8878                                           Stream &s,
8879                                           lldb::DescriptionLevel level) {
8880   if (type) {
8881     clang::QualType qual_type =
8882         RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
8883 
8884     llvm::SmallVector<char, 1024> buf;
8885     llvm::raw_svector_ostream llvm_ostrm(buf);
8886 
8887     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8888     switch (type_class) {
8889     case clang::Type::ObjCObject:
8890     case clang::Type::ObjCInterface: {
8891       GetCompleteType(type);
8892 
8893       auto *objc_class_type =
8894           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
8895       assert(objc_class_type);
8896       if (!objc_class_type)
8897         break;
8898       clang::ObjCInterfaceDecl *class_interface_decl =
8899             objc_class_type->getInterface();
8900       if (!class_interface_decl)
8901         break;
8902       if (level == eDescriptionLevelVerbose)
8903         class_interface_decl->dump(llvm_ostrm);
8904       else
8905         class_interface_decl->print(llvm_ostrm,
8906                                     getASTContext().getPrintingPolicy(),
8907                                     s.GetIndentLevel());
8908     } break;
8909 
8910     case clang::Type::Typedef: {
8911       auto *typedef_type = qual_type->getAs<clang::TypedefType>();
8912       if (!typedef_type)
8913         break;
8914       const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
8915       if (level == eDescriptionLevelVerbose)
8916         typedef_decl->dump(llvm_ostrm);
8917       else {
8918         std::string clang_typedef_name(GetTypeNameForDecl(typedef_decl));
8919         if (!clang_typedef_name.empty()) {
8920           s.PutCString("typedef ");
8921           s.PutCString(clang_typedef_name);
8922         }
8923       }
8924     } break;
8925 
8926     case clang::Type::Record: {
8927       GetCompleteType(type);
8928 
8929       auto *record_type = llvm::cast<clang::RecordType>(qual_type.getTypePtr());
8930       const clang::RecordDecl *record_decl = record_type->getDecl();
8931       if (level == eDescriptionLevelVerbose)
8932         record_decl->dump(llvm_ostrm);
8933       else {
8934         record_decl->print(llvm_ostrm, getASTContext().getPrintingPolicy(),
8935                            s.GetIndentLevel());
8936       }
8937     } break;
8938 
8939     default: {
8940       if (auto *tag_type =
8941               llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr())) {
8942         if (clang::TagDecl *tag_decl = tag_type->getDecl()) {
8943           if (level == eDescriptionLevelVerbose)
8944             tag_decl->dump(llvm_ostrm);
8945           else
8946             tag_decl->print(llvm_ostrm, 0);
8947         }
8948       } else {
8949         if (level == eDescriptionLevelVerbose)
8950           qual_type->dump(llvm_ostrm, getASTContext());
8951         else {
8952           std::string clang_type_name(qual_type.getAsString());
8953           if (!clang_type_name.empty())
8954             s.PutCString(clang_type_name);
8955         }
8956       }
8957     }
8958     }
8959 
8960     if (buf.size() > 0) {
8961       s.Write(buf.data(), buf.size());
8962     }
8963 }
8964 }
8965 
8966 void TypeSystemClang::DumpTypeName(const CompilerType &type) {
8967   if (ClangUtil::IsClangType(type)) {
8968     clang::QualType qual_type(
8969         ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
8970 
8971     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8972     switch (type_class) {
8973     case clang::Type::Record: {
8974       const clang::CXXRecordDecl *cxx_record_decl =
8975           qual_type->getAsCXXRecordDecl();
8976       if (cxx_record_decl)
8977         printf("class %s", cxx_record_decl->getName().str().c_str());
8978     } break;
8979 
8980     case clang::Type::Enum: {
8981       clang::EnumDecl *enum_decl =
8982           llvm::cast<clang::EnumType>(qual_type)->getDecl();
8983       if (enum_decl) {
8984         printf("enum %s", enum_decl->getName().str().c_str());
8985       }
8986     } break;
8987 
8988     case clang::Type::ObjCObject:
8989     case clang::Type::ObjCInterface: {
8990       const clang::ObjCObjectType *objc_class_type =
8991           llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
8992       if (objc_class_type) {
8993         clang::ObjCInterfaceDecl *class_interface_decl =
8994             objc_class_type->getInterface();
8995         // We currently can't complete objective C types through the newly
8996         // added ASTContext because it only supports TagDecl objects right
8997         // now...
8998         if (class_interface_decl)
8999           printf("@class %s", class_interface_decl->getName().str().c_str());
9000       }
9001     } break;
9002 
9003     case clang::Type::Typedef:
9004       printf("typedef %s", llvm::cast<clang::TypedefType>(qual_type)
9005                                ->getDecl()
9006                                ->getName()
9007                                .str()
9008                                .c_str());
9009       break;
9010 
9011     case clang::Type::Auto:
9012       printf("auto ");
9013       return DumpTypeName(CompilerType(type.GetTypeSystem(),
9014                                        llvm::cast<clang::AutoType>(qual_type)
9015                                            ->getDeducedType()
9016                                            .getAsOpaquePtr()));
9017 
9018     case clang::Type::Elaborated:
9019       printf("elaborated ");
9020       return DumpTypeName(CompilerType(
9021           type.GetTypeSystem(), llvm::cast<clang::ElaboratedType>(qual_type)
9022                                     ->getNamedType()
9023                                     .getAsOpaquePtr()));
9024 
9025     case clang::Type::Paren:
9026       printf("paren ");
9027       return DumpTypeName(CompilerType(
9028           type.GetTypeSystem(),
9029           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
9030 
9031     default:
9032       printf("TypeSystemClang::DumpTypeName() type_class = %u", type_class);
9033       break;
9034     }
9035   }
9036 }
9037 
9038 clang::ClassTemplateDecl *TypeSystemClang::ParseClassTemplateDecl(
9039     clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
9040     lldb::AccessType access_type, const char *parent_name, int tag_decl_kind,
9041     const TypeSystemClang::TemplateParameterInfos &template_param_infos) {
9042   if (template_param_infos.IsValid()) {
9043     std::string template_basename(parent_name);
9044     // With -gsimple-template-names we may omit template parameters in the name.
9045     if (auto i = template_basename.find('<'); i != std::string::npos)
9046       template_basename.erase(i);
9047 
9048     return CreateClassTemplateDecl(decl_ctx, owning_module, access_type,
9049                                    template_basename.c_str(), tag_decl_kind,
9050                                    template_param_infos);
9051   }
9052   return nullptr;
9053 }
9054 
9055 void TypeSystemClang::CompleteTagDecl(clang::TagDecl *decl) {
9056   SymbolFile *sym_file = GetSymbolFile();
9057   if (sym_file) {
9058     CompilerType clang_type = GetTypeForDecl(decl);
9059     if (clang_type)
9060       sym_file->CompleteType(clang_type);
9061   }
9062 }
9063 
9064 void TypeSystemClang::CompleteObjCInterfaceDecl(
9065     clang::ObjCInterfaceDecl *decl) {
9066   SymbolFile *sym_file = GetSymbolFile();
9067   if (sym_file) {
9068     CompilerType clang_type = GetTypeForDecl(decl);
9069     if (clang_type)
9070       sym_file->CompleteType(clang_type);
9071   }
9072 }
9073 
9074 DWARFASTParser *TypeSystemClang::GetDWARFParser() {
9075   if (!m_dwarf_ast_parser_up)
9076     m_dwarf_ast_parser_up = std::make_unique<DWARFASTParserClang>(*this);
9077   return m_dwarf_ast_parser_up.get();
9078 }
9079 
9080 PDBASTParser *TypeSystemClang::GetPDBParser() {
9081   if (!m_pdb_ast_parser_up)
9082     m_pdb_ast_parser_up = std::make_unique<PDBASTParser>(*this);
9083   return m_pdb_ast_parser_up.get();
9084 }
9085 
9086 npdb::PdbAstBuilder *TypeSystemClang::GetNativePDBParser() {
9087   if (!m_native_pdb_ast_parser_up)
9088     m_native_pdb_ast_parser_up = std::make_unique<npdb::PdbAstBuilder>(*this);
9089   return m_native_pdb_ast_parser_up.get();
9090 }
9091 
9092 bool TypeSystemClang::LayoutRecordType(
9093     const clang::RecordDecl *record_decl, uint64_t &bit_size,
9094     uint64_t &alignment,
9095     llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
9096     llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9097         &base_offsets,
9098     llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9099         &vbase_offsets) {
9100   lldb_private::ClangASTImporter *importer = nullptr;
9101   if (m_dwarf_ast_parser_up)
9102     importer = &m_dwarf_ast_parser_up->GetClangASTImporter();
9103   if (!importer && m_pdb_ast_parser_up)
9104     importer = &m_pdb_ast_parser_up->GetClangASTImporter();
9105   if (!importer && m_native_pdb_ast_parser_up)
9106     importer = &m_native_pdb_ast_parser_up->GetClangASTImporter();
9107   if (!importer)
9108     return false;
9109 
9110   return importer->LayoutRecordType(record_decl, bit_size, alignment,
9111                                     field_offsets, base_offsets, vbase_offsets);
9112 }
9113 
9114 // CompilerDecl override functions
9115 
9116 ConstString TypeSystemClang::DeclGetName(void *opaque_decl) {
9117   if (opaque_decl) {
9118     clang::NamedDecl *nd =
9119         llvm::dyn_cast<NamedDecl>((clang::Decl *)opaque_decl);
9120     if (nd != nullptr)
9121       return ConstString(GetTypeNameForDecl(nd, /*qualified=*/false));
9122   }
9123   return ConstString();
9124 }
9125 
9126 ConstString TypeSystemClang::DeclGetMangledName(void *opaque_decl) {
9127   if (opaque_decl) {
9128     clang::NamedDecl *nd =
9129         llvm::dyn_cast<clang::NamedDecl>((clang::Decl *)opaque_decl);
9130     if (nd != nullptr && !llvm::isa<clang::ObjCMethodDecl>(nd)) {
9131       clang::MangleContext *mc = getMangleContext();
9132       if (mc && mc->shouldMangleCXXName(nd)) {
9133         llvm::SmallVector<char, 1024> buf;
9134         llvm::raw_svector_ostream llvm_ostrm(buf);
9135         if (llvm::isa<clang::CXXConstructorDecl>(nd)) {
9136           mc->mangleName(
9137               clang::GlobalDecl(llvm::dyn_cast<clang::CXXConstructorDecl>(nd),
9138                                 Ctor_Complete),
9139               llvm_ostrm);
9140         } else if (llvm::isa<clang::CXXDestructorDecl>(nd)) {
9141           mc->mangleName(
9142               clang::GlobalDecl(llvm::dyn_cast<clang::CXXDestructorDecl>(nd),
9143                                 Dtor_Complete),
9144               llvm_ostrm);
9145         } else {
9146           mc->mangleName(nd, llvm_ostrm);
9147         }
9148         if (buf.size() > 0)
9149           return ConstString(buf.data(), buf.size());
9150       }
9151     }
9152   }
9153   return ConstString();
9154 }
9155 
9156 CompilerDeclContext TypeSystemClang::DeclGetDeclContext(void *opaque_decl) {
9157   if (opaque_decl)
9158     return CreateDeclContext(((clang::Decl *)opaque_decl)->getDeclContext());
9159   return CompilerDeclContext();
9160 }
9161 
9162 CompilerType TypeSystemClang::DeclGetFunctionReturnType(void *opaque_decl) {
9163   if (clang::FunctionDecl *func_decl =
9164           llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9165     return GetType(func_decl->getReturnType());
9166   if (clang::ObjCMethodDecl *objc_method =
9167           llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9168     return GetType(objc_method->getReturnType());
9169   else
9170     return CompilerType();
9171 }
9172 
9173 size_t TypeSystemClang::DeclGetFunctionNumArguments(void *opaque_decl) {
9174   if (clang::FunctionDecl *func_decl =
9175           llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9176     return func_decl->param_size();
9177   if (clang::ObjCMethodDecl *objc_method =
9178           llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9179     return objc_method->param_size();
9180   else
9181     return 0;
9182 }
9183 
9184 static CompilerContextKind GetCompilerKind(clang::Decl::Kind clang_kind,
9185                                            clang::DeclContext const *decl_ctx) {
9186   switch (clang_kind) {
9187   case Decl::TranslationUnit:
9188     return CompilerContextKind::TranslationUnit;
9189   case Decl::Namespace:
9190     return CompilerContextKind::Namespace;
9191   case Decl::Var:
9192     return CompilerContextKind::Variable;
9193   case Decl::Enum:
9194     return CompilerContextKind::Enum;
9195   case Decl::Typedef:
9196     return CompilerContextKind::Typedef;
9197   default:
9198     // Many other kinds have multiple values
9199     if (decl_ctx) {
9200       if (decl_ctx->isFunctionOrMethod())
9201         return CompilerContextKind::Function;
9202       if (decl_ctx->isRecord())
9203         return CompilerContextKind::ClassOrStruct | CompilerContextKind::Union;
9204     }
9205     break;
9206   }
9207   return CompilerContextKind::Any;
9208 }
9209 
9210 static void
9211 InsertCompilerContext(TypeSystemClang *ts, clang::DeclContext *decl_ctx,
9212                       std::vector<lldb_private::CompilerContext> &context) {
9213   if (decl_ctx == nullptr)
9214     return;
9215   InsertCompilerContext(ts, decl_ctx->getParent(), context);
9216   clang::Decl::Kind clang_kind = decl_ctx->getDeclKind();
9217   if (clang_kind == Decl::TranslationUnit)
9218     return; // Stop at the translation unit.
9219   const CompilerContextKind compiler_kind =
9220       GetCompilerKind(clang_kind, decl_ctx);
9221   ConstString decl_ctx_name = ts->DeclContextGetName(decl_ctx);
9222   context.push_back({compiler_kind, decl_ctx_name});
9223 }
9224 
9225 std::vector<lldb_private::CompilerContext>
9226 TypeSystemClang::DeclGetCompilerContext(void *opaque_decl) {
9227   std::vector<lldb_private::CompilerContext> context;
9228   ConstString decl_name = DeclGetName(opaque_decl);
9229   if (decl_name) {
9230     clang::Decl *decl = (clang::Decl *)opaque_decl;
9231     // Add the entire decl context first
9232     clang::DeclContext *decl_ctx = decl->getDeclContext();
9233     InsertCompilerContext(this, decl_ctx, context);
9234     // Now add the decl information
9235     auto compiler_kind =
9236         GetCompilerKind(decl->getKind(), dyn_cast<DeclContext>(decl));
9237     context.push_back({compiler_kind, decl_name});
9238   }
9239   return context;
9240 }
9241 
9242 CompilerType TypeSystemClang::DeclGetFunctionArgumentType(void *opaque_decl,
9243                                                           size_t idx) {
9244   if (clang::FunctionDecl *func_decl =
9245           llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl)) {
9246     if (idx < func_decl->param_size()) {
9247       ParmVarDecl *var_decl = func_decl->getParamDecl(idx);
9248       if (var_decl)
9249         return GetType(var_decl->getOriginalType());
9250     }
9251   } else if (clang::ObjCMethodDecl *objc_method =
9252                  llvm::dyn_cast<clang::ObjCMethodDecl>(
9253                      (clang::Decl *)opaque_decl)) {
9254     if (idx < objc_method->param_size())
9255       return GetType(objc_method->parameters()[idx]->getOriginalType());
9256   }
9257   return CompilerType();
9258 }
9259 
9260 Scalar TypeSystemClang::DeclGetConstantValue(void *opaque_decl) {
9261   clang::Decl *decl = static_cast<clang::Decl *>(opaque_decl);
9262   clang::VarDecl *var_decl = llvm::dyn_cast<clang::VarDecl>(decl);
9263   if (!var_decl)
9264     return Scalar();
9265   clang::Expr *init_expr = var_decl->getInit();
9266   if (!init_expr)
9267     return Scalar();
9268   std::optional<llvm::APSInt> value =
9269       init_expr->getIntegerConstantExpr(getASTContext());
9270   if (!value)
9271     return Scalar();
9272   return Scalar(*value);
9273 }
9274 
9275 // CompilerDeclContext functions
9276 
9277 std::vector<CompilerDecl> TypeSystemClang::DeclContextFindDeclByName(
9278     void *opaque_decl_ctx, ConstString name, const bool ignore_using_decls) {
9279   std::vector<CompilerDecl> found_decls;
9280   SymbolFile *symbol_file = GetSymbolFile();
9281   if (opaque_decl_ctx && symbol_file) {
9282     DeclContext *root_decl_ctx = (DeclContext *)opaque_decl_ctx;
9283     std::set<DeclContext *> searched;
9284     std::multimap<DeclContext *, DeclContext *> search_queue;
9285 
9286     for (clang::DeclContext *decl_context = root_decl_ctx;
9287          decl_context != nullptr && found_decls.empty();
9288          decl_context = decl_context->getParent()) {
9289       search_queue.insert(std::make_pair(decl_context, decl_context));
9290 
9291       for (auto it = search_queue.find(decl_context); it != search_queue.end();
9292            it++) {
9293         if (!searched.insert(it->second).second)
9294           continue;
9295         symbol_file->ParseDeclsForContext(
9296             CreateDeclContext(it->second));
9297 
9298         for (clang::Decl *child : it->second->decls()) {
9299           if (clang::UsingDirectiveDecl *ud =
9300                   llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
9301             if (ignore_using_decls)
9302               continue;
9303             clang::DeclContext *from = ud->getCommonAncestor();
9304             if (searched.find(ud->getNominatedNamespace()) == searched.end())
9305               search_queue.insert(
9306                   std::make_pair(from, ud->getNominatedNamespace()));
9307           } else if (clang::UsingDecl *ud =
9308                          llvm::dyn_cast<clang::UsingDecl>(child)) {
9309             if (ignore_using_decls)
9310               continue;
9311             for (clang::UsingShadowDecl *usd : ud->shadows()) {
9312               clang::Decl *target = usd->getTargetDecl();
9313               if (clang::NamedDecl *nd =
9314                       llvm::dyn_cast<clang::NamedDecl>(target)) {
9315                 IdentifierInfo *ii = nd->getIdentifier();
9316                 if (ii != nullptr && ii->getName() == name.AsCString(nullptr))
9317                   found_decls.push_back(GetCompilerDecl(nd));
9318               }
9319             }
9320           } else if (clang::NamedDecl *nd =
9321                          llvm::dyn_cast<clang::NamedDecl>(child)) {
9322             IdentifierInfo *ii = nd->getIdentifier();
9323             if (ii != nullptr && ii->getName() == name.AsCString(nullptr))
9324               found_decls.push_back(GetCompilerDecl(nd));
9325           }
9326         }
9327       }
9328     }
9329   }
9330   return found_decls;
9331 }
9332 
9333 // Look for child_decl_ctx's lookup scope in frame_decl_ctx and its parents,
9334 // and return the number of levels it took to find it, or
9335 // LLDB_INVALID_DECL_LEVEL if not found.  If the decl was imported via a using
9336 // declaration, its name and/or type, if set, will be used to check that the
9337 // decl found in the scope is a match.
9338 //
9339 // The optional name is required by languages (like C++) to handle using
9340 // declarations like:
9341 //
9342 //     void poo();
9343 //     namespace ns {
9344 //         void foo();
9345 //         void goo();
9346 //     }
9347 //     void bar() {
9348 //         using ns::foo;
9349 //         // CountDeclLevels returns 0 for 'foo', 1 for 'poo', and
9350 //         // LLDB_INVALID_DECL_LEVEL for 'goo'.
9351 //     }
9352 //
9353 // The optional type is useful in the case that there's a specific overload
9354 // that we're looking for that might otherwise be shadowed, like:
9355 //
9356 //     void foo(int);
9357 //     namespace ns {
9358 //         void foo();
9359 //     }
9360 //     void bar() {
9361 //         using ns::foo;
9362 //         // CountDeclLevels returns 0 for { 'foo', void() },
9363 //         // 1 for { 'foo', void(int) }, and
9364 //         // LLDB_INVALID_DECL_LEVEL for { 'foo', void(int, int) }.
9365 //     }
9366 //
9367 // NOTE: Because file statics are at the TranslationUnit along with globals, a
9368 // function at file scope will return the same level as a function at global
9369 // scope. Ideally we'd like to treat the file scope as an additional scope just
9370 // below the global scope.  More work needs to be done to recognise that, if
9371 // the decl we're trying to look up is static, we should compare its source
9372 // file with that of the current scope and return a lower number for it.
9373 uint32_t TypeSystemClang::CountDeclLevels(clang::DeclContext *frame_decl_ctx,
9374                                           clang::DeclContext *child_decl_ctx,
9375                                           ConstString *child_name,
9376                                           CompilerType *child_type) {
9377   SymbolFile *symbol_file = GetSymbolFile();
9378   if (frame_decl_ctx && symbol_file) {
9379     std::set<DeclContext *> searched;
9380     std::multimap<DeclContext *, DeclContext *> search_queue;
9381 
9382     // Get the lookup scope for the decl we're trying to find.
9383     clang::DeclContext *parent_decl_ctx = child_decl_ctx->getParent();
9384 
9385     // Look for it in our scope's decl context and its parents.
9386     uint32_t level = 0;
9387     for (clang::DeclContext *decl_ctx = frame_decl_ctx; decl_ctx != nullptr;
9388          decl_ctx = decl_ctx->getParent()) {
9389       if (!decl_ctx->isLookupContext())
9390         continue;
9391       if (decl_ctx == parent_decl_ctx)
9392         // Found it!
9393         return level;
9394       search_queue.insert(std::make_pair(decl_ctx, decl_ctx));
9395       for (auto it = search_queue.find(decl_ctx); it != search_queue.end();
9396            it++) {
9397         if (searched.find(it->second) != searched.end())
9398           continue;
9399 
9400         // Currently DWARF has one shared translation unit for all Decls at top
9401         // level, so this would erroneously find using statements anywhere.  So
9402         // don't look at the top-level translation unit.
9403         // TODO fix this and add a testcase that depends on it.
9404 
9405         if (llvm::isa<clang::TranslationUnitDecl>(it->second))
9406           continue;
9407 
9408         searched.insert(it->second);
9409         symbol_file->ParseDeclsForContext(
9410             CreateDeclContext(it->second));
9411 
9412         for (clang::Decl *child : it->second->decls()) {
9413           if (clang::UsingDirectiveDecl *ud =
9414                   llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
9415             clang::DeclContext *ns = ud->getNominatedNamespace();
9416             if (ns == parent_decl_ctx)
9417               // Found it!
9418               return level;
9419             clang::DeclContext *from = ud->getCommonAncestor();
9420             if (searched.find(ns) == searched.end())
9421               search_queue.insert(std::make_pair(from, ns));
9422           } else if (child_name) {
9423             if (clang::UsingDecl *ud =
9424                     llvm::dyn_cast<clang::UsingDecl>(child)) {
9425               for (clang::UsingShadowDecl *usd : ud->shadows()) {
9426                 clang::Decl *target = usd->getTargetDecl();
9427                 clang::NamedDecl *nd = llvm::dyn_cast<clang::NamedDecl>(target);
9428                 if (!nd)
9429                   continue;
9430                 // Check names.
9431                 IdentifierInfo *ii = nd->getIdentifier();
9432                 if (ii == nullptr ||
9433                     ii->getName() != child_name->AsCString(nullptr))
9434                   continue;
9435                 // Check types, if one was provided.
9436                 if (child_type) {
9437                   CompilerType clang_type = GetTypeForDecl(nd);
9438                   if (!AreTypesSame(clang_type, *child_type,
9439                                     /*ignore_qualifiers=*/true))
9440                     continue;
9441                 }
9442                 // Found it!
9443                 return level;
9444               }
9445             }
9446           }
9447         }
9448       }
9449       ++level;
9450     }
9451   }
9452   return LLDB_INVALID_DECL_LEVEL;
9453 }
9454 
9455 ConstString TypeSystemClang::DeclContextGetName(void *opaque_decl_ctx) {
9456   if (opaque_decl_ctx) {
9457     clang::NamedDecl *named_decl =
9458         llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
9459     if (named_decl) {
9460       std::string name;
9461       llvm::raw_string_ostream stream{name};
9462       auto policy = GetTypePrintingPolicy();
9463       policy.AlwaysIncludeTypeForTemplateArgument = true;
9464       named_decl->getNameForDiagnostic(stream, policy, /*qualified=*/false);
9465       return ConstString(name);
9466     }
9467   }
9468   return ConstString();
9469 }
9470 
9471 ConstString
9472 TypeSystemClang::DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) {
9473   if (opaque_decl_ctx) {
9474     clang::NamedDecl *named_decl =
9475         llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
9476     if (named_decl)
9477       return ConstString(GetTypeNameForDecl(named_decl));
9478   }
9479   return ConstString();
9480 }
9481 
9482 bool TypeSystemClang::DeclContextIsClassMethod(void *opaque_decl_ctx) {
9483   if (!opaque_decl_ctx)
9484     return false;
9485 
9486   clang::DeclContext *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9487   if (llvm::isa<clang::ObjCMethodDecl>(decl_ctx)) {
9488     return true;
9489   } else if (llvm::isa<clang::CXXMethodDecl>(decl_ctx)) {
9490     return true;
9491   } else if (clang::FunctionDecl *fun_decl =
9492                  llvm::dyn_cast<clang::FunctionDecl>(decl_ctx)) {
9493     if (std::optional<ClangASTMetadata> metadata = GetMetadata(fun_decl))
9494       return metadata->HasObjectPtr();
9495   }
9496 
9497   return false;
9498 }
9499 
9500 std::vector<lldb_private::CompilerContext>
9501 TypeSystemClang::DeclContextGetCompilerContext(void *opaque_decl_ctx) {
9502   auto *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9503   std::vector<lldb_private::CompilerContext> context;
9504   InsertCompilerContext(this, decl_ctx, context);
9505   return context;
9506 }
9507 
9508 bool TypeSystemClang::DeclContextIsContainedInLookup(
9509     void *opaque_decl_ctx, void *other_opaque_decl_ctx) {
9510   auto *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9511   auto *other = (clang::DeclContext *)other_opaque_decl_ctx;
9512 
9513   // If we have an inline or anonymous namespace, then the lookup of the
9514   // parent context also includes those namespace contents.
9515   auto is_transparent_lookup_allowed = [](clang::DeclContext *DC) {
9516     if (DC->isInlineNamespace())
9517       return true;
9518 
9519     if (auto const *NS = dyn_cast<NamespaceDecl>(DC))
9520       return NS->isAnonymousNamespace();
9521 
9522     return false;
9523   };
9524 
9525   do {
9526     // A decl context always includes its own contents in its lookup.
9527     if (decl_ctx == other)
9528       return true;
9529   } while (is_transparent_lookup_allowed(other) &&
9530            (other = other->getParent()));
9531 
9532   return false;
9533 }
9534 
9535 lldb::LanguageType
9536 TypeSystemClang::DeclContextGetLanguage(void *opaque_decl_ctx) {
9537   if (!opaque_decl_ctx)
9538     return eLanguageTypeUnknown;
9539 
9540   auto *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9541   if (llvm::isa<clang::ObjCMethodDecl>(decl_ctx)) {
9542     return eLanguageTypeObjC;
9543   } else if (llvm::isa<clang::CXXMethodDecl>(decl_ctx)) {
9544     return eLanguageTypeC_plus_plus;
9545   } else if (auto *fun_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_ctx)) {
9546     if (std::optional<ClangASTMetadata> metadata = GetMetadata(fun_decl))
9547       return metadata->GetObjectPtrLanguage();
9548   }
9549 
9550   return eLanguageTypeUnknown;
9551 }
9552 
9553 static bool IsClangDeclContext(const CompilerDeclContext &dc) {
9554   return dc.IsValid() && isa<TypeSystemClang>(dc.GetTypeSystem());
9555 }
9556 
9557 clang::DeclContext *
9558 TypeSystemClang::DeclContextGetAsDeclContext(const CompilerDeclContext &dc) {
9559   if (IsClangDeclContext(dc))
9560     return (clang::DeclContext *)dc.GetOpaqueDeclContext();
9561   return nullptr;
9562 }
9563 
9564 ObjCMethodDecl *
9565 TypeSystemClang::DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc) {
9566   if (IsClangDeclContext(dc))
9567     return llvm::dyn_cast<clang::ObjCMethodDecl>(
9568         (clang::DeclContext *)dc.GetOpaqueDeclContext());
9569   return nullptr;
9570 }
9571 
9572 CXXMethodDecl *
9573 TypeSystemClang::DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc) {
9574   if (IsClangDeclContext(dc))
9575     return llvm::dyn_cast<clang::CXXMethodDecl>(
9576         (clang::DeclContext *)dc.GetOpaqueDeclContext());
9577   return nullptr;
9578 }
9579 
9580 clang::FunctionDecl *
9581 TypeSystemClang::DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc) {
9582   if (IsClangDeclContext(dc))
9583     return llvm::dyn_cast<clang::FunctionDecl>(
9584         (clang::DeclContext *)dc.GetOpaqueDeclContext());
9585   return nullptr;
9586 }
9587 
9588 clang::NamespaceDecl *
9589 TypeSystemClang::DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc) {
9590   if (IsClangDeclContext(dc))
9591     return llvm::dyn_cast<clang::NamespaceDecl>(
9592         (clang::DeclContext *)dc.GetOpaqueDeclContext());
9593   return nullptr;
9594 }
9595 
9596 std::optional<ClangASTMetadata>
9597 TypeSystemClang::DeclContextGetMetaData(const CompilerDeclContext &dc,
9598                                         const Decl *object) {
9599   TypeSystemClang *ast = llvm::cast<TypeSystemClang>(dc.GetTypeSystem());
9600   return ast->GetMetadata(object);
9601 }
9602 
9603 clang::ASTContext *
9604 TypeSystemClang::DeclContextGetTypeSystemClang(const CompilerDeclContext &dc) {
9605   TypeSystemClang *ast =
9606       llvm::dyn_cast_or_null<TypeSystemClang>(dc.GetTypeSystem());
9607   if (ast)
9608     return &ast->getASTContext();
9609   return nullptr;
9610 }
9611 
9612 void TypeSystemClang::RequireCompleteType(CompilerType type) {
9613   // Technically, enums can be incomplete too, but we don't handle those as they
9614   // are emitted even under -flimit-debug-info.
9615   if (!TypeSystemClang::IsCXXClassType(type))
9616     return;
9617 
9618   if (type.GetCompleteType())
9619     return;
9620 
9621   // No complete definition in this module.  Mark the class as complete to
9622   // satisfy local ast invariants, but make a note of the fact that
9623   // it is not _really_ complete so we can later search for a definition in a
9624   // different module.
9625   // Since we provide layout assistance, layouts of types containing this class
9626   // will be correct even if we  are not able to find the definition elsewhere.
9627   bool started = TypeSystemClang::StartTagDeclarationDefinition(type);
9628   lldbassert(started && "Unable to start a class type definition.");
9629   TypeSystemClang::CompleteTagDeclarationDefinition(type);
9630   const clang::TagDecl *td = ClangUtil::GetAsTagDecl(type);
9631   auto ts = type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();
9632   if (ts)
9633     ts->SetDeclIsForcefullyCompleted(td);
9634 }
9635 
9636 namespace {
9637 /// A specialized scratch AST used within ScratchTypeSystemClang.
9638 /// These are the ASTs backing the different IsolatedASTKinds. They behave
9639 /// like a normal ScratchTypeSystemClang but they don't own their own
9640 /// persistent  storage or target reference.
9641 class SpecializedScratchAST : public TypeSystemClang {
9642 public:
9643   /// \param name The display name of the TypeSystemClang instance.
9644   /// \param triple The triple used for the TypeSystemClang instance.
9645   /// \param ast_source The ClangASTSource that should be used to complete
9646   ///                   type information.
9647   SpecializedScratchAST(llvm::StringRef name, llvm::Triple triple,
9648                         std::unique_ptr<ClangASTSource> ast_source)
9649       : TypeSystemClang(name, triple),
9650         m_scratch_ast_source_up(std::move(ast_source)) {
9651     // Setup the ClangASTSource to complete this AST.
9652     m_scratch_ast_source_up->InstallASTContext(*this);
9653     llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
9654         m_scratch_ast_source_up->CreateProxy());
9655     SetExternalSource(proxy_ast_source);
9656   }
9657 
9658   /// The ExternalASTSource that performs lookups and completes types.
9659   std::unique_ptr<ClangASTSource> m_scratch_ast_source_up;
9660 };
9661 } // namespace
9662 
9663 char ScratchTypeSystemClang::ID;
9664 const std::nullopt_t ScratchTypeSystemClang::DefaultAST = std::nullopt;
9665 
9666 ScratchTypeSystemClang::ScratchTypeSystemClang(Target &target,
9667                                                llvm::Triple triple)
9668     : TypeSystemClang("scratch ASTContext", triple), m_triple(triple),
9669       m_target_wp(target.shared_from_this()),
9670       m_persistent_variables(
9671           new ClangPersistentVariables(target.shared_from_this())) {
9672   m_scratch_ast_source_up = CreateASTSource();
9673   m_scratch_ast_source_up->InstallASTContext(*this);
9674   llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
9675       m_scratch_ast_source_up->CreateProxy());
9676   SetExternalSource(proxy_ast_source);
9677 }
9678 
9679 void ScratchTypeSystemClang::Finalize() {
9680   TypeSystemClang::Finalize();
9681   m_scratch_ast_source_up.reset();
9682 }
9683 
9684 TypeSystemClangSP
9685 ScratchTypeSystemClang::GetForTarget(Target &target,
9686                                      std::optional<IsolatedASTKind> ast_kind,
9687                                      bool create_on_demand) {
9688   auto type_system_or_err = target.GetScratchTypeSystemForLanguage(
9689       lldb::eLanguageTypeC, create_on_demand);
9690   if (auto err = type_system_or_err.takeError()) {
9691     LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
9692                    "Couldn't get scratch TypeSystemClang: {0}");
9693     return nullptr;
9694   }
9695   auto ts_sp = *type_system_or_err;
9696   ScratchTypeSystemClang *scratch_ast =
9697       llvm::dyn_cast_or_null<ScratchTypeSystemClang>(ts_sp.get());
9698   if (!scratch_ast)
9699     return nullptr;
9700   // If no dedicated sub-AST was requested, just return the main AST.
9701   if (ast_kind == DefaultAST)
9702     return std::static_pointer_cast<TypeSystemClang>(ts_sp);
9703   // Search the sub-ASTs.
9704   return std::static_pointer_cast<TypeSystemClang>(
9705       scratch_ast->GetIsolatedAST(*ast_kind).shared_from_this());
9706 }
9707 
9708 /// Returns a human-readable name that uniquely identifiers the sub-AST kind.
9709 static llvm::StringRef
9710 GetNameForIsolatedASTKind(ScratchTypeSystemClang::IsolatedASTKind kind) {
9711   switch (kind) {
9712   case ScratchTypeSystemClang::IsolatedASTKind::CppModules:
9713     return "C++ modules";
9714   }
9715   llvm_unreachable("Unimplemented IsolatedASTKind?");
9716 }
9717 
9718 void ScratchTypeSystemClang::Dump(llvm::raw_ostream &output) {
9719   // First dump the main scratch AST.
9720   output << "State of scratch Clang type system:\n";
9721   TypeSystemClang::Dump(output);
9722 
9723   // Now sort the isolated sub-ASTs.
9724   typedef std::pair<IsolatedASTKey, TypeSystem *> KeyAndTS;
9725   std::vector<KeyAndTS> sorted_typesystems;
9726   for (const auto &a : m_isolated_asts)
9727     sorted_typesystems.emplace_back(a.first, a.second.get());
9728   llvm::stable_sort(sorted_typesystems, llvm::less_first());
9729 
9730   // Dump each sub-AST too.
9731   for (const auto &a : sorted_typesystems) {
9732     IsolatedASTKind kind =
9733         static_cast<ScratchTypeSystemClang::IsolatedASTKind>(a.first);
9734     output << "State of scratch Clang type subsystem "
9735            << GetNameForIsolatedASTKind(kind) << ":\n";
9736     a.second->Dump(output);
9737   }
9738 }
9739 
9740 UserExpression *ScratchTypeSystemClang::GetUserExpression(
9741     llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language,
9742     Expression::ResultType desired_type,
9743     const EvaluateExpressionOptions &options, ValueObject *ctx_obj) {
9744   TargetSP target_sp = m_target_wp.lock();
9745   if (!target_sp)
9746     return nullptr;
9747 
9748   return new ClangUserExpression(*target_sp.get(), expr, prefix, language,
9749                                  desired_type, options, ctx_obj);
9750 }
9751 
9752 FunctionCaller *ScratchTypeSystemClang::GetFunctionCaller(
9753     const CompilerType &return_type, const Address &function_address,
9754     const ValueList &arg_value_list, const char *name) {
9755   TargetSP target_sp = m_target_wp.lock();
9756   if (!target_sp)
9757     return nullptr;
9758 
9759   Process *process = target_sp->GetProcessSP().get();
9760   if (!process)
9761     return nullptr;
9762 
9763   return new ClangFunctionCaller(*process, return_type, function_address,
9764                                  arg_value_list, name);
9765 }
9766 
9767 std::unique_ptr<UtilityFunction>
9768 ScratchTypeSystemClang::CreateUtilityFunction(std::string text,
9769                                               std::string name) {
9770   TargetSP target_sp = m_target_wp.lock();
9771   if (!target_sp)
9772     return {};
9773 
9774   return std::make_unique<ClangUtilityFunction>(
9775       *target_sp.get(), std::move(text), std::move(name),
9776       target_sp->GetDebugUtilityExpression());
9777 }
9778 
9779 PersistentExpressionState *
9780 ScratchTypeSystemClang::GetPersistentExpressionState() {
9781   return m_persistent_variables.get();
9782 }
9783 
9784 void ScratchTypeSystemClang::ForgetSource(ASTContext *src_ctx,
9785                                           ClangASTImporter &importer) {
9786   // Remove it as a source from the main AST.
9787   importer.ForgetSource(&getASTContext(), src_ctx);
9788   // Remove it as a source from all created sub-ASTs.
9789   for (const auto &a : m_isolated_asts)
9790     importer.ForgetSource(&a.second->getASTContext(), src_ctx);
9791 }
9792 
9793 std::unique_ptr<ClangASTSource> ScratchTypeSystemClang::CreateASTSource() {
9794   return std::make_unique<ClangASTSource>(
9795       m_target_wp.lock()->shared_from_this(),
9796       m_persistent_variables->GetClangASTImporter());
9797 }
9798 
9799 static llvm::StringRef
9800 GetSpecializedASTName(ScratchTypeSystemClang::IsolatedASTKind feature) {
9801   switch (feature) {
9802   case ScratchTypeSystemClang::IsolatedASTKind::CppModules:
9803     return "scratch ASTContext for C++ module types";
9804   }
9805   llvm_unreachable("Unimplemented ASTFeature kind?");
9806 }
9807 
9808 TypeSystemClang &ScratchTypeSystemClang::GetIsolatedAST(
9809     ScratchTypeSystemClang::IsolatedASTKind feature) {
9810   auto found_ast = m_isolated_asts.find(feature);
9811   if (found_ast != m_isolated_asts.end())
9812     return *found_ast->second;
9813 
9814   // Couldn't find the requested sub-AST, so create it now.
9815   std::shared_ptr<TypeSystemClang> new_ast_sp =
9816       std::make_shared<SpecializedScratchAST>(GetSpecializedASTName(feature),
9817                                               m_triple, CreateASTSource());
9818   m_isolated_asts.insert({feature, new_ast_sp});
9819   return *new_ast_sp;
9820 }
9821 
9822 bool TypeSystemClang::IsForcefullyCompleted(lldb::opaque_compiler_type_t type) {
9823   if (type) {
9824     clang::QualType qual_type(GetQualType(type));
9825     const clang::RecordType *record_type =
9826         llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr());
9827     if (record_type) {
9828       const clang::RecordDecl *record_decl = record_type->getDecl();
9829       assert(record_decl);
9830       if (std::optional<ClangASTMetadata> metadata = GetMetadata(record_decl))
9831         return metadata->IsForcefullyCompleted();
9832     }
9833   }
9834   return false;
9835 }
9836 
9837 bool TypeSystemClang::SetDeclIsForcefullyCompleted(const clang::TagDecl *td) {
9838   if (td == nullptr)
9839     return false;
9840   std::optional<ClangASTMetadata> metadata = GetMetadata(td);
9841   if (!metadata)
9842     return false;
9843   m_has_forcefully_completed_types = true;
9844   metadata->SetIsForcefullyCompleted();
9845   SetMetadata(td, *metadata);
9846 
9847   return true;
9848 }
9849 
9850 void TypeSystemClang::LogCreation() const {
9851   if (auto *log = GetLog(LLDBLog::Expressions))
9852     LLDB_LOG(log, "Created new TypeSystem for (ASTContext*){0:x} '{1}'",
9853              &getASTContext(), getDisplayName());
9854 }
9855