LLDB mainline
TypeSystemClang.cpp
Go to the documentation of this file.
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
58#include "lldb/Core/Module.h"
66#include "lldb/Target/Process.h"
67#include "lldb/Target/Target.h"
70#include "lldb/Utility/Flags.h"
74#include "lldb/Utility/Scalar.h"
76
81
82#include <cstdio>
83
84#include <mutex>
85#include <optional>
86
87using namespace lldb;
88using namespace lldb_private;
89using namespace lldb_private::dwarf;
90using namespace lldb_private::plugin::dwarf;
91using namespace clang;
92using llvm::StringSwitch;
93
95
96namespace {
97static 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
106static inline bool
107TypeSystemClangSupportsLanguage(lldb::LanguageType language) {
108 return language == eLanguageTypeUnknown || // Clang is the default type system
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).
124bool 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.
152void 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
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)
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)
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
235
236 auto vbtable_ptr_addr = valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
237 if (vbtable_ptr_addr == 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)
254
255 return data.GetAddress(&vbtable_ptr_offset);
256}
257
258static 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
291static 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) {
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
319
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
330 bool is_complete_objc_class)
331 : m_payload(owning_module.GetValue()) {
332 SetIsCompleteObjCClass(is_complete_objc_class);
333}
334
336 assert(id.GetValue() < ObjCClassBit);
337 bool is_complete = IsCompleteObjCClass();
338 m_payload = id.GetValue();
339 SetIsCompleteObjCClass(is_complete);
340}
341
342static 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
364
365bool 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
446clang::AccessSpecifier
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
463static 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
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.
504
505 LogCreation();
506}
507
508TypeSystemClang::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
521
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
561 LanguageSet languages;
563 languages.Insert(lldb::eLanguageTypeC);
575 return languages;
576}
577
579 LanguageSet languages;
587 return languages;
588}
589
592 GetPluginNameStatic(), "clang base AST context plug-in", CreateInstance,
594}
595
598}
599
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();
612 m_source_manager_up.reset();
613 m_language_options_up.reset();
614}
615
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
623 return m_target_triple.c_str();
624}
625
626void TypeSystemClang::SetTargetTriple(llvm::StringRef target_triple) {
627 m_target_triple = target_triple.str();
628}
629
631 llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) {
632 ASTContext &ast = getASTContext();
633 ast.getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
634 ast.setExternalSource(ast_source_up);
635}
636
638 assert(m_ast_up);
639 return *m_ast_up;
640}
641
642class NullDiagnosticConsumer : public DiagnosticConsumer {
643public:
644 NullDiagnosticConsumer() { m_log = GetLog(LLDBLog::Expressions); }
645
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
656 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
657 return new NullDiagnosticConsumer();
658 }
659
660private:
662};
663
665 assert(!m_ast_up);
666 m_ast_owned = true;
667
668 m_language_options_up = std::make_unique<LangOptions>();
670
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());
683 std::make_unique<DiagnosticsEngine>(diag_id_sp, new DiagnosticOptions());
684
685 m_source_manager_up = std::make_unique<clang::SourceManager>(
687 m_ast_up = std::make_unique<ASTContext>(
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(
705 SetExternalSource(ast_source_up);
706}
707
709 TypeSystemClang *clang_ast = GetASTMap().Lookup(ast);
710 return clang_ast;
711}
712
713clang::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
719std::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)
724 }
725 return m_target_options_rp;
726}
727
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
738static 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
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
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
867 if (m_pointer_byte_size == 0)
868 if (auto size = GetBasicType(lldb::eBasicTypeVoid)
870 .GetByteSize(nullptr))
871 m_pointer_byte_size = *size;
872 return m_pointer_byte_size;
873}
874
876 clang::ASTContext &ast = getASTContext();
877
879 GetOpaqueCompilerType(&ast, basic_type);
880
881 if (clang_type)
882 return CompilerType(weak_from_this(), clang_type);
883 return CompilerType();
884}
885
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
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
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
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
1145 // Check that the DeclContext actually belongs to this ASTContext.
1146 assert(&ctx->getParentASTContext() == &getASTContext());
1147 return CompilerDeclContext(this, ctx);
1148}
1149
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
1162 return GetType(getASTContext().getTagDeclType(decl));
1163}
1164
1165CompilerType TypeSystemClang::GetTypeForDecl(ObjCInterfaceDecl *decl) {
1166 return GetType(getASTContext().getObjCInterfaceType(decl));
1167}
1168
1169CompilerType TypeSystemClang::GetTypeForDecl(clang::ValueDecl *value_decl) {
1170 return GetType(value_decl->getType());
1171}
1172
1173#pragma mark Structure, Unions, Classes
1174
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
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>(
1202 m_module_map_up = std::make_unique<clang::ModuleMap>(
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
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
1292namespace {
1293/// Returns true iff the given TemplateArgument should be represented as an
1294/// NonTypeTemplateParmDecl in the AST.
1295bool IsValueParam(const clang::TemplateArgument &argument) {
1296 return argument.getKind() == TemplateArgument::Integral;
1297}
1298
1299void 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
1323static 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
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
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
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`.
1451static 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.
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).
1489 ClassTemplateDecl *class_template_decl,
1490 const TypeSystemClang::TemplateParameterInfos &instantiation_values) {
1491
1492 TemplateParameterList &params = *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() &&
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
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(
1609
1610 decl_ctx->addDecl(class_template_decl);
1611
1612 VerifyDecl(class_template_decl);
1613
1614 return class_template_decl;
1615}
1616
1617TemplateTemplateParmDecl *
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
1641ClassTemplateSpecializationDecl *
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
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
1686static 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
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
1730clang::AccessSpecifier
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
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
1763bool 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
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
1822bool TypeSystemClang::BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) {
1823 return !TypeSystemClang::RecordHasFields(b->getType()->getAsCXXRecordDecl());
1824}
1825
1826uint32_t
1827TypeSystemClang::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
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
1912clang::BlockDecl *
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
1926clang::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
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
1961clang::UsingDecl *
1962TypeSystemClang::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
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
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();
2008 return ast->SignedCharTy.getAsOpaquePtr();
2010 return ast->UnsignedCharTy.getAsOpaquePtr();
2011 case eBasicTypeWChar:
2012 return ast->getWCharType().getAsOpaquePtr();
2014 return ast->getSignedWCharType().getAsOpaquePtr();
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();
2026 return ast->UnsignedShortTy.getAsOpaquePtr();
2027 case eBasicTypeInt:
2028 return ast->IntTy.getAsOpaquePtr();
2030 return ast->UnsignedIntTy.getAsOpaquePtr();
2031 case eBasicTypeLong:
2032 return ast->LongTy.getAsOpaquePtr();
2034 return ast->UnsignedLongTy.getAsOpaquePtr();
2035 case eBasicTypeLongLong:
2036 return ast->LongLongTy.getAsOpaquePtr();
2038 return ast->UnsignedLongLongTy.getAsOpaquePtr();
2039 case eBasicTypeInt128:
2040 return ast->Int128Ty.getAsOpaquePtr();
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();
2052 return ast->LongDoubleTy.getAsOpaquePtr();
2054 return ast->getComplexType(ast->FloatTy).getAsOpaquePtr();
2056 return ast->getComplexType(ast->DoubleTy).getAsOpaquePtr();
2058 return ast->getComplexType(ast->LongDoubleTy).getAsOpaquePtr();
2059 case eBasicTypeObjCID:
2060 return ast->getObjCIdType().getAsOpaquePtr();
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
2074clang::DeclarationName
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();
2095 is_method, op_kind, num_params))
2096 return clang::DeclarationName();
2097
2098 return getASTContext().DeclarationNames.getCXXOperatorName(op_kind);
2099}
2100
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
2123std::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
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
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
2203 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2204 const char *name, const CompilerType &param_type, int storage,
2205 bool add_decl) {
2206 ASTContext &ast = getASTContext();
2207 auto *decl = ParmVarDecl::CreateDeserialized(ast, GlobalDeclID());
2208 decl->setDeclContext(decl_ctx);
2209 if (name && name[0])
2210 decl->setDeclName(&ast.Idents.get(name));
2211 decl->setType(ClangUtil::GetQualType(param_type));
2212 decl->setStorageClass(static_cast<clang::StorageClass>(storage));
2213 SetOwningModule(decl, owning_module);
2214 if (add_decl)
2215 decl_ctx->addDecl(decl);
2216
2217 return decl;
2218}
2219
2221 FunctionDecl *function_decl, llvm::ArrayRef<ParmVarDecl *> params) {
2222 if (function_decl)
2223 function_decl->setParams(params);
2224}
2225
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
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
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);
2279 for (const auto &field : type_fields)
2280 AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic,
2281 0);
2282 if (packed)
2283 SetIsPacked(type);
2285 return type;
2286}
2287
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
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
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
2376 return GetIntTypeFromBitSize(
2377 getASTContext().getTypeSize(getASTContext().VoidPtrTy), is_signed);
2378}
2379
2380void 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
2394void 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
2416bool 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
2452void 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
2459void 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
2466void TypeSystemClang::SetMetadata(const clang::Decl *object,
2467 ClangASTMetadata &metadata) {
2468 m_decl_metadata[object] = metadata;
2469}
2470
2471void TypeSystemClang::SetMetadata(const clang::Type *object,
2472 ClangASTMetadata &metadata) {
2473 m_type_metadata[object] = metadata;
2474}
2475
2477 auto It = m_decl_metadata.find(object);
2478 if (It != m_decl_metadata.end())
2479 return &It->second;
2480 return nullptr;
2481}
2482
2484 auto It = m_type_metadata.find(object);
2485 if (It != m_type_metadata.end())
2486 return &It->second;
2487 return nullptr;
2488}
2489
2490void 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
2498clang::AccessSpecifier
2499TypeSystemClang::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
2506clang::DeclContext *
2509}
2510
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.
2522static QualType
2523RemoveWrappingTypes(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
2551clang::DeclContext *
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.
2581static 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.
2627static 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.
2663static const clang::ObjCObjectType *
2664GetCompleteObjCObjectType(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
2699static 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
2750static clang::ObjCIvarDecl::AccessControl
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
2771 return !type || llvm::isa<clang::Type>(GetQualType(type).getTypePtr());
2772}
2773#endif
2774
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
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
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
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
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
2943 return GetQualType(type).getUnqualifiedType()->isCharType();
2944}
2945
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;
2954 allow_completion);
2955}
2956
2958 return GetQualType(type).isConstQualified();
2959}
2960
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
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
2995unsigned
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
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
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"
3024uint32_t
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
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
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
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
3162 auto isMemberFunctionPointerType = [](clang::QualType qual_type) {
3163 return qual_type->isMemberFunctionPointerType();
3164 };
3165
3166 return IsTypeImpl(type, isMemberFunctionPointerType);
3167}
3168
3170 auto isFunctionPointerType = [](clang::QualType qual_type) {
3171 return qual_type->isFunctionPointerType();
3172 };
3173
3174 return IsTypeImpl(type, isFunctionPointerType);
3175}
3176
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
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
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
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
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
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
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
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
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
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
3482 if (ClangUtil::IsClangType(type))
3483 return ClangUtil::GetCanonicalQualType(type)->isObjCObjectOrInterfaceType();
3484 return false;
3485}
3486
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
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
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
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
3667 if (!type)
3668 return false;
3669
3670 return (GetTypeInfo(type, nullptr) & eTypeIsScalar) != 0;
3671}
3672
3674 if (!type)
3675 return false;
3676 return RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef})
3677 ->getTypeClass() == clang::Type::Typedef;
3678}
3679
3681 if (!type)
3682 return false;
3683 return GetCanonicalQualType(type)->isVoidType();
3684}
3685
3687 if (auto *record_decl =
3689 return record_decl->canPassInRegisters();
3690 }
3691 return false;
3692}
3693
3695 return TypeSystemClangSupportsLanguage(language);
3696}
3697
3698std::optional<std::string>
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
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
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
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
3763 if (!type)
3764 return false;
3765 const bool allow_completion = true;
3767 allow_completion);
3768}
3769
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
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
3816uint32_t
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
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())
4029 if (qual_type->getPointeeCXXRecordDecl())
4031
4032 clang::QualType pointee_type(qual_type->getPointeeType());
4033 if (pointee_type->getPointeeCXXRecordDecl())
4035 if (pointee_type->isObjCObjectOrInterfaceType())
4037 if (pointee_type->isObjCClassType())
4039 if (pointee_type.getTypePtr() ==
4040 getASTContext().ObjCBuiltinIdTy.getTypePtr())
4042 } else {
4043 if (qual_type->isObjCObjectOrInterfaceType())
4045 if (qual_type->getAsCXXRecordDecl())
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:
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())
4098 }
4099 }
4100 return lldb::eLanguageTypeC;
4101}
4102
4103lldb::TypeClass
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
4242 if (type)
4243 return GetQualType(type).getQualifiers().getCVRQualifiers();
4244 return 0;
4245}
4246
4247// Creating related types
4248
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
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
4285 if (type)
4286 return GetType(GetCanonicalQualType(type));
4287 return CompilerType();
4288}
4289
4290static 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
4311 if (type)
4312 return GetType(
4314 return CompilerType();
4315}
4316
4319 if (type)
4321 return CompilerType();
4322}
4323
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
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
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
4361size_t
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 &&
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
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())
4451 else if (llvm::isa<clang::CXXConstructorDecl>(cxx_method_decl))
4453 else if (llvm::isa<clang::CXXDestructorDecl>(cxx_method_decl))
4455 else
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 &&
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())
4488 else
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())
4518 else
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
4540 if (type)
4541 return GetType(GetQualType(type).getNonReferenceType());
4542 return CompilerType();
4543}
4544
4547 if (type) {
4548 clang::QualType qual_type(GetQualType(type));
4549 return GetType(qual_type.getTypePtr()->getPointeeType());
4550 }
4551 return CompilerType();
4552}
4553
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
4573 if (type)
4574 return GetType(getASTContext().getLValueReferenceType(GetQualType(type)));
4575 else
4576 return CompilerType();
4577}
4578
4581 if (type)
4582 return GetType(getASTContext().getRValueReferenceType(GetQualType(type)));
4583 else
4584 return CompilerType();
4585}
4586
4588 if (!type)
4589 return CompilerType();
4590 return GetType(getASTContext().getAtomicType(GetQualType(type)));
4591}
4592
4595 if (type) {
4596 clang::QualType result(GetQualType(type));
4597 result.addConst();
4598 return GetType(result);
4599 }
4600 return CompilerType();
4601}
4602
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
4618 if (type) {
4619 clang::QualType result(GetQualType(type));
4620 result.addVolatile();
4621 return GetType(result);
4622 }
4623 return CompilerType();
4624}
4625
4628 if (type) {
4629 clang::QualType result(GetQualType(type));
4630 result.addRestrict();
4631 return GetType(result);
4632 }
4633 return CompilerType();
4634}
4635
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 =
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
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
4692 return TypeSystemClang::GetBasicType(basic_type);
4693}
4694
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
4711const llvm::fltSemantics &
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
4728std::optional<uint64_t>
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
4792std::optional<size_t>
4794 ExecutionContextScope *exe_scope) {
4795 if (GetCompleteType(type))
4796 return getASTContext().getTypeAlign(GetQualType(type));
4797 return {};
4798}
4799
4801 uint64_t &count) {
4802 if (!type)
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
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:
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: {
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()
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;
5143}
5144
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
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:
5208 case clang::BuiltinType::Char32:
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
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
5306static 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
5320static std::optional<SymbolFile::ArrayInfo>
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
5331llvm::Expected<uint32_t>
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
5494}
5495
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:
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:
5519 case clang::BuiltinType::SChar:
5520 return eBasicTypeSignedChar;
5521 case clang::BuiltinType::WChar_S:
5522 return eBasicTypeSignedWChar;
5523 case clang::BuiltinType::WChar_U:
5525 case clang::BuiltinType::Short:
5526 return eBasicTypeShort;
5527 case clang::BuiltinType::UShort:
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:
5537 case clang::BuiltinType::LongLong:
5538 return eBasicTypeLongLong;
5539 case clang::BuiltinType::ULongLong:
5541 case clang::BuiltinType::Int128:
5542 return eBasicTypeInt128;
5543 case clang::BuiltinType::UInt128:
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
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
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 &&
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
5658GetObjCFieldAtIndex(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
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 &&
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: