| //===-- TypeSystemClang.cpp -----------------------------------------------===// |
| // |
| // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| // See https://llvm.org/LICENSE.txt for license information. |
| // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| // |
| //===----------------------------------------------------------------------===// |
| |
| #include "TypeSystemClang.h" |
| |
| #include "clang/AST/DeclBase.h" |
| #include "clang/AST/ExprCXX.h" |
| #include "llvm/Support/Casting.h" |
| #include "llvm/Support/FormatAdapters.h" |
| #include "llvm/Support/FormatVariadic.h" |
| |
| #include <mutex> |
| #include <memory> |
| #include <string> |
| #include <vector> |
| |
| #include "clang/AST/ASTContext.h" |
| #include "clang/AST/ASTImporter.h" |
| #include "clang/AST/Attr.h" |
| #include "clang/AST/CXXInheritance.h" |
| #include "clang/AST/DeclObjC.h" |
| #include "clang/AST/DeclTemplate.h" |
| #include "clang/AST/Mangle.h" |
| #include "clang/AST/RecordLayout.h" |
| #include "clang/AST/Type.h" |
| #include "clang/AST/VTableBuilder.h" |
| #include "clang/Basic/Builtins.h" |
| #include "clang/Basic/Diagnostic.h" |
| #include "clang/Basic/FileManager.h" |
| #include "clang/Basic/FileSystemOptions.h" |
| #include "clang/Basic/LangStandard.h" |
| #include "clang/Basic/SourceManager.h" |
| #include "clang/Basic/TargetInfo.h" |
| #include "clang/Basic/TargetOptions.h" |
| #include "clang/Frontend/FrontendOptions.h" |
| #include "clang/Lex/HeaderSearch.h" |
| #include "clang/Lex/HeaderSearchOptions.h" |
| #include "clang/Lex/ModuleMap.h" |
| #include "clang/Sema/Sema.h" |
| |
| #include "llvm/Support/Signals.h" |
| #include "llvm/Support/Threading.h" |
| |
| #include "Plugins/ExpressionParser/Clang/ClangASTImporter.h" |
| #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h" |
| #include "Plugins/ExpressionParser/Clang/ClangExternalASTSourceCallbacks.h" |
| #include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h" |
| #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h" |
| #include "Plugins/ExpressionParser/Clang/ClangUserExpression.h" |
| #include "Plugins/ExpressionParser/Clang/ClangUtil.h" |
| #include "Plugins/ExpressionParser/Clang/ClangUtilityFunction.h" |
| #include "lldb/Core/Debugger.h" |
| #include "lldb/Core/DumpDataExtractor.h" |
| #include "lldb/Core/Module.h" |
| #include "lldb/Core/PluginManager.h" |
| #include "lldb/Core/UniqueCStringMap.h" |
| #include "lldb/Host/StreamFile.h" |
| #include "lldb/Symbol/ObjectFile.h" |
| #include "lldb/Symbol/SymbolFile.h" |
| #include "lldb/Target/ExecutionContext.h" |
| #include "lldb/Target/Language.h" |
| #include "lldb/Target/Process.h" |
| #include "lldb/Target/Target.h" |
| #include "lldb/Utility/ArchSpec.h" |
| #include "lldb/Utility/DataExtractor.h" |
| #include "lldb/Utility/Flags.h" |
| #include "lldb/Utility/LLDBAssert.h" |
| #include "lldb/Utility/LLDBLog.h" |
| #include "lldb/Utility/RegularExpression.h" |
| #include "lldb/Utility/Scalar.h" |
| #include "lldb/Utility/ThreadSafeDenseMap.h" |
| |
| #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" |
| #include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h" |
| #include "Plugins/SymbolFile/PDB/PDBASTParser.h" |
| #include "Plugins/SymbolFile/NativePDB/PdbAstBuilder.h" |
| |
| #include <cstdio> |
| |
| #include <mutex> |
| #include <optional> |
| |
| using namespace lldb; |
| using namespace lldb_private; |
| using namespace lldb_private::dwarf; |
| using namespace lldb_private::plugin::dwarf; |
| using namespace clang; |
| using llvm::StringSwitch; |
| |
| LLDB_PLUGIN_DEFINE(TypeSystemClang) |
| |
| namespace { |
| static void VerifyDecl(clang::Decl *decl) { |
| assert(decl && "VerifyDecl called with nullptr?"); |
| #ifndef NDEBUG |
| // We don't care about the actual access value here but only want to trigger |
| // that Clang calls its internal Decl::AccessDeclContextCheck validation. |
| decl->getAccess(); |
| #endif |
| } |
| |
| static inline bool |
| TypeSystemClangSupportsLanguage(lldb::LanguageType language) { |
| return language == eLanguageTypeUnknown || // Clang is the default type system |
| lldb_private::Language::LanguageIsC(language) || |
| lldb_private::Language::LanguageIsCPlusPlus(language) || |
| lldb_private::Language::LanguageIsObjC(language) || |
| lldb_private::Language::LanguageIsPascal(language) || |
| // Use Clang for Rust until there is a proper language plugin for it |
| language == eLanguageTypeRust || |
| // Use Clang for D until there is a proper language plugin for it |
| language == eLanguageTypeD || |
| // Open Dylan compiler debug info is designed to be Clang-compatible |
| language == eLanguageTypeDylan; |
| } |
| |
| // Checks whether m1 is an overload of m2 (as opposed to an override). This is |
| // called by addOverridesForMethod to distinguish overrides (which share a |
| // vtable entry) from overloads (which require distinct entries). |
| bool isOverload(clang::CXXMethodDecl *m1, clang::CXXMethodDecl *m2) { |
| // FIXME: This should detect covariant return types, but currently doesn't. |
| lldbassert(&m1->getASTContext() == &m2->getASTContext() && |
| "Methods should have the same AST context"); |
| clang::ASTContext &context = m1->getASTContext(); |
| |
| const auto *m1Type = llvm::cast<clang::FunctionProtoType>( |
| context.getCanonicalType(m1->getType())); |
| |
| const auto *m2Type = llvm::cast<clang::FunctionProtoType>( |
| context.getCanonicalType(m2->getType())); |
| |
| auto compareArgTypes = [&context](const clang::QualType &m1p, |
| const clang::QualType &m2p) { |
| return context.hasSameType(m1p.getUnqualifiedType(), |
| m2p.getUnqualifiedType()); |
| }; |
| |
| // FIXME: In C++14 and later, we can just pass m2Type->param_type_end() |
| // as a fourth parameter to std::equal(). |
| return (m1->getNumParams() != m2->getNumParams()) || |
| !std::equal(m1Type->param_type_begin(), m1Type->param_type_end(), |
| m2Type->param_type_begin(), compareArgTypes); |
| } |
| |
| // If decl is a virtual method, walk the base classes looking for methods that |
| // decl overrides. This table of overridden methods is used by IRGen to |
| // determine the vtable layout for decl's parent class. |
| void addOverridesForMethod(clang::CXXMethodDecl *decl) { |
| if (!decl->isVirtual()) |
| return; |
| |
| clang::CXXBasePaths paths; |
| llvm::SmallVector<clang::NamedDecl *, 4> decls; |
| |
| auto find_overridden_methods = |
| [&decls, decl](const clang::CXXBaseSpecifier *specifier, |
| clang::CXXBasePath &path) { |
| if (auto *base_record = llvm::dyn_cast<clang::CXXRecordDecl>( |
| specifier->getType()->castAs<clang::RecordType>()->getDecl())) { |
| |
| clang::DeclarationName name = decl->getDeclName(); |
| |
| // If this is a destructor, check whether the base class destructor is |
| // virtual. |
| if (name.getNameKind() == clang::DeclarationName::CXXDestructorName) |
| if (auto *baseDtorDecl = base_record->getDestructor()) { |
| if (baseDtorDecl->isVirtual()) { |
| decls.push_back(baseDtorDecl); |
| return true; |
| } else |
| return false; |
| } |
| |
| // Otherwise, search for name in the base class. |
| for (path.Decls = base_record->lookup(name).begin(); |
| path.Decls != path.Decls.end(); ++path.Decls) { |
| if (auto *method_decl = |
| llvm::dyn_cast<clang::CXXMethodDecl>(*path.Decls)) |
| if (method_decl->isVirtual() && !isOverload(decl, method_decl)) { |
| decls.push_back(method_decl); |
| return true; |
| } |
| } |
| } |
| |
| return false; |
| }; |
| |
| if (decl->getParent()->lookupInBases(find_overridden_methods, paths)) { |
| for (auto *overridden_decl : decls) |
| decl->addOverriddenMethod( |
| llvm::cast<clang::CXXMethodDecl>(overridden_decl)); |
| } |
| } |
| } |
| |
| static lldb::addr_t GetVTableAddress(Process &process, |
| VTableContextBase &vtable_ctx, |
| ValueObject &valobj, |
| const ASTRecordLayout &record_layout) { |
| // Retrieve type info |
| CompilerType pointee_type; |
| CompilerType this_type(valobj.GetCompilerType()); |
| uint32_t type_info = this_type.GetTypeInfo(&pointee_type); |
| if (!type_info) |
| return LLDB_INVALID_ADDRESS; |
| |
| // Check if it's a pointer or reference |
| bool ptr_or_ref = false; |
| if (type_info & (eTypeIsPointer | eTypeIsReference)) { |
| ptr_or_ref = true; |
| type_info = pointee_type.GetTypeInfo(); |
| } |
| |
| // We process only C++ classes |
| const uint32_t cpp_class = eTypeIsClass | eTypeIsCPlusPlus; |
| if ((type_info & cpp_class) != cpp_class) |
| return LLDB_INVALID_ADDRESS; |
| |
| // Calculate offset to VTable pointer |
| lldb::offset_t vbtable_ptr_offset = |
| vtable_ctx.isMicrosoft() ? record_layout.getVBPtrOffset().getQuantity() |
| : 0; |
| |
| if (ptr_or_ref) { |
| // We have a pointer / ref to object, so read |
| // VTable pointer from process memory |
| |
| if (valobj.GetAddressTypeOfChildren() != eAddressTypeLoad) |
| return LLDB_INVALID_ADDRESS; |
| |
| auto vbtable_ptr_addr = valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS); |
| if (vbtable_ptr_addr == LLDB_INVALID_ADDRESS) |
| return LLDB_INVALID_ADDRESS; |
| |
| vbtable_ptr_addr += vbtable_ptr_offset; |
| |
| Status err; |
| return process.ReadPointerFromMemory(vbtable_ptr_addr, err); |
| } |
| |
| // We have an object already read from process memory, |
| // so just extract VTable pointer from it |
| |
| DataExtractor data; |
| Status err; |
| auto size = valobj.GetData(data, err); |
| if (err.Fail() || vbtable_ptr_offset + data.GetAddressByteSize() > size) |
| return LLDB_INVALID_ADDRESS; |
| |
| return data.GetAddress(&vbtable_ptr_offset); |
| } |
| |
| static int64_t ReadVBaseOffsetFromVTable(Process &process, |
| VTableContextBase &vtable_ctx, |
| lldb::addr_t vtable_ptr, |
| const CXXRecordDecl *cxx_record_decl, |
| const CXXRecordDecl *base_class_decl) { |
| if (vtable_ctx.isMicrosoft()) { |
| clang::MicrosoftVTableContext &msoft_vtable_ctx = |
| static_cast<clang::MicrosoftVTableContext &>(vtable_ctx); |
| |
| // Get the index into the virtual base table. The |
| // index is the index in uint32_t from vbtable_ptr |
| const unsigned vbtable_index = |
| msoft_vtable_ctx.getVBTableIndex(cxx_record_decl, base_class_decl); |
| const lldb::addr_t base_offset_addr = vtable_ptr + vbtable_index * 4; |
| Status err; |
| return process.ReadSignedIntegerFromMemory(base_offset_addr, 4, INT64_MAX, |
| err); |
| } |
| |
| clang::ItaniumVTableContext &itanium_vtable_ctx = |
| static_cast<clang::ItaniumVTableContext &>(vtable_ctx); |
| |
| clang::CharUnits base_offset_offset = |
| itanium_vtable_ctx.getVirtualBaseOffsetOffset(cxx_record_decl, |
| base_class_decl); |
| const lldb::addr_t base_offset_addr = |
| vtable_ptr + base_offset_offset.getQuantity(); |
| const uint32_t base_offset_size = process.GetAddressByteSize(); |
| Status err; |
| return process.ReadSignedIntegerFromMemory(base_offset_addr, base_offset_size, |
| INT64_MAX, err); |
| } |
| |
| 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) { |
| ExecutionContext exe_ctx(valobj.GetExecutionContextRef()); |
| Process *process = exe_ctx.GetProcessPtr(); |
| if (!process) |
| return false; |
| |
| lldb::addr_t vtable_ptr = |
| GetVTableAddress(*process, vtable_ctx, valobj, record_layout); |
| if (vtable_ptr == LLDB_INVALID_ADDRESS) |
| return false; |
| |
| auto base_offset = ReadVBaseOffsetFromVTable( |
| *process, vtable_ctx, vtable_ptr, cxx_record_decl, base_class_decl); |
| if (base_offset == INT64_MAX) |
| return false; |
| |
| bit_offset = base_offset * 8; |
| |
| return true; |
| } |
| |
| typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, TypeSystemClang *> |
| ClangASTMap; |
| |
| static ClangASTMap &GetASTMap() { |
| static ClangASTMap *g_map_ptr = nullptr; |
| static llvm::once_flag g_once_flag; |
| llvm::call_once(g_once_flag, []() { |
| g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins |
| }); |
| return *g_map_ptr; |
| } |
| |
| TypePayloadClang::TypePayloadClang(OptionalClangModuleID owning_module, |
| bool is_complete_objc_class) |
| : m_payload(owning_module.GetValue()) { |
| SetIsCompleteObjCClass(is_complete_objc_class); |
| } |
| |
| void TypePayloadClang::SetOwningModule(OptionalClangModuleID id) { |
| assert(id.GetValue() < ObjCClassBit); |
| bool is_complete = IsCompleteObjCClass(); |
| m_payload = id.GetValue(); |
| SetIsCompleteObjCClass(is_complete); |
| } |
| |
| static void SetMemberOwningModule(clang::Decl *member, |
| const clang::Decl *parent) { |
| if (!member || !parent) |
| return; |
| |
| OptionalClangModuleID id(parent->getOwningModuleID()); |
| if (!id.HasValue()) |
| return; |
| |
| member->setFromASTFile(); |
| member->setOwningModuleID(id.GetValue()); |
| member->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible); |
| if (llvm::isa<clang::NamedDecl>(member)) |
| if (auto *dc = llvm::dyn_cast<clang::DeclContext>(parent)) { |
| dc->setHasExternalVisibleStorage(true); |
| // This triggers ExternalASTSource::FindExternalVisibleDeclsByName() to be |
| // called when searching for members. |
| dc->setHasExternalLexicalStorage(true); |
| } |
| } |
| |
| char TypeSystemClang::ID; |
| |
| bool TypeSystemClang::IsOperator(llvm::StringRef name, |
| clang::OverloadedOperatorKind &op_kind) { |
| // All operators have to start with "operator". |
| if (!name.consume_front("operator")) |
| return false; |
| |
| // Remember if there was a space after "operator". This is necessary to |
| // check for collisions with strangely named functions like "operatorint()". |
| bool space_after_operator = name.consume_front(" "); |
| |
| op_kind = StringSwitch<clang::OverloadedOperatorKind>(name) |
| .Case("+", clang::OO_Plus) |
| .Case("+=", clang::OO_PlusEqual) |
| .Case("++", clang::OO_PlusPlus) |
| .Case("-", clang::OO_Minus) |
| .Case("-=", clang::OO_MinusEqual) |
| .Case("--", clang::OO_MinusMinus) |
| .Case("->", clang::OO_Arrow) |
| .Case("->*", clang::OO_ArrowStar) |
| .Case("*", clang::OO_Star) |
| .Case("*=", clang::OO_StarEqual) |
| .Case("/", clang::OO_Slash) |
| .Case("/=", clang::OO_SlashEqual) |
| .Case("%", clang::OO_Percent) |
| .Case("%=", clang::OO_PercentEqual) |
| .Case("^", clang::OO_Caret) |
| .Case("^=", clang::OO_CaretEqual) |
| .Case("&", clang::OO_Amp) |
| .Case("&=", clang::OO_AmpEqual) |
| .Case("&&", clang::OO_AmpAmp) |
| .Case("|", clang::OO_Pipe) |
| .Case("|=", clang::OO_PipeEqual) |
| .Case("||", clang::OO_PipePipe) |
| .Case("~", clang::OO_Tilde) |
| .Case("!", clang::OO_Exclaim) |
| .Case("!=", clang::OO_ExclaimEqual) |
| .Case("=", clang::OO_Equal) |
| .Case("==", clang::OO_EqualEqual) |
| .Case("<", clang::OO_Less) |
| .Case("<=>", clang::OO_Spaceship) |
| .Case("<<", clang::OO_LessLess) |
| .Case("<<=", clang::OO_LessLessEqual) |
| .Case("<=", clang::OO_LessEqual) |
| .Case(">", clang::OO_Greater) |
| .Case(">>", clang::OO_GreaterGreater) |
| .Case(">>=", clang::OO_GreaterGreaterEqual) |
| .Case(">=", clang::OO_GreaterEqual) |
| .Case("()", clang::OO_Call) |
| .Case("[]", clang::OO_Subscript) |
| .Case(",", clang::OO_Comma) |
| .Default(clang::NUM_OVERLOADED_OPERATORS); |
| |
| // We found a fitting operator, so we can exit now. |
| if (op_kind != clang::NUM_OVERLOADED_OPERATORS) |
| return true; |
| |
| // After the "operator " or "operator" part is something unknown. This means |
| // it's either one of the named operators (new/delete), a conversion operator |
| // (e.g. operator bool) or a function which name starts with "operator" |
| // (e.g. void operatorbool). |
| |
| // If it's a function that starts with operator it can't have a space after |
| // "operator" because identifiers can't contain spaces. |
| // E.g. "operator int" (conversion operator) |
| // vs. "operatorint" (function with colliding name). |
| if (!space_after_operator) |
| return false; // not an operator. |
| |
| // Now the operator is either one of the named operators or a conversion |
| // operator. |
| op_kind = StringSwitch<clang::OverloadedOperatorKind>(name) |
| .Case("new", clang::OO_New) |
| .Case("new[]", clang::OO_Array_New) |
| .Case("delete", clang::OO_Delete) |
| .Case("delete[]", clang::OO_Array_Delete) |
| // conversion operators hit this case. |
| .Default(clang::NUM_OVERLOADED_OPERATORS); |
| |
| return true; |
| } |
| |
| clang::AccessSpecifier |
| TypeSystemClang::ConvertAccessTypeToAccessSpecifier(AccessType access) { |
| switch (access) { |
| default: |
| break; |
| case eAccessNone: |
| return AS_none; |
| case eAccessPublic: |
| return AS_public; |
| case eAccessPrivate: |
| return AS_private; |
| case eAccessProtected: |
| return AS_protected; |
| } |
| return AS_none; |
| } |
| |
| static void ParseLangArgs(LangOptions &Opts, ArchSpec arch) { |
| // FIXME: Cleanup per-file based stuff. |
| |
| std::vector<std::string> Includes; |
| LangOptions::setLangDefaults(Opts, clang::Language::ObjCXX, arch.GetTriple(), |
| Includes, clang::LangStandard::lang_gnucxx98); |
| |
| Opts.setValueVisibilityMode(DefaultVisibility); |
| |
| // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs is |
| // specified, or -std is set to a conforming mode. |
| Opts.Trigraphs = !Opts.GNUMode; |
| Opts.CharIsSigned = arch.CharIsSignedByDefault(); |
| Opts.OptimizeSize = 0; |
| |
| // FIXME: Eliminate this dependency. |
| // unsigned Opt = |
| // Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags); |
| // Opts.Optimize = Opt != 0; |
| unsigned Opt = 0; |
| |
| // This is the __NO_INLINE__ define, which just depends on things like the |
| // optimization level and -fno-inline, not actually whether the backend has |
| // inlining enabled. |
| // |
| // FIXME: This is affected by other options (-fno-inline). |
| Opts.NoInlineDefine = !Opt; |
| |
| // This is needed to allocate the extra space for the owning module |
| // on each decl. |
| Opts.ModulesLocalVisibility = 1; |
| } |
| |
| TypeSystemClang::TypeSystemClang(llvm::StringRef name, |
| llvm::Triple target_triple) { |
| m_display_name = name.str(); |
| if (!target_triple.str().empty()) |
| SetTargetTriple(target_triple.str()); |
| // The caller didn't pass an ASTContext so create a new one for this |
| // TypeSystemClang. |
| CreateASTContext(); |
| |
| LogCreation(); |
| } |
| |
| TypeSystemClang::TypeSystemClang(llvm::StringRef name, |
| ASTContext &existing_ctxt) { |
| m_display_name = name.str(); |
| SetTargetTriple(existing_ctxt.getTargetInfo().getTriple().str()); |
| |
| m_ast_up.reset(&existing_ctxt); |
| GetASTMap().Insert(&existing_ctxt, this); |
| |
| LogCreation(); |
| } |
| |
| // Destructor |
| TypeSystemClang::~TypeSystemClang() { Finalize(); } |
| |
| lldb::TypeSystemSP TypeSystemClang::CreateInstance(lldb::LanguageType language, |
| lldb_private::Module *module, |
| Target *target) { |
| if (!TypeSystemClangSupportsLanguage(language)) |
| return lldb::TypeSystemSP(); |
| ArchSpec arch; |
| if (module) |
| arch = module->GetArchitecture(); |
| else if (target) |
| arch = target->GetArchitecture(); |
| |
| if (!arch.IsValid()) |
| return lldb::TypeSystemSP(); |
| |
| llvm::Triple triple = arch.GetTriple(); |
| // LLVM wants this to be set to iOS or MacOSX; if we're working on |
| // a bare-boards type image, change the triple for llvm's benefit. |
| if (triple.getVendor() == llvm::Triple::Apple && |
| triple.getOS() == llvm::Triple::UnknownOS) { |
| if (triple.getArch() == llvm::Triple::arm || |
| triple.getArch() == llvm::Triple::aarch64 || |
| triple.getArch() == llvm::Triple::aarch64_32 || |
| triple.getArch() == llvm::Triple::thumb) { |
| triple.setOS(llvm::Triple::IOS); |
| } else { |
| triple.setOS(llvm::Triple::MacOSX); |
| } |
| } |
| |
| if (module) { |
| std::string ast_name = |
| "ASTContext for '" + module->GetFileSpec().GetPath() + "'"; |
| return std::make_shared<TypeSystemClang>(ast_name, triple); |
| } else if (target && target->IsValid()) |
| return std::make_shared<ScratchTypeSystemClang>(*target, triple); |
| return lldb::TypeSystemSP(); |
| } |
| |
| LanguageSet TypeSystemClang::GetSupportedLanguagesForTypes() { |
| LanguageSet languages; |
| languages.Insert(lldb::eLanguageTypeC89); |
| languages.Insert(lldb::eLanguageTypeC); |
| languages.Insert(lldb::eLanguageTypeC11); |
| languages.Insert(lldb::eLanguageTypeC_plus_plus); |
| languages.Insert(lldb::eLanguageTypeC99); |
| languages.Insert(lldb::eLanguageTypeObjC); |
| languages.Insert(lldb::eLanguageTypeObjC_plus_plus); |
| languages.Insert(lldb::eLanguageTypeC_plus_plus_03); |
| languages.Insert(lldb::eLanguageTypeC_plus_plus_11); |
| languages.Insert(lldb::eLanguageTypeC11); |
| languages.Insert(lldb::eLanguageTypeC_plus_plus_14); |
| languages.Insert(lldb::eLanguageTypeC_plus_plus_17); |
| languages.Insert(lldb::eLanguageTypeC_plus_plus_20); |
| return languages; |
| } |
| |
| LanguageSet TypeSystemClang::GetSupportedLanguagesForExpressions() { |
| LanguageSet languages; |
| languages.Insert(lldb::eLanguageTypeC_plus_plus); |
| languages.Insert(lldb::eLanguageTypeObjC_plus_plus); |
| languages.Insert(lldb::eLanguageTypeC_plus_plus_03); |
| languages.Insert(lldb::eLanguageTypeC_plus_plus_11); |
| languages.Insert(lldb::eLanguageTypeC_plus_plus_14); |
| languages.Insert(lldb::eLanguageTypeC_plus_plus_17); |
| languages.Insert(lldb::eLanguageTypeC_plus_plus_20); |
| return languages; |
| } |
| |
| void TypeSystemClang::Initialize() { |
| PluginManager::RegisterPlugin( |
| GetPluginNameStatic(), "clang base AST context plug-in", CreateInstance, |
| GetSupportedLanguagesForTypes(), GetSupportedLanguagesForExpressions()); |
| } |
| |
| void TypeSystemClang::Terminate() { |
| PluginManager::UnregisterPlugin(CreateInstance); |
| } |
| |
| void TypeSystemClang::Finalize() { |
| assert(m_ast_up); |
| GetASTMap().Erase(m_ast_up.get()); |
| if (!m_ast_owned) |
| m_ast_up.release(); |
| |
| m_builtins_up.reset(); |
| m_selector_table_up.reset(); |
| m_identifier_table_up.reset(); |
| m_target_info_up.reset(); |
| m_target_options_rp.reset(); |
| m_diagnostics_engine_up.reset(); |
| m_source_manager_up.reset(); |
| m_language_options_up.reset(); |
| } |
| |
| void TypeSystemClang::setSema(Sema *s) { |
| // Ensure that the new sema actually belongs to our ASTContext. |
| assert(s == nullptr || &s->getASTContext() == m_ast_up.get()); |
| m_sema = s; |
| } |
| |
| const char *TypeSystemClang::GetTargetTriple() { |
| return m_target_triple.c_str(); |
| } |
| |
| void TypeSystemClang::SetTargetTriple(llvm::StringRef target_triple) { |
| m_target_triple = target_triple.str(); |
| } |
| |
| void TypeSystemClang::SetExternalSource( |
| llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) { |
| ASTContext &ast = getASTContext(); |
| ast.getTranslationUnitDecl()->setHasExternalLexicalStorage(true); |
| ast.setExternalSource(ast_source_up); |
| } |
| |
| ASTContext &TypeSystemClang::getASTContext() const { |
| assert(m_ast_up); |
| return *m_ast_up; |
| } |
| |
| class NullDiagnosticConsumer : public DiagnosticConsumer { |
| public: |
| NullDiagnosticConsumer() { m_log = GetLog(LLDBLog::Expressions); } |
| |
| void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, |
| const clang::Diagnostic &info) override { |
| if (m_log) { |
| llvm::SmallVector<char, 32> diag_str(10); |
| info.FormatDiagnostic(diag_str); |
| diag_str.push_back('\0'); |
| LLDB_LOGF(m_log, "Compiler diagnostic: %s\n", diag_str.data()); |
| } |
| } |
| |
| DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const { |
| return new NullDiagnosticConsumer(); |
| } |
| |
| private: |
| Log *m_log; |
| }; |
| |
| void TypeSystemClang::CreateASTContext() { |
| assert(!m_ast_up); |
| m_ast_owned = true; |
| |
| m_language_options_up = std::make_unique<LangOptions>(); |
| ParseLangArgs(*m_language_options_up, ArchSpec(GetTargetTriple())); |
| |
| m_identifier_table_up = |
| std::make_unique<IdentifierTable>(*m_language_options_up, nullptr); |
| m_builtins_up = std::make_unique<Builtin::Context>(); |
| |
| m_selector_table_up = std::make_unique<SelectorTable>(); |
| |
| clang::FileSystemOptions file_system_options; |
| m_file_manager_up = std::make_unique<clang::FileManager>( |
| file_system_options, FileSystem::Instance().GetVirtualFileSystem()); |
| |
| llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs()); |
| m_diagnostics_engine_up = |
| std::make_unique<DiagnosticsEngine>(diag_id_sp, new DiagnosticOptions()); |
| |
| m_source_manager_up = std::make_unique<clang::SourceManager>( |
| *m_diagnostics_engine_up, *m_file_manager_up); |
| m_ast_up = std::make_unique<ASTContext>( |
| *m_language_options_up, *m_source_manager_up, *m_identifier_table_up, |
| *m_selector_table_up, *m_builtins_up, TU_Complete); |
| |
| m_diagnostic_consumer_up = std::make_unique<NullDiagnosticConsumer>(); |
| m_ast_up->getDiagnostics().setClient(m_diagnostic_consumer_up.get(), false); |
| |
| // This can be NULL if we don't know anything about the architecture or if |
| // the target for an architecture isn't enabled in the llvm/clang that we |
| // built |
| TargetInfo *target_info = getTargetInfo(); |
| if (target_info) |
| m_ast_up->InitBuiltinTypes(*target_info); |
| else { |
| std::string err = |
| llvm::formatv( |
| "Failed to initialize builtin ASTContext types for target '{0}'. " |
| "Printing variables may behave unexpectedly.", |
| m_target_triple) |
| .str(); |
| |
| LLDB_LOG(GetLog(LLDBLog::Expressions), err.c_str()); |
| |
| static std::once_flag s_uninitialized_target_warning; |
| Debugger::ReportWarning(std::move(err), /*debugger_id=*/std::nullopt, |
| &s_uninitialized_target_warning); |
| } |
| |
| GetASTMap().Insert(m_ast_up.get(), this); |
| |
| llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_up( |
| new ClangExternalASTSourceCallbacks(*this)); |
| SetExternalSource(ast_source_up); |
| } |
| |
| TypeSystemClang *TypeSystemClang::GetASTContext(clang::ASTContext *ast) { |
| TypeSystemClang *clang_ast = GetASTMap().Lookup(ast); |
| return clang_ast; |
| } |
| |
| clang::MangleContext *TypeSystemClang::getMangleContext() { |
| if (m_mangle_ctx_up == nullptr) |
| m_mangle_ctx_up.reset(getASTContext().createMangleContext()); |
| return m_mangle_ctx_up.get(); |
| } |
| |
| std::shared_ptr<clang::TargetOptions> &TypeSystemClang::getTargetOptions() { |
| if (m_target_options_rp == nullptr && !m_target_triple.empty()) { |
| m_target_options_rp = std::make_shared<clang::TargetOptions>(); |
| if (m_target_options_rp != nullptr) |
| m_target_options_rp->Triple = m_target_triple; |
| } |
| return m_target_options_rp; |
| } |
| |
| TargetInfo *TypeSystemClang::getTargetInfo() { |
| // target_triple should be something like "x86_64-apple-macosx" |
| if (m_target_info_up == nullptr && !m_target_triple.empty()) |
| m_target_info_up.reset(TargetInfo::CreateTargetInfo( |
| getASTContext().getDiagnostics(), getTargetOptions())); |
| return m_target_info_up.get(); |
| } |
| |
| #pragma mark Basic Types |
| |
| static inline bool QualTypeMatchesBitSize(const uint64_t bit_size, |
| ASTContext &ast, QualType qual_type) { |
| uint64_t qual_type_bit_size = ast.getTypeSize(qual_type); |
| return qual_type_bit_size == bit_size; |
| } |
| |
| CompilerType |
| TypeSystemClang::GetBuiltinTypeForEncodingAndBitSize(Encoding encoding, |
| size_t bit_size) { |
| ASTContext &ast = getASTContext(); |
| |
| if (!ast.VoidPtrTy) |
| return {}; |
| |
| switch (encoding) { |
| case eEncodingInvalid: |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy)) |
| return GetType(ast.VoidPtrTy); |
| break; |
| |
| case eEncodingUint: |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) |
| return GetType(ast.UnsignedCharTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) |
| return GetType(ast.UnsignedShortTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy)) |
| return GetType(ast.UnsignedIntTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy)) |
| return GetType(ast.UnsignedLongTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy)) |
| return GetType(ast.UnsignedLongLongTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty)) |
| return GetType(ast.UnsignedInt128Ty); |
| break; |
| |
| case eEncodingSint: |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy)) |
| return GetType(ast.SignedCharTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy)) |
| return GetType(ast.ShortTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy)) |
| return GetType(ast.IntTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy)) |
| return GetType(ast.LongTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy)) |
| return GetType(ast.LongLongTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty)) |
| return GetType(ast.Int128Ty); |
| break; |
| |
| case eEncodingIEEE754: |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy)) |
| return GetType(ast.FloatTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy)) |
| return GetType(ast.DoubleTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy)) |
| return GetType(ast.LongDoubleTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy)) |
| return GetType(ast.HalfTy); |
| break; |
| |
| case eEncodingVector: |
| // Sanity check that bit_size is a multiple of 8's. |
| if (bit_size && !(bit_size & 0x7u)) |
| return GetType(ast.getExtVectorType(ast.UnsignedCharTy, bit_size / 8)); |
| break; |
| } |
| |
| return CompilerType(); |
| } |
| |
| lldb::BasicType TypeSystemClang::GetBasicTypeEnumeration(llvm::StringRef name) { |
| static const llvm::StringMap<lldb::BasicType> g_type_map = { |
| // "void" |
| {"void", eBasicTypeVoid}, |
| |
| // "char" |
| {"char", eBasicTypeChar}, |
| {"signed char", eBasicTypeSignedChar}, |
| {"unsigned char", eBasicTypeUnsignedChar}, |
| {"wchar_t", eBasicTypeWChar}, |
| {"signed wchar_t", eBasicTypeSignedWChar}, |
| {"unsigned wchar_t", eBasicTypeUnsignedWChar}, |
| |
| // "short" |
| {"short", eBasicTypeShort}, |
| {"short int", eBasicTypeShort}, |
| {"unsigned short", eBasicTypeUnsignedShort}, |
| {"unsigned short int", eBasicTypeUnsignedShort}, |
| |
| // "int" |
| {"int", eBasicTypeInt}, |
| {"signed int", eBasicTypeInt}, |
| {"unsigned int", eBasicTypeUnsignedInt}, |
| {"unsigned", eBasicTypeUnsignedInt}, |
| |
| // "long" |
| {"long", eBasicTypeLong}, |
| {"long int", eBasicTypeLong}, |
| {"unsigned long", eBasicTypeUnsignedLong}, |
| {"unsigned long int", eBasicTypeUnsignedLong}, |
| |
| // "long long" |
| {"long long", eBasicTypeLongLong}, |
| {"long long int", eBasicTypeLongLong}, |
| {"unsigned long long", eBasicTypeUnsignedLongLong}, |
| {"unsigned long long int", eBasicTypeUnsignedLongLong}, |
| |
| // "int128" |
| {"__int128_t", eBasicTypeInt128}, |
| {"__uint128_t", eBasicTypeUnsignedInt128}, |
| |
| // "bool" |
| {"bool", eBasicTypeBool}, |
| {"_Bool", eBasicTypeBool}, |
| |
| // Miscellaneous |
| {"float", eBasicTypeFloat}, |
| {"double", eBasicTypeDouble}, |
| {"long double", eBasicTypeLongDouble}, |
| {"id", eBasicTypeObjCID}, |
| {"SEL", eBasicTypeObjCSel}, |
| {"nullptr", eBasicTypeNullPtr}, |
| }; |
| |
| auto iter = g_type_map.find(name); |
| if (iter == g_type_map.end()) |
| return eBasicTypeInvalid; |
| |
| return iter->second; |
| } |
| |
| uint32_t TypeSystemClang::GetPointerByteSize() { |
| if (m_pointer_byte_size == 0) |
| if (auto size = GetBasicType(lldb::eBasicTypeVoid) |
| .GetPointerType() |
| .GetByteSize(nullptr)) |
| m_pointer_byte_size = *size; |
| return m_pointer_byte_size; |
| } |
| |
| CompilerType TypeSystemClang::GetBasicType(lldb::BasicType basic_type) { |
| clang::ASTContext &ast = getASTContext(); |
| |
| lldb::opaque_compiler_type_t clang_type = |
| GetOpaqueCompilerType(&ast, basic_type); |
| |
| if (clang_type) |
| return CompilerType(weak_from_this(), clang_type); |
| return CompilerType(); |
| } |
| |
| CompilerType TypeSystemClang::GetBuiltinTypeForDWARFEncodingAndBitSize( |
| llvm::StringRef type_name, uint32_t dw_ate, uint32_t bit_size) { |
| ASTContext &ast = getASTContext(); |
| |
| if (!ast.VoidPtrTy) |
| return {}; |
| |
| switch (dw_ate) { |
| default: |
| break; |
| |
| case DW_ATE_address: |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy)) |
| return GetType(ast.VoidPtrTy); |
| break; |
| |
| case DW_ATE_boolean: |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.BoolTy)) |
| return GetType(ast.BoolTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) |
| return GetType(ast.UnsignedCharTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) |
| return GetType(ast.UnsignedShortTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy)) |
| return GetType(ast.UnsignedIntTy); |
| break; |
| |
| case DW_ATE_lo_user: |
| // This has been seen to mean DW_AT_complex_integer |
| if (type_name.contains("complex")) { |
| CompilerType complex_int_clang_type = |
| GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed, |
| bit_size / 2); |
| return GetType( |
| ast.getComplexType(ClangUtil::GetQualType(complex_int_clang_type))); |
| } |
| break; |
| |
| case DW_ATE_complex_float: { |
| CanQualType FloatComplexTy = ast.getComplexType(ast.FloatTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, FloatComplexTy)) |
| return GetType(FloatComplexTy); |
| |
| CanQualType DoubleComplexTy = ast.getComplexType(ast.DoubleTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, DoubleComplexTy)) |
| return GetType(DoubleComplexTy); |
| |
| CanQualType LongDoubleComplexTy = ast.getComplexType(ast.LongDoubleTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, LongDoubleComplexTy)) |
| return GetType(LongDoubleComplexTy); |
| |
| CompilerType complex_float_clang_type = |
| GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float, |
| bit_size / 2); |
| return GetType( |
| ast.getComplexType(ClangUtil::GetQualType(complex_float_clang_type))); |
| } |
| |
| case DW_ATE_float: |
| if (type_name == "float" && |
| QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy)) |
| return GetType(ast.FloatTy); |
| if (type_name == "double" && |
| QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy)) |
| return GetType(ast.DoubleTy); |
| if (type_name == "long double" && |
| QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy)) |
| return GetType(ast.LongDoubleTy); |
| // Fall back to not requiring a name match |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy)) |
| return GetType(ast.FloatTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy)) |
| return GetType(ast.DoubleTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy)) |
| return GetType(ast.LongDoubleTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy)) |
| return GetType(ast.HalfTy); |
| break; |
| |
| case DW_ATE_signed: |
| if (!type_name.empty()) { |
| if (type_name == "wchar_t" && |
| QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy) && |
| (getTargetInfo() && |
| TargetInfo::isTypeSigned(getTargetInfo()->getWCharType()))) |
| return GetType(ast.WCharTy); |
| if (type_name == "void" && |
| QualTypeMatchesBitSize(bit_size, ast, ast.VoidTy)) |
| return GetType(ast.VoidTy); |
| if (type_name.contains("long long") && |
| QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy)) |
| return GetType(ast.LongLongTy); |
| if (type_name.contains("long") && |
| QualTypeMatchesBitSize(bit_size, ast, ast.LongTy)) |
| return GetType(ast.LongTy); |
| if (type_name.contains("short") && |
| QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy)) |
| return GetType(ast.ShortTy); |
| if (type_name.contains("char")) { |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy)) |
| return GetType(ast.CharTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy)) |
| return GetType(ast.SignedCharTy); |
| } |
| if (type_name.contains("int")) { |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy)) |
| return GetType(ast.IntTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty)) |
| return GetType(ast.Int128Ty); |
| } |
| } |
| // We weren't able to match up a type name, just search by size |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy)) |
| return GetType(ast.CharTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy)) |
| return GetType(ast.ShortTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy)) |
| return GetType(ast.IntTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy)) |
| return GetType(ast.LongTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy)) |
| return GetType(ast.LongLongTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty)) |
| return GetType(ast.Int128Ty); |
| break; |
| |
| case DW_ATE_signed_char: |
| if (type_name == "char") { |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy)) |
| return GetType(ast.CharTy); |
| } |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy)) |
| return GetType(ast.SignedCharTy); |
| break; |
| |
| case DW_ATE_unsigned: |
| if (!type_name.empty()) { |
| if (type_name == "wchar_t") { |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy)) { |
| if (!(getTargetInfo() && |
| TargetInfo::isTypeSigned(getTargetInfo()->getWCharType()))) |
| return GetType(ast.WCharTy); |
| } |
| } |
| if (type_name.contains("long long")) { |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy)) |
| return GetType(ast.UnsignedLongLongTy); |
| } else if (type_name.contains("long")) { |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy)) |
| return GetType(ast.UnsignedLongTy); |
| } else if (type_name.contains("short")) { |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) |
| return GetType(ast.UnsignedShortTy); |
| } else if (type_name.contains("char")) { |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) |
| return GetType(ast.UnsignedCharTy); |
| } else if (type_name.contains("int")) { |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy)) |
| return GetType(ast.UnsignedIntTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty)) |
| return GetType(ast.UnsignedInt128Ty); |
| } |
| } |
| // We weren't able to match up a type name, just search by size |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) |
| return GetType(ast.UnsignedCharTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) |
| return GetType(ast.UnsignedShortTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy)) |
| return GetType(ast.UnsignedIntTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy)) |
| return GetType(ast.UnsignedLongTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy)) |
| return GetType(ast.UnsignedLongLongTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty)) |
| return GetType(ast.UnsignedInt128Ty); |
| break; |
| |
| case DW_ATE_unsigned_char: |
| if (type_name == "char") { |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy)) |
| return GetType(ast.CharTy); |
| } |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) |
| return GetType(ast.UnsignedCharTy); |
| if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) |
| return GetType(ast.UnsignedShortTy); |
| break; |
| |
| case DW_ATE_imaginary_float: |
| break; |
| |
| case DW_ATE_UTF: |
| switch (bit_size) { |
| case 8: |
| return GetType(ast.Char8Ty); |
| case 16: |
| return GetType(ast.Char16Ty); |
| case 32: |
| return GetType(ast.Char32Ty); |
| default: |
| if (!type_name.empty()) { |
| if (type_name == "char16_t") |
| return GetType(ast.Char16Ty); |
| if (type_name == "char32_t") |
| return GetType(ast.Char32Ty); |
| if (type_name == "char8_t") |
| return GetType(ast.Char8Ty); |
| } |
| } |
| break; |
| } |
| |
| Log *log = GetLog(LLDBLog::Types); |
| LLDB_LOG(log, |
| "error: need to add support for DW_TAG_base_type '{0}' " |
| "encoded with DW_ATE = {1:x}, bit_size = {2}", |
| type_name, dw_ate, bit_size); |
| return CompilerType(); |
| } |
| |
| CompilerType TypeSystemClang::GetCStringType(bool is_const) { |
| ASTContext &ast = getASTContext(); |
| QualType char_type(ast.CharTy); |
| |
| if (is_const) |
| char_type.addConst(); |
| |
| return GetType(ast.getPointerType(char_type)); |
| } |
| |
| bool TypeSystemClang::AreTypesSame(CompilerType type1, CompilerType type2, |
| bool ignore_qualifiers) { |
| auto ast = type1.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>(); |
| if (!ast || type1.GetTypeSystem() != type2.GetTypeSystem()) |
| return false; |
| |
| if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType()) |
| return true; |
| |
| QualType type1_qual = ClangUtil::GetQualType(type1); |
| QualType type2_qual = ClangUtil::GetQualType(type2); |
| |
| if (ignore_qualifiers) { |
| type1_qual = type1_qual.getUnqualifiedType(); |
| type2_qual = type2_qual.getUnqualifiedType(); |
| } |
| |
| return ast->getASTContext().hasSameType(type1_qual, type2_qual); |
| } |
| |
| CompilerType TypeSystemClang::GetTypeForDecl(void *opaque_decl) { |
| if (!opaque_decl) |
| return CompilerType(); |
| |
| clang::Decl *decl = static_cast<clang::Decl *>(opaque_decl); |
| if (auto *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl)) |
| return GetTypeForDecl(named_decl); |
| return CompilerType(); |
| } |
| |
| CompilerDeclContext TypeSystemClang::CreateDeclContext(DeclContext *ctx) { |
| // Check that the DeclContext actually belongs to this ASTContext. |
| assert(&ctx->getParentASTContext() == &getASTContext()); |
| return CompilerDeclContext(this, ctx); |
| } |
| |
| CompilerType TypeSystemClang::GetTypeForDecl(clang::NamedDecl *decl) { |
| if (clang::ObjCInterfaceDecl *interface_decl = |
| llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) |
| return GetTypeForDecl(interface_decl); |
| if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) |
| return GetTypeForDecl(tag_decl); |
| if (clang::ValueDecl *value_decl = llvm::dyn_cast<clang::ValueDecl>(decl)) |
| return GetTypeForDecl(value_decl); |
| return CompilerType(); |
| } |
| |
| CompilerType TypeSystemClang::GetTypeForDecl(TagDecl *decl) { |
| return GetType(getASTContext().getTagDeclType(decl)); |
| } |
| |
| CompilerType TypeSystemClang::GetTypeForDecl(ObjCInterfaceDecl *decl) { |
| return GetType(getASTContext().getObjCInterfaceType(decl)); |
| } |
| |
| CompilerType TypeSystemClang::GetTypeForDecl(clang::ValueDecl *value_decl) { |
| return GetType(value_decl->getType()); |
| } |
| |
| #pragma mark Structure, Unions, Classes |
| |
| void TypeSystemClang::SetOwningModule(clang::Decl *decl, |
| OptionalClangModuleID owning_module) { |
| if (!decl || !owning_module.HasValue()) |
| return; |
| |
| decl->setFromASTFile(); |
| decl->setOwningModuleID(owning_module.GetValue()); |
| decl->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible); |
| } |
| |
| OptionalClangModuleID |
| TypeSystemClang::GetOrCreateClangModule(llvm::StringRef name, |
| OptionalClangModuleID parent, |
| bool is_framework, bool is_explicit) { |
| // Get the external AST source which holds the modules. |
| auto *ast_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>( |
| getASTContext().getExternalSource()); |
| assert(ast_source && "external ast source was lost"); |
| if (!ast_source) |
| return {}; |
| |
| // Lazily initialize the module map. |
| if (!m_header_search_up) { |
| auto HSOpts = std::make_shared<clang::HeaderSearchOptions>(); |
| m_header_search_up = std::make_unique<clang::HeaderSearch>( |
| HSOpts, *m_source_manager_up, *m_diagnostics_engine_up, |
| *m_language_options_up, m_target_info_up.get()); |
| m_module_map_up = std::make_unique<clang::ModuleMap>( |
| *m_source_manager_up, *m_diagnostics_engine_up, *m_language_options_up, |
| m_target_info_up.get(), *m_header_search_up); |
| } |
| |
| // Get or create the module context. |
| bool created; |
| clang::Module *module; |
| auto parent_desc = ast_source->getSourceDescriptor(parent.GetValue()); |
| std::tie(module, created) = m_module_map_up->findOrCreateModule( |
| name, parent_desc ? parent_desc->getModuleOrNull() : nullptr, |
| is_framework, is_explicit); |
| if (!created) |
| return ast_source->GetIDForModule(module); |
| |
| return ast_source->RegisterModule(module); |
| } |
| |
| CompilerType TypeSystemClang::CreateRecordType( |
| clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, |
| AccessType access_type, llvm::StringRef name, int kind, |
| LanguageType language, std::optional<ClangASTMetadata> metadata, |
| bool exports_symbols) { |
| ASTContext &ast = getASTContext(); |
| |
| if (decl_ctx == nullptr) |
| decl_ctx = ast.getTranslationUnitDecl(); |
| |
| if (language == eLanguageTypeObjC || |
| language == eLanguageTypeObjC_plus_plus) { |
| bool isInternal = false; |
| return CreateObjCClass(name, decl_ctx, owning_module, isInternal, metadata); |
| } |
| |
| // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and |
| // we will need to update this code. I was told to currently always use the |
| // CXXRecordDecl class since we often don't know from debug information if |
| // something is struct or a class, so we default to always use the more |
| // complete definition just in case. |
| |
| bool has_name = !name.empty(); |
| CXXRecordDecl *decl = CXXRecordDecl::CreateDeserialized(ast, GlobalDeclID()); |
| decl->setTagKind(static_cast<TagDecl::TagKind>(kind)); |
| decl->setDeclContext(decl_ctx); |
| if (has_name) |
| decl->setDeclName(&ast.Idents.get(name)); |
| SetOwningModule(decl, owning_module); |
| |
| if (!has_name) { |
| // In C++ a lambda is also represented as an unnamed class. This is |
| // different from an *anonymous class* that the user wrote: |
| // |
| // struct A { |
| // // anonymous class (GNU/MSVC extension) |
| // struct { |
| // int x; |
| // }; |
| // // unnamed class within a class |
| // struct { |
| // int y; |
| // } B; |
| // }; |
| // |
| // void f() { |
| // // unammed class outside of a class |
| // struct { |
| // int z; |
| // } C; |
| // } |
| // |
| // Anonymous classes is a GNU/MSVC extension that clang supports. It |
| // requires the anonymous class be embedded within a class. So the new |
| // heuristic verifies this condition. |
| if (isa<CXXRecordDecl>(decl_ctx) && exports_symbols) |
| decl->setAnonymousStructOrUnion(true); |
| } |
| |
| if (metadata) |
| SetMetadata(decl, *metadata); |
| |
| if (access_type != eAccessNone) |
| decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type)); |
| |
| if (decl_ctx) |
| decl_ctx->addDecl(decl); |
| |
| return GetType(ast.getTagDeclType(decl)); |
| } |
| |
| namespace { |
| /// Returns true iff the given TemplateArgument should be represented as an |
| /// NonTypeTemplateParmDecl in the AST. |
| bool IsValueParam(const clang::TemplateArgument &argument) { |
| return argument.getKind() == TemplateArgument::Integral; |
| } |
| |
| void AddAccessSpecifierDecl(clang::CXXRecordDecl *cxx_record_decl, |
| ASTContext &ct, |
| clang::AccessSpecifier previous_access, |
| clang::AccessSpecifier access_specifier) { |
| if (!cxx_record_decl->isClass() && !cxx_record_decl->isStruct()) |
| return; |
| if (previous_access != access_specifier) { |
| // For struct, don't add AS_public if it's the first AccessSpecDecl. |
| // For class, don't add AS_private if it's the first AccessSpecDecl. |
| if ((cxx_record_decl->isStruct() && |
| previous_access == clang::AccessSpecifier::AS_none && |
| access_specifier == clang::AccessSpecifier::AS_public) || |
| (cxx_record_decl->isClass() && |
| previous_access == clang::AccessSpecifier::AS_none && |
| access_specifier == clang::AccessSpecifier::AS_private)) { |
| return; |
| } |
| cxx_record_decl->addDecl( |
| AccessSpecDecl::Create(ct, access_specifier, cxx_record_decl, |
| SourceLocation(), SourceLocation())); |
| } |
| } |
| } // namespace |
| |
| static TemplateParameterList *CreateTemplateParameterList( |
| ASTContext &ast, |
| const TypeSystemClang::TemplateParameterInfos &template_param_infos, |
| llvm::SmallVector<NamedDecl *, 8> &template_param_decls) { |
| const bool parameter_pack = false; |
| const bool is_typename = false; |
| const unsigned depth = 0; |
| const size_t num_template_params = template_param_infos.Size(); |
| DeclContext *const decl_context = |
| ast.getTranslationUnitDecl(); // Is this the right decl context?, |
| |
| auto const &args = template_param_infos.GetArgs(); |
| auto const &names = template_param_infos.GetNames(); |
| for (size_t i = 0; i < num_template_params; ++i) { |
| const char *name = names[i]; |
| |
| IdentifierInfo *identifier_info = nullptr; |
| if (name && name[0]) |
| identifier_info = &ast.Idents.get(name); |
| TemplateArgument const &targ = args[i]; |
| if (IsValueParam(targ)) { |
| QualType template_param_type = targ.getIntegralType(); |
| template_param_decls.push_back(NonTypeTemplateParmDecl::Create( |
| ast, decl_context, SourceLocation(), SourceLocation(), depth, i, |
| identifier_info, template_param_type, parameter_pack, |
| ast.getTrivialTypeSourceInfo(template_param_type))); |
| } else { |
| template_param_decls.push_back(TemplateTypeParmDecl::Create( |
| ast, decl_context, SourceLocation(), SourceLocation(), depth, i, |
| identifier_info, is_typename, parameter_pack)); |
| } |
| } |
| |
| if (template_param_infos.hasParameterPack()) { |
| IdentifierInfo *identifier_info = nullptr; |
| if (template_param_infos.HasPackName()) |
| identifier_info = &ast.Idents.get(template_param_infos.GetPackName()); |
| const bool parameter_pack_true = true; |
| |
| if (!template_param_infos.GetParameterPack().IsEmpty() && |
| IsValueParam(template_param_infos.GetParameterPack().Front())) { |
| QualType template_param_type = |
| template_param_infos.GetParameterPack().Front().getIntegralType(); |
| template_param_decls.push_back(NonTypeTemplateParmDecl::Create( |
| ast, decl_context, SourceLocation(), SourceLocation(), depth, |
| num_template_params, identifier_info, template_param_type, |
| parameter_pack_true, |
| ast.getTrivialTypeSourceInfo(template_param_type))); |
| } else { |
| template_param_decls.push_back(TemplateTypeParmDecl::Create( |
| ast, decl_context, SourceLocation(), SourceLocation(), depth, |
| num_template_params, identifier_info, is_typename, |
| parameter_pack_true)); |
| } |
| } |
| clang::Expr *const requires_clause = nullptr; // TODO: Concepts |
| TemplateParameterList *template_param_list = TemplateParameterList::Create( |
| ast, SourceLocation(), SourceLocation(), template_param_decls, |
| SourceLocation(), requires_clause); |
| return template_param_list; |
| } |
| |
| clang::FunctionTemplateDecl *TypeSystemClang::CreateFunctionTemplateDecl( |
| clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, |
| clang::FunctionDecl *func_decl, |
| const TemplateParameterInfos &template_param_infos) { |
| // /// Create a function template node. |
| ASTContext &ast = getASTContext(); |
| |
| llvm::SmallVector<NamedDecl *, 8> template_param_decls; |
| TemplateParameterList *template_param_list = CreateTemplateParameterList( |
| ast, template_param_infos, template_param_decls); |
| FunctionTemplateDecl *func_tmpl_decl = |
| FunctionTemplateDecl::CreateDeserialized(ast, GlobalDeclID()); |
| func_tmpl_decl->setDeclContext(decl_ctx); |
| func_tmpl_decl->setLocation(func_decl->getLocation()); |
| func_tmpl_decl->setDeclName(func_decl->getDeclName()); |
| func_tmpl_decl->setTemplateParameters(template_param_list); |
| func_tmpl_decl->init(func_decl); |
| SetOwningModule(func_tmpl_decl, owning_module); |
| |
| for (size_t i = 0, template_param_decl_count = template_param_decls.size(); |
| i < template_param_decl_count; ++i) { |
| // TODO: verify which decl context we should put template_param_decls into.. |
| template_param_decls[i]->setDeclContext(func_decl); |
| } |
| // Function templates inside a record need to have an access specifier. |
| // It doesn't matter what access specifier we give the template as LLDB |
| // anyway allows accessing everything inside a record. |
| if (decl_ctx->isRecord()) |
| func_tmpl_decl->setAccess(clang::AccessSpecifier::AS_public); |
| |
| return func_tmpl_decl; |
| } |
| |
| void TypeSystemClang::CreateFunctionTemplateSpecializationInfo( |
| FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl, |
| const TemplateParameterInfos &infos) { |
| TemplateArgumentList *template_args_ptr = TemplateArgumentList::CreateCopy( |
| func_decl->getASTContext(), infos.GetArgs()); |
| |
| func_decl->setFunctionTemplateSpecialization(func_tmpl_decl, |
| template_args_ptr, nullptr); |
| } |
| |
| /// Returns true if the given template parameter can represent the given value. |
| /// For example, `typename T` can represent `int` but not integral values such |
| /// as `int I = 3`. |
| static bool TemplateParameterAllowsValue(NamedDecl *param, |
| const TemplateArgument &value) { |
| if (llvm::isa<TemplateTypeParmDecl>(param)) { |
| // Compare the argument kind, i.e. ensure that <typename> != <int>. |
| if (value.getKind() != TemplateArgument::Type) |
| return false; |
| } else if (auto *type_param = |
| llvm::dyn_cast<NonTypeTemplateParmDecl>(param)) { |
| // Compare the argument kind, i.e. ensure that <typename> != <int>. |
| if (!IsValueParam(value)) |
| return false; |
| // Compare the integral type, i.e. ensure that <int> != <char>. |
| if (type_param->getType() != value.getIntegralType()) |
| return false; |
| } else { |
| // There is no way to create other parameter decls at the moment, so we |
| // can't reach this case during normal LLDB usage. Log that this happened |
| // and assert. |
| Log *log = GetLog(LLDBLog::Expressions); |
| LLDB_LOG(log, |
| "Don't know how to compare template parameter to passed" |
| " value. Decl kind of parameter is: {0}", |
| param->getDeclKindName()); |
| lldbassert(false && "Can't compare this TemplateParmDecl subclass"); |
| // In release builds just fall back to marking the parameter as not |
| // accepting the value so that we don't try to fit an instantiation to a |
| // template that doesn't fit. E.g., avoid that `S<1>` is being connected to |
| // `template<typename T> struct S;`. |
| return false; |
| } |
| return true; |
| } |
| |
| /// Returns true if the given class template declaration could produce an |
| /// instantiation with the specified values. |
| /// For example, `<typename T>` allows the arguments `float`, but not for |
| /// example `bool, float` or `3` (as an integer parameter value). |
| static bool ClassTemplateAllowsToInstantiationArgs( |
| ClassTemplateDecl *class_template_decl, |
| const TypeSystemClang::TemplateParameterInfos &instantiation_values) { |
| |
| TemplateParameterList ¶ms = *class_template_decl->getTemplateParameters(); |
| |
| // Save some work by iterating only once over the found parameters and |
| // calculate the information related to parameter packs. |
| |
| // Contains the first pack parameter (or non if there are none). |
| std::optional<NamedDecl *> pack_parameter; |
| // Contains the number of non-pack parameters. |
| size_t non_pack_params = params.size(); |
| for (size_t i = 0; i < params.size(); ++i) { |
| NamedDecl *param = params.getParam(i); |
| if (param->isParameterPack()) { |
| pack_parameter = param; |
| non_pack_params = i; |
| break; |
| } |
| } |
| |
| // The found template needs to have compatible non-pack template arguments. |
| // E.g., ensure that <typename, typename> != <typename>. |
| // The pack parameters are compared later. |
| if (non_pack_params != instantiation_values.Size()) |
| return false; |
| |
| // Ensure that <typename...> != <typename>. |
| if (pack_parameter.has_value() != instantiation_values.hasParameterPack()) |
| return false; |
| |
| // Compare the first pack parameter that was found with the first pack |
| // parameter value. The special case of having an empty parameter pack value |
| // always fits to a pack parameter. |
| // E.g., ensure that <int...> != <typename...>. |
| if (pack_parameter && !instantiation_values.GetParameterPack().IsEmpty() && |
| !TemplateParameterAllowsValue( |
| *pack_parameter, instantiation_values.GetParameterPack().Front())) |
| return false; |
| |
| // Compare all the non-pack parameters now. |
| // E.g., ensure that <int> != <long>. |
| for (const auto pair : |
| llvm::zip_first(instantiation_values.GetArgs(), params)) { |
| const TemplateArgument &passed_arg = std::get<0>(pair); |
| NamedDecl *found_param = std::get<1>(pair); |
| if (!TemplateParameterAllowsValue(found_param, passed_arg)) |
| return false; |
| } |
| |
| return class_template_decl; |
| } |
| |
| ClassTemplateDecl *TypeSystemClang::CreateClassTemplateDecl( |
| DeclContext *decl_ctx, OptionalClangModuleID owning_module, |
| lldb::AccessType access_type, llvm::StringRef class_name, int kind, |
| const TemplateParameterInfos &template_param_infos) { |
| ASTContext &ast = getASTContext(); |
| |
| ClassTemplateDecl *class_template_decl = nullptr; |
| if (decl_ctx == nullptr) |
| decl_ctx = ast.getTranslationUnitDecl(); |
| |
| IdentifierInfo &identifier_info = ast.Idents.get(class_name); |
| DeclarationName decl_name(&identifier_info); |
| |
| // Search the AST for an existing ClassTemplateDecl that could be reused. |
| clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name); |
| for (NamedDecl *decl : result) { |
| class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl); |
| if (!class_template_decl) |
| continue; |
| // The class template has to be able to represents the instantiation |
| // values we received. Without this we might end up putting an instantiation |
| // with arguments such as <int, int> to a template such as: |
| // template<typename T> struct S; |
| // Connecting the instantiation to an incompatible template could cause |
| // problems later on. |
| if (!ClassTemplateAllowsToInstantiationArgs(class_template_decl, |
| template_param_infos)) |
| continue; |
| return class_template_decl; |
| } |
| |
| llvm::SmallVector<NamedDecl *, 8> template_param_decls; |
| |
| TemplateParameterList *template_param_list = CreateTemplateParameterList( |
| ast, template_param_infos, template_param_decls); |
| |
| CXXRecordDecl *template_cxx_decl = |
| CXXRecordDecl::CreateDeserialized(ast, GlobalDeclID()); |
| template_cxx_decl->setTagKind(static_cast<TagDecl::TagKind>(kind)); |
| // What decl context do we use here? TU? The actual decl context? |
| template_cxx_decl->setDeclContext(decl_ctx); |
| template_cxx_decl->setDeclName(decl_name); |
| SetOwningModule(template_cxx_decl, owning_module); |
| |
| for (size_t i = 0, template_param_decl_count = template_param_decls.size(); |
| i < template_param_decl_count; ++i) { |
| template_param_decls[i]->setDeclContext(template_cxx_decl); |
| } |
| |
| // With templated classes, we say that a class is templated with |
| // specializations, but that the bare class has no functions. |
| // template_cxx_decl->startDefinition(); |
| // template_cxx_decl->completeDefinition(); |
| |
| class_template_decl = |
| ClassTemplateDecl::CreateDeserialized(ast, GlobalDeclID()); |
| // What decl context do we use here? TU? The actual decl context? |
| class_template_decl->setDeclContext(decl_ctx); |
| class_template_decl->setDeclName(decl_name); |
| class_template_decl->setTemplateParameters(template_param_list); |
| class_template_decl->init(template_cxx_decl); |
| template_cxx_decl->setDescribedClassTemplate(class_template_decl); |
| SetOwningModule(class_template_decl, owning_module); |
| |
| if (access_type != eAccessNone) |
| class_template_decl->setAccess( |
| ConvertAccessTypeToAccessSpecifier(access_type)); |
| |
| decl_ctx->addDecl(class_template_decl); |
| |
| VerifyDecl(class_template_decl); |
| |
| return class_template_decl; |
| } |
| |
| TemplateTemplateParmDecl * |
| TypeSystemClang::CreateTemplateTemplateParmDecl(const char *template_name) { |
| ASTContext &ast = getASTContext(); |
| |
| auto *decl_ctx = ast.getTranslationUnitDecl(); |
| |
| IdentifierInfo &identifier_info = ast.Idents.get(template_name); |
| llvm::SmallVector<NamedDecl *, 8> template_param_decls; |
| |
| TypeSystemClang::TemplateParameterInfos template_param_infos; |
| TemplateParameterList *template_param_list = CreateTemplateParameterList( |
| ast, template_param_infos, template_param_decls); |
| |
| // LLDB needs to create those decls only to be able to display a |
| // type that includes a template template argument. Only the name matters for |
| // this purpose, so we use dummy values for the other characteristics of the |
| // type. |
| return TemplateTemplateParmDecl::Create(ast, decl_ctx, SourceLocation(), |
| /*Depth=*/0, /*Position=*/0, |
| /*IsParameterPack=*/false, |
| &identifier_info, /*Typename=*/false, |
| template_param_list); |
| } |
| |
| ClassTemplateSpecializationDecl * |
| TypeSystemClang::CreateClassTemplateSpecializationDecl( |
| DeclContext *decl_ctx, OptionalClangModuleID owning_module, |
| ClassTemplateDecl *class_template_decl, int kind, |
| const TemplateParameterInfos &template_param_infos) { |
| ASTContext &ast = getASTContext(); |
| llvm::SmallVector<clang::TemplateArgument, 2> args( |
| template_param_infos.Size() + |
| (template_param_infos.hasParameterPack() ? 1 : 0)); |
| |
| auto const &orig_args = template_param_infos.GetArgs(); |
| std::copy(orig_args.begin(), orig_args.end(), args.begin()); |
| if (template_param_infos.hasParameterPack()) { |
| args[args.size() - 1] = TemplateArgument::CreatePackCopy( |
| ast, template_param_infos.GetParameterPackArgs()); |
| } |
| ClassTemplateSpecializationDecl *class_template_specialization_decl = |
| ClassTemplateSpecializationDecl::CreateDeserialized(ast, GlobalDeclID()); |
| class_template_specialization_decl->setTagKind( |
| static_cast<TagDecl::TagKind>(kind)); |
| class_template_specialization_decl->setDeclContext(decl_ctx); |
| class_template_specialization_decl->setInstantiationOf(class_template_decl); |
| class_template_specialization_decl->setTemplateArgs( |
| TemplateArgumentList::CreateCopy(ast, args)); |
| ast.getTypeDeclType(class_template_specialization_decl, nullptr); |
| class_template_specialization_decl->setDeclName( |
| class_template_decl->getDeclName()); |
| SetOwningModule(class_template_specialization_decl, owning_module); |
| decl_ctx->addDecl(class_template_specialization_decl); |
| |
| class_template_specialization_decl->setSpecializationKind( |
| TSK_ExplicitSpecialization); |
| |
| return class_template_specialization_decl; |
| } |
| |
| CompilerType TypeSystemClang::CreateClassTemplateSpecializationType( |
| ClassTemplateSpecializationDecl *class_template_specialization_decl) { |
| if (class_template_specialization_decl) { |
| ASTContext &ast = getASTContext(); |
| return GetType(ast.getTagDeclType(class_template_specialization_decl)); |
| } |
| return CompilerType(); |
| } |
| |
| static inline bool check_op_param(bool is_method, |
| clang::OverloadedOperatorKind op_kind, |
| bool unary, bool binary, |
| uint32_t num_params) { |
| // Special-case call since it can take any number of operands |
| if (op_kind == OO_Call) |
| return true; |
| |
| // The parameter count doesn't include "this" |
| if (is_method) |
| ++num_params; |
| if (num_params == 1) |
| return unary; |
| if (num_params == 2) |
| return binary; |
| else |
| return false; |
| } |
| |
| bool TypeSystemClang::CheckOverloadedOperatorKindParameterCount( |
| bool is_method, clang::OverloadedOperatorKind op_kind, |
| uint32_t num_params) { |
| switch (op_kind) { |
| default: |
| break; |
| // C++ standard allows any number of arguments to new/delete |
| case OO_New: |
| case OO_Array_New: |
| case OO_Delete: |
| case OO_Array_Delete: |
| return true; |
| } |
| |
| #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ |
| case OO_##Name: \ |
| return check_op_param(is_method, op_kind, Unary, Binary, num_params); |
| switch (op_kind) { |
| #include "clang/Basic/OperatorKinds.def" |
| default: |
| break; |
| } |
| return false; |
| } |
| |
| clang::AccessSpecifier |
| TypeSystemClang::UnifyAccessSpecifiers(clang::AccessSpecifier lhs, |
| clang::AccessSpecifier rhs) { |
| // Make the access equal to the stricter of the field and the nested field's |
| // access |
| if (lhs == AS_none || rhs == AS_none) |
| return AS_none; |
| if (lhs == AS_private || rhs == AS_private) |
| return AS_private; |
| if (lhs == AS_protected || rhs == AS_protected) |
| return AS_protected; |
| return AS_public; |
| } |
| |
| bool TypeSystemClang::FieldIsBitfield(FieldDecl *field, |
| uint32_t &bitfield_bit_size) { |
| ASTContext &ast = getASTContext(); |
| if (field == nullptr) |
| return false; |
| |
| if (field->isBitField()) { |
| Expr *bit_width_expr = field->getBitWidth(); |
| if (bit_width_expr) { |
| if (std::optional<llvm::APSInt> bit_width_apsint = |
| bit_width_expr->getIntegerConstantExpr(ast)) { |
| bitfield_bit_size = bit_width_apsint->getLimitedValue(UINT32_MAX); |
| return true; |
| } |
| } |
| } |
| return false; |
| } |
| |
| bool TypeSystemClang::RecordHasFields(const RecordDecl *record_decl) { |
| if (record_decl == nullptr) |
| return false; |
| |
| if (!record_decl->field_empty()) |
| return true; |
| |
| // No fields, lets check this is a CXX record and check the base classes |
| const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl); |
| if (cxx_record_decl) { |
| CXXRecordDecl::base_class_const_iterator base_class, base_class_end; |
| for (base_class = cxx_record_decl->bases_begin(), |
| base_class_end = cxx_record_decl->bases_end(); |
| base_class != base_class_end; ++base_class) { |
| const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>( |
| base_class->getType()->getAs<RecordType>()->getDecl()); |
| if (RecordHasFields(base_class_decl)) |
| return true; |
| } |
| } |
| |
| // We always want forcefully completed types to show up so we can print a |
| // message in the summary that indicates that the type is incomplete. |
| // This will help users know when they are running into issues with |
| // -flimit-debug-info instead of just seeing nothing if this is a base class |
| // (since we were hiding empty base classes), or nothing when you turn open |
| // an valiable whose type was incomplete. |
| if (std::optional<ClangASTMetadata> meta_data = GetMetadata(record_decl); |
| meta_data && meta_data->IsForcefullyCompleted()) |
| return true; |
| |
| return false; |
| } |
| |
| #pragma mark Objective-C Classes |
| |
| CompilerType TypeSystemClang::CreateObjCClass( |
| llvm::StringRef name, clang::DeclContext *decl_ctx, |
| OptionalClangModuleID owning_module, bool isInternal, |
| std::optional<ClangASTMetadata> metadata) { |
| ASTContext &ast = getASTContext(); |
| assert(!name.empty()); |
| if (!decl_ctx) |
| decl_ctx = ast.getTranslationUnitDecl(); |
| |
| ObjCInterfaceDecl *decl = |
| ObjCInterfaceDecl::CreateDeserialized(ast, GlobalDeclID()); |
| decl->setDeclContext(decl_ctx); |
| decl->setDeclName(&ast.Idents.get(name)); |
| decl->setImplicit(isInternal); |
| SetOwningModule(decl, owning_module); |
| |
| if (metadata) |
| SetMetadata(decl, *metadata); |
| |
| return GetType(ast.getObjCInterfaceType(decl)); |
| } |
| |
| bool TypeSystemClang::BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) { |
| return !TypeSystemClang::RecordHasFields(b->getType()->getAsCXXRecordDecl()); |
| } |
| |
| uint32_t |
| TypeSystemClang::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl, |
| bool omit_empty_base_classes) { |
| uint32_t num_bases = 0; |
| if (cxx_record_decl) { |
| if (omit_empty_base_classes) { |
| CXXRecordDecl::base_class_const_iterator base_class, base_class_end; |
| for (base_class = cxx_record_decl->bases_begin(), |
| base_class_end = cxx_record_decl->bases_end(); |
| base_class != base_class_end; ++base_class) { |
| // Skip empty base classes |
| if (BaseSpecifierIsEmpty(base_class)) |
| continue; |
| ++num_bases; |
| } |
| } else |
| num_bases = cxx_record_decl->getNumBases(); |
| } |
| return num_bases; |
| } |
| |
| #pragma mark Namespace Declarations |
| |
| NamespaceDecl *TypeSystemClang::GetUniqueNamespaceDeclaration( |
| const char *name, clang::DeclContext *decl_ctx, |
| OptionalClangModuleID owning_module, bool is_inline) { |
| NamespaceDecl *namespace_decl = nullptr; |
| ASTContext &ast = getASTContext(); |
| TranslationUnitDecl *translation_unit_decl = ast.getTranslationUnitDecl(); |
| if (!decl_ctx) |
| decl_ctx = translation_unit_decl; |
| |
| if (name) { |
| IdentifierInfo &identifier_info = ast.Idents.get(name); |
| DeclarationName decl_name(&identifier_info); |
| clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name); |
| for (NamedDecl *decl : result) { |
| namespace_decl = dyn_cast<clang::NamespaceDecl>(decl); |
| if (namespace_decl) |
| return namespace_decl; |
| } |
| |
| namespace_decl = NamespaceDecl::Create(ast, decl_ctx, is_inline, |
| SourceLocation(), SourceLocation(), |
| &identifier_info, nullptr, false); |
| |
| decl_ctx->addDecl(namespace_decl); |
| } else { |
| if (decl_ctx == translation_unit_decl) { |
| namespace_decl = translation_unit_decl->getAnonymousNamespace(); |
| if (namespace_decl) |
| return namespace_decl; |
| |
| namespace_decl = |
| NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(), |
| SourceLocation(), nullptr, nullptr, false); |
| translation_unit_decl->setAnonymousNamespace(namespace_decl); |
| translation_unit_decl->addDecl(namespace_decl); |
| assert(namespace_decl == translation_unit_decl->getAnonymousNamespace()); |
| } else { |
| NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx); |
| if (parent_namespace_decl) { |
| namespace_decl = parent_namespace_decl->getAnonymousNamespace(); |
| if (namespace_decl) |
| return namespace_decl; |
| namespace_decl = |
| NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(), |
| SourceLocation(), nullptr, nullptr, false); |
| parent_namespace_decl->setAnonymousNamespace(namespace_decl); |
| parent_namespace_decl->addDecl(namespace_decl); |
| assert(namespace_decl == |
| parent_namespace_decl->getAnonymousNamespace()); |
| } else { |
| assert(false && "GetUniqueNamespaceDeclaration called with no name and " |
| "no namespace as decl_ctx"); |
| } |
| } |
| } |
| // Note: namespaces can span multiple modules, so perhaps this isn't a good |
| // idea. |
| SetOwningModule(namespace_decl, owning_module); |
| |
| VerifyDecl(namespace_decl); |
| return namespace_decl; |
| } |
| |
| clang::BlockDecl * |
| TypeSystemClang::CreateBlockDeclaration(clang::DeclContext *ctx, |
| OptionalClangModuleID owning_module) { |
| if (ctx) { |
| clang::BlockDecl *decl = |
| clang::BlockDecl::CreateDeserialized(getASTContext(), GlobalDeclID()); |
| decl->setDeclContext(ctx); |
| ctx->addDecl(decl); |
| SetOwningModule(decl, owning_module); |
| return decl; |
| } |
| return nullptr; |
| } |
| |
| clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left, |
| clang::DeclContext *right, |
| clang::DeclContext *root) { |
| if (root == nullptr) |
| return nullptr; |
| |
| std::set<clang::DeclContext *> path_left; |
| for (clang::DeclContext *d = left; d != nullptr; d = d->getParent()) |
| path_left.insert(d); |
| |
| for (clang::DeclContext *d = right; d != nullptr; d = d->getParent()) |
| if (path_left.find(d) != path_left.end()) |
| return d; |
| |
| return nullptr; |
| } |
| |
| clang::UsingDirectiveDecl *TypeSystemClang::CreateUsingDirectiveDeclaration( |
| clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, |
| clang::NamespaceDecl *ns_decl) { |
| if (decl_ctx && ns_decl) { |
| auto *translation_unit = getASTContext().getTranslationUnitDecl(); |
| clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create( |
| getASTContext(), decl_ctx, clang::SourceLocation(), |
| clang::SourceLocation(), clang::NestedNameSpecifierLoc(), |
| clang::SourceLocation(), ns_decl, |
| FindLCABetweenDecls(decl_ctx, ns_decl, |
| translation_unit)); |
| decl_ctx->addDecl(using_decl); |
| SetOwningModule(using_decl, owning_module); |
| return using_decl; |
| } |
| return nullptr; |
| } |
| |
| clang::UsingDecl * |
| TypeSystemClang::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx, |
| OptionalClangModuleID owning_module, |
| clang::NamedDecl *target) { |
| if (current_decl_ctx && target) { |
| clang::UsingDecl *using_decl = clang::UsingDecl::Create( |
| getASTContext(), current_decl_ctx, clang::SourceLocation(), |
| clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false); |
| SetOwningModule(using_decl, owning_module); |
| clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create( |
| getASTContext(), current_decl_ctx, clang::SourceLocation(), |
| target->getDeclName(), using_decl, target); |
| SetOwningModule(shadow_decl, owning_module); |
| using_decl->addShadowDecl(shadow_decl); |
| current_decl_ctx->addDecl(using_decl); |
| return using_decl; |
| } |
| return nullptr; |
| } |
| |
| clang::VarDecl *TypeSystemClang::CreateVariableDeclaration( |
| clang::DeclContext *decl_context, OptionalClangModuleID owning_module, |
| const char *name, clang::QualType type) { |
| if (decl_context) { |
| clang::VarDecl *var_decl = |
| clang::VarDecl::CreateDeserialized(getASTContext(), GlobalDeclID()); |
| var_decl->setDeclContext(decl_context); |
| if (name && name[0]) |
| var_decl->setDeclName(&getASTContext().Idents.getOwn(name)); |
| var_decl->setType(type); |
| SetOwningModule(var_decl, owning_module); |
| var_decl->setAccess(clang::AS_public); |
| decl_context->addDecl(var_decl); |
| return var_decl; |
| } |
| return nullptr; |
| } |
| |
| lldb::opaque_compiler_type_t |
| TypeSystemClang::GetOpaqueCompilerType(clang::ASTContext *ast, |
| lldb::BasicType basic_type) { |
| switch (basic_type) { |
| case eBasicTypeVoid: |
| return ast->VoidTy.getAsOpaquePtr(); |
| case eBasicTypeChar: |
| return ast->CharTy.getAsOpaquePtr(); |
| case eBasicTypeSignedChar: |
| return ast->SignedCharTy.getAsOpaquePtr(); |
| case eBasicTypeUnsignedChar: |
| return ast->UnsignedCharTy.getAsOpaquePtr(); |
| case eBasicTypeWChar: |
| return ast->getWCharType().getAsOpaquePtr(); |
| case eBasicTypeSignedWChar: |
| return ast->getSignedWCharType().getAsOpaquePtr(); |
| case eBasicTypeUnsignedWChar: |
| return ast->getUnsignedWCharType().getAsOpaquePtr(); |
| case eBasicTypeChar8: |
| return ast->Char8Ty.getAsOpaquePtr(); |
| case eBasicTypeChar16: |
| return ast->Char16Ty.getAsOpaquePtr(); |
| case eBasicTypeChar32: |
| return ast->Char32Ty.getAsOpaquePtr(); |
| case eBasicTypeShort: |
| return ast->ShortTy.getAsOpaquePtr(); |
| case eBasicTypeUnsignedShort: |
| return ast->UnsignedShortTy.getAsOpaquePtr(); |
| case eBasicTypeInt: |
| return ast->IntTy.getAsOpaquePtr(); |
| case eBasicTypeUnsignedInt: |
| return ast->UnsignedIntTy.getAsOpaquePtr(); |
| case eBasicTypeLong: |
| return ast->LongTy.getAsOpaquePtr(); |
| case eBasicTypeUnsignedLong: |
| return ast->UnsignedLongTy.getAsOpaquePtr(); |
| case eBasicTypeLongLong: |
| return ast->LongLongTy.getAsOpaquePtr(); |
| case eBasicTypeUnsignedLongLong: |
| return ast->UnsignedLongLongTy.getAsOpaquePtr(); |
| case eBasicTypeInt128: |
| return ast->Int128Ty.getAsOpaquePtr(); |
| case eBasicTypeUnsignedInt128: |
| return ast->UnsignedInt128Ty.getAsOpaquePtr(); |
| case eBasicTypeBool: |
| return ast->BoolTy.getAsOpaquePtr(); |
| case eBasicTypeHalf: |
| return ast->HalfTy.getAsOpaquePtr(); |
| case eBasicTypeFloat: |
| return ast->FloatTy.getAsOpaquePtr(); |
| case eBasicTypeDouble: |
| return ast->DoubleTy.getAsOpaquePtr(); |
| case eBasicTypeLongDouble: |
| return ast->LongDoubleTy.getAsOpaquePtr(); |
| case eBasicTypeFloatComplex: |
| return ast->getComplexType(ast->FloatTy).getAsOpaquePtr(); |
| case eBasicTypeDoubleComplex: |
| return ast->getComplexType(ast->DoubleTy).getAsOpaquePtr(); |
| case eBasicTypeLongDoubleComplex: |
| return ast->getComplexType(ast->LongDoubleTy).getAsOpaquePtr(); |
| case eBasicTypeObjCID: |
| return ast->getObjCIdType().getAsOpaquePtr(); |
| case eBasicTypeObjCClass: |
| return ast->getObjCClassType().getAsOpaquePtr(); |
| case eBasicTypeObjCSel: |
| return ast->getObjCSelType().getAsOpaquePtr(); |
| case eBasicTypeNullPtr: |
| return ast->NullPtrTy.getAsOpaquePtr(); |
| default: |
| return nullptr; |
| } |
| } |
| |
| #pragma mark Function Types |
| |
| clang::DeclarationName |
| TypeSystemClang::GetDeclarationName(llvm::StringRef name, |
| const CompilerType &function_clang_type) { |
| clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS; |
| if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS) |
| return DeclarationName(&getASTContext().Idents.get( |
| name)); // Not operator, but a regular function. |
| |
| // Check the number of operator parameters. Sometimes we have seen bad DWARF |
| // that doesn't correctly describe operators and if we try to create a method |
| // and add it to the class, clang will assert and crash, so we need to make |
| // sure things are acceptable. |
| clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type)); |
| const clang::FunctionProtoType *function_type = |
| llvm::dyn_cast<clang::FunctionProtoType>(method_qual_type.getTypePtr()); |
| if (function_type == nullptr) |
| return clang::DeclarationName(); |
| |
| const bool is_method = false; |
| const unsigned int num_params = function_type->getNumParams(); |
| if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount( |
| is_method, op_kind, num_params)) |
| return clang::DeclarationName(); |
| |
| return getASTContext().DeclarationNames.getCXXOperatorName(op_kind); |
| } |
| |
| PrintingPolicy TypeSystemClang::GetTypePrintingPolicy() { |
| clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy()); |
| printing_policy.SuppressTagKeyword = true; |
| // Inline namespaces are important for some type formatters (e.g., libc++ |
| // and libstdc++ are differentiated by their inline namespaces). |
| printing_policy.SuppressInlineNamespace = false; |
| printing_policy.SuppressUnwrittenScope = false; |
| // Default arguments are also always important for type formatters. Otherwise |
| // we would need to always specify two type names for the setups where we do |
| // know the default arguments and where we don't know default arguments. |
| // |
| // For example, without this we would need to have formatters for both: |
| // std::basic_string<char> |
| // and |
| // std::basic_string<char, std::char_traits<char>, std::allocator<char> > |
| // to support setups where LLDB was able to reconstruct default arguments |
| // (and we then would have suppressed them from the type name) and also setups |
| // where LLDB wasn't able to reconstruct the default arguments. |
| printing_policy.SuppressDefaultTemplateArgs = false; |
| return printing_policy; |
| } |
| |
| std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl, |
| bool qualified) { |
| clang::PrintingPolicy printing_policy = GetTypePrintingPolicy(); |
| std::string result; |
| llvm::raw_string_ostream os(result); |
| named_decl->getNameForDiagnostic(os, printing_policy, qualified); |
| return result; |
| } |
| |
| FunctionDecl *TypeSystemClang::CreateFunctionDeclaration( |
| clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, |
| llvm::StringRef name, const CompilerType &function_clang_type, |
| clang::StorageClass storage, bool is_inline) { |
| FunctionDecl *func_decl = nullptr; |
| ASTContext &ast = getASTContext(); |
| if (!decl_ctx) |
| decl_ctx = ast.getTranslationUnitDecl(); |
| |
| const bool hasWrittenPrototype = true; |
| const bool isConstexprSpecified = false; |
| |
| clang::DeclarationName declarationName = |
| GetDeclarationName(name, function_clang_type); |
| func_decl = FunctionDecl::CreateDeserialized(ast, GlobalDeclID()); |
| func_decl->setDeclContext(decl_ctx); |
| func_decl->setDeclName(declarationName); |
| func_decl->setType(ClangUtil::GetQualType(function_clang_type)); |
| func_decl->setStorageClass(storage); |
| func_decl->setInlineSpecified(is_inline); |
| func_decl->setHasWrittenPrototype(hasWrittenPrototype); |
| func_decl->setConstexprKind(isConstexprSpecified |
| ? ConstexprSpecKind::Constexpr |
| : ConstexprSpecKind::Unspecified); |
| SetOwningModule(func_decl, owning_module); |
| decl_ctx->addDecl(func_decl); |
| |
| VerifyDecl(func_decl); |
| |
| return func_decl; |
| } |
| |
| CompilerType TypeSystemClang::CreateFunctionType( |
| const CompilerType &result_type, const CompilerType *args, |
| unsigned num_args, bool is_variadic, unsigned type_quals, |
| clang::CallingConv cc, clang::RefQualifierKind ref_qual) { |
| if (!result_type || !ClangUtil::IsClangType(result_type)) |
| return CompilerType(); // invalid return type |
| |
| std::vector<QualType> qual_type_args; |
| if (num_args > 0 && args == nullptr) |
| return CompilerType(); // invalid argument array passed in |
| |
| // Verify that all arguments are valid and the right type |
| for (unsigned i = 0; i < num_args; ++i) { |
| if (args[i]) { |
| // Make sure we have a clang type in args[i] and not a type from another |
| // language whose name might match |
| const bool is_clang_type = ClangUtil::IsClangType(args[i]); |
| lldbassert(is_clang_type); |
| if (is_clang_type) |
| qual_type_args.push_back(ClangUtil::GetQualType(args[i])); |
| else |
| return CompilerType(); // invalid argument type (must be a clang type) |
| } else |
| return CompilerType(); // invalid argument type (empty) |
| } |
| |
| // TODO: Detect calling convention in DWARF? |
| FunctionProtoType::ExtProtoInfo proto_info; |
| proto_info.ExtInfo = cc; |
| proto_info.Variadic = is_variadic; |
| proto_info.ExceptionSpec = EST_None; |
| proto_info.TypeQuals = clang::Qualifiers::fromFastMask(type_quals); |
| proto_info.RefQualifier = ref_qual; |
| |
| return GetType(getASTContext().getFunctionType( |
| ClangUtil::GetQualType(result_type), qual_type_args, proto_info)); |
| } |
| |
| ParmVarDecl *TypeSystemClang::CreateParameterDeclaration( |
| clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, |
| const char *name, const CompilerType ¶m_type, int storage, |
| bool add_decl) { |
| ASTContext &ast = getASTContext(); |
| auto *decl = ParmVarDecl::CreateDeserialized(ast, GlobalDeclID()); |
| decl->setDeclContext(decl_ctx); |
| if (name && name[0]) |
| decl->setDeclName(&ast.Idents.get(name)); |
| decl->setType(ClangUtil::GetQualType(param_type)); |
| decl->setStorageClass(static_cast<clang::StorageClass>(storage)); |
| SetOwningModule(decl, owning_module); |
| if (add_decl) |
| decl_ctx->addDecl(decl); |
| |
| return decl; |
| } |
| |
| void TypeSystemClang::SetFunctionParameters( |
| FunctionDecl *function_decl, llvm::ArrayRef<ParmVarDecl *> params) { |
| if (function_decl) |
| function_decl->setParams(params); |
| } |
| |
| CompilerType |
| TypeSystemClang::CreateBlockPointerType(const CompilerType &function_type) { |
| QualType block_type = m_ast_up->getBlockPointerType( |
| clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType())); |
| |
| return GetType(block_type); |
| } |
| |
| #pragma mark Array Types |
| |
| CompilerType |
| TypeSystemClang::CreateArrayType(const CompilerType &element_type, |
| std::optional<size_t> element_count, |
| bool is_vector) { |
| if (!element_type.IsValid()) |
| return {}; |
| |
| ASTContext &ast = getASTContext(); |
| |
| // Unknown number of elements; this is an incomplete array |
| // (e.g., variable length array with non-constant bounds, or |
| // a flexible array member). |
| if (!element_count) |
| return GetType( |
| ast.getIncompleteArrayType(ClangUtil::GetQualType(element_type), |
| clang::ArraySizeModifier::Normal, 0)); |
| |
| if (is_vector) |
| return GetType(ast.getExtVectorType(ClangUtil::GetQualType(element_type), |
| *element_count)); |
| |
| llvm::APInt ap_element_count(64, *element_count); |
| return GetType(ast.getConstantArrayType(ClangUtil::GetQualType(element_type), |
| ap_element_count, nullptr, |
| clang::ArraySizeModifier::Normal, 0)); |
| } |
| |
| CompilerType TypeSystemClang::CreateStructForIdentifier( |
| llvm::StringRef type_name, |
| const std::initializer_list<std::pair<const char *, CompilerType>> |
| &type_fields, |
| bool packed) { |
| CompilerType type; |
| if (!type_name.empty() && |
| (type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)) |
| .IsValid()) { |
| lldbassert(0 && "Trying to create a type for an existing name"); |
| return type; |
| } |
| |
| type = CreateRecordType( |
| nullptr, OptionalClangModuleID(), lldb::eAccessPublic, type_name, |
| llvm::to_underlying(clang::TagTypeKind::Struct), lldb::eLanguageTypeC); |
| StartTagDeclarationDefinition(type); |
| for (const auto &field : type_fields) |
| AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic, |
| 0); |
| if (packed) |
| SetIsPacked(type); |
| CompleteTagDeclarationDefinition(type); |
| return type; |
| } |
| |
| CompilerType TypeSystemClang::GetOrCreateStructForIdentifier( |
| llvm::StringRef type_name, |
| const std::initializer_list<std::pair<const char *, CompilerType>> |
| &type_fields, |
| bool packed) { |
| CompilerType type; |
| if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid()) |
| return type; |
| |
| return CreateStructForIdentifier(type_name, type_fields, packed); |
| } |
| |
| #pragma mark Enumeration Types |
| |
| CompilerType TypeSystemClang::CreateEnumerationType( |
| llvm::StringRef name, clang::DeclContext *decl_ctx, |
| OptionalClangModuleID owning_module, const Declaration &decl, |
| const CompilerType &integer_clang_type, bool is_scoped) { |
| // TODO: Do something intelligent with the Declaration object passed in |
| // like maybe filling in the SourceLocation with it... |
| ASTContext &ast = getASTContext(); |
| |
| // TODO: ask about these... |
| // const bool IsFixed = false; |
| EnumDecl *enum_decl = EnumDecl::CreateDeserialized(ast, GlobalDeclID()); |
| enum_decl->setDeclContext(decl_ctx); |
| if (!name.empty()) |
| enum_decl->setDeclName(&ast.Idents.get(name)); |
| enum_decl->setScoped(is_scoped); |
| enum_decl->setScopedUsingClassTag(is_scoped); |
| enum_decl->setFixed(false); |
| SetOwningModule(enum_decl, owning_module); |
| if (decl_ctx) |
| decl_ctx->addDecl(enum_decl); |
| |
| // TODO: check if we should be setting the promotion type too? |
| enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type)); |
| |
| enum_decl->setAccess(AS_public); // TODO respect what's in the debug info |
| |
| return GetType(ast.getTagDeclType(enum_decl)); |
| } |
| |
| CompilerType TypeSystemClang::GetIntTypeFromBitSize(size_t bit_size, |
| bool is_signed) { |
| clang::ASTContext &ast = getASTContext(); |
| |
| if (!ast.VoidPtrTy) |
| return {}; |
| |
| if (is_signed) { |
| if (bit_size == ast.getTypeSize(ast.SignedCharTy)) |
| return GetType(ast.SignedCharTy); |
| |
| if (bit_size == ast.getTypeSize(ast.ShortTy)) |
| return GetType(ast.ShortTy); |
| |
| if (bit_size == ast.getTypeSize(ast.IntTy)) |
| return GetType(ast.IntTy); |
| |
| if (bit_size == ast.getTypeSize(ast.LongTy)) |
| return GetType(ast.LongTy); |
| |
| if (bit_size == ast.getTypeSize(ast.LongLongTy)) |
| return GetType(ast.LongLongTy); |
| |
| if (bit_size == ast.getTypeSize(ast.Int128Ty)) |
| return GetType(ast.Int128Ty); |
| } else { |
| if (bit_size == ast.getTypeSize(ast.UnsignedCharTy)) |
| return GetType(ast.UnsignedCharTy); |
| |
| if (bit_size == ast.getTypeSize(ast.UnsignedShortTy)) |
| return GetType(ast.UnsignedShortTy); |
| |
| if (bit_size == ast.getTypeSize(ast.UnsignedIntTy)) |
| return GetType(ast.UnsignedIntTy); |
| |
| if (bit_size == ast.getTypeSize(ast.UnsignedLongTy)) |
| return GetType(ast.UnsignedLongTy); |
| |
| if (bit_size == ast.getTypeSize(ast.UnsignedLongLongTy)) |
| return GetType(ast.UnsignedLongLongTy); |
| |
| if (bit_size == ast.getTypeSize(ast.UnsignedInt128Ty)) |
| return GetType(ast.UnsignedInt128Ty); |
| } |
| return CompilerType(); |
| } |
| |
| CompilerType TypeSystemClang::GetPointerSizedIntType(bool is_signed) { |
| if (!getASTContext().VoidPtrTy) |
| return {}; |
| |
| return GetIntTypeFromBitSize( |
| getASTContext().getTypeSize(getASTContext().VoidPtrTy), is_signed); |
| } |
| |
| void TypeSystemClang::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) { |
| if (decl_ctx) { |
| DumpDeclContextHiearchy(decl_ctx->getParent()); |
| |
| clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl_ctx); |
| if (named_decl) { |
| printf("%20s: %s\n", decl_ctx->getDeclKindName(), |
| named_decl->getDeclName().getAsString().c_str()); |
| } else { |
| printf("%20s\n", decl_ctx->getDeclKindName()); |
| } |
| } |
| } |
| |
| void TypeSystemClang::DumpDeclHiearchy(clang::Decl *decl) { |
| if (decl == nullptr) |
| return; |
| DumpDeclContextHiearchy(decl->getDeclContext()); |
| |
| clang::RecordDecl *record_decl = llvm::dyn_cast<clang::RecordDecl>(decl); |
| if (record_decl) { |
| printf("%20s: %s%s\n", decl->getDeclKindName(), |
| record_decl->getDeclName().getAsString().c_str(), |
| record_decl->isInjectedClassName() ? " (injected class name)" : ""); |
| |
| } else { |
| clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl); |
| if (named_decl) { |
| printf("%20s: %s\n", decl->getDeclKindName(), |
| named_decl->getDeclName().getAsString().c_str()); |
| } else { |
| printf("%20s\n", decl->getDeclKindName()); |
| } |
| } |
| } |
| |
| bool TypeSystemClang::GetCompleteDecl(clang::ASTContext *ast, |
| clang::Decl *decl) { |
| if (!decl) |
| return false; |
| |
| ExternalASTSource *ast_source = ast->getExternalSource(); |
| |
| if (!ast_source) |
| return false; |
| |
| if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) { |
| if (tag_decl->isCompleteDefinition()) |
| return true; |
| |
| if (!tag_decl->hasExternalLexicalStorage()) |
| return false; |
| |
| ast_source->CompleteType(tag_decl); |
| |
| return !tag_decl->getTypeForDecl()->isIncompleteType(); |
| } else if (clang::ObjCInterfaceDecl *objc_interface_decl = |
| llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) { |
| if (objc_interface_decl->getDefinition()) |
| return true; |
| |
| if (!objc_interface_decl->hasExternalLexicalStorage()) |
| return false; |
| |
| ast_source->CompleteType(objc_interface_decl); |
| |
| return !objc_interface_decl->getTypeForDecl()->isIncompleteType(); |
| } else { |
| return false; |
| } |
| } |
| |
| void TypeSystemClang::SetMetadataAsUserID(const clang::Decl *decl, |
| user_id_t user_id) { |
| ClangASTMetadata meta_data; |
| meta_data.SetUserID(user_id); |
| SetMetadata(decl, meta_data); |
| } |
| |
| void TypeSystemClang::SetMetadataAsUserID(const clang::Type *type, |
| user_id_t user_id) { |
| ClangASTMetadata meta_data; |
| meta_data.SetUserID(user_id); |
| SetMetadata(type, meta_data); |
| } |
| |
| void TypeSystemClang::SetMetadata(const clang::Decl *object, |
| ClangASTMetadata metadata) { |
| m_decl_metadata[object] = metadata; |
| } |
| |
| void TypeSystemClang::SetMetadata(const clang::Type *object, |
| ClangASTMetadata metadata) { |
| m_type_metadata[object] = metadata; |
| } |
| |
| std::optional<ClangASTMetadata> |
| TypeSystemClang::GetMetadata(const clang::Decl *object) { |
| auto It = m_decl_metadata.find(object); |
| if (It != m_decl_metadata.end()) |
| return It->second; |
| |
| return std::nullopt; |
| } |
| |
| std::optional<ClangASTMetadata> |
| TypeSystemClang::GetMetadata(const clang::Type *object) { |
| auto It = m_type_metadata.find(object); |
| if (It != m_type_metadata.end()) |
| return It->second; |
| |
| return std::nullopt; |
| } |
| |
| void TypeSystemClang::SetCXXRecordDeclAccess(const clang::CXXRecordDecl *object, |
| clang::AccessSpecifier access) { |
| if (access == clang::AccessSpecifier::AS_none) |
| m_cxx_record_decl_access.erase(object); |
| else |
| m_cxx_record_decl_access[object] = access; |
| } |
| |
| clang::AccessSpecifier |
| TypeSystemClang::GetCXXRecordDeclAccess(const clang::CXXRecordDecl *object) { |
| auto It = m_cxx_record_decl_access.find(object); |
| if (It != m_cxx_record_decl_access.end()) |
| return It->second; |
| return clang::AccessSpecifier::AS_none; |
| } |
| |
| clang::DeclContext * |
| TypeSystemClang::GetDeclContextForType(const CompilerType &type) { |
| return GetDeclContextForType(ClangUtil::GetQualType(type)); |
| } |
| |
| CompilerDeclContext |
| TypeSystemClang::GetCompilerDeclContextForType(const CompilerType &type) { |
| if (auto *decl_context = GetDeclContextForType(type)) |
| return CreateDeclContext(decl_context); |
| return CompilerDeclContext(); |
| } |
| |
| /// Aggressively desugar the provided type, skipping past various kinds of |
| /// syntactic sugar and other constructs one typically wants to ignore. |
| /// The \p mask argument allows one to skip certain kinds of simplifications, |
| /// when one wishes to handle a certain kind of type directly. |
| static QualType |
| RemoveWrappingTypes(QualType type, ArrayRef<clang::Type::TypeClass> mask = {}) { |
| while (true) { |
| if (find(mask, type->getTypeClass()) != mask.end()) |
| return type; |
| switch (type->getTypeClass()) { |
| // This is not fully correct as _Atomic is more than sugar, but it is |
| // sufficient for the purposes we care about. |
| case clang::Type::Atomic: |
| type = cast<clang::AtomicType>(type)->getValueType(); |
| break; |
| case clang::Type::Auto: |
| case clang::Type::Decltype: |
| case clang::Type::Elaborated: |
| case clang::Type::Paren: |
| case clang::Type::SubstTemplateTypeParm: |
| case clang::Type::TemplateSpecialization: |
| case clang::Type::Typedef: |
| case clang::Type::TypeOf: |
| case clang::Type::TypeOfExpr: |
| case clang::Type::Using: |
| type = type->getLocallyUnqualifiedSingleStepDesugaredType(); |
| break; |
| default: |
| return type; |
| } |
| } |
| } |
| |
| clang::DeclContext * |
| TypeSystemClang::GetDeclContextForType(clang::QualType type) { |
| if (type.isNull()) |
| return nullptr; |
| |
| clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType()); |
| const clang::Type::TypeClass type_class = qual_type->getTypeClass(); |
| switch (type_class) { |
| case clang::Type::ObjCInterface: |
| return llvm::cast<clang::ObjCObjectType>(qual_type.getTypePtr()) |
| ->getInterface(); |
| case clang::Type::ObjCObjectPointer: |
| return GetDeclContextForType( |
| llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr()) |
| ->getPointeeType()); |
| case clang::Type::Record: |
| return llvm::cast<clang::RecordType>(qual_type)->getDecl(); |
| case clang::Type::Enum: |
| return llvm::cast<clang::EnumType>(qual_type)->getDecl(); |
| default: |
| break; |
| } |
| // No DeclContext in this type... |
| return nullptr; |
| } |
| |
| /// Returns the clang::RecordType of the specified \ref qual_type. This |
| /// function will try to complete the type if necessary (and allowed |
| /// by the specified \ref allow_completion). If we fail to return a *complete* |
| /// type, returns nullptr. |
| static const clang::RecordType *GetCompleteRecordType(clang::ASTContext *ast, |
| clang::QualType qual_type, |
| bool allow_completion) { |
| assert(qual_type->isRecordType()); |
| |
| const auto *tag_type = llvm::cast<clang::RecordType>(qual_type.getTypePtr()); |
| |
| clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); |
| |
| // RecordType with no way of completing it, return the plain |
| // TagType. |
| if (!cxx_record_decl || !cxx_record_decl->hasExternalLexicalStorage()) |
| return tag_type; |
| |
| const bool is_complete = cxx_record_decl->isCompleteDefinition(); |
| const bool fields_loaded = |
| cxx_record_decl->hasLoadedFieldsFromExternalStorage(); |
| |
| // Already completed this type, nothing to be done. |
| if (is_complete && fields_loaded) |
| return tag_type; |
| |
| if (!allow_completion) |
| return nullptr; |
| |
| // Call the field_begin() accessor to for it to use the external source |
| // to load the fields... |
| // |
| // TODO: if we need to complete the type but have no external source, |
| // shouldn't we error out instead? |
| clang::ExternalASTSource *external_ast_source = ast->getExternalSource(); |
| if (external_ast_source) { |
| external_ast_source->CompleteType(cxx_record_decl); |
| if (cxx_record_decl->isCompleteDefinition()) { |
| cxx_record_decl->field_begin(); |
| cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true); |
| } |
| } |
| |
| return tag_type; |
| } |
| |
| /// Returns the clang::EnumType of the specified \ref qual_type. This |
| /// function will try to complete the type if necessary (and allowed |
| /// by the specified \ref allow_completion). If we fail to return a *complete* |
| /// type, returns nullptr. |
| static const clang::EnumType *GetCompleteEnumType(clang::ASTContext *ast, |
| clang::QualType qual_type, |
| bool allow_completion) { |
| assert(qual_type->isEnumeralType()); |
| assert(ast); |
| |
| const clang::EnumType *enum_type = |
| llvm::cast<clang::EnumType>(qual_type.getTypePtr()); |
| |
| auto *tag_decl = enum_type->getAsTagDecl(); |
| assert(tag_decl); |
| |
| // Already completed, nothing to be done. |
| if (tag_decl->getDefinition()) |
| return enum_type; |
| |
| if (!allow_completion) |
| return nullptr; |
| |
| // No definition but can't complete it, error out. |
| if (!tag_decl->hasExternalLexicalStorage()) |
| return nullptr; |
| |
| // We can't complete the type without an external source. |
| clang::ExternalASTSource *external_ast_source = ast->getExternalSource(); |
| if (!external_ast_source) |
| return nullptr; |
| |
| external_ast_source->CompleteType(tag_decl); |
| return enum_type; |
| } |
| |
| /// Returns the clang::ObjCObjectType of the specified \ref qual_type. This |
| /// function will try to complete the type if necessary (and allowed |
| /// by the specified \ref allow_completion). If we fail to return a *complete* |
| /// type, returns nullptr. |
| static const clang::ObjCObjectType * |
| GetCompleteObjCObjectType(clang::ASTContext *ast, QualType qual_type, |
| bool allow_completion) { |
| assert(qual_type->isObjCObjectType()); |
| assert(ast); |
| |
| const clang::ObjCObjectType *objc_class_type = |
| llvm::cast<clang::ObjCObjectType>(qual_type); |
| |
| clang::ObjCInterfaceDecl *class_interface_decl = |
| objc_class_type->getInterface(); |
| // We currently can't complete objective C types through the newly added |
| // ASTContext because it only supports TagDecl objects right now... |
| if (!class_interface_decl) |
| return objc_class_type; |
| |
| // Already complete, nothing to be done. |
| if (class_interface_decl->getDefinition()) |
| return objc_class_type; |
| |
| if (!allow_completion) |
| return nullptr; |
| |
| // No definition but can't complete it, error out. |
| if (!class_interface_decl->hasExternalLexicalStorage()) |
| return nullptr; |
| |
| // We can't complete the type without an external source. |
| clang::ExternalASTSource *external_ast_source = ast->getExternalSource(); |
| if (!external_ast_source) |
| return nullptr; |
| |
| external_ast_source->CompleteType(class_interface_decl); |
| return objc_class_type; |
| } |
| |
| static bool GetCompleteQualType(clang::ASTContext *ast, |
| clang::QualType qual_type, |
| bool allow_completion = true) { |
| qual_type = RemoveWrappingTypes(qual_type); |
| const clang::Type::TypeClass type_class = qual_type->getTypeClass(); |
| switch (type_class) { |
| case clang::Type::ConstantArray: |
| case clang::Type::IncompleteArray: |
| case clang::Type::VariableArray: { |
| const clang::ArrayType *array_type = |
| llvm::dyn_cast<clang::ArrayType>(qual_type.getTypePtr()); |
| |
| if (array_type) |
| return GetCompleteQualType(ast, array_type->getElementType(), |
| allow_completion); |
| } break; |
| case clang::Type::Record: { |
| if (const auto *RT = |
| GetCompleteRecordType(ast, qual_type, allow_completion)) |
| return !RT->isIncompleteType(); |
| |
| return false; |
| } break; |
| |
| case clang::Type::Enum: { |
| if (const auto *ET = GetCompleteEnumType(ast, qual_type, allow_completion)) |
| return !ET->isIncompleteType(); |
| |
| return false; |
| } break; |
| case clang::Type::ObjCObject: |
| case clang::Type::ObjCInterface: { |
| if (const auto *OT = |
| GetCompleteObjCObjectType(ast, qual_type, allow_completion)) |
| return !OT->isIncompleteType(); |
| |
| return false; |
| } break; |
| |
| case clang::Type::Attributed: |
| return GetCompleteQualType( |
| ast, llvm::cast<clang::AttributedType>(qual_type)->getModifiedType(), |
| allow_completion); |
| |
| case clang::Type::MemberPointer: |
| // MS C++ ABI requires type of the class to be complete of which the pointee |
| // is a member. |
| if (ast->getTargetInfo().getCXXABI().isMicrosoft()) { |
| auto *MPT = qual_type.getTypePtr()->castAs<clang::MemberPointerType>(); |
| if (MPT->getClass()->isRecordType()) |
| GetCompleteRecordType(ast, clang::QualType(MPT->getClass(), 0), |
| allow_completion); |
| |
| return !qual_type.getTypePtr()->isIncompleteType(); |
| } |
| break; |
| |
| default: |
| break; |
| } |
| |
| return true; |
| } |
| |
| static clang::ObjCIvarDecl::AccessControl |
| ConvertAccessTypeToObjCIvarAccessControl(AccessType access) { |
| switch (access) { |
| case eAccessNone: |
| return clang::ObjCIvarDecl::None; |
| case eAccessPublic: |
| return clang::ObjCIvarDecl::Public; |
| case eAccessPrivate: |
| return clang::ObjCIvarDecl::Private; |
| case eAccessProtected: |
| return clang::ObjCIvarDecl::Protected; |
| case eAccessPackage: |
| return clang::ObjCIvarDecl::Package; |
| } |
| return clang::ObjCIvarDecl::None; |
| } |
| |
| // Tests |
| |
| #ifndef NDEBUG |
| bool TypeSystemClang::Verify(lldb::opaque_compiler_type_t type) { |
| return !type || llvm::isa<clang::Type>(GetQualType(type).getTypePtr()); |
| } |
| #endif |
| |
| bool TypeSystemClang:: |