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