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