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