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