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