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