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